CombinedText stringlengths 4 3.42M |
|---|
// @(#)root/proof:$Name: $:$Id: TProof.cxx,v 1.189 2007/03/16 17:06:19 rdm Exp $
// Author: Fons Rademakers 13/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProof //
// //
// This class controls a Parallel ROOT Facility, PROOF, cluster. //
// It fires the slave servers, it keeps track of how many slaves are //
// running, it keeps track of the slaves running status, it broadcasts //
// messages to all slaves, it collects results, etc. //
// //
//////////////////////////////////////////////////////////////////////////
#include <fcntl.h>
#include <errno.h>
#ifdef WIN32
# include <io.h>
# include <sys/stat.h>
# include <sys/types.h>
#else
# include <unistd.h>
#endif
#include <vector>
#ifdef R__HAVE_CONFIG
#include "RConfigure.h"
#endif
#include "Riostream.h"
#include "Getline.h"
#include "TBrowser.h"
#include "TChain.h"
#include "TCondor.h"
#include "TDSet.h"
#include "TError.h"
#include "TEnv.h"
#include "TEventList.h"
#include "TFile.h"
#include "TFileInfo.h"
#include "TFileMerger.h"
#include "TFTP.h"
#include "TInterpreter.h"
#include "TMap.h"
#include "TMessage.h"
#include "TMonitor.h"
#include "TMutex.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TParameter.h"
#include "TProof.h"
#include "TProofNodeInfo.h"
#include "TVirtualProofPlayer.h"
#include "TProofServ.h"
#include "TPluginManager.h"
#include "TQueryResult.h"
#include "TRandom.h"
#include "TRegexp.h"
#include "TROOT.h"
#include "TSemaphore.h"
#include "TSlave.h"
#include "TSocket.h"
#include "TSortedList.h"
#include "TSystem.h"
#include "TThread.h"
#include "TTree.h"
#include "TUrl.h"
TProof *gProof = 0;
TVirtualMutex *gProofMutex = 0;
TList *TProof::fgProofEnvList = 0; // List of env vars for proofserv
ClassImp(TProof)
//----- Helper classes used for parallel startup -------------------------------
//______________________________________________________________________________
TProofThreadArg::TProofThreadArg(const char *h, Int_t po, const char *o,
Int_t pe, const char *i, const char *w,
TList *s, TProof *prf)
: fOrd(o), fPerf(pe), fImage(i), fWorkdir(w),
fSlaves(s), fProof(prf), fCslave(0), fClaims(0),
fType(TSlave::kSlave)
{
// Constructor
fUrl = new TUrl(Form("%s:%d",h,po));
}
//______________________________________________________________________________
TProofThreadArg::TProofThreadArg(TCondorSlave *csl, TList *clist,
TList *s, TProof *prf)
: fUrl(0), fOrd(0), fPerf(-1), fImage(0), fWorkdir(0),
fSlaves(s), fProof(prf), fCslave(csl), fClaims(clist),
fType(TSlave::kSlave)
{
// Constructor
if (csl) {
fUrl = new TUrl(Form("%s:%d",csl->fHostname.Data(),csl->fPort));
fImage = csl->fImage;
fOrd = csl->fOrdinal;
fWorkdir = csl->fWorkDir;
fPerf = csl->fPerfIdx;
}
}
//______________________________________________________________________________
TProofThreadArg::TProofThreadArg(const char *h, Int_t po, const char *o,
const char *i, const char *w, const char *m,
TList *s, TProof *prf)
: fOrd(o), fPerf(-1), fImage(i), fWorkdir(w),
fMsd(m), fSlaves(s), fProof(prf), fCslave(0), fClaims(0),
fType(TSlave::kSlave)
{
// Constructor
fUrl = new TUrl(Form("%s:%d",h,po));
}
//----- PROOF Interrupt signal handler -----------------------------------------
//______________________________________________________________________________
Bool_t TProofInterruptHandler::Notify()
{
// TProof interrupt handler.
Info("Notify","Processing interrupt signal ...");
// Stop any remote processing
fProof->StopProcess(kTRUE);
// Handle also interrupt condition on socket(s)
fProof->Interrupt(TProof::kLocalInterrupt);
return kTRUE;
}
//----- Input handler for messages from TProofServ -----------------------------
//______________________________________________________________________________
TProofInputHandler::TProofInputHandler(TProof *p, TSocket *s)
: TFileHandler(s->GetDescriptor(),1),
fSocket(s), fProof(p)
{
// Constructor
}
//______________________________________________________________________________
Bool_t TProofInputHandler::Notify()
{
// Handle input
fProof->CollectInputFrom(fSocket);
return kTRUE;
}
//------------------------------------------------------------------------------
ClassImp(TSlaveInfo)
//______________________________________________________________________________
Int_t TSlaveInfo::Compare(const TObject *obj) const
{
// Used to sort slaveinfos by ordinal.
if (!obj) return 1;
const TSlaveInfo *si = dynamic_cast<const TSlaveInfo*>(obj);
if (!si) return fOrdinal.CompareTo(obj->GetName());
const char *myord = GetOrdinal();
const char *otherord = si->GetOrdinal();
while (myord && otherord) {
Int_t myval = atoi(myord);
Int_t otherval = atoi(otherord);
if (myval < otherval) return 1;
if (myval > otherval) return -1;
myord = strchr(myord, '.');
if (myord) myord++;
otherord = strchr(otherord, '.');
if (otherord) otherord++;
}
if (myord) return -1;
if (otherord) return 1;
return 0;
}
//______________________________________________________________________________
void TSlaveInfo::Print(Option_t *opt) const
{
// Print slave info. If opt = "active" print only the active
// slaves, if opt="notactive" print only the not active slaves,
// if opt = "bad" print only the bad slaves, else
// print all slaves.
TString stat = fStatus == kActive ? "active" :
fStatus == kBad ? "bad" :
"not active";
TString msd = fMsd.IsNull() ? "<null>" : fMsd.Data();
if (!opt) opt = "";
if (!strcmp(opt, "active") && fStatus != kActive)
return;
if (!strcmp(opt, "notactive") && fStatus != kNotActive)
return;
if (!strcmp(opt, "bad") && fStatus != kBad)
return;
cout << "Slave: " << fOrdinal
<< " hostname: " << fHostName
<< " msd: " << msd
<< " perf index: " << fPerfIndex
<< " " << stat
<< endl;
}
//------------------------------------------------------------------------------
//______________________________________________________________________________
static char *CollapseSlashesInPath(const char *path)
{
// Get rid of spare slashes in a path. Returned path must be deleted[]
// by the user.
if (path) {
Int_t i = 1; // current index as we go along the string
Int_t j = 0; // current end of new path in newPath
char *newPath = new char [strlen(path) + 1];
newPath[0] = path[0];
while (path[i]) {
if (path[i] != '/' || newPath[j] != '/') {
j++;
newPath[j] = path[i];
}
i++;
}
if (newPath[j] != '/')
j++;
newPath[j] = 0; // We have to terminate the new path.
return newPath;
}
return 0;
}
ClassImp(TProof)
TSemaphore *TProof::fgSemaphore = 0;
//______________________________________________________________________________
TProof::TProof(const char *masterurl, const char *conffile, const char *confdir,
Int_t loglevel, const char *alias, TProofMgr *mgr)
: fUrl(masterurl)
{
// Create a PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). Masterurl is of
// the form: [proof[s]://]host[:port]. Conffile is the name of the config
// file describing the remote PROOF cluster (this argument alows you to
// describe different cluster configurations).
// The default is proof.conf. Confdir is the directory where the config
// file and other PROOF related files are (like motd and noproof files).
// Loglevel is the log level (default = 1). User specified custom config
// files will be first looked for in $HOME/.conffile.
// This may be needed during init
fManager = mgr;
// Default server type
fServType = TProofMgr::kXProofd;
// Default query mode
fQueryMode = kSync;
if (!conffile || strlen(conffile) == 0)
conffile = kPROOF_ConfFile;
if (!confdir || strlen(confdir) == 0)
confdir = kPROOF_ConfDir;
Init(masterurl, conffile, confdir, loglevel, alias);
// If called by a manager, make sure it stays in lasto position
// for cleaning
if (mgr) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(mgr);
gROOT->GetListOfSockets()->Add(mgr);
}
// Old-style server type: we add this to the list and set the global pointer
if (IsProofd() || IsMaster())
gROOT->GetListOfProofs()->Add(this);
// Still needed by the packetizers: needs to be changed
gProof = this;
}
//______________________________________________________________________________
TProof::TProof() : fUrl(""), fServType(TProofMgr::kXProofd)
{
// Protected constructor to be used by classes deriving from TProof
// (they have to call Init themselves and override StartSlaves
// appropriately).
//
// This constructor simply closes any previous gProof and sets gProof
// to this instance.
gROOT->GetListOfProofs()->Add(this);
gProof = this;
}
//______________________________________________________________________________
TProof::~TProof()
{
// Clean up PROOF environment.
while (TChain *chain = dynamic_cast<TChain*> (fChains->First()) ) {
// remove "chain" from list
chain->SetProof(0);
RemoveChain(chain);
}
// remove links to packages enabled on the client
if (!IsMaster()) {
// iterate over all packages
TIter nextpackage(fEnabledPackagesOnClient);
while (TObjString *package = dynamic_cast<TObjString*>(nextpackage())) {
FileStat_t stat;
gSystem->GetPathInfo(package->String(), stat);
// check if symlink, if so unlink
// NOTE: GetPathnfo() returns 1 in case of symlink that does not point to
// existing file or to a directory, but if fIsLink is true the symlink exists
if (stat.fIsLink)
gSystem->Unlink(package->String());
}
}
Close();
SafeDelete(fIntHandler);
SafeDelete(fSlaves);
SafeDelete(fActiveSlaves);
SafeDelete(fInactiveSlaves);
SafeDelete(fUniqueSlaves);
SafeDelete(fAllUniqueSlaves);
SafeDelete(fNonUniqueMasters);
SafeDelete(fBadSlaves);
SafeDelete(fAllMonitor);
SafeDelete(fActiveMonitor);
SafeDelete(fUniqueMonitor);
SafeDelete(fAllUniqueMonitor);
SafeDelete(fSlaveInfo);
SafeDelete(fChains);
SafeDelete(fPlayer);
SafeDelete(fFeedback);
SafeDelete(fWaitingSlaves);
SafeDelete(fAvailablePackages);
SafeDelete(fEnabledPackages);
SafeDelete(fEnabledPackagesOnClient);
SafeDelete(fPackageLock);
// remove file with redirected logs
if (!IsMaster()) {
if (fLogFileR)
fclose(fLogFileR);
if (fLogFileW)
fclose(fLogFileW);
if (fLogFileName.Length())
gSystem->Unlink(fLogFileName);
}
// For those interested in our destruction ...
Emit("~TProof()");
}
//______________________________________________________________________________
Int_t TProof::Init(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel, const char *alias)
{
// Start the PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). For a description
// of the arguments see the TProof ctor. Returns the number of started
// master or slave servers, returns 0 in case of error, in which case
// fValid remains false.
R__ASSERT(gSystem);
fValid = kFALSE;
if (strlen(fUrl.GetOptions()) > 0 && !(strncmp(fUrl.GetOptions(),"std",3))) {
fServType = TProofMgr::kProofd;
fUrl.SetOptions("");
}
if (!masterurl || !*masterurl) {
fUrl.SetProtocol("proof");
fUrl.SetHost("__master__");
} else if (!(strstr(masterurl, "://"))) {
fUrl.SetProtocol("proof");
}
if (fUrl.GetPort() == TUrl(" ").GetPort())
fUrl.SetPort(TUrl("proof:// ").GetPort());
// If in attach mode, options is filled with additiona info
Bool_t attach = kFALSE;
if (strlen(fUrl.GetOptions()) > 0) {
attach = kTRUE;
// A flag from the GUI
TString opts = fUrl.GetOptions();
if (opts.Contains("GUI")) {
SetBit(TProof::kUsingSessionGui);
opts.Remove(opts.Index("GUI"));
fUrl.SetOptions(opts);
}
}
if (strlen(fUrl.GetUser()) <= 0) {
// Get user logon name
UserGroup_t *pw = gSystem->GetUserInfo();
if (pw) {
fUrl.SetUser(pw->fUser);
delete pw;
}
}
// Make sure to store the FQDN, so to get a solid reference for
// subsequent checks (strings corresponding to non-existing hosts
// - like "__master__" - will not be touched by this)
if (!strlen(fUrl.GetHost()))
fMaster = gSystem->GetHostByName(gSystem->HostName()).GetHostName();
else
fMaster = gSystem->GetHostByName(fUrl.GetHost()).GetHostName();
fConfDir = confdir;
fConfFile = conffile;
fWorkDir = gSystem->WorkingDirectory();
fLogLevel = loglevel;
fProtocol = kPROOF_Protocol;
fMasterServ = (fMaster == "__master__") ? kTRUE : kFALSE;
fSendGroupView = kTRUE;
fImage = fMasterServ ? "" : "<local>";
fIntHandler = 0;
fStatus = 0;
fSlaveInfo = 0;
fChains = new TList;
fAvailablePackages = 0;
fEnabledPackages = 0;
fEndMaster = IsMaster() ? kTRUE : kFALSE;
// Default entry point for the data pool is the master
if (!IsMaster())
fDataPoolUrl.Form("root://%s", fMaster.Data());
else
fDataPoolUrl = "";
fProgressDialog = 0;
fProgressDialogStarted = kFALSE;
// Default alias is the master name
TString al = (alias) ? alias : fMaster.Data();
SetAlias(al);
// Client logging of messages from the master and slaves
fRedirLog = kFALSE;
if (!IsMaster()) {
fLogFileName = "ProofLog_";
if ((fLogFileW = gSystem->TempFileName(fLogFileName)) == 0)
Error("Init", "could not create temporary logfile");
if ((fLogFileR = fopen(fLogFileName, "r")) == 0)
Error("Init", "could not open temp logfile for reading");
}
fLogToWindowOnly = kFALSE;
// Status of cluster
fIdle = kTRUE;
// Query type
fSync = kTRUE;
// List of queries
fQueries = 0;
fOtherQueries = 0;
fDrawQueries = 0;
fMaxDrawQueries = 1;
fSeqNum = 0;
// Remote ID of the session
fSessionID = -1;
// Part of active query
fWaitingSlaves = 0;
// Make remote PROOF player
fPlayer = 0;
MakePlayer();
fFeedback = new TList;
fFeedback->SetOwner();
fFeedback->SetName("FeedbackList");
AddInput(fFeedback);
// sort slaves by descending performance index
fSlaves = new TSortedList(kSortDescending);
fActiveSlaves = new TList;
fInactiveSlaves = new TList;
fUniqueSlaves = new TList;
fAllUniqueSlaves = new TList;
fNonUniqueMasters = new TList;
fBadSlaves = new TList;
fAllMonitor = new TMonitor;
fActiveMonitor = new TMonitor;
fUniqueMonitor = new TMonitor;
fAllUniqueMonitor = new TMonitor;
fCurrentMonitor = 0;
fPackageLock = 0;
fEnabledPackagesOnClient = 0;
if (!IsMaster()) {
fPackageDir = kPROOF_WorkDir;
gSystem->ExpandPathName(fPackageDir);
if (gSystem->AccessPathName(fPackageDir)) {
if (gSystem->MakeDirectory(fPackageDir) == -1) {
Error("Init", "failure creating directory %s", fPackageDir.Data());
return 0;
}
}
fPackageDir += TString("/") + kPROOF_PackDir;
if (gSystem->AccessPathName(fPackageDir)) {
if (gSystem->MakeDirectory(fPackageDir) == -1) {
Error("Init", "failure creating directory %s", fPackageDir.Data());
return 0;
}
}
UserGroup_t *ug = gSystem->GetUserInfo();
fPackageLock = new TProofLockPath(Form("%s%s", kPROOF_PackageLockFile, ug->fUser.Data()));
delete ug;
fEnabledPackagesOnClient = new TList;
fEnabledPackagesOnClient->SetOwner();
}
// Master may want parallel startup
Bool_t parallelStartup = kFALSE;
if (!attach && IsMaster()) {
parallelStartup = gEnv->GetValue("Proof.ParallelStartup", kFALSE);
PDB(kGlobal,1) Info("Init", "Parallel Startup: %s",
parallelStartup ? "kTRUE" : "kFALSE");
if (parallelStartup) {
// Load thread lib, if not done already
#ifdef ROOTLIBDIR
TString threadLib = TString(ROOTLIBDIR) + "/libThread";
#else
TString threadLib = TString(gRootDir) + "/lib/libThread";
#endif
char *p;
if ((p = gSystem->DynamicPathName(threadLib, kTRUE))) {
delete[]p;
if (gSystem->Load(threadLib) == -1) {
Warning("Init",
"Cannot load libThread: switch to serial startup (%s)",
threadLib.Data());
parallelStartup = kFALSE;
}
} else {
Warning("Init",
"Cannot find libThread: switch to serial startup (%s)",
threadLib.Data());
parallelStartup = kFALSE;
}
// Get no of parallel requests and set semaphore correspondingly
Int_t parallelRequests = gEnv->GetValue("Proof.ParallelStartupRequests", 0);
if (parallelRequests > 0) {
PDB(kGlobal,1)
Info("Init", "Parallel Startup Requests: %d", parallelRequests);
fgSemaphore = new TSemaphore((UInt_t)(parallelRequests));
}
}
}
// Start slaves
if (!StartSlaves(parallelStartup, attach))
return 0;
if (fgSemaphore)
SafeDelete(fgSemaphore);
// we are now properly initialized
fValid = kTRUE;
// De-activate monitor (will be activated in Collect)
fAllMonitor->DeActivateAll();
// By default go into parallel mode
GoParallel(9999, attach);
// Send relevant initial state to slaves
if (!attach)
SendInitialState();
else if (!IsIdle())
// redirect log
fRedirLog = kTRUE;
// Done at this point, the alias will be communicated to the coordinator, if any
if (!IsMaster())
SetAlias(al);
SetActive(kFALSE);
if (IsValid()) {
// Activate input handler
ActivateAsyncInput();
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
void TProof::SetManager(TProofMgr *mgr)
{
// Set manager and schedule its destruction after this for clean
// operations.
fManager = mgr;
if (mgr) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(mgr);
gROOT->GetListOfSockets()->Add(mgr);
}
}
//______________________________________________________________________________
Bool_t TProof::StartSlaves(Bool_t parallel, Bool_t attach)
{
// Start up PROOF slaves.
// If this is a master server, find the config file and start slave
// servers as specified in the config file
if (IsMaster()) {
Int_t pc = 0;
TList *workerList = new TList;
// Get list of workers
if (gProofServ->GetWorkers(workerList, pc) == TProofServ::kQueryStop) {
Error("StartSlaves", "getting list of worker nodes");
return kFALSE;
}
fImage = gProofServ->GetImage();
// Get all workers
UInt_t nSlaves = workerList->GetSize();
UInt_t nSlavesDone = 0;
Int_t ord = 0;
// Init arrays for threads, if neeeded
std::vector<TProofThread *> thrHandlers;
if (parallel) {
thrHandlers.reserve(nSlaves);
if (thrHandlers.max_size() < nSlaves) {
PDB(kGlobal,1)
Info("StartSlaves","cannot reserve enough space for thread"
" handlers - switch to serial startup");
parallel = kFALSE;
}
}
// Loop over all workers and start them
TListIter next(workerList);
TObject *to;
TProofNodeInfo *worker;
while ((to = next())) {
// Get the next worker from the list
worker = (TProofNodeInfo *)to;
// Read back worker node info
const Char_t *image = worker->GetImage().Data();
const Char_t *workdir = worker->GetWorkDir().Data();
Int_t perfidx = worker->GetPerfIndex();
Int_t sport = worker->GetPort();
if (sport == -1)
sport = fUrl.GetPort();
// create slave server
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
if (parallel) {
// Prepare arguments
TProofThreadArg *ta =
new TProofThreadArg(worker->GetNodeName().Data(), sport,
fullord, perfidx, image, workdir,
fSlaves, this);
if (ta) {
// The type of the thread func makes it a detached thread
TThread *th = new TThread(SlaveStartupThread, ta);
if (!th) {
Info("StartSlaves","Can't create startup thread:"
" out of system resources");
SafeDelete(ta);
} else {
// Save in vector
thrHandlers.push_back(new TProofThread(th, ta));
// Run the thread
th->Run();
// Notify opening of connection
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Opening connections to workers") << nSlaves
<< nSlavesDone << kTRUE;
gProofServ->GetSocket()->Send(m);
}
} // end if (ta)
else {
Info("StartSlaves","Can't create thread arguments object:"
" out of system resources");
}
} // end if parallel
else {
// create slave server
TUrl u(Form("%s:%d",worker->GetNodeName().Data(), sport));
TSlave *slave = CreateSlave(u.GetUrl(), fullord, perfidx,
image, workdir);
// Add to global list (we will add to the monitor list after
// finalizing the server startup)
Bool_t slaveOk = kTRUE;
if (slave->IsValid()) {
fSlaves->Add(slave);
} else {
slaveOk = kFALSE;
fBadSlaves->Add(slave);
}
PDB(kGlobal,3)
Info("StartSlaves", "worker on host %s created"
" and added to list", worker->GetNodeName().Data());
// Notify opening of connection
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Opening connections to workers") << nSlaves
<< nSlavesDone << slaveOk;
gProofServ->GetSocket()->Send(m);
}
ord++;
} //end of worker loop
// Cleanup
SafeDelete(workerList);
nSlavesDone = 0;
if (parallel) {
// Wait completion of startup operations
std::vector<TProofThread *>::iterator i;
for (i = thrHandlers.begin(); i != thrHandlers.end(); ++i) {
TProofThread *pt = *i;
// Wait on this condition
if (pt && pt->fThread->GetState() == TThread::kRunningState) {
PDB(kGlobal,3)
Info("Init",
"parallel startup: waiting for worker %s (%s:%d)",
pt->fArgs->fOrd.Data(), pt->fArgs->fUrl->GetHost(),
pt->fArgs->fUrl->GetPort());
pt->fThread->Join();
}
// Notify end of startup operations
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Setting up worker servers") << nSlaves
<< nSlavesDone << kTRUE;
gProofServ->GetSocket()->Send(m);
}
TIter next(fSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *)next())) {
if (sl->IsValid())
fAllMonitor->Add(sl->GetSocket());
else
fBadSlaves->Add(sl);
}
// We can cleanup now
while (!thrHandlers.empty()) {
i = thrHandlers.end()-1;
if (*i) {
SafeDelete(*i);
thrHandlers.erase(i);
}
}
} else {
// Here we finalize the server startup: in this way the bulk
// of remote operations are almost parallelized
TIter nxsl(fSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *) nxsl())) {
// Finalize setup of the server
if (sl->IsValid())
sl->SetupServ(TSlave::kSlave, 0);
// Monitor good slaves
Bool_t slaveOk = kTRUE;
if (sl->IsValid()) {
fAllMonitor->Add(sl->GetSocket());
} else {
slaveOk = kFALSE;
fBadSlaves->Add(sl);
}
// Notify end of startup operations
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Setting up worker servers") << nSlaves
<< nSlavesDone << slaveOk;
gProofServ->GetSocket()->Send(m);
}
}
} else {
// create master server
fprintf(stderr,"Starting master: opening connection ... \n");
TSlave *slave = CreateSubmaster(fUrl.GetUrl(), "0", "master", 0);
if (slave->IsValid()) {
// Notify
fprintf(stderr,"Starting master:"
" connection open: setting up server ... \r");
StartupMessage("Connection to master opened", kTRUE, 1, 1);
if (!attach) {
// Set worker interrupt handler
slave->SetInterruptHandler(kTRUE);
// Finalize setup of the server
slave->SetupServ(TSlave::kMaster, fConfFile);
if (slave->IsValid()) {
// Notify
fprintf(stderr,"Starting master: OK \n");
StartupMessage("Master started", kTRUE, 1, 1);
// check protocol compatibility
// protocol 1 is not supported anymore
if (fProtocol == 1) {
Error("StartSlaves",
"client and remote protocols not compatible (%d and %d)",
kPROOF_Protocol, fProtocol);
slave->Close("S");
delete slave;
return kFALSE;
}
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
// Unset worker interrupt handler
slave->SetInterruptHandler(kFALSE);
// Set interrupt PROOF handler from now on
fIntHandler = new TProofInterruptHandler(this);
Collect(slave);
Int_t slStatus = slave->GetStatus();
if (slStatus == -99 || slStatus == -98) {
fSlaves->Remove(slave);
fAllMonitor->Remove(slave->GetSocket());
if (slStatus == -99)
Error("StartSlaves", "not allowed to connect to PROOF master server");
else if (slStatus == -98)
Error("StartSlaves", "could not setup output redirection on master");
else
Error("StartSlaves", "setting up master");
slave->Close("S");
delete slave;
return 0;
}
if (!slave->IsValid()) {
fSlaves->Remove(slave);
fAllMonitor->Remove(slave->GetSocket());
slave->Close("S");
delete slave;
Error("StartSlaves",
"failed to setup connection with PROOF master server");
return kFALSE;
}
if (!gROOT->IsBatch()) {
if ((fProgressDialog =
gROOT->GetPluginManager()->FindHandler("TProofProgressDialog")))
if (fProgressDialog->LoadPlugin() == -1)
fProgressDialog = 0;
}
} else {
// Notify
fprintf(stderr,"Starting master: failure\n");
}
} else {
// Notify
if (attach) {
fprintf(stderr,"Starting master: OK \n");
StartupMessage("Master attached", kTRUE, 1, 1);
if (!gROOT->IsBatch()) {
if ((fProgressDialog =
gROOT->GetPluginManager()->FindHandler("TProofProgressDialog")))
if (fProgressDialog->LoadPlugin() == -1)
fProgressDialog = 0;
}
} else {
fprintf(stderr,"Starting manager: OK \n");
StartupMessage("Manager started", kTRUE, 1, 1);
}
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
fIntHandler = new TProofInterruptHandler(this);
}
} else {
delete slave;
Error("StartSlaves", "failed to connect to a PROOF master server");
return kFALSE;
}
}
return kTRUE;
}
//______________________________________________________________________________
void TProof::Close(Option_t *opt)
{
// Close all open slave servers.
// Client can decide to shutdown the remote session by passing option is 'S'
// or 's'. Default for clients is detach, if supported. Masters always
// shutdown the remote counterpart.
if (fSlaves) {
if (fIntHandler)
fIntHandler->Remove();
TIter nxs(fSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *)nxs()))
sl->Close(opt);
fActiveSlaves->Clear("nodelete");
fUniqueSlaves->Clear("nodelete");
fAllUniqueSlaves->Clear("nodelete");
fNonUniqueMasters->Clear("nodelete");
fBadSlaves->Clear("nodelete");
fSlaves->Delete();
}
{
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(this);
if (IsProofd()) {
gROOT->GetListOfProofs()->Remove(this);
if (gProof && gProof == this) {
// Set previous proofd-related as default
TIter pvp(gROOT->GetListOfProofs(), kIterBackward);
while ((gProof = (TProof *)pvp())) {
if (gProof->IsProofd())
break;
}
}
}
}
}
//______________________________________________________________________________
TSlave *TProof::CreateSlave(const char *url, const char *ord,
Int_t perf, const char *image, const char *workdir)
{
// Create a new TSlave of type TSlave::kSlave.
// Note: creation of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave* sl = TSlave::Create(url, ord, perf, image,
this, TSlave::kSlave, workdir, 0);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
// must set fParallel to 1 for slaves since they do not
// report their fParallel with a LOG_DONE message
sl->fParallel = 1;
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::CreateSubmaster(const char *url, const char *ord,
const char *image, const char *msd)
{
// Create a new TSlave of type TSlave::kMaster.
// Note: creation of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave *sl = TSlave::Create(url, ord, 100, image, this,
TSlave::kMaster, 0, msd);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::FindSlave(TSocket *s) const
{
// Find slave that has TSocket s. Returns 0 in case slave is not found.
TSlave *sl;
TIter next(fSlaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid() && sl->GetSocket() == s)
return sl;
}
return 0;
}
//______________________________________________________________________________
void TProof::FindUniqueSlaves()
{
// Add to the fUniqueSlave list the active slaves that have a unique
// (user) file system image. This information is used to transfer files
// only once to nodes that share a file system (an image). Submasters
// which are not in fUniqueSlaves are put in the fNonUniqueMasters
// list. That list is used to trigger the transferring of files to
// the submaster's unique slaves without the need to transfer the file
// to the submaster.
fUniqueSlaves->Clear();
fUniqueMonitor->RemoveAll();
fAllUniqueSlaves->Clear();
fAllUniqueMonitor->RemoveAll();
fNonUniqueMasters->Clear();
TIter next(fActiveSlaves);
while (TSlave *sl = dynamic_cast<TSlave*>(next())) {
if (fImage == sl->fImage) {
if (sl->GetSlaveType() == TSlave::kMaster) {
fNonUniqueMasters->Add(sl);
fAllUniqueSlaves->Add(sl);
fAllUniqueMonitor->Add(sl->GetSocket());
}
continue;
}
TIter next2(fUniqueSlaves);
TSlave *replace_slave = 0;
Bool_t add = kTRUE;
while (TSlave *sl2 = dynamic_cast<TSlave*>(next2())) {
if (sl->fImage == sl2->fImage) {
add = kFALSE;
if (sl->GetSlaveType() == TSlave::kMaster) {
if (sl2->GetSlaveType() == TSlave::kSlave) {
// give preference to master
replace_slave = sl2;
add = kTRUE;
} else if (sl2->GetSlaveType() == TSlave::kMaster) {
fNonUniqueMasters->Add(sl);
fAllUniqueSlaves->Add(sl);
fAllUniqueMonitor->Add(sl->GetSocket());
} else {
Error("FindUniqueSlaves", "TSlave is neither Master nor Slave");
R__ASSERT(0);
}
}
break;
}
}
if (add) {
fUniqueSlaves->Add(sl);
fAllUniqueSlaves->Add(sl);
fUniqueMonitor->Add(sl->GetSocket());
fAllUniqueMonitor->Add(sl->GetSocket());
if (replace_slave) {
fUniqueSlaves->Remove(replace_slave);
fAllUniqueSlaves->Remove(replace_slave);
fUniqueMonitor->Remove(replace_slave->GetSocket());
fAllUniqueMonitor->Remove(replace_slave->GetSocket());
}
}
}
// will be actiavted in Collect()
fUniqueMonitor->DeActivateAll();
fAllUniqueMonitor->DeActivateAll();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfSlaves() const
{
// Return number of slaves as described in the config file.
return fSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfActiveSlaves() const
{
// Return number of active slaves, i.e. slaves that are valid and in
// the current computing group.
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfInactiveSlaves() const
{
// Return number of inactive slaves, i.e. slaves that are valid but not in
// the current computing group.
return fInactiveSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfUniqueSlaves() const
{
// Return number of unique slaves, i.e. active slaves that have each a
// unique different user files system.
return fUniqueSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfBadSlaves() const
{
// Return number of bad slaves. This are slaves that we in the config
// file, but refused to startup or that died during the PROOF session.
return fBadSlaves->GetSize();
}
//______________________________________________________________________________
void TProof::AskStatistics()
{
// Ask the for the statistics of the slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETSTATS, kActive);
Collect(kActive);
}
//______________________________________________________________________________
void TProof::AskParallel()
{
// Ask the for the number of parallel slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETPARALLEL, kActive);
Collect(kActive);
}
//______________________________________________________________________________
TList *TProof::GetListOfQueries(Option_t *opt)
{
// Ask the master for the list of queries.
if (!IsValid() || IsMaster()) return (TList *)0;
Bool_t all = ((strchr(opt,'A') || strchr(opt,'a'))) ? kTRUE : kFALSE;
TMessage m(kPROOF_QUERYLIST);
m << all;
Broadcast(m, kActive);
Collect(kActive);
// This should have been filled by now
return fQueries;
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfQueries()
{
// Number of queries processed by this session
if (fQueries)
return fQueries->GetSize() - fOtherQueries;
return 0;
}
//______________________________________________________________________________
void TProof::SetMaxDrawQueries(Int_t max)
{
// Set max number of draw queries whose results are saved
if (max > 0) {
if (fPlayer)
fPlayer->SetMaxDrawQueries(max);
fMaxDrawQueries = max;
}
}
//______________________________________________________________________________
void TProof::GetMaxQueries()
{
// Get max number of queries whose full results are kept in the
// remote sandbox
TMessage m(kPROOF_MAXQUERIES);
m << kFALSE;
Broadcast(m, kActive);
Collect(kActive);
}
//______________________________________________________________________________
TList *TProof::GetQueryResults()
{
// Return pointer to the list of query results in the player
return fPlayer->GetListOfResults();
}
//______________________________________________________________________________
TQueryResult *TProof::GetQueryResult(const char *ref)
{
// Return pointer to the full TQueryResult instance owned by the player
// and referenced by 'ref'. If ref = 0 or "", return the last query result.
return fPlayer->GetQueryResult(ref);
}
//______________________________________________________________________________
void TProof::ShowQueries(Option_t *opt)
{
// Ask the master for the list of queries.
// Options:
// "A" show information about all the queries known to the
// server, i.e. even those processed by other sessions
// "L" show only information about queries locally available
// i.e. already retrieved. If "L" is specified, "A" is
// ignored.
// "F" show all details available about queries
// "H" print help menu
// Default ""
Bool_t help = ((strchr(opt,'H') || strchr(opt,'h'))) ? kTRUE : kFALSE;
if (help) {
// Help
Printf("+++");
Printf("+++ Options: \"A\" show all queries known to server");
Printf("+++ \"L\" show retrieved queries");
Printf("+++ \"F\" full listing of query info");
Printf("+++ \"H\" print this menu");
Printf("+++");
Printf("+++ (case insensitive)");
Printf("+++");
Printf("+++ Use Retrieve(<#>) to retrieve the full"
" query results from the master");
Printf("+++ e.g. Retrieve(8)");
Printf("+++");
return;
}
if (!IsValid()) return;
Bool_t local = ((strchr(opt,'L') || strchr(opt,'l'))) ? kTRUE : kFALSE;
TObject *pq = 0;
if (!local) {
GetListOfQueries(opt);
if (!fQueries) return;
TIter nxq(fQueries);
// Queries processed by other sessions
if (fOtherQueries > 0) {
Printf("+++");
Printf("+++ Queries processed during other sessions: %d", fOtherQueries);
Int_t nq = 0;
while (nq++ < fOtherQueries && (pq = nxq()))
pq->Print(opt);
}
// Queries processed by this session
Printf("+++");
Printf("+++ Queries processed during this session: selector: %d, draw: %d",
GetNumberOfQueries(), fDrawQueries);
while ((pq = nxq()))
pq->Print(opt);
} else {
// Queries processed by this session
Printf("+++");
Printf("+++ Queries processed during this session: selector: %d, draw: %d",
GetNumberOfQueries(), fDrawQueries);
// Queries available locally
TList *listlocal = fPlayer->GetListOfResults();
if (listlocal) {
Printf("+++");
Printf("+++ Queries available locally: %d", listlocal->GetSize());
TIter nxlq(listlocal);
while ((pq = nxlq()))
pq->Print(opt);
}
}
Printf("+++");
}
//______________________________________________________________________________
Bool_t TProof::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready)
{
// See if the data is ready to be analyzed.
if (!IsValid()) return kFALSE;
TList submasters;
TIter nextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) {
if (sl->GetSlaveType() == TSlave::kMaster) {
submasters.Add(sl);
}
}
fDataReady = kTRUE; //see if any submasters set it to false
fBytesReady = 0;
fTotalBytes = 0;
//loop over submasters and see if data is ready
if (submasters.GetSize() > 0) {
Broadcast(kPROOF_DATA_READY, &submasters);
Collect(&submasters);
}
bytesready = fBytesReady;
totalbytes = fTotalBytes;
EmitVA("IsDataReady(Long64_t,Long64_t)", 2, totalbytes, bytesready);
//PDB(kGlobal,2)
Info("IsDataReady", "%lld / %lld (%s)",
bytesready, totalbytes, fDataReady?"READY":"NOT READY");
return fDataReady;
}
//______________________________________________________________________________
void TProof::Interrupt(EUrgent type, ESlaves list)
{
// Send interrupt OOB byte to master or slave servers.
if (!IsValid()) return;
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
if (slaves->GetSize() == 0) return;
TSlave *sl;
TIter next(slaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
// Ask slave to progate the interrupt request
sl->Interrupt((Int_t)type);
}
}
}
//______________________________________________________________________________
Int_t TProof::GetParallel() const
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// iterate over active slaves and return total number of slaves
TIter nextSlave(GetListOfActiveSlaves());
Int_t nparallel = 0;
while (TSlave* sl = dynamic_cast<TSlave*>(nextSlave()))
if (sl->GetParallel() >= 0)
nparallel += sl->GetParallel();
return nparallel;
}
//______________________________________________________________________________
TList *TProof::GetSlaveInfo()
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return 0;
if (fSlaveInfo == 0) {
fSlaveInfo = new TSortedList(kSortDescending);
fSlaveInfo->SetOwner();
} else {
fSlaveInfo->Delete();
}
TList masters;
TIter next(GetListOfSlaves());
TSlave *slave;
while((slave = (TSlave *) next()) != 0) {
if (slave->GetSlaveType() == TSlave::kSlave) {
TSlaveInfo *slaveinfo = new TSlaveInfo(slave->GetOrdinal(),
slave->GetName(),
slave->GetPerfIdx());
fSlaveInfo->Add(slaveinfo);
TIter nextactive(GetListOfActiveSlaves());
TSlave *activeslave;
while ((activeslave = (TSlave *) nextactive())) {
if (TString(slaveinfo->GetOrdinal()) == activeslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kActive);
break;
}
}
TIter nextbad(GetListOfBadSlaves());
TSlave *badslave;
while ((badslave = (TSlave *) nextbad())) {
if (TString(slaveinfo->GetOrdinal()) == badslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kBad);
break;
}
}
} else if (slave->GetSlaveType() == TSlave::kMaster) {
if (slave->IsValid()) {
if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1)
MarkBad(slave);
else
masters.Add(slave);
}
} else {
Error("GetSlaveInfo", "TSlave is neither Master nor Slave");
R__ASSERT(0);
}
}
if (masters.GetSize() > 0) Collect(&masters);
return fSlaveInfo;
}
//______________________________________________________________________________
void TProof::Activate(TList *slaves)
{
// Activate slave server list.
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
slaves = !slaves ? fActiveSlaves : slaves;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave*) next())) {
if (sl->IsValid())
mon->Activate(sl->GetSocket());
}
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, TList *slaves)
{
// Broadcast a message to all slaves in the specified list. Returns
// the number of slaves the message was successfully sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->Send(mess) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, ESlaves list)
{
// Broadcast a message to all slaves in the specified list (either
// all slaves or only the active slaves). Returns the number of slaves
// the message was successfully sent to. Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, TList *slaves)
{
// Broadcast a character string buffer to all slaves in the specified
// list. Use kind to set the TMessage what field. Returns the number of
// slaves the message was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, ESlaves list)
{
// Broadcast a character string buffer to all slaves in the specified
// list (either all slaves or only the active slaves). Use kind to
// set the TMessage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, TList *slaves)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, ESlaves list)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, TList *slaves)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->SendRaw(buffer, length) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, ESlaves list)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
return BroadcastRaw(buffer, length, slaves);
}
//______________________________________________________________________________
Int_t TProof::Collect(const TSlave *sl, Long_t timeout)
{
// Collect responses from slave sl. Returns the number of slaves that
// responded (=1).
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
if (!sl->IsValid()) return 0;
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
mon->Activate(sl->GetSocket());
return Collect(mon, timeout);
}
//______________________________________________________________________________
Int_t TProof::Collect(TList *slaves, Long_t timeout)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave*) next())) {
if (sl->IsValid())
mon->Activate(sl->GetSocket());
}
return Collect(mon, timeout);
}
//______________________________________________________________________________
Int_t TProof::Collect(ESlaves list, Long_t timeout)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
TMonitor *mon = 0;
if (list == kAll) mon = fAllMonitor;
if (list == kActive) mon = fActiveMonitor;
if (list == kUnique) mon = fUniqueMonitor;
if (list == kAllUnique) mon = fAllUniqueMonitor;
mon->ActivateAll();
return Collect(mon, timeout);
}
//______________________________________________________________________________
Int_t TProof::Collect(TMonitor *mon, Long_t timeout)
{
// Collect responses from the slave servers. Returns the number of messages
// received. Can be 0 if there are no active slaves.
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
fStatus = 0;
if (!mon->GetActive()) return 0;
DeActivateAsyncInput();
// Used by external code to know what we are monitoring
fCurrentMonitor = mon;
// We want messages on the main window during synchronous collection,
// but we save the present status to restore it at the end
Bool_t saveRedirLog = fRedirLog;
if (!IsIdle() && !IsSync())
fRedirLog = kFALSE;
int cnt = 0, rc = 0;
fBytesRead = 0;
fRealTime = 0.0;
fCpuTime = 0.0;
// Timeout counter
Long_t nto = timeout;
if (gDebug > 2)
Info("Collect","active: %d", mon->GetActive());
// On clients, handle Ctrl-C during collection
if (fIntHandler)
fIntHandler->Add();
while (mon->GetActive() && (nto < 0 || nto > 0)) {
// Wait for a ready socket
TSocket *s = mon->Select(1000);
if (s && s != (TSocket *)(-1)) {
// Get and analyse the info it did receive
if ((rc = CollectInputFrom(s)) == 1) {
// Deactivate it if we are done with it
mon->DeActivate(s);
if (gDebug > 2)
Info("Collect","deactivating %p (active: %d, %p)",
s, mon->GetActive(),
mon->GetListOfActives()->First());
}
// Update counter (if no error occured)
if (rc >= 0)
cnt++;
} else {
// If not timed-out, exit if not stopped or not aborted
// (player exits status is finished in such a case); otherwise,
// we still need to collect the partial output info
if (!s)
if (fPlayer && (fPlayer->GetExitStatus() == TVirtualProofPlayer::kFinished))
mon->DeActivateAll();
// Decrease the timeout counter if requested
if (s == (TSocket *)(-1) && nto > 0)
nto--;
}
}
// If timed-out, deactivate the remaining sockets
if (nto == 0)
mon->DeActivateAll();
// Deactivate Ctrl-C special handler
if (fIntHandler)
fIntHandler->Remove();
// make sure group view is up to date
SendGroupView();
// Restore redirection setting
fRedirLog = saveRedirLog;
// To avoid useless loops in external code
fCurrentMonitor = 0;
ActivateAsyncInput();
return cnt;
}
//______________________________________________________________________________
R__HIDDEN void TProof::CleanGDirectory(TList *ol)
{
// Remove links to objects in list 'ol' from gDirectory
if (ol) {
TIter nxo(ol);
TObject *o = 0;
while ((o = nxo()))
gDirectory->RecursiveRemove(o);
}
}
//______________________________________________________________________________
Int_t TProof::CollectInputFrom(TSocket *s)
{
// Collect and analyze available input from socket s.
// Returns 0 on success, -1 if any failure occurs.
TMessage *mess;
Int_t rc = 0;
char str[512];
TSlave *sl;
TObject *obj;
Int_t what;
Bool_t delete_mess = kTRUE;
if (s->Recv(mess) < 0) {
MarkBad(s);
return -1;
}
if (!mess) {
// we get here in case the remote server died
MarkBad(s);
return -1;
}
what = mess->What();
PDB(kGlobal,3) {
sl = FindSlave(s);
Info("CollectInputFrom","got %d from %s", what, (sl ? sl->GetOrdinal() : "undef"));
}
switch (what) {
case kMESS_OBJECT:
fPlayer->HandleRecvHisto(mess);
break;
case kPROOF_FATAL:
MarkBad(s);
break;
case kPROOF_GETOBJECT:
// send slave object it asks for
mess->ReadString(str, sizeof(str));
obj = gDirectory->Get(str);
if (obj)
s->SendObject(obj);
else
s->Send(kMESS_NOTOK);
break;
case kPROOF_GETPACKET:
{
TDSetElement *elem = 0;
sl = FindSlave(s);
elem = fPlayer->GetNextPacket(sl, mess);
if (elem != (TDSetElement*) -1) {
TMessage answ(kPROOF_GETPACKET);
answ << elem;
s->Send(answ);
while (fWaitingSlaves != 0 && fWaitingSlaves->GetSize()) {
TPair *p = (TPair*) fWaitingSlaves->First();
s = (TSocket*) p->Key();
sl = FindSlave(s);
TMessage *m = (TMessage*) p->Value();
elem = fPlayer->GetNextPacket(sl, m);
if (elem != (TDSetElement*) -1) {
TMessage a(kPROOF_GETPACKET);
a << elem;
s->Send(a);
// remove has to happen via Links because TPair does not have
// a Compare() function and therefore RemoveFirst() and
// Remove(TObject*) do not work
fWaitingSlaves->Remove(fWaitingSlaves->FirstLink());
delete p;
delete m;
} else {
break;
}
}
} else {
if (fWaitingSlaves == 0) fWaitingSlaves = new TList;
fWaitingSlaves->Add(new TPair(s, mess));
delete_mess = kFALSE;
}
}
break;
case kPROOF_LOGFILE:
{
Int_t size;
(*mess) >> size;
RecvLogFile(s, size);
}
break;
case kPROOF_LOGDONE:
sl = FindSlave(s);
(*mess) >> sl->fStatus >> sl->fParallel;
PDB(kGlobal,2)
Info("CollectInputFrom","kPROOF_LOGDONE:%s: status %d parallel %d",
sl->GetOrdinal(), sl->fStatus, sl->fParallel);
if (sl->fStatus != 0) fStatus = sl->fStatus; //return last nonzero status
rc = 1;
break;
case kPROOF_GETSTATS:
sl = FindSlave(s);
(*mess) >> sl->fBytesRead >> sl->fRealTime >> sl->fCpuTime
>> sl->fWorkDir >> sl->fProofWorkDir;
fBytesRead += sl->fBytesRead;
fRealTime += sl->fRealTime;
fCpuTime += sl->fCpuTime;
rc = 1;
break;
case kPROOF_GETPARALLEL:
sl = FindSlave(s);
(*mess) >> sl->fParallel;
rc = 1;
break;
case kPROOF_PACKAGE_LIST:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_PACKAGE_LIST: enter");
Int_t type = 0;
(*mess) >> type;
switch (type) {
case TProof::kListEnabledPackages:
SafeDelete(fEnabledPackages);
fEnabledPackages = (TList *) mess->ReadObject(TList::Class());
fEnabledPackages->SetOwner();
break;
case TProof::kListPackages:
SafeDelete(fAvailablePackages);
fAvailablePackages = (TList *) mess->ReadObject(TList::Class());
fAvailablePackages->SetOwner();
break;
default:
Info("CollectInputFrom","kPROOF_PACKAGE_LIST: unknown type: %d", type);
}
}
break;
case kPROOF_OUTPUTOBJECT:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_OUTPUTOBJECT: enter");
Int_t type = 0;
(*mess) >> type;
// If a query result header, add it to the player list
if (type == 0) {
// Retrieve query result instance (output list not filled)
TQueryResult *pq =
(TQueryResult *) mess->ReadObject(TQueryResult::Class());
if (pq) {
// Add query to the result list in TProofPlayer
fPlayer->AddQueryResult(pq);
fPlayer->SetCurrentQuery(pq);
// Add the unique query tag as TNamed object to the input list
// so that it is available in TSelectors for monitoring
fPlayer->AddInput(new TNamed("PROOF_QueryTag",
Form("%s:%s",pq->GetTitle(),pq->GetName())));
} else {
Warning("CollectInputFrom","kPROOF_OUTPUTOBJECT: query result missing");
}
} else if (type > 0) {
// Read object
TObject *obj = mess->ReadObject(TObject::Class());
// Add or merge it
if ((fPlayer->AddOutputObject(obj) == 1))
// Remove the object if it has been merged
SafeDelete(obj);
if (type > 1 && !IsMaster()) {
TQueryResult *pq = fPlayer->GetCurrentQuery();
pq->SetOutputList(fPlayer->GetOutputList(), kFALSE);
pq->SetInputList(fPlayer->GetInputList(), kFALSE);
// If the last object, notify the GUI that the result arrived
QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName()));
}
}
}
break;
case kPROOF_OUTPUTLIST:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_OUTPUTLIST: enter");
TList *out = 0;
if (IsMaster() || fProtocol < 7) {
out = (TList *) mess->ReadObject(TList::Class());
} else {
TQueryResult *pq =
(TQueryResult *) mess->ReadObject(TQueryResult::Class());
if (pq) {
// Add query to the result list in TProofPlayer
fPlayer->AddQueryResult(pq);
fPlayer->SetCurrentQuery(pq);
// To avoid accidental cleanups from anywhere else
// remove objects from gDirectory and clone the list
out = pq->GetOutputList();
CleanGDirectory(out);
out = (TList *) out->Clone();
// Notify the GUI that the result arrived
QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName()));
} else {
PDB(kGlobal,2)
Info("CollectInputFrom","kPROOF_OUTPUTLIST: query result missing");
}
}
if (out) {
out->SetOwner();
fPlayer->AddOutput(out); // Incorporate the list
SafeDelete(out);
} else {
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_OUTPUTLIST: ouputlist is empty");
}
// On clients at this point processing is over
if (!IsMaster()) {
// Handle abort ...
if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kAborted) {
if (fSync)
Info("CollectInputFrom",
"processing was aborted - %lld events processed",
fPlayer->GetEventsProcessed());
if (GetRemoteProtocol() > 11) {
// New format
Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.);
} else {
Progress(-1, fPlayer->GetEventsProcessed());
}
Emit("StopProcess(Bool_t)", kTRUE);
}
// Handle stop ...
if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kStopped) {
if (fSync)
Info("CollectInputFrom",
"processing was stopped - %lld events processed",
fPlayer->GetEventsProcessed());
if (GetRemoteProtocol() > 11) {
// New format
Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.);
} else {
Progress(-1, fPlayer->GetEventsProcessed());
}
Emit("StopProcess(Bool_t)", kFALSE);
}
// Final update of the dialog box
if (GetRemoteProtocol() > 11) {
// New format
EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t,)",
7, (Long64_t)(-1), (Long64_t)(-1), (Long64_t)(-1),
(Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.));
} else {
EmitVA("Progress(Long64_t,Long64_t)", 2, (Long64_t)(-1), (Long64_t)(-1));
}
}
}
break;
case kPROOF_QUERYLIST:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_QUERYLIST: enter");
(*mess) >> fOtherQueries >> fDrawQueries;
if (fQueries) {
fQueries->Delete();
delete fQueries;
fQueries = 0;
}
fQueries = (TList *) mess->ReadObject(TList::Class());
}
break;
case kPROOF_RETRIEVE:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_RETRIEVE: enter");
TQueryResult *pq =
(TQueryResult *) mess->ReadObject(TQueryResult::Class());
if (pq) {
fPlayer->AddQueryResult(pq);
// Notify the GUI that the result arrived
QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName()));
} else {
PDB(kGlobal,2)
Info("CollectInputFrom","kPROOF_RETRIEVE: query result missing");
}
}
break;
case kPROOF_MAXQUERIES:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_MAXQUERIES: enter");
Int_t max = 0;
(*mess) >> max;
Printf("Number of queries fully kept remotely: %d", max);
}
break;
case kPROOF_SERVERSTARTED:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_SERVERSTARTED: enter");
UInt_t tot = 0, done = 0;
TString action;
Bool_t st = kTRUE;
(*mess) >> action >> tot >> done >> st;
if (!IsMaster()) {
if (tot) {
TString type = (action.Contains("submas")) ? "submasters"
: "workers";
Int_t frac = (Int_t) (done*100.)/tot;
if (frac >= 100) {
fprintf(stderr,"%s: OK (%d %s) \n",
action.Data(),tot, type.Data());
} else {
fprintf(stderr,"%s: %d out of %d (%d %%)\r",
action.Data(), done, tot, frac);
}
}
// Notify GUIs
StartupMessage(action.Data(), st, (Int_t)done, (Int_t)tot);
} else {
// Just send the message one level up
TMessage m(kPROOF_SERVERSTARTED);
m << action << tot << done << st;
gProofServ->GetSocket()->Send(m);
}
}
break;
case kPROOF_DATASET_STATUS:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_DATASET_STATUS: enter");
UInt_t tot = 0, done = 0;
TString action;
Bool_t st = kTRUE;
(*mess) >> action >> tot >> done >> st;
if (!IsMaster()) {
if (tot) {
TString type = "files";
Int_t frac = (Int_t) (done*100.)/tot;
if (frac >= 100) {
fprintf(stderr,"%s: OK (%d %s) \n",
action.Data(),tot, type.Data());
} else {
fprintf(stderr,"%s: %d out of %d (%d %%)\r",
action.Data(), done, tot, frac);
}
}
// Notify GUIs
DataSetStatus(action.Data(), st, (Int_t)done, (Int_t)tot);
} else {
// Just send the message one level up
TMessage m(kPROOF_DATASET_STATUS);
m << action << tot << done << st;
gProofServ->GetSocket()->Send(m);
}
}
break;
case kPROOF_STARTPROCESS:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_STARTPROCESS: enter");
fIdle = kFALSE;
TString selec;
Int_t dsz = -1;
Long64_t first = -1, nent = -1;
(*mess) >> selec >> dsz >> first >> nent;
// Start or reset the progress dialog
if (fProgressDialog && !TestBit(kUsingSessionGui)) {
if (!fProgressDialogStarted) {
fProgressDialog->ExecPlugin(5, this,
selec.Data(), dsz, first, nent);
fProgressDialogStarted = kTRUE;
} else {
ResetProgressDialog(selec, dsz, first, nent);
}
}
ResetBit(kUsingSessionGui);
}
break;
case kPROOF_SETIDLE:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_SETIDLE: enter");
// The session is idle
fIdle = kTRUE;
}
break;
case kPROOF_QUERYSUBMITTED:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_QUERYSUBMITTED: enter");
// We have received the sequential number
(*mess) >> fSeqNum;
rc = 1;
}
break;
case kPROOF_SESSIONTAG:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_SESSIONTAG: enter");
// We have received the unique tag and save it as name of this object
TString stag;
(*mess) >> stag;
SetName(stag);
}
break;
case kPROOF_FEEDBACK:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_FEEDBACK: enter");
TList *out = (TList *) mess->ReadObject(TList::Class());
out->SetOwner();
sl = FindSlave(s);
if (fPlayer)
fPlayer->StoreFeedback(sl, out); // Adopts the list
else
// Not yet ready: stop collect asap
rc = 1;
}
break;
case kPROOF_AUTOBIN:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_AUTOBIN: enter");
TString name;
Double_t xmin, xmax, ymin, ymax, zmin, zmax;
(*mess) >> name >> xmin >> xmax >> ymin >> ymax >> zmin >> zmax;
fPlayer->UpdateAutoBin(name,xmin,xmax,ymin,ymax,zmin,zmax);
TMessage answ(kPROOF_AUTOBIN);
answ << name << xmin << xmax << ymin << ymax << zmin << zmax;
s->Send(answ);
}
break;
case kPROOF_PROGRESS:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_PROGRESS: enter");
sl = FindSlave(s);
if (GetRemoteProtocol() > 11) {
// New format
Long64_t total, processed, bytesread;
Float_t initTime, procTime, evtrti, mbrti;
(*mess) >> total >> processed >> bytesread
>> initTime >> procTime
>> evtrti >> mbrti;
fPlayer->Progress(total, processed, bytesread,
initTime, procTime, evtrti, mbrti);
} else {
// Old format
Long64_t total, processed;
(*mess) >> total >> processed;
fPlayer->Progress(sl, total, processed);
}
}
break;
case kPROOF_STOPPROCESS:
{
// answer contains number of processed events;
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_STOPPROCESS: enter");
Long64_t events;
Bool_t abort = kFALSE;
if ((mess->BufferSize() > mess->Length()) && (fProtocol > 8))
(*mess) >> events >> abort;
else
(*mess) >> events;
fPlayer->AddEventsProcessed(events);
if (!IsMaster())
Emit("StopProcess(Bool_t)", abort);
break;
}
case kPROOF_GETSLAVEINFO:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_GETSLAVEINFO: enter");
sl = FindSlave(s);
Bool_t active = (GetListOfActiveSlaves()->FindObject(sl) != 0);
Bool_t bad = (GetListOfBadSlaves()->FindObject(sl) != 0);
TList* tmpinfo = 0;
(*mess) >> tmpinfo;
tmpinfo->SetOwner(kFALSE);
Int_t nentries = tmpinfo->GetSize();
for (Int_t i=0; i<nentries; i++) {
TSlaveInfo* slinfo =
dynamic_cast<TSlaveInfo*>(tmpinfo->At(i));
if (slinfo) {
fSlaveInfo->Add(slinfo);
if (slinfo->fStatus != TSlaveInfo::kBad) {
if (!active) slinfo->SetStatus(TSlaveInfo::kNotActive);
if (bad) slinfo->SetStatus(TSlaveInfo::kBad);
}
if (!sl->GetMsd().IsNull()) slinfo->fMsd = sl->GetMsd();
}
}
delete tmpinfo;
rc = 1;
}
break;
case kPROOF_VALIDATE_DSET:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_VALIDATE_DSET: enter");
TDSet* dset = 0;
(*mess) >> dset;
if (!fDSet)
Error("CollectInputFrom","kPROOF_VALIDATE_DSET: fDSet not set");
else
fDSet->Validate(dset);
delete dset;
}
break;
case kPROOF_DATA_READY:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_DATA_READY: enter");
Bool_t dataready = kFALSE;
Long64_t totalbytes, bytesready;
(*mess) >> dataready >> totalbytes >> bytesready;
fTotalBytes += totalbytes;
fBytesReady += bytesready;
if (dataready == kFALSE) fDataReady = dataready;
}
break;
case kPROOF_PING:
// do nothing (ping is already acknowledged)
break;
case kPROOF_MESSAGE:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_MESSAGE: enter");
// We have received the unique tag and save it as name of this object
TString msg;
(*mess) >> msg;
Bool_t lfeed = kTRUE;
if ((mess->BufferSize() > mess->Length()))
(*mess) >> lfeed;
if (!IsMaster()) {
// Notify locally taking care of redirection, windows logs, ...
NotifyLogMsg(msg, (lfeed ? "\n" : "\r"));
} else {
// Just send the message one level up
TMessage m(kPROOF_MESSAGE);
m << msg << lfeed;
gProofServ->GetSocket()->Send(m);
}
}
break;
default:
Error("Collect", "unknown command received from slave (what = %d)", what);
break;
}
// Cleanup
if (delete_mess)
delete mess;
// We are done successfully
return rc;
}
//______________________________________________________________________________
void TProof::ActivateAsyncInput()
{
// Activate the a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Add();
}
//______________________________________________________________________________
void TProof::DeActivateAsyncInput()
{
// De-actiate a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Remove();
}
//______________________________________________________________________________
void TProof::HandleAsyncInput(TSocket *sl)
{
// Handle input coming from the master server (when this is a client)
// or from a slave server (when this is a master server). This is mainly
// for a-synchronous communication. Normally when PROOF issues a command
// the (slave) server messages are directly handle by Collect().
TMessage *mess;
Int_t what;
if (sl->Recv(mess) <= 0)
return; // do something more intelligent here
what = mess->What();
switch (what) {
case kPROOF_PING:
// do nothing (ping is already acknowledged)
break;
default:
Error("HandleAsyncInput", "unknown command (what = %d)", what);
break;
}
delete mess;
}
//______________________________________________________________________________
void TProof::MarkBad(TSlave *sl)
{
// Add a bad slave server to the bad slave list and remove it from
// the active list and from the two monitor objects.
fActiveSlaves->Remove(sl);
FindUniqueSlaves();
fBadSlaves->Add(sl);
fAllMonitor->Remove(sl->GetSocket());
fActiveMonitor->Remove(sl->GetSocket());
sl->Close();
fSendGroupView = kTRUE;
// Update session workers files
SaveWorkerInfo();
}
//______________________________________________________________________________
void TProof::MarkBad(TSocket *s)
{
// Add slave with socket s to the bad slave list and remove if from
// the active list and from the two monitor objects.
TSlave *sl = FindSlave(s);
MarkBad(sl);
}
//______________________________________________________________________________
Int_t TProof::Ping()
{
// Ping PROOF. Returns 1 if master server responded.
return Ping(kActive);
}
//______________________________________________________________________________
Int_t TProof::Ping(ESlaves list)
{
// Ping PROOF slaves. Returns the number of slaves that responded.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->Ping() == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
void TProof::Print(Option_t *option) const
{
// Print status of PROOF cluster.
TString secCont;
if (!IsMaster()) {
Printf("Connected to: %s (%s)", GetMaster(),
IsValid() ? "valid" : "invalid");
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
TSlave *sl = (TSlave *)fActiveSlaves->First();
if (sl) {
TString sc;
if (sl->GetSocket()->GetSecContext())
Printf("Security context: %s",
sl->GetSocket()->GetSecContext()->AsString(sc));
Printf("Proofd protocol version: %d", sl->GetSocket()->GetRemoteProtocol());
} else {
Printf("Security context: Error - No connection");
Printf("Proofd protocol version: Error - No connection");
}
Printf("Client protocol version: %d", GetClientProtocol());
Printf("Remote protocol version: %d", GetRemoteProtocol());
Printf("Log level: %d", GetLogLevel());
Printf("Session unique tag: %s", IsValid() ? GetSessionTag() : "");
Printf("Default data pool: %s", IsValid() ? GetDataPoolUrl() : "");
if (IsValid())
const_cast<TProof*>(this)->SendPrint(option);
} else {
const_cast<TProof*>(this)->AskStatistics();
if (IsParallel())
Printf("*** Master server %s (parallel mode, %d slaves):",
gProofServ->GetOrdinal(), GetParallel());
else
Printf("*** Master server %s (sequential mode):",
gProofServ->GetOrdinal());
Printf("Master host name: %s", gSystem->HostName());
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
Printf("Protocol version: %d", GetClientProtocol());
Printf("Image name: %s", GetImage());
Printf("Working directory: %s", gSystem->WorkingDirectory());
Printf("Config directory: %s", GetConfDir());
Printf("Config file: %s", GetConfFile());
Printf("Log level: %d", GetLogLevel());
Printf("Number of workers: %d", GetNumberOfSlaves());
Printf("Number of active workers: %d", GetNumberOfActiveSlaves());
Printf("Number of unique workers: %d", GetNumberOfUniqueSlaves());
Printf("Number of inactive workers: %d", GetNumberOfInactiveSlaves());
Printf("Number of bad workers: %d", GetNumberOfBadSlaves());
Printf("Total MB's processed: %.2f", float(GetBytesRead())/(1024*1024));
Printf("Total real time used (s): %.3f", GetRealTime());
Printf("Total CPU time used (s): %.3f", GetCpuTime());
if (TString(option).Contains("a", TString::kIgnoreCase) && GetNumberOfSlaves()) {
Printf("List of workers:");
TList masters;
TIter nextslave(fSlaves);
while (TSlave* sl = dynamic_cast<TSlave*>(nextslave())) {
if (!sl->IsValid()) continue;
if (sl->GetSlaveType() == TSlave::kSlave) {
sl->Print(option);
} else if (sl->GetSlaveType() == TSlave::kMaster) {
TMessage mess(kPROOF_PRINT);
mess.WriteString(option);
if (sl->GetSocket()->Send(mess) == -1)
const_cast<TProof*>(this)->MarkBad(sl);
else
masters.Add(sl);
} else {
Error("Print", "TSlave is neither Master nor Worker");
R__ASSERT(0);
}
}
const_cast<TProof*>(this)->Collect(&masters);
}
}
}
//______________________________________________________________________________
Long64_t TProof::Process(TDSet *dset, const char *selector, Option_t *option,
Long64_t nentries, Long64_t first, TEventList *evl)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// The return value is -1 in case of error and TSelector::GetStatus() in
// in case of success.
if (!IsValid()) return -1;
// Resolve query mode
fSync = (GetQueryMode(option) == kSync);
if (fSync && !IsIdle()) {
Info("Process","not idle, cannot submit synchronous query");
return -1;
}
// deactivate the default application interrupt handler
// ctrl-c's will be forwarded to PROOF to stop the processing
TSignalHandler *sh = 0;
if (fSync) {
if (gApplication)
sh = gSystem->RemoveSignalHandler(gApplication->GetSignalHandler());
}
Long64_t rv = fPlayer->Process(dset, selector, option, nentries, first, evl);
// // Clear input list
// fPlayer->ClearInput();
if (fSync) {
// reactivate the default application interrupt handler
if (sh)
gSystem->AddSignalHandler(sh);
}
return rv;
}
//______________________________________________________________________________
Int_t TProof::GetQueryReference(Int_t qry, TString &ref)
{
// Get reference for the qry-th query in fQueries (as
// displayed by ShowQueries).
ref = "";
if (qry > 0) {
if (!fQueries)
GetListOfQueries();
if (fQueries) {
TIter nxq(fQueries);
TQueryResult *qr = 0;
while ((qr = (TQueryResult *) nxq()))
if (qr->GetSeqNum() == qry) {
ref = Form("%s:%s", qr->GetTitle(), qr->GetName());
return 0;
}
}
}
return -1;
}
//______________________________________________________________________________
Long64_t TProof::Finalize(Int_t qry, Bool_t force)
{
// Finalize the qry-th query in fQueries.
// If force, force retrieval if the query is found in the local list
// but has already been finalized (default kFALSE).
// If query < 0, finalize current query.
// Return 0 on success, -1 on error
if (fPlayer) {
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0) {
return Finalize(ref, force);
} else {
Info("Finalize", "query #%d not found", qry);
}
} else {
// The last query
return fPlayer->Finalize(force);
}
}
return -1;
}
//______________________________________________________________________________
Long64_t TProof::Finalize(const char *ref, Bool_t force)
{
// Finalize query with reference ref.
// If force, force retrieval if the query is found in the local list
// but has already been finalized (default kFALSE).
// If ref = 0, finalize current query.
// Return 0 on success, -1 on error
if (fPlayer) {
if (ref) {
// Get the pointer to the query
TQueryResult *qr = fPlayer->GetQueryResult(ref);
// If not found, try retrieving it
Bool_t retrieve = kFALSE;
if (!qr) {
retrieve = kTRUE;
} else {
if (qr->IsFinalized()) {
if (force) {
retrieve = kTRUE;
} else {
Info("Finalize","query already finalized:"
" use Finalize(<qry>,kTRUE) to force new retrieval");
qr = 0;
}
}
}
if (retrieve) {
Retrieve(ref);
qr = fPlayer->GetQueryResult(ref);
}
if (qr)
return fPlayer->Finalize(qr);
}
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Retrieve(Int_t qry, const char *path)
{
// Send retrieve request for the qry-th query in fQueries.
// If path is defined save it to path.
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0)
return Retrieve(ref, path);
else
Info("Retrieve", "query #%d not found", qry);
} else {
Info("Retrieve","positive argument required - do nothing");
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Retrieve(const char *ref, const char *path)
{
// Send retrieve request for the query specified by ref.
// If path is defined save it to path.
// Generic method working for all queries known by the server.
if (ref) {
TMessage m(kPROOF_RETRIEVE);
m << TString(ref);
Broadcast(m, kActive);
Collect(kActive);
// Archive ir locally, if required
if (path) {
// Get pointer to query
TQueryResult *qr = fPlayer ? fPlayer->GetQueryResult(ref) : 0;
if (qr) {
TFile *farc = TFile::Open(path,"UPDATE");
if (!(farc->IsOpen())) {
Info("Retrieve", "archive file cannot be open (%s)", path);
return 0;
}
farc->cd();
// Update query status
qr->SetArchived(path);
// Write to file
qr->Write();
farc->Close();
SafeDelete(farc);
} else {
Info("Retrieve", "query not found after retrieve");
return -1;
}
}
return 0;
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Remove(Int_t qry, Bool_t all)
{
// Send remove request for the qry-th query in fQueries.
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0)
return Remove(ref, all);
else
Info("Remove", "query #%d not found", qry);
} else {
Info("Remove","positive argument required - do nothing");
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Remove(const char *ref, Bool_t all)
{
// Send remove request for the query specified by ref.
// If all = TRUE remove also local copies of the query, if any.
// Generic method working for all queries known by the server.
// This method can be also used to reset the list of queries
// waiting to be processed: for that purpose use ref == "cleanupqueue".
if (all) {
// Remove also local copies, if any
if (fPlayer)
fPlayer->RemoveQueryResult(ref);
}
if (ref) {
TMessage m(kPROOF_REMOVE);
m << TString(ref);
Broadcast(m, kActive);
Collect(kActive);
return 0;
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Archive(Int_t qry, const char *path)
{
// Send archive request for the qry-th query in fQueries.
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0)
return Archive(ref, path);
else
Info("Archive", "query #%d not found", qry);
} else {
Info("Archive","positive argument required - do nothing");
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Archive(const char *ref, const char *path)
{
// Send archive request for the query specified by ref.
// Generic method working for all queries known by the server.
// If ref == "Default", path is understood as a default path for
// archiving.
if (ref) {
TMessage m(kPROOF_ARCHIVE);
m << TString(ref) << TString(path);
Broadcast(m, kActive);
Collect(kActive);
return 0;
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::CleanupSession(const char *sessiontag)
{
// Send cleanup request for the session specified by tag.
if (sessiontag) {
TMessage m(kPROOF_CLEANUPSESSION);
m << TString(sessiontag);
Broadcast(m, kActive);
Collect(kActive);
return 0;
}
return -1;
}
//_____________________________________________________________________________
void TProof::SetQueryMode(EQueryMode mode)
{
// Change query running mode to the one specified by 'mode'.
fQueryMode = mode;
if (gDebug > 0)
Info("SetQueryMode","query mode is set to: %s", fQueryMode == kSync ?
"Sync" : "Async");
}
//______________________________________________________________________________
TProof::EQueryMode TProof::GetQueryMode(Option_t *mode) const
{
// Find out the query mode based on the current setting and 'mode'.
EQueryMode qmode = fQueryMode;
if (mode && (strlen(mode) > 0)) {
TString m(mode);
m.ToUpper();
if (m.Contains("ASYN")) {
qmode = kAsync;
} else if (m.Contains("SYNC")) {
qmode = kSync;
}
}
if (gDebug > 0)
Info("GetQueryMode","query mode is set to: %s", qmode == kSync ?
"Sync" : "Async");
return qmode;
}
//______________________________________________________________________________
Long64_t TProof::DrawSelect(TDSet *dset, const char *varexp, const char *selection, Option_t *option,
Long64_t nentries, Long64_t first)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error or number of selected events in case of success.
if (!IsValid()) return -1;
// Make sure that asynchronous processing is not active
if (!IsIdle()) {
Info("DrawSelect","not idle, asynchronous Draw not supported");
return -1;
}
TString opt(option);
Int_t idx = opt.Index("ASYN", 0, TString::kIgnoreCase);
if (idx != kNPOS)
opt.Replace(idx,4,"");
return fPlayer->DrawSelect(dset, varexp, selection, opt, nentries, first);
}
//______________________________________________________________________________
void TProof::StopProcess(Bool_t abort, Int_t timeout)
{
// Send STOPPROCESS message to master and workers.
PDB(kGlobal,2)
Info("StopProcess","enter %d", abort);
if (!IsValid())
return;
if (fPlayer)
fPlayer->StopProcess(abort, timeout);
// Stop any blocking 'Collect' request
if (!IsMaster())
InterruptCurrentMonitor();
if (fSlaves->GetSize() == 0)
return;
// Notify the remote counterpart
TSlave *sl;
TIter next(fSlaves);
while ((sl = (TSlave *)next()))
if (sl->IsValid())
// Ask slave to progate the stop/abort request
sl->StopProcess(abort, timeout);
}
//______________________________________________________________________________
void TProof::RecvLogFile(TSocket *s, Int_t size)
{
// Receive the log file of the slave with socket s.
const Int_t kMAXBUF = 16384; //32768 //16384 //65536;
char buf[kMAXBUF];
// Append messages to active logging unit
Int_t fdout = -1;
if (!fLogToWindowOnly) {
fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout);
if (fdout < 0) {
Warning("RecvLogFile", "file descriptor for outputs undefined (%d):"
" will not log msgs", fdout);
return;
}
lseek(fdout, (off_t) 0, SEEK_END);
}
Int_t left, rec, r;
Long_t filesize = 0;
while (filesize < size) {
left = Int_t(size - filesize);
if (left > kMAXBUF)
left = kMAXBUF;
rec = s->RecvRaw(&buf, left);
filesize = (rec > 0) ? (filesize + rec) : filesize;
if (!fLogToWindowOnly) {
if (rec > 0) {
char *p = buf;
r = rec;
while (r) {
Int_t w;
w = write(fdout, p, r);
if (w < 0) {
SysError("RecvLogFile", "error writing to unit: %d", fdout);
break;
}
r -= w;
p += w;
}
} else if (rec < 0) {
Error("RecvLogFile", "error during receiving log file");
break;
}
}
if (rec > 0) {
buf[rec] = 0;
EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE);
}
}
// If idle restore logs to main session window
if (fRedirLog && IsIdle())
fRedirLog = kFALSE;
}
//______________________________________________________________________________
void TProof::NotifyLogMsg(const char *msg, const char *sfx)
{
// Notify locally 'msg' to the appropriate units (file, stdout, window)
// If defined, 'sfx' is added after 'msg' (typically a line-feed);
// Must have somenthing to notify
Int_t len = 0;
if (!msg || (len = strlen(msg)) <= 0)
return;
// Get suffix length if any
Int_t lsfx = (sfx) ? strlen(sfx) : 0;
// Append messages to active logging unit
Int_t fdout = -1;
if (!fLogToWindowOnly) {
fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout);
if (fdout < 0) {
Warning("NotifyLogMsg", "file descriptor for outputs undefined (%d):"
" will not notify msgs", fdout);
return;
}
lseek(fdout, (off_t) 0, SEEK_END);
}
if (!fLogToWindowOnly) {
// Write to output unit (stdout or a log file)
if (len > 0) {
char *p = (char *)msg;
Int_t r = len;
while (r) {
Int_t w = write(fdout, p, r);
if (w < 0) {
SysError("NotifyLogMsg", "error writing to unit: %d", fdout);
break;
}
r -= w;
p += w;
}
// Add a suffix, if requested
if (lsfx > 0)
write(fdout, sfx, lsfx);
}
}
if (len > 0) {
// Publish the message to the separate window (if the latter is missing
// the message will just get lost)
EmitVA("LogMessage(const char*,Bool_t)", 2, msg, kFALSE);
}
// If idle restore logs to main session window
if (fRedirLog && IsIdle())
fRedirLog = kFALSE;
}
//______________________________________________________________________________
void TProof::LogMessage(const char *msg, Bool_t all)
{
// Log a message into the appropriate window by emitting a signal.
PDB(kGlobal,1)
Info("LogMessage","Enter ... %s, 'all: %s", msg ? msg : "",
all ? "true" : "false");
if (gROOT->IsBatch()) {
PDB(kGlobal,1) Info("LogMessage","GUI not started - use TProof::ShowLog()");
return;
}
if (msg)
EmitVA("LogMessage(const char*,Bool_t)", 2, msg, all);
// Re-position at the beginning of the file, if requested.
// This is used by the dialog when it re-opens the log window to
// provide all the session messages
if (all)
lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET);
const Int_t kMAXBUF = 32768;
char buf[kMAXBUF];
Int_t len;
do {
while ((len = read(fileno(fLogFileR), buf, kMAXBUF-1)) < 0 &&
TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
Error("LogMessage", "error reading log file");
break;
}
if (len > 0) {
buf[len] = 0;
EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE);
}
} while (len > 0);
}
//______________________________________________________________________________
Int_t TProof::SendGroupView()
{
// Send to all active slaves servers the current slave group size
// and their unique id. Returns number of active slaves.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (!IsMaster()) return 0;
if (!fSendGroupView) return 0;
fSendGroupView = kFALSE;
TIter next(fActiveSlaves);
TSlave *sl;
int bad = 0, cnt = 0, size = GetNumberOfActiveSlaves();
char str[32];
while ((sl = (TSlave *)next())) {
sprintf(str, "%d %d", cnt, size);
if (sl->GetSocket()->Send(str, kPROOF_GROUPVIEW) == -1) {
MarkBad(sl);
bad++;
} else
cnt++;
}
// Send the group view again in case there was a change in the
// group size due to a bad slave
if (bad) SendGroupView();
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Int_t TProof::Exec(const char *cmd, Bool_t plusMaster)
{
// Send command to be executed on the PROOF master and/or slaves.
// If plusMaster is kTRUE then exeucte on slaves and master too.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
return Exec(cmd, kActive, plusMaster);
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::Exec(const char *cmd, ESlaves list, Bool_t plusMaster)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
if (!IsValid()) return -1;
TString s = cmd;
s = s.Strip(TString::kBoth);
if (!s.Length()) return 0;
// check for macro file and make sure the file is available on all slaves
if (s.BeginsWith(".L") || s.BeginsWith(".x") || s.BeginsWith(".X")) {
TString file = s(2, s.Length());
TString acm, arg, io;
TString filename = gSystem->SplitAclicMode(file, acm, arg, io);
char *fn = gSystem->Which(TROOT::GetMacroPath(), filename, kReadPermission);
if (fn) {
if (GetNumberOfUniqueSlaves() > 0) {
if (SendFile(fn, kAscii | kForward) < 0) {
Error("Exec", "file %s could not be transfered", fn);
delete [] fn;
return -1;
}
} else {
TString scmd = s(0,3) + fn;
Int_t n = SendCommand(scmd, list);
delete [] fn;
return n;
}
} else {
Error("Exec", "macro %s not found", file.Data());
return -1;
}
delete [] fn;
}
if (plusMaster) {
Int_t n = GetParallel();
SetParallelSilent(0);
Int_t res = SendCommand(cmd, list);
SetParallelSilent(n);
if (res < 0)
return res;
}
return SendCommand(cmd, list);
}
//______________________________________________________________________________
Int_t TProof::SendCommand(const char *cmd, ESlaves list)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command, however commands
// like ".x file.C" or ".L file.C" will not cause the file.C to be
// transfered to the PROOF cluster. In that case use TProof::Exec().
// Returns the status send by the remote server as part of the
// kPROOF_LOGDONE message. Typically this is the return code of the
// command on the remote side. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(cmd, kMESS_CINT, list);
Collect(list);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::SendCurrentState(ESlaves list)
{
// Transfer the current state of the master to the active slave servers.
// The current state includes: the current working directory, etc.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// Go to the new directory, reset the interpreter environment and
// tell slave to delete all objects from its new current directory.
Broadcast(gDirectory->GetPath(), kPROOF_RESET, list);
return GetParallel();
}
//______________________________________________________________________________
Int_t TProof::SendInitialState()
{
// Transfer the initial (i.e. current) state of the master to all
// slave servers. Currently the initial state includes: log level.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
SetLogLevel(fLogLevel, gProofDebugMask);
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Bool_t TProof::CheckFile(const char *file, TSlave *slave, Long_t modtime)
{
// Check if a file needs to be send to the slave. Use the following
// algorithm:
// - check if file appears in file map
// - if yes, get file's modtime and check against time in map,
// if modtime not same get md5 and compare against md5 in map,
// if not same return kTRUE.
// - if no, get file's md5 and modtime and store in file map, ask
// slave if file exists with specific md5, if yes return kFALSE,
// if no return kTRUE.
// Returns kTRUE in case file needs to be send, returns kFALSE in case
// file is already on remote node.
Bool_t sendto = kFALSE;
// create slave based filename
TString sn = slave->GetName();
sn += ":";
sn += slave->GetOrdinal();
sn += ":";
sn += gSystem->BaseName(file);
// check if file is in map
FileMap_t::const_iterator it;
if ((it = fFileMap.find(sn)) != fFileMap.end()) {
// file in map
MD5Mod_t md = (*it).second;
if (md.fModtime != modtime) {
TMD5 *md5 = TMD5::FileChecksum(file);
if (md5) {
if ((*md5) != md.fMD5) {
sendto = kTRUE;
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
// When on the master, the master and/or slaves may share
// their file systems and cache. Therefore always make a
// check for the file. If the file already exists with the
// expected md5 the kPROOF_CHECKFILE command will cause the
// file to be copied from cache to slave sandbox.
if (IsMaster()) {
sendto = kFALSE;
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
}
delete md5;
} else {
Error("CheckFile", "could not calculate local MD5 check sum - dont send");
return kFALSE;
}
}
} else {
// file not in map
TMD5 *md5 = TMD5::FileChecksum(file);
MD5Mod_t md;
if (md5) {
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
delete md5;
} else {
Error("CheckFile", "could not calculate local MD5 check sum - dont send");
return kFALSE;
}
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
return sendto;
}
//______________________________________________________________________________
Int_t TProof::SendFile(const char *file, Int_t opt, const char *rfile, TSlave *wrk)
{
// Send a file to master or slave servers. Returns number of slaves
// the file was sent to, maybe 0 in case master and slaves have the same
// file system image, -1 in case of error.
// If defined, send to worker 'wrk' only.
// If defined, the full path of the remote path will be rfile.
// The mask 'opt' is an or of ESendFileOpt:
//
// kAscii (0x0) if set true ascii file transfer is used
// kBinary (0x1) if set true binary file transfer is used
// kForce (0x2) if not set an attempt is done to find out
// whether the file really needs to be downloaded
// (a valid copy may already exist in the cache
// from a previous run); the bit is set by
// UploadPackage, since the check is done elsewhere.
// kForward (0x4) if set, ask server to forward the file to slave
// or submaster (meaningless for slave servers).
//
if (!IsValid()) return -1;
// Use the active slaves list ...
TList *slaves = fActiveSlaves;
// ... or the specified slave, if any
if (wrk) {
slaves = new TList();
slaves->Add(wrk);
}
if (slaves->GetSize() == 0) return 0;
#ifndef R__WIN32
Int_t fd = open(file, O_RDONLY);
#else
Int_t fd = open(file, O_RDONLY | O_BINARY);
#endif
if (fd < 0) {
SysError("SendFile", "cannot open file %s", file);
return -1;
}
// Get info about the file
Long64_t size;
Long_t id, flags, modtime;
if (gSystem->GetPathInfo(file, &id, &size, &flags, &modtime) == 1) {
Error("SendFile", "cannot stat file %s", file);
return -1;
}
if (size == 0) {
Error("SendFile", "empty file %s", file);
return -1;
}
// Decode options
Bool_t bin = (opt & kBinary) ? kTRUE : kFALSE;
Bool_t force = (opt & kForce) ? kTRUE : kFALSE;
Bool_t fw = (opt & kForward) ? kTRUE : kFALSE;
const Int_t kMAXBUF = 32768; //16384 //65536;
char buf[kMAXBUF];
Int_t nsl = 0;
TIter next(slaves);
TSlave *sl;
const char *fnam = (rfile) ? rfile : gSystem->BaseName(file);
while ((sl = (TSlave *)next())) {
if (!sl->IsValid())
continue;
Bool_t sendto = force ? kTRUE : CheckFile(file, sl, modtime);
// Don't send the kPROOF_SENDFILE command to real slaves when sendto
// is false. Masters might still need to send the file to newly added
// slaves.
if (sl->fSlaveType == TSlave::kSlave && !sendto)
continue;
// The value of 'size' is used as flag remotely, so we need to
// reset it to 0 if we are not going to send the file
size = sendto ? size : 0;
PDB(kPackage,2)
if (size > 0) {
if (!nsl)
Info("SendFile", "sending file %s to:", file);
printf(" slave = %s:%s\n", sl->GetName(), sl->GetOrdinal());
}
sprintf(buf, "%s %d %lld %d", fnam, bin, size, fw);
if (sl->GetSocket()->Send(buf, kPROOF_SENDFILE) == -1) {
MarkBad(sl);
continue;
}
if (!sendto)
continue;
lseek(fd, 0, SEEK_SET);
Int_t len;
do {
while ((len = read(fd, buf, kMAXBUF)) < 0 && TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
SysError("SendFile", "error reading from file %s", file);
Interrupt(kSoftInterrupt, kActive);
close(fd);
return -1;
}
if (len > 0 && sl->GetSocket()->SendRaw(buf, len) == -1) {
SysError("SendFile", "error writing to slave %s:%s (now offline)",
sl->GetName(), sl->GetOrdinal());
MarkBad(sl);
break;
}
} while (len > 0);
nsl++;
}
close(fd);
// Cleanup temporary list, if any
if (slaves != fActiveSlaves)
SafeDelete(slaves);
return nsl;
}
//______________________________________________________________________________
Int_t TProof::SendObject(const TObject *obj, ESlaves list)
{
// Send object to master or slave servers. Returns number of slaves object
// was sent to, -1 in case of error.
if (!IsValid() || !obj) return -1;
TMessage mess(kMESS_OBJECT);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::SendPrint(Option_t *option)
{
// Send print command to master server. Returns number of slaves message
// was sent to. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(option, kPROOF_PRINT, kActive);
return Collect(kActive);
}
//______________________________________________________________________________
void TProof::SetLogLevel(Int_t level, UInt_t mask)
{
// Set server logging level.
char str[32];
fLogLevel = level;
gProofDebugLevel = level;
gProofDebugMask = (TProofDebug::EProofDebugMask) mask;
sprintf(str, "%d %u", level, mask);
Broadcast(str, kPROOF_LOGLEVEL, kAll);
}
//______________________________________________________________________________
void TProof::SetRealTimeLog(Bool_t on)
{
// Switch ON/OFF the real-time logging facility. When this option is
// ON, log messages from processing are sent back as they come, instead of
// being sent back at the end in one go. This may help debugging or monitoring
// in some cases, but, depending on the amount of log, it may have significant
// consequencies on the load over the network, so it must be used with care.
if (IsValid()) {
TMessage mess(kPROOF_REALTIMELOG);
mess << on;
Broadcast(mess);
} else {
Warning("SetRealTimeLog","session is invalid - do nothing");
}
}
//______________________________________________________________________________
Int_t TProof::SetParallelSilent(Int_t nodes, Bool_t random)
{
// Tell RPOOF how many slaves to use in parallel. If random is TRUE a random
// selection is done (if nodes is less than the available nodes).
// Returns the number of parallel slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
if (IsMaster()) {
GoParallel(nodes, kFALSE, random);
return SendCurrentState();
} else {
PDB(kGlobal,1) Info("SetParallelSilent", "request %d node%s", nodes,
nodes == 1 ? "" : "s");
TMessage mess(kPROOF_PARALLEL);
mess << nodes << random;
Broadcast(mess);
Collect();
Int_t n = GetParallel();
PDB(kGlobal,1) Info("SetParallelSilent", "got %d node%s", n, n == 1 ? "" : "s");
return n;
}
}
//______________________________________________________________________________
Int_t TProof::SetParallel(Int_t nodes, Bool_t random)
{
// Tell PROOF how many slaves to use in parallel. Returns the number of
// parallel slaves. Returns -1 in case of error.
Int_t n = SetParallelSilent(nodes, random);
if (!IsMaster()) {
if (n < 1) {
Printf("PROOF set to sequential mode");
} else {
TString subfix = (n == 1) ? "" : "s";
if (random)
subfix += ", randomly selected";
Printf("PROOF set to parallel mode (%d worker%s)", n, subfix.Data());
}
}
return n;
}
//______________________________________________________________________________
Int_t TProof::GoParallel(Int_t nodes, Bool_t attach, Bool_t random)
{
// Go in parallel mode with at most "nodes" slaves. Since the fSlaves
// list is sorted by slave performace the active list will contain first
// the most performant nodes. Returns the number of active slaves.
// If random is TRUE, and nodes is less than the number of available workers,
// a random selection is done.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (nodes < 0) nodes = 0;
fActiveSlaves->Clear();
fActiveMonitor->RemoveAll();
// Prepare the list of candidates first.
// Algorithm depends on random option.
TSlave *sl = 0;
TList *wlst = new TList;
TIter nxt(fSlaves);
fInactiveSlaves->Clear();
while ((sl = (TSlave *)nxt())) {
if (sl->IsValid() && !fBadSlaves->FindObject(sl)) {
if (strcmp("IGNORE", sl->GetImage()) == 0) continue;
if ((sl->GetSlaveType() != TSlave::kSlave) &&
(sl->GetSlaveType() != TSlave::kMaster)) {
Error("GoParallel", "TSlave is neither Master nor Slave");
R__ASSERT(0);
}
// Good candidate
wlst->Add(sl);
// Set it inactive
fInactiveSlaves->Add(sl);
sl->SetStatus(TSlave::kInactive);
}
}
Int_t nwrks = (nodes > wlst->GetSize()) ? wlst->GetSize() : nodes;
int cnt = 0;
fEndMaster = IsMaster() ? kTRUE : kFALSE;
while (cnt < nwrks) {
// Random choice, if requested
if (random) {
Int_t iwrk = (Int_t) (gRandom->Rndm() * wlst->GetSize());
sl = (TSlave *) wlst->At(iwrk);
} else {
// The first available
sl = (TSlave *) wlst->First();
}
if (!sl) {
Error("GoParallel", "attaching to candidate!");
break;
}
Int_t slavenodes = 0;
if (sl->GetSlaveType() == TSlave::kSlave) {
sl->SetStatus(TSlave::kActive);
fActiveSlaves->Add(sl);
fInactiveSlaves->Remove(sl);
fActiveMonitor->Add(sl->GetSocket());
slavenodes = 1;
} else if (sl->GetSlaveType() == TSlave::kMaster) {
fEndMaster = kFALSE;
TMessage mess(kPROOF_PARALLEL);
if (!attach) {
mess << nodes-cnt;
} else {
// To get the number of slaves
mess.SetWhat(kPROOF_LOGFILE);
mess << -1 << -1;
}
if (sl->GetSocket()->Send(mess) == -1) {
MarkBad(sl);
slavenodes = 0;
} else {
Collect(sl);
sl->SetStatus(TSlave::kActive);
fActiveSlaves->Add(sl);
fInactiveSlaves->Remove(sl);
fActiveMonitor->Add(sl->GetSocket());
if (sl->GetParallel() > 0) {
slavenodes = sl->GetParallel();
} else {
slavenodes = 0;
}
}
}
// Remove from the list
wlst->Remove(sl);
cnt += slavenodes;
}
// Cleanup list
wlst->SetOwner(0);
SafeDelete(wlst);
// Get slave status (will set the slaves fWorkDir correctly)
AskStatistics();
// Find active slaves with unique image
FindUniqueSlaves();
// Send new group-view to slaves
if (!attach)
SendGroupView();
Int_t n = GetParallel();
if (!IsMaster()) {
if (n < 1)
printf("PROOF set to sequential mode\n");
else
printf("PROOF set to parallel mode (%d worker%s)\n",
n, n == 1 ? "" : "s");
}
PDB(kGlobal,1) Info("GoParallel", "got %d node%s", n, n == 1 ? "" : "s");
return n;
}
//______________________________________________________________________________
void TProof::ShowCache(Bool_t all)
{
// List contents of file cache. If all is true show all caches also on
// slaves. If everything is ok all caches are to be the same.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowCache) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubCache) << all;
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ClearCache()
{
// Remove files from all file caches.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kClearCache);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kClearSubCache);
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
// clear file map so files get send again to remote nodes
fFileMap.clear();
}
//______________________________________________________________________________
void TProof::ShowPackages(Bool_t all)
{
// List contents of package directory. If all is true show all package
// directries also on slaves. If everything is ok all package directories
// should be the same.
if (!IsValid()) return;
if (!IsMaster()) {
printf("*** Package cache client:%s ***\n", fPackageDir.Data());
fflush(stdout);
gSystem->Exec(Form("%s %s", kLS, fPackageDir.Data()));
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowPackages) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubPackages) << all;
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ShowEnabledPackages(Bool_t all)
{
// List which packages are enabled. If all is true show enabled packages
// for all active slaves. If everything is ok all active slaves should
// have the same packages enabled.
if (!IsValid()) return;
if (!IsMaster()) {
printf("*** Enabled packages on client on %s\n", gSystem->HostName());
TIter next(fEnabledPackagesOnClient);
while (TObjString *str = (TObjString*) next())
printf("%s\n", str->GetName());
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowEnabledPackages) << all;
Broadcast(mess);
Collect();
}
//______________________________________________________________________________
Int_t TProof::ClearPackages()
{
// Remove all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (UnloadPackages() == -1)
return -1;
if (DisablePackages() == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::ClearPackage(const char *package)
{
// Remove a specific package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("ClearPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (UnloadPackage(pac) == -1)
return -1;
if (DisablePackage(pac) == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::DisablePackage(const char *package)
{
// Remove a specific package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("DisablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (DisablePackageOnClient(pac) == -1)
return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::DisablePackageOnClient(const char *package)
{
// Remove a specific package from the client.
// Returns 0 in case of success and -1 in case of error.
if (!IsMaster()) {
// remove package directory and par file
fPackageLock->Lock();
gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(), package));
gSystem->Exec(Form("%s %s/%s.par", kRM, fPackageDir.Data(), package));
fPackageLock->Unlock();
}
return 0;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::DisablePackages()
{
// Remove all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
// remove all packages on client
if (!IsMaster()) {
fPackageLock->Lock();
gSystem->Exec(Form("%s %s/*", kRM, fPackageDir.Data()));
fPackageLock->Unlock();
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackages);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackages);
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::BuildPackage(const char *package, EBuildPackageOpt opt)
{
// Build specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists on all unique nodes. If opt is -1
// then submit build command to slaves, but don't wait
// for results. If opt is 1 then collect result from slaves.
// To be used on the master.
// If opt = 0 (default) then submit and wait for results
// (to be used on the client).
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("BuildPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
Bool_t buildOnClient = kTRUE;
if (opt == kDontBuildOnClient) {
buildOnClient = kFALSE;
opt = kBuildAll;
}
if (opt <= 0) {
TMessage mess(kPROOF_CACHE);
mess << Int_t(kBuildPackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kBuildSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
}
if (opt >= 0) {
// by first forwarding the build commands to the master and slaves
// and only then building locally we build in parallel
Int_t st = 0;
if (buildOnClient)
st = BuildPackageOnClient(pac);
Collect(kAllUnique);
if (fStatus < 0 || st < 0)
return -1;
}
return 0;
}
//______________________________________________________________________________
Int_t TProof::BuildPackageOnClient(const TString &package)
{
// Build specified package on the client. Executes the PROOF-INF/BUILD.sh
// script if it exists on the client.
// Returns 0 in case of success and -1 in case of error.
// The code is equivalent to the one in TProofServ.cxx (TProof::kBuildPackage
// case). Keep in sync in case of changes.
if (!IsMaster()) {
Int_t status = 0;
TString pdir, ocwd;
fPackageLock->Lock();
// check that package and PROOF-INF directory exists
pdir = fPackageDir + "/" + package;
if (gSystem->AccessPathName(pdir)) {
Error("BuildPackageOnClient", "package %s does not exist",
package.Data());
fPackageLock->Unlock();
return -1;
} else if (gSystem->AccessPathName(pdir + "/PROOF-INF")) {
Error("BuildPackageOnClient", "package %s does not have a PROOF-INF directory",
package.Data());
fPackageLock->Unlock();
return -1;
}
PDB(kPackage, 1)
Info("BuildPackageOnCLient",
"package %s exists and has PROOF-INF directory", package.Data());
ocwd = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(pdir);
// check for BUILD.sh and execute
if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
// read version from file proofvers.txt, and if current version is
// not the same do a "BUILD.sh clean"
FILE *f = fopen("PROOF-INF/proofvers.txt", "r");
if (f) {
TString v;
v.Gets(f);
fclose(f);
if (v != gROOT->GetVersion()) {
if (gSystem->Exec("PROOF-INF/BUILD.sh clean")) {
Error("BuildPackageOnClient", "cleaning package %s on the client failed", package.Data());
status = -1;
}
}
}
if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
Error("BuildPackageOnClient", "building package %s on the client failed", package.Data());
status = -1;
}
f = fopen("PROOF-INF/proofvers.txt", "w");
if (f) {
fputs(gROOT->GetVersion(), f);
fclose(f);
}
} else {
PDB(kPackage, 1)
Info("BuildPackageOnCLient",
"package %s exists but has no PROOF-INF/BUILD.sh script", package.Data());
}
gSystem->ChangeDirectory(ocwd);
fPackageLock->Unlock();
return status;
}
return 0;
}
//______________________________________________________________________________
Int_t TProof::LoadPackage(const char *package, Bool_t notOnClient)
{
// Load specified package. Executes the PROOF-INF/SETUP.C script
// on all active nodes. If notOnClient = true, don't load package
// on the client. The default is to load the package also on the client.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("LoadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (!notOnClient)
if (LoadPackageOnClient(pac) == -1)
return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kLoadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::LoadPackageOnClient(const TString &package)
{
// Load specified package in the client. Executes the PROOF-INF/SETUP.C
// script on the client. Returns 0 in case of success and -1 in case of error.
// The code is equivalent to the one in TProofServ.cxx (TProof::kLoadPackage
// case). Keep in sync in case of changes.
if (!IsMaster()) {
Int_t status = 0;
TString pdir, ocwd;
// If already loaded don't do it again
if (fEnabledPackagesOnClient->FindObject(package)) {
Info("LoadPackageOnClient",
"package %s already loaded", package.Data());
return 0;
}
// always follows BuildPackage so no need to check for PROOF-INF
pdir = fPackageDir + "/" + package;
ocwd = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(pdir);
// check for SETUP.C and execute
if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
Int_t err = 0;
Int_t errm = gROOT->Macro("PROOF-INF/SETUP.C", &err);
if (errm < 0)
status = -1;
if (err > TInterpreter::kNoError && err <= TInterpreter::kFatal)
status = -1;
} else {
PDB(kPackage, 1)
Info("LoadPackageOnCLient",
"package %s exists but has no PROOF-INF/SETUP.C script", package.Data());
}
gSystem->ChangeDirectory(ocwd);
if (!status) {
// create link to package in working directory
fPackageLock->Lock();
FileStat_t stat;
Int_t st = gSystem->GetPathInfo(package, stat);
// check if symlink, if so unlink, if not give error
// NOTE: GetPathnfo() returns 1 in case of symlink that does not point to
// existing file or to a directory, but if fIsLink is true the symlink exists
if (stat.fIsLink)
gSystem->Unlink(package);
else if (st == 0) {
Error("LoadPackageOnClient", "cannot create symlink %s in %s on client, "
"another item with same name already exists", package.Data(), ocwd.Data());
fPackageLock->Unlock();
return -1;
}
gSystem->Symlink(pdir, package);
fPackageLock->Unlock();
// add package to list of include directories to be searched by ACliC
gSystem->AddIncludePath(TString("-I") + package);
// add package to list of include directories to be searched by CINT
gROOT->ProcessLine(TString(".include ") + package);
fEnabledPackagesOnClient->Add(new TObjString(package));
PDB(kPackage, 1)
Info("LoadPackageOnClient",
"package %s successfully loaded", package.Data());
} else
Error("LoadPackageOnClient", "loading package %s on client failed", package.Data());
return status;
}
return 0;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::UnloadPackage(const char *package)
{
// Unload specified package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("UnloadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (UnloadPackageOnClient(pac) == -1)
return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::UnloadPackageOnClient(const char *package)
{
// Unload a specific package on the client.
// Returns 0 in case of success and -1 in case of error.
// The code is equivalent to the one in TProofServ.cxx (TProof::UnloadPackage
// case). Keep in sync in case of changes.
if (!IsMaster()) {
TObjString *pack = (TObjString *) fEnabledPackagesOnClient->FindObject(package);
if (pack) {
// Remove entry from include path
TString aclicincpath = gSystem->GetIncludePath();
TString cintincpath = gInterpreter->GetIncludePath();
// remove interpreter part of gSystem->GetIncludePath()
aclicincpath.Remove(aclicincpath.Length() - cintincpath.Length() - 1);
// remove package's include path
aclicincpath.ReplaceAll(TString(" -I") + package, "");
gSystem->SetIncludePath(aclicincpath);
//TODO reset interpreter include path
// remove entry from enabled packages list
delete fEnabledPackagesOnClient->Remove(pack);
}
// cleanup the link
if (!gSystem->AccessPathName(package))
if (gSystem->Unlink(package) != 0)
Warning("UnloadPackageOnClient", "unable to remove symlink to %s", package);
}
return 0;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::UnloadPackages()
{
// Unload all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!IsMaster()) {
// Iterate over packages on the client and remove each package
TIter nextpackage(fEnabledPackagesOnClient);
while (TObjString *objstr = dynamic_cast<TObjString*>(nextpackage()))
if (UnloadPackageOnClient(objstr->String()) == -1 )
return -1;
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackages);
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::EnablePackage(const char *package, Bool_t notOnClient)
{
// Enable specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists followed by the PROOF-INF/SETUP.C script.
// In case notOnClient = true, don't enable the package on the client.
// The default is to enable packages also on the client.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("EnablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
EBuildPackageOpt opt = kBuildAll;
if (notOnClient)
opt = kDontBuildOnClient;
if (BuildPackage(pac, opt) == -1)
return -1;
if (LoadPackage(pac, notOnClient) == -1)
return -1;
return 0;
}
//______________________________________________________________________________
Int_t TProof::UploadPackage(const char *tpar, EUploadPackageOpt opt)
{
// Upload a PROOF archive (PAR file). A PAR file is a compressed
// tar file with one special additional directory, PROOF-INF
// (blatantly copied from Java's jar format). It must have the extension
// .par. A PAR file can be directly a binary or a source with a build
// procedure. In the PROOF-INF directory there can be a build script:
// BUILD.sh to be called to build the package, in case of a binary PAR
// file don't specify a build script or make it a no-op. Then there is
// SETUP.C which sets the right environment variables to use the package,
// like LD_LIBRARY_PATH, etc.
// The 'opt' allows to specify whether the .PAR should be just unpacked
// in the existing dir (opt = kUntar, default) or a remove of the existing
// directory should be executed (opt = kRemoveOld), so triggering a full
// re-build. The option if effective only for PROOF protocol > 8 .
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
TString par = tpar;
if (!par.EndsWith(".par")) {
Error("UploadPackage", "package %s must have extension .par", tpar);
return -1;
}
gSystem->ExpandPathName(par);
if (gSystem->AccessPathName(par, kReadPermission)) {
Error("UploadPackage", "package %s does not exist", par.Data());
return -1;
}
// Strategy:
// On the client:
// get md5 of package and check if it is different
// from the one stored in the local package directory. If it is lock
// the package directory and copy the package, unlock the directory.
// On the masters:
// get md5 of package and check if it is different from the
// one stored on the remote node. If it is different lock the remote
// package directory and use TFTP or SendFile to ftp the package to the
// remote node, unlock the directory.
TMD5 *md5 = TMD5::FileChecksum(par);
if (UploadPackageOnClient(par, opt, md5) == -1) {
delete md5;
return -1;
}
TMessage mess(kPROOF_CHECKFILE);
mess << TString("+")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess2(kPROOF_CHECKFILE);
mess2 << TString("-")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess3(kPROOF_CHECKFILE);
mess3 << TString("=")+TString(gSystem->BaseName(par)) << (*md5);
delete md5;
if (fProtocol > 8) {
// Send also the option
mess << (UInt_t) opt;
mess2 << (UInt_t) opt;
mess3 << (UInt_t) opt;
}
// loop over all selected nodes
TIter next(fUniqueSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *) next())) {
if (!sl->IsValid())
continue;
sl->GetSocket()->Send(mess);
TMessage *reply;
sl->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
if (fProtocol > 5) {
// remote directory is locked, upload file over the open channel
if (SendFile(par, (kBinary | kForce), Form("%s/%s/%s",
sl->GetProofWorkDir(), kPROOF_PackDir,
gSystem->BaseName(par)), sl) < 0) {
Error("UploadPackage", "problems uploading file %s", par.Data());
SafeDelete(reply);
return -1;
}
} else {
// old servers receive it via TFTP
TFTP ftp(TString("root://")+sl->GetName(), 1);
if (!ftp.IsZombie()) {
ftp.cd(Form("%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir));
ftp.put(par, gSystem->BaseName(par));
}
}
// install package and unlock dir
sl->GetSocket()->Send(mess2);
SafeDelete(reply);
sl->GetSocket()->Recv(reply);
if (!reply || reply->What() != kPROOF_CHECKFILE) {
Error("UploadPackage", "unpacking of package %s failed", par.Data());
SafeDelete(reply);
return -1;
}
}
SafeDelete(reply);
}
// loop over all other master nodes
TIter nextmaster(fNonUniqueMasters);
TSlave *ma;
while ((ma = (TSlave *) nextmaster())) {
if (!ma->IsValid())
continue;
ma->GetSocket()->Send(mess3);
TMessage *reply = 0;
ma->GetSocket()->Recv(reply);
if (!reply || reply->What() != kPROOF_CHECKFILE) {
// error -> package should have been found
Error("UploadPackage", "package %s did not exist on submaster %s",
par.Data(), ma->GetOrdinal());
SafeDelete(reply);
return -1;
}
SafeDelete(reply);
}
return 0;
}
//______________________________________________________________________________
Int_t TProof::UploadPackageOnClient(const TString &par, EUploadPackageOpt opt, TMD5 *md5)
{
// Upload a package on the client in ~/proof/packages.
// The 'opt' allows to specify whether the .PAR should be just unpacked
// in the existing dir (opt = kUntar, default) or a remove of the existing
// directory should be executed (opt = kRemoveOld), thereby triggering a full
// re-build. The option if effective only for PROOF protocol > 8 .
// Returns 0 in case of success and -1 in case of error.
// Strategy:
// get md5 of package and check if it is different
// from the one stored in the local package directory. If it is lock
// the package directory and copy the package, unlock the directory.
Int_t status = 0;
if (!IsMaster()) {
// the fPackageDir directory exists (has been created in Init())
// create symlink to the par file in the fPackageDir (needed by
// master in case we run on the localhost)
fPackageLock->Lock();
TString lpar = fPackageDir + "/" + gSystem->BaseName(par);
FileStat_t stat;
Int_t st = gSystem->GetPathInfo(lpar, stat);
// check if symlink, if so unlink, if not give error
// NOTE: GetPathInfo() returns 1 in case of symlink that does not point to
// existing file, but if fIsLink is true the symlink exists
if (stat.fIsLink)
gSystem->Unlink(lpar);
else if (st == 0) {
Error("UploadPackageOnClient", "cannot create symlink %s on client, "
"another item with same name already exists",
lpar.Data());
fPackageLock->Unlock();
return -1;
}
if (!gSystem->IsAbsoluteFileName(par)) {
TString fpar = par;
gSystem->Symlink(gSystem->PrependPathName(gSystem->WorkingDirectory(), fpar), lpar);
} else
gSystem->Symlink(par, lpar);
// TODO: On Windows need to copy instead of symlink
// compare md5
TString packnam = par(0, par.Length() - 4); // strip off ".par"
packnam = gSystem->BaseName(packnam); // strip off path
TString md5f = fPackageDir + "/" + packnam + "/PROOF-INF/md5.txt";
TMD5 *md5local = TMD5::ReadChecksum(md5f);
if (!md5local || (*md5) != (*md5local)) {
// if not, unzip and untar package in package directory
Int_t st = 0;
if ((opt & TProof::kRemoveOld)) {
// remove any previous package directory with same name
st = gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(),
packnam.Data()));
if (st)
Error("UploadPackageOnClient", "failure executing: %s %s/%s",
kRM, fPackageDir.Data(), packnam.Data());
}
// find gunzip
char *gunzip = gSystem->Which(gSystem->Getenv("PATH"), kGUNZIP,
kExecutePermission);
if (gunzip) {
// untar package
st = gSystem->Exec(Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data()));
if (st)
Error("Uploadpackage", "failure executing: %s",
Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data()));
delete [] gunzip;
} else
Error("UploadPackageOnClient", "%s not found", kGUNZIP);
// check that fPackageDir/packnam now exists
if (gSystem->AccessPathName(fPackageDir + "/" + packnam, kWritePermission)) {
// par file did not unpack itself in the expected directory, failure
Error("UploadPackageOnClient",
"package %s did not unpack into %s/%s", par.Data(), fPackageDir.Data(),
packnam.Data());
status = -1;
} else {
// store md5 in package/PROOF-INF/md5.txt
TMD5::WriteChecksum(md5f, md5);
}
}
fPackageLock->Unlock();
delete md5local;
}
return status;
}
//______________________________________________________________________________
Int_t TProof::AddDynamicPath(const char *libpath)
{
// Add 'libpath' to the lib path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!libpath || !strlen(libpath))) {
if (gDebug > 0)
Info("AddDynamicPath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("lib") << (Bool_t)kTRUE;
// Add paths
if (libpath && strlen(libpath))
m << TString(libpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
Int_t TProof::AddIncludePath(const char *incpath)
{
// Add 'incpath' to the inc path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!incpath || !strlen(incpath))) {
if (gDebug > 0)
Info("AddIncludePath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("inc") << (Bool_t)kTRUE;
// Add paths
if (incpath && strlen(incpath))
m << TString(incpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
Int_t TProof::RemoveDynamicPath(const char *libpath)
{
// Remove 'libpath' from the lib path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!libpath || !strlen(libpath))) {
if (gDebug > 0)
Info("AddDynamicPath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("lib") <<(Bool_t)kFALSE;
// Add paths
if (libpath && strlen(libpath))
m << TString(libpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
Int_t TProof::RemoveIncludePath(const char *incpath)
{
// Remove 'incpath' from the inc path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!incpath || !strlen(incpath))) {
if (gDebug > 0)
Info("RemoveIncludePath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("inc") << (Bool_t)kFALSE;
// Add paths
if (incpath && strlen(incpath))
m << TString(incpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
TList *TProof::GetListOfPackages()
{
// Get from the master the list of names of the packages available.
if (!IsValid())
return (TList *)0;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kListPackages);
Broadcast(mess);
Collect();
return fAvailablePackages;
}
//______________________________________________________________________________
TList *TProof::GetListOfEnabledPackages()
{
// Get from the master the list of names of the packages enabled.
if (!IsValid())
return (TList *)0;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kListEnabledPackages);
Broadcast(mess);
Collect();
return fEnabledPackages;
}
//______________________________________________________________________________
void TProof::PrintProgress(Long64_t total, Long64_t processed, Float_t procTime)
{
// Print a progress bar on stderr. Used in batch mode.
fprintf(stderr, "[TProof::Progress] Total %lld events\t|", total);
for (int l = 0; l < 20; l++) {
if (total > 0) {
if (l < 20*processed/total)
fprintf(stderr, "=");
else if (l == 20*processed/total)
fprintf(stderr, ">");
else if (l > 20*processed/total)
fprintf(stderr, ".");
} else
fprintf(stderr, "=");
}
Float_t evtrti = (procTime > 0. && processed > 0) ? processed / procTime : -1.;
if (evtrti > 0.)
fprintf(stderr, "| %.02f %% [%.1f evts/s]\r",
100.0*(total ? (processed/total) : 1), evtrti);
else
fprintf(stderr, "| %.02f %%\r",
100.0*(total ? (processed/total) : 1));
if (processed >= total)
fprintf(stderr, "\n");
}
//______________________________________________________________________________
void TProof::Progress(Long64_t total, Long64_t processed)
{
// Get query progress information. Connect a slot to this signal
// to track progress.
PDB(kGlobal,1)
Info("Progress","%2f (%lld/%lld)", 100.*processed/total, processed, total);
if (gROOT->IsBatch()) {
// Simple progress bar
PrintProgress(total, processed);
} else {
EmitVA("Progress(Long64_t,Long64_t)", 2, total, processed);
}
}
//______________________________________________________________________________
void TProof::Progress(Long64_t total, Long64_t processed, Long64_t bytesread,
Float_t initTime, Float_t procTime,
Float_t evtrti, Float_t mbrti)
{
// Get query progress information. Connect a slot to this signal
// to track progress.
PDB(kGlobal,1)
Info("Progress","%lld %lld %lld %f %f %f %f", total, processed, bytesread,
initTime, procTime, evtrti, mbrti);
if (gROOT->IsBatch()) {
// Simple progress bar
PrintProgress(total, processed, procTime);
} else {
EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
7, total, processed, bytesread, initTime, procTime, evtrti, mbrti);
}
}
//______________________________________________________________________________
void TProof::Feedback(TList *objs)
{
// Get list of feedback objects. Connect a slot to this signal
// to monitor the feedback object.
PDB(kGlobal,1)
Info("Feedback","%d objects", objs->GetSize());
PDB(kFeedback,1) {
Info("Feedback","%d objects", objs->GetSize());
objs->ls();
}
Emit("Feedback(TList *objs)", (Long_t) objs);
}
//______________________________________________________________________________
void TProof::CloseProgressDialog()
{
// Close progress dialog.
PDB(kGlobal,1)
Info("CloseProgressDialog",
"called: have progress dialog: %d", fProgressDialogStarted);
// Nothing to do if not there
if (!fProgressDialogStarted)
return;
Emit("CloseProgressDialog()");
}
//______________________________________________________________________________
void TProof::ResetProgressDialog(const char *sel, Int_t sz, Long64_t fst,
Long64_t ent)
{
// Reset progress dialog.
PDB(kGlobal,1)
Info("ResetProgressDialog","(%s,%d,%lld,%lld)", sel, sz, fst, ent);
EmitVA("ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)",
4, sel, sz, fst, ent);
}
//______________________________________________________________________________
void TProof::StartupMessage(const char *msg, Bool_t st, Int_t done, Int_t total)
{
// Send startup message.
PDB(kGlobal,1)
Info("StartupMessage","(%s,%d,%d,%d)", msg, st, done, total);
EmitVA("StartupMessage(const char*,Bool_t,Int_t,Int_t)",
4, msg, st, done, total);
}
//______________________________________________________________________________
void TProof::DataSetStatus(const char *msg, Bool_t st, Int_t done, Int_t total)
{
// Send dataset preparation status.
PDB(kGlobal,1)
Info("DataSetStatus","(%s,%d,%d,%d)", msg, st, done, total);
EmitVA("DataSetStatus(const char*,Bool_t,Int_t,Int_t)",
4, msg, st, done, total);
}
//______________________________________________________________________________
void TProof::SendDataSetStatus(const char *msg, UInt_t n,
UInt_t tot, Bool_t st)
{
// Send data set status
if (IsMaster()) {
TMessage mess(kPROOF_DATASET_STATUS);
mess << TString(msg) << tot << n << st;
gProofServ->GetSocket()->Send(mess);
}
}
//______________________________________________________________________________
void TProof::QueryResultReady(const char *ref)
{
// Notify availability of a query result.
PDB(kGlobal,1)
Info("QueryResultReady","ref: %s", ref);
Emit("QueryResultReady(const char*)",ref);
}
//______________________________________________________________________________
void TProof::ValidateDSet(TDSet *dset)
{
// Validate a TDSet.
if (dset->ElementsValid()) return;
TList nodes;
nodes.SetOwner();
TList slholder;
slholder.SetOwner();
TList elemholder;
elemholder.SetOwner();
// build nodelist with slaves and elements
TIter nextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) {
TList *sllist = 0;
TPair *p = dynamic_cast<TPair*>(nodes.FindObject(sl->GetName()));
if (!p) {
sllist = new TList;
sllist->SetName(sl->GetName());
slholder.Add(sllist);
TList *elemlist = new TList;
elemlist->SetName(TString(sl->GetName())+"_elem");
elemholder.Add(elemlist);
nodes.Add(new TPair(sllist, elemlist));
} else {
sllist = dynamic_cast<TList*>(p->Key());
}
sllist->Add(sl);
}
// add local elements to nodes
TList nonLocal; // list of nonlocal elements
// make two iterations - first add local elements - then distribute nonlocals
for (Int_t i = 0; i < 2; i++) {
Bool_t local = i>0?kFALSE:kTRUE;
TIter nextElem(local ? dset->GetListOfElements() : &nonLocal);
while (TDSetElement *elem = dynamic_cast<TDSetElement*>(nextElem())) {
if (elem->GetValid()) continue;
TPair *p = dynamic_cast<TPair*>(local?nodes.FindObject(TUrl(elem->GetFileName()).GetHost()):nodes.At(0));
if (p) {
TList *eli = dynamic_cast<TList*>(p->Value());
TList *sli = dynamic_cast<TList*>(p->Key());
eli->Add(elem);
// order list by elements/slave
TPair *p2 = p;
Bool_t stop = kFALSE;
while (!stop) {
TPair *p3 = dynamic_cast<TPair*>(nodes.After(p2->Key()));
if (p3) {
Int_t nelem = dynamic_cast<TList*>(p3->Value())->GetSize();
Int_t nsl = dynamic_cast<TList*>(p3->Key())->GetSize();
if (nelem*sli->GetSize() < eli->GetSize()*nsl) p2 = p3;
else stop = kTRUE;
} else {
stop = kTRUE;
}
}
if (p2!=p) {
nodes.Remove(p->Key());
nodes.AddAfter(p2->Key(), p);
}
} else {
if (local) {
nonLocal.Add(elem);
} else {
Error("ValidateDSet", "No Node to allocate TDSetElement to");
R__ASSERT(0);
}
}
}
}
// send to slaves
TList usedslaves;
TIter nextNode(&nodes);
SetDSet(dset); // set dset to be validated in Collect()
while (TPair *node = dynamic_cast<TPair*>(nextNode())) {
TList *slaves = dynamic_cast<TList*>(node->Key());
TList *setelements = dynamic_cast<TList*>(node->Value());
// distribute elements over the slaves
Int_t nslaves = slaves->GetSize();
Int_t nelements = setelements->GetSize();
for (Int_t i=0; i<nslaves; i++) {
TDSet copyset(dset->GetType(), dset->GetObjName(),
dset->GetDirectory());
for (Int_t j = (i*nelements)/nslaves;
j < ((i+1)*nelements)/nslaves;
j++) {
TDSetElement *elem =
dynamic_cast<TDSetElement*>(setelements->At(j));
copyset.Add(elem->GetFileName(), elem->GetObjName(),
elem->GetDirectory(), elem->GetFirst(),
elem->GetNum(), elem->GetMsd());
}
if (copyset.GetListOfElements()->GetSize()>0) {
TMessage mesg(kPROOF_VALIDATE_DSET);
mesg << ©set;
TSlave *sl = dynamic_cast<TSlave*>(slaves->At(i));
PDB(kGlobal,1) Info("ValidateDSet",
"Sending TDSet with %d elements to slave %s"
" to be validated",
copyset.GetListOfElements()->GetSize(),
sl->GetOrdinal());
sl->GetSocket()->Send(mesg);
usedslaves.Add(sl);
}
}
}
PDB(kGlobal,1) Info("ValidateDSet","Calling Collect");
Collect(&usedslaves);
SetDSet(0);
}
//______________________________________________________________________________
void TProof::AddInput(TObject *obj)
{
// Add objects that might be needed during the processing of
// the selector (see Process()).
fPlayer->AddInput(obj);
}
//______________________________________________________________________________
void TProof::ClearInput()
{
// Clear input object list.
fPlayer->ClearInput();
// the system feedback list is always in the input list
AddInput(fFeedback);
}
//______________________________________________________________________________
TObject *TProof::GetOutput(const char *name)
{
// Get specified object that has been produced during the processing
// (see Process()).
return fPlayer->GetOutput(name);
}
//______________________________________________________________________________
TList *TProof::GetOutputList()
{
// Get list with all object created during processing (see Process()).
return fPlayer->GetOutputList();
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, const char *value)
{
// Set input list parameter. If the parameter is already
// set it will be set to the new value.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TNamed(par, value));
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, Long_t value)
{
// Set an input list parameter.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TParameter<Long_t>(par, value));
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, Long64_t value)
{
// Set an input list parameter.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TParameter<Long64_t>(par, value));
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, Double_t value)
{
// Set an input list parameter.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TParameter<Double_t>(par, value));
}
//______________________________________________________________________________
TObject *TProof::GetParameter(const char *par) const
{
// Get specified parameter. A parameter set via SetParameter() is either
// a TParameter or a TNamed or 0 in case par is not defined.
TList *il = fPlayer->GetInputList();
return il->FindObject(par);
}
//______________________________________________________________________________
void TProof::DeleteParameters(const char *wildcard)
{
// Delete the input list parameters specified by a wildcard (e.g. PROOF_*)
// or exact name (e.g. PROOF_MaxSlavesPerNode).
if (!wildcard) wildcard = "";
TRegexp re(wildcard, kTRUE);
Int_t nch = strlen(wildcard);
TList *il = fPlayer->GetInputList();
TObject *p;
TIter next(il);
while ((p = next())) {
TString s = p->GetName();
if (nch && s != wildcard && s.Index(re) == kNPOS) continue;
il->Remove(p);
delete p;
}
}
//______________________________________________________________________________
void TProof::ShowParameters(const char *wildcard) const
{
// Show the input list parameters specified by the wildcard.
// Default is the special PROOF control parameters (PROOF_*).
if (!wildcard) wildcard = "";
TRegexp re(wildcard, kTRUE);
Int_t nch = strlen(wildcard);
TList *il = fPlayer->GetInputList();
TObject *p;
TIter next(il);
while ((p = next())) {
TString s = p->GetName();
if (nch && s != wildcard && s.Index(re) == kNPOS) continue;
if (p->IsA() == TNamed::Class()) {
Printf("%s\t\t\t%s", s.Data(), p->GetTitle());
} else if (p->IsA() == TParameter<Long_t>::Class()) {
Printf("%s\t\t\t%ld", s.Data(), dynamic_cast<TParameter<Long_t>*>(p)->GetVal());
} else if (p->IsA() == TParameter<Long64_t>::Class()) {
Printf("%s\t\t\t%lld", s.Data(), dynamic_cast<TParameter<Long64_t>*>(p)->GetVal());
} else if (p->IsA() == TParameter<Double_t>::Class()) {
Printf("%s\t\t\t%f", s.Data(), dynamic_cast<TParameter<Double_t>*>(p)->GetVal());
} else {
Printf("%s\t\t\t%s", s.Data(), p->GetTitle());
}
}
}
//______________________________________________________________________________
void TProof::AddFeedback(const char *name)
{
// Add object to feedback list.
PDB(kFeedback, 3)
Info("AddFeedback", "Adding object \"%s\" to feedback", name);
if (fFeedback->FindObject(name) == 0)
fFeedback->Add(new TObjString(name));
}
//______________________________________________________________________________
void TProof::RemoveFeedback(const char *name)
{
// Remove object from feedback list.
TObject *obj = fFeedback->FindObject(name);
if (obj != 0) {
fFeedback->Remove(obj);
delete obj;
}
}
//______________________________________________________________________________
void TProof::ClearFeedback()
{
// Clear feedback list.
fFeedback->Delete();
}
//______________________________________________________________________________
void TProof::ShowFeedback() const
{
// Show items in feedback list.
if (fFeedback->GetSize() == 0) {
Info("","no feedback requested");
return;
}
fFeedback->Print();
}
//______________________________________________________________________________
TList *TProof::GetFeedbackList() const
{
// Return feedback list.
return fFeedback;
}
//______________________________________________________________________________
TTree *TProof::GetTreeHeader(TDSet *dset)
{
// Creates a tree header (a tree with nonexisting files) object for
// the DataSet.
TList *l = GetListOfActiveSlaves();
TSlave *sl = (TSlave*) l->First();
if (sl == 0) {
Error("GetTreeHeader", "No connection");
return 0;
}
TSocket *soc = sl->GetSocket();
TMessage msg(kPROOF_GETTREEHEADER);
msg << dset;
soc->Send(msg);
TMessage *reply;
Int_t d = soc->Recv(reply);
if (reply <= 0) {
Error("GetTreeHeader", "Error getting a replay from the master.Result %d", (int) d);
return 0;
}
TString s1;
TTree * t;
(*reply) >> s1;
(*reply) >> t;
PDB(kGlobal, 1)
if (t)
Info("GetTreeHeader", Form("%s, message size: %d, entries: %d\n",
s1.Data(), reply->BufferSize(), (int) t->GetMaxEntryLoop()));
else
Info("GetTreeHeader", Form("%s, message size: %d\n", s1.Data(), reply->BufferSize()));
delete reply;
return t;
}
//______________________________________________________________________________
TDrawFeedback *TProof::CreateDrawFeedback()
{
// Draw feedback creation proxy. When accessed via TProof avoids
// link dependency on libProofPlayer.
return fPlayer->CreateDrawFeedback(this);
}
//______________________________________________________________________________
void TProof::SetDrawFeedbackOption(TDrawFeedback *f, Option_t *opt)
{
// Set draw feedback option.
fPlayer->SetDrawFeedbackOption(f, opt);
}
//______________________________________________________________________________
void TProof::DeleteDrawFeedback(TDrawFeedback *f)
{
// Delete draw feedback object.
fPlayer->DeleteDrawFeedback(f);
}
//______________________________________________________________________________
TList *TProof::GetOutputNames()
{
// FIXME: to be written
return 0;
/*
TMessage msg(kPROOF_GETOUTPUTLIST);
TList* slaves = fActiveSlaves;
Broadcast(msg, slaves);
TMonitor mon;
TList* outputList = new TList();
TIter si(slaves);
TSlave *slave;
while ((slave = (TSlave*)si.Next()) != 0) {
PDB(kGlobal,4) Info("GetOutputNames","Socket added to monitor: %p (%s)",
slave->GetSocket(), slave->GetName());
mon.Add(slave->GetSocket());
}
mon.ActivateAll();
((TProof*)gProof)->DeActivateAsyncInput();
((TProof*)gProof)->fCurrentMonitor = &mon;
while (mon.GetActive() != 0) {
TSocket *sock = mon.Select();
if (!sock) {
Error("GetOutputList","TMonitor::.Select failed!");
break;
}
mon.DeActivate(sock);
TMessage *reply;
if (sock->Recv(reply) <= 0) {
MarkBad(slave);
// Error("GetOutputList","Recv failed! for slave-%d (%s)",
// slave->GetOrdinal(), slave->GetName());
continue;
}
if (reply->What() != kPROOF_GETOUTPUTNAMES ) {
// Error("GetOutputList","unexpected message %d from slawe-%d (%s)", reply->What(),
// slave->GetOrdinal(), slave->GetName());
MarkBad(slave);
continue;
}
TList* l;
(*reply) >> l;
TIter next(l);
TNamed *n;
while ( (n = dynamic_cast<TNamed*> (next())) ) {
if (!outputList->FindObject(n->GetName()))
outputList->Add(n);
}
delete reply;
}
((TProof*)gProof)->fCurrentMonitor = 0;
return outputList;
*/
}
//______________________________________________________________________________
void TProof::Browse(TBrowser *b)
{
// Build the PROOF's structure in the browser.
b->Add(fActiveSlaves, fActiveSlaves->Class(), "fActiveSlaves");
b->Add(&fMaster, fMaster.Class(), "fMaster");
b->Add(fFeedback, fFeedback->Class(), "fFeedback");
b->Add(fChains, fChains->Class(), "fChains");
b->Add(fPlayer->GetInputList(), fPlayer->GetInputList()->Class(), "InputList");
if (fPlayer->GetOutputList())
b->Add(fPlayer->GetOutputList(), fPlayer->GetOutputList()->Class(), "OutputList");
if (fPlayer->GetListOfResults())
b->Add(fPlayer->GetListOfResults(),
fPlayer->GetListOfResults()->Class(), "ListOfResults");
}
//______________________________________________________________________________
void TProof::SetPlayer(TVirtualProofPlayer *player)
{
// Set a new PROOF player.
if (fPlayer)
delete fPlayer;
fPlayer = player;
};
//______________________________________________________________________________
TVirtualProofPlayer *TProof::MakePlayer(const char *player, TSocket *s)
{
// Construct a TProofPlayer object. The player string specifies which
// player should be created: remote, slave, sm (supermaster) or base.
// Default is remote. Socket is needed in case a slave player is created.
if (!player)
player = "remote";
SetPlayer(TVirtualProofPlayer::Create(player, this, s));
return GetPlayer();
}
//______________________________________________________________________________
void TProof::AddChain(TChain *chain)
{
// Add chain to data set
fChains->Add(chain);
}
//______________________________________________________________________________
void TProof::RemoveChain(TChain *chain)
{
// Remove chain from data set
fChains->Remove(chain);
}
//_____________________________________________________________________________
void *TProof::SlaveStartupThread(void *arg)
{
// Function executed in the slave startup thread.
if (fgSemaphore) fgSemaphore->Wait();
TProofThreadArg *ta = (TProofThreadArg *)arg;
PDB(kGlobal,1)
::Info("TProof::SlaveStartupThread",
"Starting slave %s on host %s", ta->fOrd.Data(), ta->fUrl->GetHost());
TSlave *sl = 0;
if (ta->fType == TSlave::kSlave) {
// Open the connection
sl = ta->fProof->CreateSlave(ta->fUrl->GetUrl(), ta->fOrd,
ta->fPerf, ta->fImage, ta->fWorkdir);
// Finalize setup of the server
if (sl && sl->IsValid())
sl->SetupServ(TSlave::kSlave, 0);
} else {
// Open the connection
sl = ta->fProof->CreateSubmaster(ta->fUrl->GetUrl(), ta->fOrd,
ta->fImage, ta->fMsd);
// Finalize setup of the server
if (sl && sl->IsValid())
sl->SetupServ(TSlave::kMaster, ta->fWorkdir);
}
if (sl && sl->IsValid()) {
{ R__LOCKGUARD2(gProofMutex);
// Add to the started slaves list
ta->fSlaves->Add(sl);
if (ta->fClaims) { // Condor slave
// Remove from the pending claims list
TCondorSlave *c = ta->fCslave;
ta->fClaims->Remove(c);
}
}
// Notify we are done
PDB(kGlobal,1)
::Info("TProof::SlaveStartupThread",
"slave %s on host %s created and added to list",
ta->fOrd.Data(), ta->fUrl->GetHost());
} else {
// Failure
SafeDelete(sl);
::Error("TProof::SlaveStartupThread",
"slave %s on host %s could not be created",
ta->fOrd.Data(), ta->fUrl->GetHost());
}
if (fgSemaphore) fgSemaphore->Post();
return 0;
}
//______________________________________________________________________________
void TProof::GetLog(Int_t start, Int_t end)
{
// Ask for remote logs in the range [start, end]. If start == -1 all the
// messages not yet received are sent back.
if (!IsValid() || IsMaster()) return;
TMessage msg(kPROOF_LOGFILE);
msg << start << end;
Broadcast(msg, kActive);
Collect(kActive);
}
//______________________________________________________________________________
void TProof::PutLog(TQueryResult *pq)
{
// Display log of query pq into the log window frame
if (!pq) return;
TList *lines = pq->GetLogFile()->GetListOfLines();
if (lines) {
TIter nxl(lines);
TObjString *l = 0;
while ((l = (TObjString *)nxl()))
EmitVA("LogMessage(const char*,Bool_t)", 2, l->GetName(), kFALSE);
}
}
//______________________________________________________________________________
void TProof::ShowLog(const char *queryref)
{
// Display on screen the content of the temporary log file for query
// in reference
// Make sure we have all info (GetListOfQueries retrieves the
// head info only)
Retrieve(queryref);
if (fPlayer) {
if (queryref) {
if (fPlayer->GetListOfResults()) {
TIter nxq(fPlayer->GetListOfResults());
TQueryResult *qr = 0;
while ((qr = (TQueryResult *) nxq()))
if (strstr(queryref, qr->GetTitle()) &&
strstr(queryref, qr->GetName()))
break;
if (qr) {
PutLog(qr);
return;
}
}
}
}
}
//______________________________________________________________________________
void TProof::ShowLog(Int_t qry)
{
// Display on screen the content of the temporary log file.
// If qry == -2 show messages from the last (current) query.
// If qry == -1 all the messages not yet displayed are shown (default).
// If qry == 0, all the messages in the file are shown.
// If qry > 0, only the messages related to query 'qry' are shown.
// For qry != -1 the original file offset is restored at the end
// Save present offset
Int_t nowlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_CUR);
// Get extremes
Int_t startlog = nowlog;
Int_t endlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_END);
lseek(fileno(fLogFileR), (off_t) nowlog, SEEK_SET);
if (qry == 0) {
startlog = 0;
lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET);
} else if (qry != -1) {
TQueryResult *pq = 0;
if (qry == -2) {
// Pickup the last one
pq = (GetQueryResults()) ? ((TQueryResult *)(GetQueryResults()->Last())) : 0;
if (!pq) {
GetListOfQueries();
if (fQueries)
pq = (TQueryResult *)(fQueries->Last());
}
} else if (qry > 0) {
TList *queries = GetQueryResults();
if (queries) {
TIter nxq(queries);
while ((pq = (TQueryResult *)nxq()))
if (qry == pq->GetSeqNum())
break;
}
if (!pq) {
queries = GetListOfQueries();
TIter nxq(queries);
while ((pq = (TQueryResult *)nxq()))
if (qry == pq->GetSeqNum())
break;
}
}
if (pq) {
PutLog(pq);
return;
} else {
if (gDebug > 0)
Info("ShowLog","query %d not found in list", qry);
qry = -1;
}
}
// Number of bytes to log
UInt_t tolog = (UInt_t)(endlog - startlog);
// Perhaps nothing
if (tolog <= 0)
// Set starting point
lseek(fileno(fLogFileR), (off_t) startlog, SEEK_SET);
// Now we go
Int_t np = 0;
char line[2048];
Int_t wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog;
while (fgets(line, wanted, fLogFileR)) {
Int_t r = strlen(line);
if (!SendingLogToWindow()) {
if (line[r-1] != '\n') line[r-1] = '\n';
if (r > 0) {
char *p = line;
while (r) {
Int_t w = write(fileno(stdout), p, r);
if (w < 0) {
SysError("ShowLogFile", "error writing to stdout");
break;
}
r -= w;
p += w;
}
}
tolog -= strlen(line);
np++;
// Ask if more is wanted
if (!(np%10)) {
char *opt = Getline("More (y/n)? [y]");
if (opt[0] == 'n')
break;
}
// We may be over
if (tolog <= 0)
break;
// Update wanted bytes
wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog;
} else {
// Log to window
if (line[r-1] == '\n') line[r-1] = 0;
LogMessage(line, kFALSE);
}
}
if (!SendingLogToWindow()) {
// Avoid screwing up the prompt
write(fileno(stdout), "\n", 1);
}
// Restore original pointer
if (qry > -1)
lseek(fileno(fLogFileR), (off_t) nowlog, SEEK_SET);
}
//______________________________________________________________________________
void TProof::cd(Int_t id)
{
// Set session with 'id' the default one. If 'id' is not found in the list,
// the current session is set as default
if (GetManager()) {
TProofDesc *d = GetManager()->GetProofDesc(id);
if (d) {
if (d->GetProof()) {
gProof = d->GetProof();
return;
}
}
// Id not found or undefined: set as default this session
gProof = this;
}
return;
}
//______________________________________________________________________________
void TProof::Detach(Option_t *opt)
{
// Detach this instance to its proofserv.
// If opt is 'S' or 's' the remote server is shutdown
// Nothing to do if not in contact with proofserv
if (!IsValid()) return;
// Get worker and socket instances
TSlave *sl = (TSlave *) fActiveSlaves->First();
TSocket *s = sl->GetSocket();
if (!sl || !(sl->IsValid()) || !s) {
Error("Detach","corrupted worker instance: wrk:%p, sock:%p", sl, s);
return;
}
Bool_t shutdown = (strchr(opt,'s') || strchr(opt,'S')) ? kTRUE : kFALSE;
// If processing, try to stop processing first
if (shutdown && !IsIdle()) {
// Remove pending requests
Remove("cleanupqueue");
// Do not wait for ever, but al least 20 seconds
Long_t timeout = gEnv->GetValue("Proof.ShutdownTimeout", 60);
timeout = (timeout > 20) ? timeout : 20;
// Send stop signal
StopProcess(kFALSE, (Long_t) (timeout / 2));
// Receive results
Collect(kActive, timeout);
}
// Avoid spurious messages: deactivate new inputs ...
DeActivateAsyncInput();
// ... and discard existing ones
sl->FlushSocket();
// Close session (we always close the connection)
Close(opt);
// Close the progress dialog, if any
if (fProgressDialogStarted)
CloseProgressDialog();
// Update info in the table of our manager, if any
if (GetManager() && GetManager()->QuerySessions("L")) {
TIter nxd(GetManager()->QuerySessions("L"));
TProofDesc *d = 0;
while ((d = (TProofDesc *)nxd())) {
if (d->GetProof() == this) {
d->SetProof(0);
GetManager()->QuerySessions("L")->Remove(d);
break;
}
}
}
// Delete this instance
if (!fProgressDialogStarted)
delete this;
else
// ~TProgressDialog will delete this
fValid = kFALSE;
return;
}
//______________________________________________________________________________
void TProof::SetAlias(const char *alias)
{
// Set an alias for this session. If reconnection is supported, the alias
// will be communicated to the remote coordinator so that it can be recovered
// when reconnecting
// Set it locally
TNamed::SetTitle(alias);
if (IsMaster())
// Set the name at the same value
TNamed::SetName(alias);
// Nothing to do if not in contact with coordinator
if (!IsValid()) return;
if (!IsProofd() && !IsMaster()) {
TSlave *sl = (TSlave *) fActiveSlaves->First();
if (sl)
sl->SetAlias(alias);
}
return;
}
//______________________________________________________________________________
Int_t TProof::UploadDataSet(const char *dataSetName,
TList *files,
const char *desiredDest,
Int_t opt,
TList *skippedFiles)
{
// Upload a set of files and save the list of files by name dataSetName.
// The 'files' argument is a list of TFileInfo objects describing the files
// as first url.
// The mask 'opt' is a combination of EUploadOpt:
// kAppend (0x1) if set true files will be appended to
// the dataset existing by given name
// kOverwriteDataSet (0x2) if dataset with given name exited it
// would be overwritten
// kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists
// kOverwriteAllFiles (0x8) overwrite all files that may exist
// kOverwriteNoFiles (0x10) overwrite none
// kAskUser (0x0) ask user before overwriteng dataset/files
// The default value is kAskUser.
// The user will be asked to confirm overwriting dataset or files unless
// specified opt provides the answer!
// If kOverwriteNoFiles is set, then a pointer to TList must be passed as
// skippedFiles argument. The function will add to this list TFileInfo
// objects describing all files that existed on the cluster and were
// not uploaded.
//
// Communication Summary
// Client Master
// |------------>DataSetName----------->|
// |<-------kMESS_OK/kMESS_NOTOK<-------| (Name OK/file exist)
// (*)|-------> call CreateDataSet ------->|
// (*) - optional
// check if dataSetName is not excluded
if (strchr(dataSetName, '/')) {
if (strstr(dataSetName, "public") != dataSetName) {
Error("UploadDataSet",
"Name of public dataset should start with public/");
return kError;
}
}
if (opt & kOverwriteAllFiles && opt & kOverwriteNoFiles
|| opt & kNoOverwriteDataSet && opt & kAppend
|| opt & kOverwriteDataSet && opt & kAppend
|| opt & kNoOverwriteDataSet && opt & kOverwriteDataSet
|| opt & kAskUser && opt & (kOverwriteDataSet |
kNoOverwriteDataSet |
kAppend |
kOverwriteAllFiles |
kOverwriteNoFiles)) {
Error("UploadDataSet", "you specified contradicting options.");
return kError;
}
// Decode options
Int_t overwriteAll = (opt & kOverwriteAllFiles) ? kTRUE : kFALSE;
Int_t overwriteNone = (opt & kOverwriteNoFiles) ? kTRUE : kFALSE;
Int_t goodName = (opt & (kOverwriteDataSet | kAppend)) ? 1 : -1;
Int_t appendToDataSet = (opt & kAppend) ? kTRUE : kFALSE;
Int_t overwriteNoDataSet = (opt & kNoOverwriteDataSet) ? kTRUE : kFALSE;
//If skippedFiles is not provided we can not return list of skipped files.
if ((!skippedFiles || !&skippedFiles) && overwriteNone) {
Error("UploadDataSet",
"Provide pointer to TList object as skippedFiles argument when using kOverwriteNoFiles option.");
return kError;
}
//If skippedFiles is provided but did not point to a TList the have to STOP
if (skippedFiles && &skippedFiles)
if (skippedFiles->Class() != TList::Class()) {
Error("UploadDataSet",
"Provided skippedFiles argument does not point to a TList object.");
return kError;
}
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("UploadDataSet", "No connection to the master!");
return kError;
}
Int_t fileCount = 0; // return value
TMessage *retMess;
if (goodName == -1) { // -1 for undefined
// First check whether this dataset already exists unless
// kAppend or kOverWriteDataSet
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kCheckDataSetName);
nameMess << TString(dataSetName);
Broadcast(nameMess);
master->Recv(retMess);
Collect(); //after each call to HandleDataSets
if (retMess->What() == kMESS_NOTOK) {
//We ask user to agree on overwriting the dataset name
while (goodName == -1 && !overwriteNoDataSet) {
Printf("Dataset %s already exist. ",
dataSetName);
Printf("Do you want to overwrite it[Yes/No/Append]?");
TString answer;
answer.ReadToken(cin);
if (!strncasecmp(answer.Data(), "y", 1)) {
goodName = 1;
} else if (!strncasecmp(answer.Data(), "n", 1)) {
goodName = 0;
} else if (!strncasecmp(answer.Data(), "a", 1)) {
goodName = 1;
appendToDataSet = kTRUE;
}
}
}
else if (retMess->What() == kMESS_OK)
goodName = 1;
else
Error("UploadDataSet", "unrecongnized message type: %d!",
retMess->What());
delete retMess;
} // if (goodName == -1)
if (goodName == 1) { //must be == 1 as -1 was used for a bad name!
//Code for enforcing writing in user "home dir" only
char *relativeDestDir = Form("%s/%s/",
gSystem->GetUserInfo()->fUser.Data(),
desiredDest?desiredDest:"");
//Consider adding dataSetName to the path
relativeDestDir = CollapseSlashesInPath(relativeDestDir);
TString dest = Form("%s/%s", GetDataPoolUrl(), relativeDestDir);
delete[] relativeDestDir;
// Now we will actually copy files and create the TList object
TList *fileList = new TList();
TFileMerger fileCopier;
TIter next(files);
while (TFileInfo *fileInfo = ((TFileInfo*)next())) {
TUrl *fileUrl = fileInfo->GetFirstUrl();
if (gSystem->AccessPathName(fileUrl->GetUrl()) == kFALSE) {
//matching dir entry
//getting the file name from the path represented by fileUrl
const char *ent = gSystem->BaseName(fileUrl->GetFile());
Int_t goodFileName = 1;
if (!overwriteAll &&
gSystem->AccessPathName(Form("%s/%s", dest.Data(), ent), kFileExists)
== kFALSE) { //Destination file exists
goodFileName = -1;
while (goodFileName == -1 && !overwriteAll && !overwriteNone) {
Printf("File %s already exists. ", Form("%s/%s", dest.Data(), ent));
Printf("Do you want to overwrite it [Yes/No/all/none]?");
TString answer;
answer.ReadToken(cin);
if (!strncasecmp(answer.Data(), "y", 1))
goodFileName = 1;
else if (!strncasecmp(answer.Data(), "all", 3))
overwriteAll = kTRUE;
else if (!strncasecmp(answer.Data(), "none", 4))
overwriteNone = kTRUE;
else if (!strncasecmp(answer.Data(), "n", 1))
goodFileName = 0;
}
} //if file exists
// Copy the file to the redirector indicated
if (goodFileName == 1 || overwriteAll) {
//must be == 1 as -1 was meant for bad name!
Printf("Uploading %s to %s/%s",
fileUrl->GetUrl(), dest.Data(), ent);
if (fileCopier.Cp(fileUrl->GetUrl(),
Form("%s/%s", dest.Data(), ent))) {
fileList->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent)));
} else
Error("UploadDataSet", "file %s was not copied", fileUrl->GetUrl());
} else { // don't overwrite, but file exist and must be included
fileList->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent)));
if (skippedFiles && &skippedFiles) {
// user specified the TList *skippedFiles argument so we create
// the list of skipped files
skippedFiles->Add(new TFileInfo(fileUrl->GetUrl()));
}
}
} //if matching dir entry
} //while
if ((fileCount = fileList->GetSize()) == 0) {
Printf("No files were copied. The dataset will not be saved");
} else {
if (CreateDataSet(dataSetName, fileList,
appendToDataSet?kAppend:kOverwriteDataSet) <= 0) {
Error("UploadDataSet", "Error while saving dataset!");
fileCount = kError;
}
}
fileList->SetOwner();
delete fileList;
} else if (overwriteNoDataSet) {
Printf("Dataset %s already exists", dataSetName);
return kDataSetExists;
} //if(goodName == 1)
return fileCount;
}
//______________________________________________________________________________
Int_t TProof::UploadDataSet(const char *dataSetName,
const char *files,
const char *desiredDest,
Int_t opt,
TList *skippedFiles)
{
// Upload a set of files and save the list of files by name dataSetName.
// The mask 'opt' is a combination of EUploadOpt:
// kAppend (0x1) if set true files will be appended to
// the dataset existing by given name
// kOverwriteDataSet (0x2) if dataset with given name exited it
// would be overwritten
// kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists
// kOverwriteAllFiles (0x8) overwrite all files that may exist
// kOverwriteNoFiles (0x10) overwrite none
// kAskUser (0x0) ask user before overwriteng dataset/files
// The default value is kAskUser.
// The user will be asked to confirm overwriting dataset or files unless
// specified opt provides the answer!
// If kOverwriteNoFiles is set, then a pointer to TList must be passed as
// skippedFiles argument. The function will add to this list TFileInfo
// objects describing all files that existed on the cluster and were
// not uploaded.
//
TList *fileList = new TList();
void *dataSetDir = gSystem->OpenDirectory(gSystem->DirName(files));
const char* ent;
TString filesExp(gSystem->BaseName(files));
filesExp.ReplaceAll("*",".*");
TRegexp rg(filesExp);
while ((ent = gSystem->GetDirEntry(dataSetDir))) {
TString entryString(ent);
if (entryString.Index(rg) != kNPOS) {
//matching dir entry
// Creating the intermediate TUrl with kTRUE flag to make sure
// file:// is added for a local file
TUrl *url = new TUrl(Form("%s/%s",
gSystem->DirName(files), ent), kTRUE);
if (gSystem->AccessPathName(url->GetUrl(), kReadPermission) == kFALSE)
fileList->Add(new TFileInfo(url->GetUrl()));
delete url;
} //if matching dir entry
} //while
Int_t fileCount;
if ((fileCount = fileList->GetSize()) == 0)
Printf("No files match your selection. The dataset will not be saved");
else
fileCount = UploadDataSet(dataSetName, fileList, desiredDest,
opt, skippedFiles);
fileList->SetOwner();
delete fileList;
return fileCount;
}
//______________________________________________________________________________
Int_t TProof::UploadDataSetFromFile(const char *dataset, const char *file,
const char *dest, Int_t opt)
{
// Upload files listed in "file" to PROOF cluster.
// Where file = name of file containing list of files and
// dataset = dataset name and opt is a combination of EUploadOpt bits.
// Each file description (line) can include wildcards.
//TODO: This method should use UploadDataSet(char *dataset, TList *l, ...)
Int_t fileCount = 0;
ifstream f;
f.open(gSystem->ExpandPathName(file), ifstream::out);
if (f.is_open()) {
while (f.good()) {
TString line;
line.ReadToDelim(f);
if (fileCount == 0) {
// when uploading the first file user may have to decide
fileCount += UploadDataSet(dataset, line.Data(), dest, opt);
} else // later - just append
fileCount += UploadDataSet(dataset, line.Data(), dest,
opt | kAppend);
}
f.close();
} else {
Error("UploadDataSetFromFile", "unable to open the specified file");
return -1;
}
return fileCount;
}
//______________________________________________________________________________
Int_t TProof::CreateDataSet(const char *dataSetName,
TList *files,
Int_t opt)
{
// Create a dataSet from files existing on the cluster (listed in files)
// and save it as dataSetName.
// No files are uploaded nor verified to exist on the cluster
// The 'files' argument is a list of TFileInfo objects describing the files
// as first url.
// The mask 'opt' is a combination of EUploadOpt:
// kAppend (0x1) if set true files will be appended to
// the dataset existing by given name
// kOverwriteDataSet (0x2) if dataset with given name exited it
// would be overwritten
// kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists
// kAskUser (0x0) ask user before overwriteng dataset/files
// The default value is kAskUser.
// The user will be asked to confirm overwriting dataset or files unless
// specified opt provides the answer!
//
// Communication Summary
// Client Master
// |------------>DataSetName----------->|
// |<-------kMESS_OK/kMESS_NOTOK<-------| (Name OK/file exist)
// (*)|------->TList of TFileInfo -------->| (dataset to save)
// (*)|<-------kMESS_OK/kMESS_NOTOK<-------| (transaction complete?)
// (*) - optional
// check if dataSetName is not excluded
if (strchr(dataSetName, '/')) {
if (strstr(dataSetName, "public") != dataSetName) {
Error("CreateDataSet",
"Name of public dataset should start with public/");
return kError;
}
}
if (opt & kOverwriteDataSet && opt & kAppend
|| opt & kNoOverwriteDataSet && opt & kAppend
|| opt & kNoOverwriteDataSet && opt & kOverwriteDataSet
|| opt & kAskUser && opt & (kOverwriteDataSet |
kNoOverwriteDataSet |
kAppend)) {
Error("CreateDataSet", "you specified contradicting options.");
return kError;
}
if (opt & kOverwriteAllFiles || opt & kOverwriteNoFiles) {
Error("CreateDataSet", "you specified unsupported options.");
return kError;
}
// Decode options
Int_t goodName = (opt & (kOverwriteDataSet | kAppend)) ? 1 : -1;
Int_t appendToDataSet = (opt & kAppend) ? kTRUE : kFALSE;
Int_t overwriteNoDataSet = (opt & kNoOverwriteDataSet) ? kTRUE : kFALSE;
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("CreateDataSet", "No connection to the master!");
return kError;
}
Int_t fileCount = 0; // return value
//TODO Below if statement is a copy from UploadDataSet
TMessage *retMess;
if (goodName == -1) { // -1 for undefined
// First check whether this dataset already exist unless
// kAppend or kOverWriteDataSet
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kCheckDataSetName);
nameMess << TString(dataSetName);
Broadcast(nameMess);
master->Recv(retMess);
Collect(); //after each call to HandleDataSets
if (retMess->What() == kMESS_NOTOK) {
//We ask user to agree on overwriting the dataset name
while (goodName == -1 && !overwriteNoDataSet) {
Printf("Dataset %s already exists. ",
dataSetName);
Printf("Do you want to overwrite it[Yes/No/Append]?");
TString answer;
answer.ReadToken(cin);
if (!strncasecmp(answer.Data(), "y", 1)) {
goodName = 1;
} else if (!strncasecmp(answer.Data(), "n", 1)) {
goodName = 0;
} else if (!strncasecmp(answer.Data(), "a", 1)) {
goodName = 1;
appendToDataSet = kTRUE;
}
}
}
else if (retMess->What() == kMESS_OK)
goodName = 1;
else
Error("CreateDataSet", "unrecongnized message type: %d!",
retMess->What());
delete retMess;
} // if (goodName == -1)
if (goodName == 1) {
if ((fileCount = files->GetSize()) == 0) {
Printf("No files specified!");
} else {
TMessage mess(kPROOF_DATASETS);
if (appendToDataSet)
mess << Int_t(kAppendDataSet);
else
mess << Int_t(kCreateDataSet);
mess << TString(dataSetName);
mess.WriteObject(files);
Broadcast(mess);
//Reusing the retMess.
if (master->Recv(retMess) <= 0) {
Error("CreateDataSet", "No response form the master");
fileCount = -1;
} else {
if (retMess->What() == kMESS_NOTOK) {
Printf("Dataset was not saved.");
fileCount = -1;
} else if (retMess->What() != kMESS_OK)
Error("CreateDataSet",
"Unexpected message type: %d", retMess->What());
delete retMess;
}
}
} else if (overwriteNoDataSet) {
Printf("Dataset %s already exists", dataSetName);
Collect();
return kDataSetExists;
} //if(goodName == 1)
Collect();
return fileCount;
}
//______________________________________________________________________________
TList *TProof::GetDataSets(const char *dir)
{
// Get TList of TObjStrings with all datasets available on master:
// * with dir undifined - just ls contents of ~/proof/datasets,
// * with dir == "public" - ls ~/proof/datasets/public
// * with dir == "~username/public" - ls ~/username/datasets/public
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("GetDataSets", "No connection to the master!");
return 0;
}
if (dir) {
// check if dir is correct; this check is not exhaustive
if (strstr(dir, "public") != dir && strchr(dir, '~') != dir) {
// dir does not start with "public" nor with '~'
Error("GetDataSets",
"directory should be of form '[~userName/]public'");
return 0;
}
}
TMessage mess(kPROOF_DATASETS);
mess << Int_t(kGetDataSets);
mess << TString(dir?dir:"");
Broadcast(mess);
TMessage *retMess;
master->Recv(retMess);
TList *dataSetList = 0;
if (retMess->What() == kMESS_OBJECT) {
dataSetList = (TList*)(retMess->ReadObject(TList::Class()));
if (!dataSetList)
Error("GetDataSets", "Error receiving list of datasets");
} else
Printf("The dataset directory could not be open");
Collect();
delete retMess;
return dataSetList;
}
//______________________________________________________________________________
void TProof::ShowDataSets(const char *dir)
{
// Show all datasets uploaded to the cluster (just ls contents of
// ~/proof/datasets or user/proof/datasets/public if 'dir' is defined).
// * with dir undifined - just ls contents of ~/proof/datasets,
// * with dir == "public" - ls ~/proof/datasets/public
// * with dir == "~username/public" - ls ~/username/datasets/public
TList *dataSetList;
if ((dataSetList = GetDataSets(dir))) {
if (dir)
Printf("DataSets in %s :", dir);
else
Printf("Existing DataSets:");
TIter next(dataSetList);
while (TObjString *obj = (TObjString*)next())
Printf("%s", obj->GetString().Data());
dataSetList->SetOwner();
delete dataSetList;
} else
Printf("Error getting a list of datasets");
}
//______________________________________________________________________________
TList *TProof::GetDataSet(const char *dataset)
{
// Get a list of TFileInfo objects describing the files of the specified
// dataset.
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("GetDataSet", "No connection to the master!");
return 0;
}
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kGetDataSet);
nameMess << TString(dataset);
if (Broadcast(nameMess) < 0)
Error("GetDataSet", "Sending request failed");
TMessage *retMess;
master->Recv(retMess);
TList *fileList = 0;
if (retMess->What() == kMESS_OK) {
if (!(fileList = (TList*)(retMess->ReadObject(TList::Class()))))
Error("GetDataSet", "Error reading list of files");
} else if (retMess->What() != kMESS_NOTOK)
Error("GetDataSet", "Wrong message type %d", retMess->What());
Collect();
delete retMess;
return fileList;
}
//______________________________________________________________________________
void TProof::ShowDataSet(const char *dataset)
{
//Show content of specific dataset (cat ~/proof/datasets/dataset).
TList *fileList;
if ((fileList = GetDataSet(dataset))) {
if (fileList->GetSize()) {
//printing sorted list
Printf("Files in %s:", dataset);
TIter next(fileList);
while (TFileInfo *obj = (TFileInfo*)next())
Printf("%s", obj->GetFirstUrl()->GetUrl());
} else
Printf("There are no files in %s", dataset);
delete fileList;
}
else
Printf("No such dataset: %s", dataset);
}
//______________________________________________________________________________
Int_t TProof::RemoveDataSet(const char *dataSet)
{
// Remove the specified dataset from the PROOF cluster.
// Files are not deleted.
// check if dataSetName is not excluded
// if (strchr(dataSet, '/')) {
// Error("RemoveDataSet", "Dataset name shall not include '/'");
// return kError;
// }
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("RemoveDataSet", "No connection to the master!");
return kError;
}
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kRemoveDataSet);
nameMess << TString(dataSet);
if (Broadcast(nameMess) < 0)
Error("RemoveDataSet", "Sending request failed");
TMessage *mess;
TString errorMess;
master->Recv(mess);
Collect();
if (mess->What() != kMESS_OK) {
if (mess->What() != kMESS_NOTOK)
Error("RemoveDataSet", "unrecongnized message type: %d!",
mess->What());
delete mess;
return -1;
} else {
delete mess;
return 0;
}
}
//______________________________________________________________________________
Int_t TProof::VerifyDataSet(const char *dataSet)
{
// Verify if all files in the specified dataset are available.
// Print a list and return the number of missing files.
Int_t nMissingFiles = 0;
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("VerifyDataSet", "No connection to the master!");
return kError;
}
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kVerifyDataSet);
nameMess << TString(dataSet);
if (Broadcast(nameMess) < 0)
Error("VerifyDataSet", "Sending request failed");
TMessage *mess;
master->Recv(mess);
Collect();
if (mess->What() == kMESS_OK) {
TList *missingFiles;
missingFiles = (TList*)(mess->ReadObject(TList::Class()));
nMissingFiles = missingFiles->GetSize();
if (nMissingFiles == 0)
Printf("The files from %s dataset are all present on the cluster",
dataSet);
else {
Printf("The following files are missing from dataset %s ", dataSet);
Printf("at the moment:");
TIter next(missingFiles);
TFileInfo* fileInfo;
while ((fileInfo = (TFileInfo*)next())) {
Printf("\t%s", fileInfo->GetFirstUrl()->GetUrl());
}
}
missingFiles->SetOwner();
delete missingFiles;
} else if (mess->What() == kMESS_NOTOK) {
Printf("ValidateDataSet: no such dataset %s", dataSet);
delete mess;
return -1;
} else
Fatal("ValidateDataSet", "unknown message type %d", mess->What());
delete mess;
return nMissingFiles;
}
//_____________________________________________________________________________
void TProof::InterruptCurrentMonitor()
{
// If in active in a monitor set ready state
if (fCurrentMonitor)
fCurrentMonitor->Interrupt();
}
//_____________________________________________________________________________
void TProof::ActivateWorker(const char *ord)
{
// Make sure that the worker identified by the ordinal number 'ord' is
// in the active list. The request will be forwarded to the master
// in direct contact with the worker. If needed, this master will move
// the worker from the inactive to the active list and rebuild the list
// of unique workers.
// Use ord = "*" to activate all inactive workers.
ModifyWorkerLists(ord, kTRUE);
}
//_____________________________________________________________________________
void TProof::DeactivateWorker(const char *ord)
{
// Remove the worker identified by the ordinal number 'ord' from the
// the active list. The request will be forwarded to the master
// in direct contact with the worker. If needed, this master will move
// the worker from the active to the inactive list and rebuild the list
// of unique workers.
// Use ord = "*" to deactivate all active workers.
ModifyWorkerLists(ord, kFALSE);
}
//_____________________________________________________________________________
void TProof::ModifyWorkerLists(const char *ord, Bool_t add)
{
// Modify the worker active/inactive list by making the worker identified by
// the ordinal number 'ord' active (add == TRUE) or inactive (add == FALSE).
// If needed, the request will be forwarded to the master in direct contact
// with the worker. The end-master will move the worker from one list to the
// other active and rebuild the list of unique active workers.
// Use ord = "*" to deactivate all active workers.
// Make sure the input make sense
if (!ord || strlen(ord) <= 0) {
Info("ModifyWorkerLists",
"An ordinal number - e.g. \"0.4\" or \"*\" for all - is required as input");
return;
}
Bool_t fw = kTRUE; // Whether to forward one step down
Bool_t rs = kFALSE; // Whether to rescan for unique workers
// Appropriate list pointing
TList *in = (add) ? fInactiveSlaves : fActiveSlaves;
TList *out = (add) ? fActiveSlaves : fInactiveSlaves;
if (IsMaster()) {
fw = IsEndMaster() ? kFALSE : kTRUE;
// Look for the worker in the inactive list
if (in->GetSize() > 0) {
TIter nxw(in);
TSlave *wrk = 0;
while ((wrk = (TSlave *) nxw())) {
if (ord[0] == '*' || !strncmp(wrk->GetOrdinal(), ord, strlen(ord))) {
// Add it to the inactive list
if (!out->FindObject(wrk)) {
out->Add(wrk);
if (add)
fActiveMonitor->Add(wrk->GetSocket());
}
// Remove it from the active list
in->Remove(wrk);
if (!add) {
fActiveMonitor->Remove(wrk->GetSocket());
wrk->SetStatus(TSlave::kInactive);
} else
wrk->SetStatus(TSlave::kActive);
// Nothing to forward (ord is unique)
fw = kFALSE;
// Rescan for unique workers (active list modified)
rs = kTRUE;
// We are done, if not option 'all'
if (ord[0] != '*')
break;
}
}
}
}
// Rescan for unique workers
if (rs)
FindUniqueSlaves();
// Forward the request one step down, if needed
Int_t action = (add) ? (Int_t) kActivateWorker : (Int_t) kDeactivateWorker;
if (fw) {
TMessage mess(kPROOF_WORKERLISTS);
mess << action << TString(ord);
Broadcast(mess);
Collect();
}
}
//_____________________________________________________________________________
TProof *TProof::Open(const char *cluster, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Start a PROOF session on a specific cluster. If cluster is 0 (the
// default) then the PROOF Session Viewer GUI pops up and 0 is returned.
// If cluster is "" (empty string) then we connect to a PROOF session
// on the localhost ("proof://localhost"). Via conffile a specific
// PROOF config file in the confir directory can be specified.
// Use loglevel to set the default loging level for debugging.
// The appropriate instance of TProofMgr is created, if not
// yet existing. The instantiated TProof object is returned.
// Use TProof::cd() to switch between PROOF sessions.
// For more info on PROOF see the TProof ctor.
const char *pn = "TProof::Open";
// Make sure libProof and dependents are loaded and TProof can be created,
// dependents are loaded via the information in the [system].rootmap file
if (!cluster) {
TPluginManager *pm = gROOT->GetPluginManager();
if (!pm) {
::Error(pn, "plugin manager not found");
return 0;
}
if (gROOT->IsBatch()) {
::Error(pn, "we are in batch mode, cannot show PROOF Session Viewer");
return 0;
}
// start PROOF Session Viewer
TPluginHandler *sv = pm->FindHandler("TSessionViewer", "");
if (!sv) {
::Error(pn, "no plugin found for TSessionViewer");
return 0;
}
if (sv->LoadPlugin() == -1) {
::Error(pn, "plugin for TSessionViewer could not be loaded");
return 0;
}
sv->ExecPlugin(0);
return 0;
} else {
// Parse input URL
TUrl u(cluster);
// Find out if we are required to attach to a specific session
TString o(u.GetOptions());
Int_t locid = -1;
Bool_t create = kFALSE;
if (o.Length() > 0) {
if (o.BeginsWith("N",TString::kIgnoreCase)) {
create = kTRUE;
} else if (o.IsDigit()) {
locid = o.Atoi();
}
u.SetOptions("");
}
// Attach-to or create the appropriate manager
TProofMgr *mgr = TProofMgr::Create(u.GetUrl());
TProof *proof = 0;
if (mgr && mgr->IsValid()) {
// If XProofd we always attempt an attach first (unless
// explicitely not requested).
Bool_t attach = (create || mgr->IsProofd()) ? kFALSE : kTRUE;
if (attach) {
TProofDesc *d = 0;
if (locid < 0)
// Get the list of sessions
d = (TProofDesc *) mgr->QuerySessions("")->First();
else
d = (TProofDesc *) mgr->GetProofDesc(locid);
if (d) {
proof = (TProof*) mgr->AttachSession(d->GetLocalId());
if (!proof || !proof->IsValid()) {
if (locid)
::Error(pn, "new session could not be attached");
SafeDelete(proof);
}
}
}
// start the PROOF session
if (!proof) {
proof = (TProof*) mgr->CreateSession(conffile, confdir, loglevel);
if (!proof || !proof->IsValid()) {
::Error(pn, "new session could not be created");
SafeDelete(proof);
}
}
}
return proof;
}
}
//_____________________________________________________________________________
TProofMgr *TProof::Mgr(const char *url)
{
// Get instance of the effective manager for 'url'
// Return 0 on failure.
if (!url)
return (TProofMgr *)0;
// Attach or create the relevant instance
return TProofMgr::Create(url);
}
//_____________________________________________________________________________
void TProof::Reset(const char *url)
{
// Wrapper around TProofMgr::Reset().
if (url) {
TProofMgr *mgr = TProof::Mgr(url);
if (mgr && mgr->IsValid())
mgr->Reset();
else
::Error("TProof::Reset",
"unable to initialize a valid manager instance");
}
}
//_____________________________________________________________________________
const TList *TProof::GetEnvVars()
{
// Get environemnt variables.
return fgProofEnvList;
}
//_____________________________________________________________________________
void TProof::AddEnvVar(const char *name, const char *value)
{
// Add an variable to the list of environment variables passed to proofserv
// on the master and slaves
if (gDebug > 0) ::Info("TProof::AddEnvVar","%s=%s", name, value);
if (fgProofEnvList == 0) {
// initialize the list if needed
fgProofEnvList = new TList;
fgProofEnvList->SetOwner();
} else {
// replace old entries with the same name
TObject *o = fgProofEnvList->FindObject(name);
if (o != 0) {
fgProofEnvList->Remove(o);
}
}
fgProofEnvList->Add(new TNamed(name, value));
}
//_____________________________________________________________________________
void TProof::DelEnvVar(const char *name)
{
// Remove an variable from the list of environment variables passed to proofserv
// on the master and slaves
if (fgProofEnvList == 0) return;
TObject *o = fgProofEnvList->FindObject(name);
if (o != 0) {
fgProofEnvList->Remove(o);
}
}
//_____________________________________________________________________________
void TProof::ResetEnvVars()
{
// Clear the list of environment variables passed to proofserv
// on the master and slaves
if (fgProofEnvList == 0) return;
SafeDelete(fgProofEnvList);
}
//______________________________________________________________________________
void TProof::SaveWorkerInfo()
{
// Save informations about the worker set in the file .workers in the working
// dir. Called each time there is a change in the worker setup, e.g. by
// TProof::MarkBad().
// We must be masters
if (!IsMaster())
return;
// We must have a server defined
if (!gProofServ) {
Error("SaveWorkerInfo","gProofServ undefined");
return;
}
// Update info
const_cast<TProof*>(this)->AskStatistics();
// The relevant lists must be defined
if (!fSlaves && !fBadSlaves) {
Warning("SaveWorkerInfo","all relevant worker lists is undefined");
return;
}
// Create or truncate the file first
TString fnwrk = Form("%s/.workers",
gSystem->DirName(gProofServ->GetSessionDir()));
FILE *fwrk = fopen(fnwrk.Data(),"w");
if (!fwrk) {
Error("SaveWorkerInfo",
"cannot open %s for writing (errno: %d)", fnwrk.Data(), errno);
return;
}
// Loop over the list of workers (active is any worker not flagged as bad)
TIter nxa(fSlaves);
TSlave *wrk = 0;
while ((wrk = (TSlave *) nxa())) {
Int_t status = (fBadSlaves && fBadSlaves->FindObject(wrk)) ? 0 : 1;
// Write out record for this worker
fprintf(fwrk,"%s@%s:%d %d %s %s.log\n",
wrk->GetUser(), wrk->GetName(), wrk->GetPort(), status,
wrk->GetOrdinal(), wrk->GetWorkDir());
}
// Close file
fclose(fwrk);
// We are done
return;
}
temporary commenting out of TFileMerger.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@18328 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/proof:$Name: $:$Id: TProof.cxx,v 1.190 2007/03/19 01:36:56 rdm Exp $
// Author: Fons Rademakers 13/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProof //
// //
// This class controls a Parallel ROOT Facility, PROOF, cluster. //
// It fires the slave servers, it keeps track of how many slaves are //
// running, it keeps track of the slaves running status, it broadcasts //
// messages to all slaves, it collects results, etc. //
// //
//////////////////////////////////////////////////////////////////////////
#include <fcntl.h>
#include <errno.h>
#ifdef WIN32
# include <io.h>
# include <sys/stat.h>
# include <sys/types.h>
#else
# include <unistd.h>
#endif
#include <vector>
#ifdef R__HAVE_CONFIG
#include "RConfigure.h"
#endif
#include "Riostream.h"
#include "Getline.h"
#include "TBrowser.h"
#include "TChain.h"
#include "TCondor.h"
#include "TDSet.h"
#include "TError.h"
#include "TEnv.h"
#include "TEventList.h"
#include "TFile.h"
#include "TFileInfo.h"
#include "TFTP.h"
#include "TInterpreter.h"
#include "TMap.h"
#include "TMessage.h"
#include "TMonitor.h"
#include "TMutex.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TParameter.h"
#include "TProof.h"
#include "TProofNodeInfo.h"
#include "TVirtualProofPlayer.h"
#include "TProofServ.h"
#include "TPluginManager.h"
#include "TQueryResult.h"
#include "TRandom.h"
#include "TRegexp.h"
#include "TROOT.h"
#include "TSemaphore.h"
#include "TSlave.h"
#include "TSocket.h"
#include "TSortedList.h"
#include "TSystem.h"
#include "TThread.h"
#include "TTree.h"
#include "TUrl.h"
TProof *gProof = 0;
TVirtualMutex *gProofMutex = 0;
TList *TProof::fgProofEnvList = 0; // List of env vars for proofserv
ClassImp(TProof)
//----- Helper classes used for parallel startup -------------------------------
//______________________________________________________________________________
TProofThreadArg::TProofThreadArg(const char *h, Int_t po, const char *o,
Int_t pe, const char *i, const char *w,
TList *s, TProof *prf)
: fOrd(o), fPerf(pe), fImage(i), fWorkdir(w),
fSlaves(s), fProof(prf), fCslave(0), fClaims(0),
fType(TSlave::kSlave)
{
// Constructor
fUrl = new TUrl(Form("%s:%d",h,po));
}
//______________________________________________________________________________
TProofThreadArg::TProofThreadArg(TCondorSlave *csl, TList *clist,
TList *s, TProof *prf)
: fUrl(0), fOrd(0), fPerf(-1), fImage(0), fWorkdir(0),
fSlaves(s), fProof(prf), fCslave(csl), fClaims(clist),
fType(TSlave::kSlave)
{
// Constructor
if (csl) {
fUrl = new TUrl(Form("%s:%d",csl->fHostname.Data(),csl->fPort));
fImage = csl->fImage;
fOrd = csl->fOrdinal;
fWorkdir = csl->fWorkDir;
fPerf = csl->fPerfIdx;
}
}
//______________________________________________________________________________
TProofThreadArg::TProofThreadArg(const char *h, Int_t po, const char *o,
const char *i, const char *w, const char *m,
TList *s, TProof *prf)
: fOrd(o), fPerf(-1), fImage(i), fWorkdir(w),
fMsd(m), fSlaves(s), fProof(prf), fCslave(0), fClaims(0),
fType(TSlave::kSlave)
{
// Constructor
fUrl = new TUrl(Form("%s:%d",h,po));
}
//----- PROOF Interrupt signal handler -----------------------------------------
//______________________________________________________________________________
Bool_t TProofInterruptHandler::Notify()
{
// TProof interrupt handler.
Info("Notify","Processing interrupt signal ...");
// Stop any remote processing
fProof->StopProcess(kTRUE);
// Handle also interrupt condition on socket(s)
fProof->Interrupt(TProof::kLocalInterrupt);
return kTRUE;
}
//----- Input handler for messages from TProofServ -----------------------------
//______________________________________________________________________________
TProofInputHandler::TProofInputHandler(TProof *p, TSocket *s)
: TFileHandler(s->GetDescriptor(),1),
fSocket(s), fProof(p)
{
// Constructor
}
//______________________________________________________________________________
Bool_t TProofInputHandler::Notify()
{
// Handle input
fProof->CollectInputFrom(fSocket);
return kTRUE;
}
//------------------------------------------------------------------------------
ClassImp(TSlaveInfo)
//______________________________________________________________________________
Int_t TSlaveInfo::Compare(const TObject *obj) const
{
// Used to sort slaveinfos by ordinal.
if (!obj) return 1;
const TSlaveInfo *si = dynamic_cast<const TSlaveInfo*>(obj);
if (!si) return fOrdinal.CompareTo(obj->GetName());
const char *myord = GetOrdinal();
const char *otherord = si->GetOrdinal();
while (myord && otherord) {
Int_t myval = atoi(myord);
Int_t otherval = atoi(otherord);
if (myval < otherval) return 1;
if (myval > otherval) return -1;
myord = strchr(myord, '.');
if (myord) myord++;
otherord = strchr(otherord, '.');
if (otherord) otherord++;
}
if (myord) return -1;
if (otherord) return 1;
return 0;
}
//______________________________________________________________________________
void TSlaveInfo::Print(Option_t *opt) const
{
// Print slave info. If opt = "active" print only the active
// slaves, if opt="notactive" print only the not active slaves,
// if opt = "bad" print only the bad slaves, else
// print all slaves.
TString stat = fStatus == kActive ? "active" :
fStatus == kBad ? "bad" :
"not active";
TString msd = fMsd.IsNull() ? "<null>" : fMsd.Data();
if (!opt) opt = "";
if (!strcmp(opt, "active") && fStatus != kActive)
return;
if (!strcmp(opt, "notactive") && fStatus != kNotActive)
return;
if (!strcmp(opt, "bad") && fStatus != kBad)
return;
cout << "Slave: " << fOrdinal
<< " hostname: " << fHostName
<< " msd: " << msd
<< " perf index: " << fPerfIndex
<< " " << stat
<< endl;
}
//------------------------------------------------------------------------------
//______________________________________________________________________________
static char *CollapseSlashesInPath(const char *path)
{
// Get rid of spare slashes in a path. Returned path must be deleted[]
// by the user.
if (path) {
Int_t i = 1; // current index as we go along the string
Int_t j = 0; // current end of new path in newPath
char *newPath = new char [strlen(path) + 1];
newPath[0] = path[0];
while (path[i]) {
if (path[i] != '/' || newPath[j] != '/') {
j++;
newPath[j] = path[i];
}
i++;
}
if (newPath[j] != '/')
j++;
newPath[j] = 0; // We have to terminate the new path.
return newPath;
}
return 0;
}
ClassImp(TProof)
TSemaphore *TProof::fgSemaphore = 0;
//______________________________________________________________________________
TProof::TProof(const char *masterurl, const char *conffile, const char *confdir,
Int_t loglevel, const char *alias, TProofMgr *mgr)
: fUrl(masterurl)
{
// Create a PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). Masterurl is of
// the form: [proof[s]://]host[:port]. Conffile is the name of the config
// file describing the remote PROOF cluster (this argument alows you to
// describe different cluster configurations).
// The default is proof.conf. Confdir is the directory where the config
// file and other PROOF related files are (like motd and noproof files).
// Loglevel is the log level (default = 1). User specified custom config
// files will be first looked for in $HOME/.conffile.
// This may be needed during init
fManager = mgr;
// Default server type
fServType = TProofMgr::kXProofd;
// Default query mode
fQueryMode = kSync;
if (!conffile || strlen(conffile) == 0)
conffile = kPROOF_ConfFile;
if (!confdir || strlen(confdir) == 0)
confdir = kPROOF_ConfDir;
Init(masterurl, conffile, confdir, loglevel, alias);
// If called by a manager, make sure it stays in lasto position
// for cleaning
if (mgr) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(mgr);
gROOT->GetListOfSockets()->Add(mgr);
}
// Old-style server type: we add this to the list and set the global pointer
if (IsProofd() || IsMaster())
gROOT->GetListOfProofs()->Add(this);
// Still needed by the packetizers: needs to be changed
gProof = this;
}
//______________________________________________________________________________
TProof::TProof() : fUrl(""), fServType(TProofMgr::kXProofd)
{
// Protected constructor to be used by classes deriving from TProof
// (they have to call Init themselves and override StartSlaves
// appropriately).
//
// This constructor simply closes any previous gProof and sets gProof
// to this instance.
gROOT->GetListOfProofs()->Add(this);
gProof = this;
}
//______________________________________________________________________________
TProof::~TProof()
{
// Clean up PROOF environment.
while (TChain *chain = dynamic_cast<TChain*> (fChains->First()) ) {
// remove "chain" from list
chain->SetProof(0);
RemoveChain(chain);
}
// remove links to packages enabled on the client
if (!IsMaster()) {
// iterate over all packages
TIter nextpackage(fEnabledPackagesOnClient);
while (TObjString *package = dynamic_cast<TObjString*>(nextpackage())) {
FileStat_t stat;
gSystem->GetPathInfo(package->String(), stat);
// check if symlink, if so unlink
// NOTE: GetPathnfo() returns 1 in case of symlink that does not point to
// existing file or to a directory, but if fIsLink is true the symlink exists
if (stat.fIsLink)
gSystem->Unlink(package->String());
}
}
Close();
SafeDelete(fIntHandler);
SafeDelete(fSlaves);
SafeDelete(fActiveSlaves);
SafeDelete(fInactiveSlaves);
SafeDelete(fUniqueSlaves);
SafeDelete(fAllUniqueSlaves);
SafeDelete(fNonUniqueMasters);
SafeDelete(fBadSlaves);
SafeDelete(fAllMonitor);
SafeDelete(fActiveMonitor);
SafeDelete(fUniqueMonitor);
SafeDelete(fAllUniqueMonitor);
SafeDelete(fSlaveInfo);
SafeDelete(fChains);
SafeDelete(fPlayer);
SafeDelete(fFeedback);
SafeDelete(fWaitingSlaves);
SafeDelete(fAvailablePackages);
SafeDelete(fEnabledPackages);
SafeDelete(fEnabledPackagesOnClient);
SafeDelete(fPackageLock);
// remove file with redirected logs
if (!IsMaster()) {
if (fLogFileR)
fclose(fLogFileR);
if (fLogFileW)
fclose(fLogFileW);
if (fLogFileName.Length())
gSystem->Unlink(fLogFileName);
}
// For those interested in our destruction ...
Emit("~TProof()");
}
//______________________________________________________________________________
Int_t TProof::Init(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel, const char *alias)
{
// Start the PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). For a description
// of the arguments see the TProof ctor. Returns the number of started
// master or slave servers, returns 0 in case of error, in which case
// fValid remains false.
R__ASSERT(gSystem);
fValid = kFALSE;
if (strlen(fUrl.GetOptions()) > 0 && !(strncmp(fUrl.GetOptions(),"std",3))) {
fServType = TProofMgr::kProofd;
fUrl.SetOptions("");
}
if (!masterurl || !*masterurl) {
fUrl.SetProtocol("proof");
fUrl.SetHost("__master__");
} else if (!(strstr(masterurl, "://"))) {
fUrl.SetProtocol("proof");
}
if (fUrl.GetPort() == TUrl(" ").GetPort())
fUrl.SetPort(TUrl("proof:// ").GetPort());
// If in attach mode, options is filled with additiona info
Bool_t attach = kFALSE;
if (strlen(fUrl.GetOptions()) > 0) {
attach = kTRUE;
// A flag from the GUI
TString opts = fUrl.GetOptions();
if (opts.Contains("GUI")) {
SetBit(TProof::kUsingSessionGui);
opts.Remove(opts.Index("GUI"));
fUrl.SetOptions(opts);
}
}
if (strlen(fUrl.GetUser()) <= 0) {
// Get user logon name
UserGroup_t *pw = gSystem->GetUserInfo();
if (pw) {
fUrl.SetUser(pw->fUser);
delete pw;
}
}
// Make sure to store the FQDN, so to get a solid reference for
// subsequent checks (strings corresponding to non-existing hosts
// - like "__master__" - will not be touched by this)
if (!strlen(fUrl.GetHost()))
fMaster = gSystem->GetHostByName(gSystem->HostName()).GetHostName();
else
fMaster = gSystem->GetHostByName(fUrl.GetHost()).GetHostName();
fConfDir = confdir;
fConfFile = conffile;
fWorkDir = gSystem->WorkingDirectory();
fLogLevel = loglevel;
fProtocol = kPROOF_Protocol;
fMasterServ = (fMaster == "__master__") ? kTRUE : kFALSE;
fSendGroupView = kTRUE;
fImage = fMasterServ ? "" : "<local>";
fIntHandler = 0;
fStatus = 0;
fSlaveInfo = 0;
fChains = new TList;
fAvailablePackages = 0;
fEnabledPackages = 0;
fEndMaster = IsMaster() ? kTRUE : kFALSE;
// Default entry point for the data pool is the master
if (!IsMaster())
fDataPoolUrl.Form("root://%s", fMaster.Data());
else
fDataPoolUrl = "";
fProgressDialog = 0;
fProgressDialogStarted = kFALSE;
// Default alias is the master name
TString al = (alias) ? alias : fMaster.Data();
SetAlias(al);
// Client logging of messages from the master and slaves
fRedirLog = kFALSE;
if (!IsMaster()) {
fLogFileName = "ProofLog_";
if ((fLogFileW = gSystem->TempFileName(fLogFileName)) == 0)
Error("Init", "could not create temporary logfile");
if ((fLogFileR = fopen(fLogFileName, "r")) == 0)
Error("Init", "could not open temp logfile for reading");
}
fLogToWindowOnly = kFALSE;
// Status of cluster
fIdle = kTRUE;
// Query type
fSync = kTRUE;
// List of queries
fQueries = 0;
fOtherQueries = 0;
fDrawQueries = 0;
fMaxDrawQueries = 1;
fSeqNum = 0;
// Remote ID of the session
fSessionID = -1;
// Part of active query
fWaitingSlaves = 0;
// Make remote PROOF player
fPlayer = 0;
MakePlayer();
fFeedback = new TList;
fFeedback->SetOwner();
fFeedback->SetName("FeedbackList");
AddInput(fFeedback);
// sort slaves by descending performance index
fSlaves = new TSortedList(kSortDescending);
fActiveSlaves = new TList;
fInactiveSlaves = new TList;
fUniqueSlaves = new TList;
fAllUniqueSlaves = new TList;
fNonUniqueMasters = new TList;
fBadSlaves = new TList;
fAllMonitor = new TMonitor;
fActiveMonitor = new TMonitor;
fUniqueMonitor = new TMonitor;
fAllUniqueMonitor = new TMonitor;
fCurrentMonitor = 0;
fPackageLock = 0;
fEnabledPackagesOnClient = 0;
if (!IsMaster()) {
fPackageDir = kPROOF_WorkDir;
gSystem->ExpandPathName(fPackageDir);
if (gSystem->AccessPathName(fPackageDir)) {
if (gSystem->MakeDirectory(fPackageDir) == -1) {
Error("Init", "failure creating directory %s", fPackageDir.Data());
return 0;
}
}
fPackageDir += TString("/") + kPROOF_PackDir;
if (gSystem->AccessPathName(fPackageDir)) {
if (gSystem->MakeDirectory(fPackageDir) == -1) {
Error("Init", "failure creating directory %s", fPackageDir.Data());
return 0;
}
}
UserGroup_t *ug = gSystem->GetUserInfo();
fPackageLock = new TProofLockPath(Form("%s%s", kPROOF_PackageLockFile, ug->fUser.Data()));
delete ug;
fEnabledPackagesOnClient = new TList;
fEnabledPackagesOnClient->SetOwner();
}
// Master may want parallel startup
Bool_t parallelStartup = kFALSE;
if (!attach && IsMaster()) {
parallelStartup = gEnv->GetValue("Proof.ParallelStartup", kFALSE);
PDB(kGlobal,1) Info("Init", "Parallel Startup: %s",
parallelStartup ? "kTRUE" : "kFALSE");
if (parallelStartup) {
// Load thread lib, if not done already
#ifdef ROOTLIBDIR
TString threadLib = TString(ROOTLIBDIR) + "/libThread";
#else
TString threadLib = TString(gRootDir) + "/lib/libThread";
#endif
char *p;
if ((p = gSystem->DynamicPathName(threadLib, kTRUE))) {
delete[]p;
if (gSystem->Load(threadLib) == -1) {
Warning("Init",
"Cannot load libThread: switch to serial startup (%s)",
threadLib.Data());
parallelStartup = kFALSE;
}
} else {
Warning("Init",
"Cannot find libThread: switch to serial startup (%s)",
threadLib.Data());
parallelStartup = kFALSE;
}
// Get no of parallel requests and set semaphore correspondingly
Int_t parallelRequests = gEnv->GetValue("Proof.ParallelStartupRequests", 0);
if (parallelRequests > 0) {
PDB(kGlobal,1)
Info("Init", "Parallel Startup Requests: %d", parallelRequests);
fgSemaphore = new TSemaphore((UInt_t)(parallelRequests));
}
}
}
// Start slaves
if (!StartSlaves(parallelStartup, attach))
return 0;
if (fgSemaphore)
SafeDelete(fgSemaphore);
// we are now properly initialized
fValid = kTRUE;
// De-activate monitor (will be activated in Collect)
fAllMonitor->DeActivateAll();
// By default go into parallel mode
GoParallel(9999, attach);
// Send relevant initial state to slaves
if (!attach)
SendInitialState();
else if (!IsIdle())
// redirect log
fRedirLog = kTRUE;
// Done at this point, the alias will be communicated to the coordinator, if any
if (!IsMaster())
SetAlias(al);
SetActive(kFALSE);
if (IsValid()) {
// Activate input handler
ActivateAsyncInput();
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
void TProof::SetManager(TProofMgr *mgr)
{
// Set manager and schedule its destruction after this for clean
// operations.
fManager = mgr;
if (mgr) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(mgr);
gROOT->GetListOfSockets()->Add(mgr);
}
}
//______________________________________________________________________________
Bool_t TProof::StartSlaves(Bool_t parallel, Bool_t attach)
{
// Start up PROOF slaves.
// If this is a master server, find the config file and start slave
// servers as specified in the config file
if (IsMaster()) {
Int_t pc = 0;
TList *workerList = new TList;
// Get list of workers
if (gProofServ->GetWorkers(workerList, pc) == TProofServ::kQueryStop) {
Error("StartSlaves", "getting list of worker nodes");
return kFALSE;
}
fImage = gProofServ->GetImage();
// Get all workers
UInt_t nSlaves = workerList->GetSize();
UInt_t nSlavesDone = 0;
Int_t ord = 0;
// Init arrays for threads, if neeeded
std::vector<TProofThread *> thrHandlers;
if (parallel) {
thrHandlers.reserve(nSlaves);
if (thrHandlers.max_size() < nSlaves) {
PDB(kGlobal,1)
Info("StartSlaves","cannot reserve enough space for thread"
" handlers - switch to serial startup");
parallel = kFALSE;
}
}
// Loop over all workers and start them
TListIter next(workerList);
TObject *to;
TProofNodeInfo *worker;
while ((to = next())) {
// Get the next worker from the list
worker = (TProofNodeInfo *)to;
// Read back worker node info
const Char_t *image = worker->GetImage().Data();
const Char_t *workdir = worker->GetWorkDir().Data();
Int_t perfidx = worker->GetPerfIndex();
Int_t sport = worker->GetPort();
if (sport == -1)
sport = fUrl.GetPort();
// create slave server
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
if (parallel) {
// Prepare arguments
TProofThreadArg *ta =
new TProofThreadArg(worker->GetNodeName().Data(), sport,
fullord, perfidx, image, workdir,
fSlaves, this);
if (ta) {
// The type of the thread func makes it a detached thread
TThread *th = new TThread(SlaveStartupThread, ta);
if (!th) {
Info("StartSlaves","Can't create startup thread:"
" out of system resources");
SafeDelete(ta);
} else {
// Save in vector
thrHandlers.push_back(new TProofThread(th, ta));
// Run the thread
th->Run();
// Notify opening of connection
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Opening connections to workers") << nSlaves
<< nSlavesDone << kTRUE;
gProofServ->GetSocket()->Send(m);
}
} // end if (ta)
else {
Info("StartSlaves","Can't create thread arguments object:"
" out of system resources");
}
} // end if parallel
else {
// create slave server
TUrl u(Form("%s:%d",worker->GetNodeName().Data(), sport));
TSlave *slave = CreateSlave(u.GetUrl(), fullord, perfidx,
image, workdir);
// Add to global list (we will add to the monitor list after
// finalizing the server startup)
Bool_t slaveOk = kTRUE;
if (slave->IsValid()) {
fSlaves->Add(slave);
} else {
slaveOk = kFALSE;
fBadSlaves->Add(slave);
}
PDB(kGlobal,3)
Info("StartSlaves", "worker on host %s created"
" and added to list", worker->GetNodeName().Data());
// Notify opening of connection
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Opening connections to workers") << nSlaves
<< nSlavesDone << slaveOk;
gProofServ->GetSocket()->Send(m);
}
ord++;
} //end of worker loop
// Cleanup
SafeDelete(workerList);
nSlavesDone = 0;
if (parallel) {
// Wait completion of startup operations
std::vector<TProofThread *>::iterator i;
for (i = thrHandlers.begin(); i != thrHandlers.end(); ++i) {
TProofThread *pt = *i;
// Wait on this condition
if (pt && pt->fThread->GetState() == TThread::kRunningState) {
PDB(kGlobal,3)
Info("Init",
"parallel startup: waiting for worker %s (%s:%d)",
pt->fArgs->fOrd.Data(), pt->fArgs->fUrl->GetHost(),
pt->fArgs->fUrl->GetPort());
pt->fThread->Join();
}
// Notify end of startup operations
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Setting up worker servers") << nSlaves
<< nSlavesDone << kTRUE;
gProofServ->GetSocket()->Send(m);
}
TIter next(fSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *)next())) {
if (sl->IsValid())
fAllMonitor->Add(sl->GetSocket());
else
fBadSlaves->Add(sl);
}
// We can cleanup now
while (!thrHandlers.empty()) {
i = thrHandlers.end()-1;
if (*i) {
SafeDelete(*i);
thrHandlers.erase(i);
}
}
} else {
// Here we finalize the server startup: in this way the bulk
// of remote operations are almost parallelized
TIter nxsl(fSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *) nxsl())) {
// Finalize setup of the server
if (sl->IsValid())
sl->SetupServ(TSlave::kSlave, 0);
// Monitor good slaves
Bool_t slaveOk = kTRUE;
if (sl->IsValid()) {
fAllMonitor->Add(sl->GetSocket());
} else {
slaveOk = kFALSE;
fBadSlaves->Add(sl);
}
// Notify end of startup operations
nSlavesDone++;
TMessage m(kPROOF_SERVERSTARTED);
m << TString("Setting up worker servers") << nSlaves
<< nSlavesDone << slaveOk;
gProofServ->GetSocket()->Send(m);
}
}
} else {
// create master server
fprintf(stderr,"Starting master: opening connection ... \n");
TSlave *slave = CreateSubmaster(fUrl.GetUrl(), "0", "master", 0);
if (slave->IsValid()) {
// Notify
fprintf(stderr,"Starting master:"
" connection open: setting up server ... \r");
StartupMessage("Connection to master opened", kTRUE, 1, 1);
if (!attach) {
// Set worker interrupt handler
slave->SetInterruptHandler(kTRUE);
// Finalize setup of the server
slave->SetupServ(TSlave::kMaster, fConfFile);
if (slave->IsValid()) {
// Notify
fprintf(stderr,"Starting master: OK \n");
StartupMessage("Master started", kTRUE, 1, 1);
// check protocol compatibility
// protocol 1 is not supported anymore
if (fProtocol == 1) {
Error("StartSlaves",
"client and remote protocols not compatible (%d and %d)",
kPROOF_Protocol, fProtocol);
slave->Close("S");
delete slave;
return kFALSE;
}
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
// Unset worker interrupt handler
slave->SetInterruptHandler(kFALSE);
// Set interrupt PROOF handler from now on
fIntHandler = new TProofInterruptHandler(this);
Collect(slave);
Int_t slStatus = slave->GetStatus();
if (slStatus == -99 || slStatus == -98) {
fSlaves->Remove(slave);
fAllMonitor->Remove(slave->GetSocket());
if (slStatus == -99)
Error("StartSlaves", "not allowed to connect to PROOF master server");
else if (slStatus == -98)
Error("StartSlaves", "could not setup output redirection on master");
else
Error("StartSlaves", "setting up master");
slave->Close("S");
delete slave;
return 0;
}
if (!slave->IsValid()) {
fSlaves->Remove(slave);
fAllMonitor->Remove(slave->GetSocket());
slave->Close("S");
delete slave;
Error("StartSlaves",
"failed to setup connection with PROOF master server");
return kFALSE;
}
if (!gROOT->IsBatch()) {
if ((fProgressDialog =
gROOT->GetPluginManager()->FindHandler("TProofProgressDialog")))
if (fProgressDialog->LoadPlugin() == -1)
fProgressDialog = 0;
}
} else {
// Notify
fprintf(stderr,"Starting master: failure\n");
}
} else {
// Notify
if (attach) {
fprintf(stderr,"Starting master: OK \n");
StartupMessage("Master attached", kTRUE, 1, 1);
if (!gROOT->IsBatch()) {
if ((fProgressDialog =
gROOT->GetPluginManager()->FindHandler("TProofProgressDialog")))
if (fProgressDialog->LoadPlugin() == -1)
fProgressDialog = 0;
}
} else {
fprintf(stderr,"Starting manager: OK \n");
StartupMessage("Manager started", kTRUE, 1, 1);
}
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
fIntHandler = new TProofInterruptHandler(this);
}
} else {
delete slave;
Error("StartSlaves", "failed to connect to a PROOF master server");
return kFALSE;
}
}
return kTRUE;
}
//______________________________________________________________________________
void TProof::Close(Option_t *opt)
{
// Close all open slave servers.
// Client can decide to shutdown the remote session by passing option is 'S'
// or 's'. Default for clients is detach, if supported. Masters always
// shutdown the remote counterpart.
if (fSlaves) {
if (fIntHandler)
fIntHandler->Remove();
TIter nxs(fSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *)nxs()))
sl->Close(opt);
fActiveSlaves->Clear("nodelete");
fUniqueSlaves->Clear("nodelete");
fAllUniqueSlaves->Clear("nodelete");
fNonUniqueMasters->Clear("nodelete");
fBadSlaves->Clear("nodelete");
fSlaves->Delete();
}
{
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(this);
if (IsProofd()) {
gROOT->GetListOfProofs()->Remove(this);
if (gProof && gProof == this) {
// Set previous proofd-related as default
TIter pvp(gROOT->GetListOfProofs(), kIterBackward);
while ((gProof = (TProof *)pvp())) {
if (gProof->IsProofd())
break;
}
}
}
}
}
//______________________________________________________________________________
TSlave *TProof::CreateSlave(const char *url, const char *ord,
Int_t perf, const char *image, const char *workdir)
{
// Create a new TSlave of type TSlave::kSlave.
// Note: creation of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave* sl = TSlave::Create(url, ord, perf, image,
this, TSlave::kSlave, workdir, 0);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
// must set fParallel to 1 for slaves since they do not
// report their fParallel with a LOG_DONE message
sl->fParallel = 1;
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::CreateSubmaster(const char *url, const char *ord,
const char *image, const char *msd)
{
// Create a new TSlave of type TSlave::kMaster.
// Note: creation of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave *sl = TSlave::Create(url, ord, 100, image, this,
TSlave::kMaster, 0, msd);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::FindSlave(TSocket *s) const
{
// Find slave that has TSocket s. Returns 0 in case slave is not found.
TSlave *sl;
TIter next(fSlaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid() && sl->GetSocket() == s)
return sl;
}
return 0;
}
//______________________________________________________________________________
void TProof::FindUniqueSlaves()
{
// Add to the fUniqueSlave list the active slaves that have a unique
// (user) file system image. This information is used to transfer files
// only once to nodes that share a file system (an image). Submasters
// which are not in fUniqueSlaves are put in the fNonUniqueMasters
// list. That list is used to trigger the transferring of files to
// the submaster's unique slaves without the need to transfer the file
// to the submaster.
fUniqueSlaves->Clear();
fUniqueMonitor->RemoveAll();
fAllUniqueSlaves->Clear();
fAllUniqueMonitor->RemoveAll();
fNonUniqueMasters->Clear();
TIter next(fActiveSlaves);
while (TSlave *sl = dynamic_cast<TSlave*>(next())) {
if (fImage == sl->fImage) {
if (sl->GetSlaveType() == TSlave::kMaster) {
fNonUniqueMasters->Add(sl);
fAllUniqueSlaves->Add(sl);
fAllUniqueMonitor->Add(sl->GetSocket());
}
continue;
}
TIter next2(fUniqueSlaves);
TSlave *replace_slave = 0;
Bool_t add = kTRUE;
while (TSlave *sl2 = dynamic_cast<TSlave*>(next2())) {
if (sl->fImage == sl2->fImage) {
add = kFALSE;
if (sl->GetSlaveType() == TSlave::kMaster) {
if (sl2->GetSlaveType() == TSlave::kSlave) {
// give preference to master
replace_slave = sl2;
add = kTRUE;
} else if (sl2->GetSlaveType() == TSlave::kMaster) {
fNonUniqueMasters->Add(sl);
fAllUniqueSlaves->Add(sl);
fAllUniqueMonitor->Add(sl->GetSocket());
} else {
Error("FindUniqueSlaves", "TSlave is neither Master nor Slave");
R__ASSERT(0);
}
}
break;
}
}
if (add) {
fUniqueSlaves->Add(sl);
fAllUniqueSlaves->Add(sl);
fUniqueMonitor->Add(sl->GetSocket());
fAllUniqueMonitor->Add(sl->GetSocket());
if (replace_slave) {
fUniqueSlaves->Remove(replace_slave);
fAllUniqueSlaves->Remove(replace_slave);
fUniqueMonitor->Remove(replace_slave->GetSocket());
fAllUniqueMonitor->Remove(replace_slave->GetSocket());
}
}
}
// will be actiavted in Collect()
fUniqueMonitor->DeActivateAll();
fAllUniqueMonitor->DeActivateAll();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfSlaves() const
{
// Return number of slaves as described in the config file.
return fSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfActiveSlaves() const
{
// Return number of active slaves, i.e. slaves that are valid and in
// the current computing group.
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfInactiveSlaves() const
{
// Return number of inactive slaves, i.e. slaves that are valid but not in
// the current computing group.
return fInactiveSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfUniqueSlaves() const
{
// Return number of unique slaves, i.e. active slaves that have each a
// unique different user files system.
return fUniqueSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfBadSlaves() const
{
// Return number of bad slaves. This are slaves that we in the config
// file, but refused to startup or that died during the PROOF session.
return fBadSlaves->GetSize();
}
//______________________________________________________________________________
void TProof::AskStatistics()
{
// Ask the for the statistics of the slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETSTATS, kActive);
Collect(kActive);
}
//______________________________________________________________________________
void TProof::AskParallel()
{
// Ask the for the number of parallel slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETPARALLEL, kActive);
Collect(kActive);
}
//______________________________________________________________________________
TList *TProof::GetListOfQueries(Option_t *opt)
{
// Ask the master for the list of queries.
if (!IsValid() || IsMaster()) return (TList *)0;
Bool_t all = ((strchr(opt,'A') || strchr(opt,'a'))) ? kTRUE : kFALSE;
TMessage m(kPROOF_QUERYLIST);
m << all;
Broadcast(m, kActive);
Collect(kActive);
// This should have been filled by now
return fQueries;
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfQueries()
{
// Number of queries processed by this session
if (fQueries)
return fQueries->GetSize() - fOtherQueries;
return 0;
}
//______________________________________________________________________________
void TProof::SetMaxDrawQueries(Int_t max)
{
// Set max number of draw queries whose results are saved
if (max > 0) {
if (fPlayer)
fPlayer->SetMaxDrawQueries(max);
fMaxDrawQueries = max;
}
}
//______________________________________________________________________________
void TProof::GetMaxQueries()
{
// Get max number of queries whose full results are kept in the
// remote sandbox
TMessage m(kPROOF_MAXQUERIES);
m << kFALSE;
Broadcast(m, kActive);
Collect(kActive);
}
//______________________________________________________________________________
TList *TProof::GetQueryResults()
{
// Return pointer to the list of query results in the player
return fPlayer->GetListOfResults();
}
//______________________________________________________________________________
TQueryResult *TProof::GetQueryResult(const char *ref)
{
// Return pointer to the full TQueryResult instance owned by the player
// and referenced by 'ref'. If ref = 0 or "", return the last query result.
return fPlayer->GetQueryResult(ref);
}
//______________________________________________________________________________
void TProof::ShowQueries(Option_t *opt)
{
// Ask the master for the list of queries.
// Options:
// "A" show information about all the queries known to the
// server, i.e. even those processed by other sessions
// "L" show only information about queries locally available
// i.e. already retrieved. If "L" is specified, "A" is
// ignored.
// "F" show all details available about queries
// "H" print help menu
// Default ""
Bool_t help = ((strchr(opt,'H') || strchr(opt,'h'))) ? kTRUE : kFALSE;
if (help) {
// Help
Printf("+++");
Printf("+++ Options: \"A\" show all queries known to server");
Printf("+++ \"L\" show retrieved queries");
Printf("+++ \"F\" full listing of query info");
Printf("+++ \"H\" print this menu");
Printf("+++");
Printf("+++ (case insensitive)");
Printf("+++");
Printf("+++ Use Retrieve(<#>) to retrieve the full"
" query results from the master");
Printf("+++ e.g. Retrieve(8)");
Printf("+++");
return;
}
if (!IsValid()) return;
Bool_t local = ((strchr(opt,'L') || strchr(opt,'l'))) ? kTRUE : kFALSE;
TObject *pq = 0;
if (!local) {
GetListOfQueries(opt);
if (!fQueries) return;
TIter nxq(fQueries);
// Queries processed by other sessions
if (fOtherQueries > 0) {
Printf("+++");
Printf("+++ Queries processed during other sessions: %d", fOtherQueries);
Int_t nq = 0;
while (nq++ < fOtherQueries && (pq = nxq()))
pq->Print(opt);
}
// Queries processed by this session
Printf("+++");
Printf("+++ Queries processed during this session: selector: %d, draw: %d",
GetNumberOfQueries(), fDrawQueries);
while ((pq = nxq()))
pq->Print(opt);
} else {
// Queries processed by this session
Printf("+++");
Printf("+++ Queries processed during this session: selector: %d, draw: %d",
GetNumberOfQueries(), fDrawQueries);
// Queries available locally
TList *listlocal = fPlayer->GetListOfResults();
if (listlocal) {
Printf("+++");
Printf("+++ Queries available locally: %d", listlocal->GetSize());
TIter nxlq(listlocal);
while ((pq = nxlq()))
pq->Print(opt);
}
}
Printf("+++");
}
//______________________________________________________________________________
Bool_t TProof::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready)
{
// See if the data is ready to be analyzed.
if (!IsValid()) return kFALSE;
TList submasters;
TIter nextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) {
if (sl->GetSlaveType() == TSlave::kMaster) {
submasters.Add(sl);
}
}
fDataReady = kTRUE; //see if any submasters set it to false
fBytesReady = 0;
fTotalBytes = 0;
//loop over submasters and see if data is ready
if (submasters.GetSize() > 0) {
Broadcast(kPROOF_DATA_READY, &submasters);
Collect(&submasters);
}
bytesready = fBytesReady;
totalbytes = fTotalBytes;
EmitVA("IsDataReady(Long64_t,Long64_t)", 2, totalbytes, bytesready);
//PDB(kGlobal,2)
Info("IsDataReady", "%lld / %lld (%s)",
bytesready, totalbytes, fDataReady?"READY":"NOT READY");
return fDataReady;
}
//______________________________________________________________________________
void TProof::Interrupt(EUrgent type, ESlaves list)
{
// Send interrupt OOB byte to master or slave servers.
if (!IsValid()) return;
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
if (slaves->GetSize() == 0) return;
TSlave *sl;
TIter next(slaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
// Ask slave to progate the interrupt request
sl->Interrupt((Int_t)type);
}
}
}
//______________________________________________________________________________
Int_t TProof::GetParallel() const
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// iterate over active slaves and return total number of slaves
TIter nextSlave(GetListOfActiveSlaves());
Int_t nparallel = 0;
while (TSlave* sl = dynamic_cast<TSlave*>(nextSlave()))
if (sl->GetParallel() >= 0)
nparallel += sl->GetParallel();
return nparallel;
}
//______________________________________________________________________________
TList *TProof::GetSlaveInfo()
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return 0;
if (fSlaveInfo == 0) {
fSlaveInfo = new TSortedList(kSortDescending);
fSlaveInfo->SetOwner();
} else {
fSlaveInfo->Delete();
}
TList masters;
TIter next(GetListOfSlaves());
TSlave *slave;
while((slave = (TSlave *) next()) != 0) {
if (slave->GetSlaveType() == TSlave::kSlave) {
TSlaveInfo *slaveinfo = new TSlaveInfo(slave->GetOrdinal(),
slave->GetName(),
slave->GetPerfIdx());
fSlaveInfo->Add(slaveinfo);
TIter nextactive(GetListOfActiveSlaves());
TSlave *activeslave;
while ((activeslave = (TSlave *) nextactive())) {
if (TString(slaveinfo->GetOrdinal()) == activeslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kActive);
break;
}
}
TIter nextbad(GetListOfBadSlaves());
TSlave *badslave;
while ((badslave = (TSlave *) nextbad())) {
if (TString(slaveinfo->GetOrdinal()) == badslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kBad);
break;
}
}
} else if (slave->GetSlaveType() == TSlave::kMaster) {
if (slave->IsValid()) {
if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1)
MarkBad(slave);
else
masters.Add(slave);
}
} else {
Error("GetSlaveInfo", "TSlave is neither Master nor Slave");
R__ASSERT(0);
}
}
if (masters.GetSize() > 0) Collect(&masters);
return fSlaveInfo;
}
//______________________________________________________________________________
void TProof::Activate(TList *slaves)
{
// Activate slave server list.
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
slaves = !slaves ? fActiveSlaves : slaves;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave*) next())) {
if (sl->IsValid())
mon->Activate(sl->GetSocket());
}
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, TList *slaves)
{
// Broadcast a message to all slaves in the specified list. Returns
// the number of slaves the message was successfully sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->Send(mess) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, ESlaves list)
{
// Broadcast a message to all slaves in the specified list (either
// all slaves or only the active slaves). Returns the number of slaves
// the message was successfully sent to. Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, TList *slaves)
{
// Broadcast a character string buffer to all slaves in the specified
// list. Use kind to set the TMessage what field. Returns the number of
// slaves the message was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, ESlaves list)
{
// Broadcast a character string buffer to all slaves in the specified
// list (either all slaves or only the active slaves). Use kind to
// set the TMessage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, TList *slaves)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, ESlaves list)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, TList *slaves)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->SendRaw(buffer, length) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, ESlaves list)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
return BroadcastRaw(buffer, length, slaves);
}
//______________________________________________________________________________
Int_t TProof::Collect(const TSlave *sl, Long_t timeout)
{
// Collect responses from slave sl. Returns the number of slaves that
// responded (=1).
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
if (!sl->IsValid()) return 0;
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
mon->Activate(sl->GetSocket());
return Collect(mon, timeout);
}
//______________________________________________________________________________
Int_t TProof::Collect(TList *slaves, Long_t timeout)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave*) next())) {
if (sl->IsValid())
mon->Activate(sl->GetSocket());
}
return Collect(mon, timeout);
}
//______________________________________________________________________________
Int_t TProof::Collect(ESlaves list, Long_t timeout)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
TMonitor *mon = 0;
if (list == kAll) mon = fAllMonitor;
if (list == kActive) mon = fActiveMonitor;
if (list == kUnique) mon = fUniqueMonitor;
if (list == kAllUnique) mon = fAllUniqueMonitor;
mon->ActivateAll();
return Collect(mon, timeout);
}
//______________________________________________________________________________
Int_t TProof::Collect(TMonitor *mon, Long_t timeout)
{
// Collect responses from the slave servers. Returns the number of messages
// received. Can be 0 if there are no active slaves.
// If timeout >= 0, wait at most timeout seconds (timeout = -1 by default,
// which means wait forever).
fStatus = 0;
if (!mon->GetActive()) return 0;
DeActivateAsyncInput();
// Used by external code to know what we are monitoring
fCurrentMonitor = mon;
// We want messages on the main window during synchronous collection,
// but we save the present status to restore it at the end
Bool_t saveRedirLog = fRedirLog;
if (!IsIdle() && !IsSync())
fRedirLog = kFALSE;
int cnt = 0, rc = 0;
fBytesRead = 0;
fRealTime = 0.0;
fCpuTime = 0.0;
// Timeout counter
Long_t nto = timeout;
if (gDebug > 2)
Info("Collect","active: %d", mon->GetActive());
// On clients, handle Ctrl-C during collection
if (fIntHandler)
fIntHandler->Add();
while (mon->GetActive() && (nto < 0 || nto > 0)) {
// Wait for a ready socket
TSocket *s = mon->Select(1000);
if (s && s != (TSocket *)(-1)) {
// Get and analyse the info it did receive
if ((rc = CollectInputFrom(s)) == 1) {
// Deactivate it if we are done with it
mon->DeActivate(s);
if (gDebug > 2)
Info("Collect","deactivating %p (active: %d, %p)",
s, mon->GetActive(),
mon->GetListOfActives()->First());
}
// Update counter (if no error occured)
if (rc >= 0)
cnt++;
} else {
// If not timed-out, exit if not stopped or not aborted
// (player exits status is finished in such a case); otherwise,
// we still need to collect the partial output info
if (!s)
if (fPlayer && (fPlayer->GetExitStatus() == TVirtualProofPlayer::kFinished))
mon->DeActivateAll();
// Decrease the timeout counter if requested
if (s == (TSocket *)(-1) && nto > 0)
nto--;
}
}
// If timed-out, deactivate the remaining sockets
if (nto == 0)
mon->DeActivateAll();
// Deactivate Ctrl-C special handler
if (fIntHandler)
fIntHandler->Remove();
// make sure group view is up to date
SendGroupView();
// Restore redirection setting
fRedirLog = saveRedirLog;
// To avoid useless loops in external code
fCurrentMonitor = 0;
ActivateAsyncInput();
return cnt;
}
//______________________________________________________________________________
R__HIDDEN void TProof::CleanGDirectory(TList *ol)
{
// Remove links to objects in list 'ol' from gDirectory
if (ol) {
TIter nxo(ol);
TObject *o = 0;
while ((o = nxo()))
gDirectory->RecursiveRemove(o);
}
}
//______________________________________________________________________________
Int_t TProof::CollectInputFrom(TSocket *s)
{
// Collect and analyze available input from socket s.
// Returns 0 on success, -1 if any failure occurs.
TMessage *mess;
Int_t rc = 0;
char str[512];
TSlave *sl;
TObject *obj;
Int_t what;
Bool_t delete_mess = kTRUE;
if (s->Recv(mess) < 0) {
MarkBad(s);
return -1;
}
if (!mess) {
// we get here in case the remote server died
MarkBad(s);
return -1;
}
what = mess->What();
PDB(kGlobal,3) {
sl = FindSlave(s);
Info("CollectInputFrom","got %d from %s", what, (sl ? sl->GetOrdinal() : "undef"));
}
switch (what) {
case kMESS_OBJECT:
fPlayer->HandleRecvHisto(mess);
break;
case kPROOF_FATAL:
MarkBad(s);
break;
case kPROOF_GETOBJECT:
// send slave object it asks for
mess->ReadString(str, sizeof(str));
obj = gDirectory->Get(str);
if (obj)
s->SendObject(obj);
else
s->Send(kMESS_NOTOK);
break;
case kPROOF_GETPACKET:
{
TDSetElement *elem = 0;
sl = FindSlave(s);
elem = fPlayer->GetNextPacket(sl, mess);
if (elem != (TDSetElement*) -1) {
TMessage answ(kPROOF_GETPACKET);
answ << elem;
s->Send(answ);
while (fWaitingSlaves != 0 && fWaitingSlaves->GetSize()) {
TPair *p = (TPair*) fWaitingSlaves->First();
s = (TSocket*) p->Key();
sl = FindSlave(s);
TMessage *m = (TMessage*) p->Value();
elem = fPlayer->GetNextPacket(sl, m);
if (elem != (TDSetElement*) -1) {
TMessage a(kPROOF_GETPACKET);
a << elem;
s->Send(a);
// remove has to happen via Links because TPair does not have
// a Compare() function and therefore RemoveFirst() and
// Remove(TObject*) do not work
fWaitingSlaves->Remove(fWaitingSlaves->FirstLink());
delete p;
delete m;
} else {
break;
}
}
} else {
if (fWaitingSlaves == 0) fWaitingSlaves = new TList;
fWaitingSlaves->Add(new TPair(s, mess));
delete_mess = kFALSE;
}
}
break;
case kPROOF_LOGFILE:
{
Int_t size;
(*mess) >> size;
RecvLogFile(s, size);
}
break;
case kPROOF_LOGDONE:
sl = FindSlave(s);
(*mess) >> sl->fStatus >> sl->fParallel;
PDB(kGlobal,2)
Info("CollectInputFrom","kPROOF_LOGDONE:%s: status %d parallel %d",
sl->GetOrdinal(), sl->fStatus, sl->fParallel);
if (sl->fStatus != 0) fStatus = sl->fStatus; //return last nonzero status
rc = 1;
break;
case kPROOF_GETSTATS:
sl = FindSlave(s);
(*mess) >> sl->fBytesRead >> sl->fRealTime >> sl->fCpuTime
>> sl->fWorkDir >> sl->fProofWorkDir;
fBytesRead += sl->fBytesRead;
fRealTime += sl->fRealTime;
fCpuTime += sl->fCpuTime;
rc = 1;
break;
case kPROOF_GETPARALLEL:
sl = FindSlave(s);
(*mess) >> sl->fParallel;
rc = 1;
break;
case kPROOF_PACKAGE_LIST:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_PACKAGE_LIST: enter");
Int_t type = 0;
(*mess) >> type;
switch (type) {
case TProof::kListEnabledPackages:
SafeDelete(fEnabledPackages);
fEnabledPackages = (TList *) mess->ReadObject(TList::Class());
fEnabledPackages->SetOwner();
break;
case TProof::kListPackages:
SafeDelete(fAvailablePackages);
fAvailablePackages = (TList *) mess->ReadObject(TList::Class());
fAvailablePackages->SetOwner();
break;
default:
Info("CollectInputFrom","kPROOF_PACKAGE_LIST: unknown type: %d", type);
}
}
break;
case kPROOF_OUTPUTOBJECT:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_OUTPUTOBJECT: enter");
Int_t type = 0;
(*mess) >> type;
// If a query result header, add it to the player list
if (type == 0) {
// Retrieve query result instance (output list not filled)
TQueryResult *pq =
(TQueryResult *) mess->ReadObject(TQueryResult::Class());
if (pq) {
// Add query to the result list in TProofPlayer
fPlayer->AddQueryResult(pq);
fPlayer->SetCurrentQuery(pq);
// Add the unique query tag as TNamed object to the input list
// so that it is available in TSelectors for monitoring
fPlayer->AddInput(new TNamed("PROOF_QueryTag",
Form("%s:%s",pq->GetTitle(),pq->GetName())));
} else {
Warning("CollectInputFrom","kPROOF_OUTPUTOBJECT: query result missing");
}
} else if (type > 0) {
// Read object
TObject *obj = mess->ReadObject(TObject::Class());
// Add or merge it
if ((fPlayer->AddOutputObject(obj) == 1))
// Remove the object if it has been merged
SafeDelete(obj);
if (type > 1 && !IsMaster()) {
TQueryResult *pq = fPlayer->GetCurrentQuery();
pq->SetOutputList(fPlayer->GetOutputList(), kFALSE);
pq->SetInputList(fPlayer->GetInputList(), kFALSE);
// If the last object, notify the GUI that the result arrived
QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName()));
}
}
}
break;
case kPROOF_OUTPUTLIST:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_OUTPUTLIST: enter");
TList *out = 0;
if (IsMaster() || fProtocol < 7) {
out = (TList *) mess->ReadObject(TList::Class());
} else {
TQueryResult *pq =
(TQueryResult *) mess->ReadObject(TQueryResult::Class());
if (pq) {
// Add query to the result list in TProofPlayer
fPlayer->AddQueryResult(pq);
fPlayer->SetCurrentQuery(pq);
// To avoid accidental cleanups from anywhere else
// remove objects from gDirectory and clone the list
out = pq->GetOutputList();
CleanGDirectory(out);
out = (TList *) out->Clone();
// Notify the GUI that the result arrived
QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName()));
} else {
PDB(kGlobal,2)
Info("CollectInputFrom","kPROOF_OUTPUTLIST: query result missing");
}
}
if (out) {
out->SetOwner();
fPlayer->AddOutput(out); // Incorporate the list
SafeDelete(out);
} else {
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_OUTPUTLIST: ouputlist is empty");
}
// On clients at this point processing is over
if (!IsMaster()) {
// Handle abort ...
if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kAborted) {
if (fSync)
Info("CollectInputFrom",
"processing was aborted - %lld events processed",
fPlayer->GetEventsProcessed());
if (GetRemoteProtocol() > 11) {
// New format
Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.);
} else {
Progress(-1, fPlayer->GetEventsProcessed());
}
Emit("StopProcess(Bool_t)", kTRUE);
}
// Handle stop ...
if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kStopped) {
if (fSync)
Info("CollectInputFrom",
"processing was stopped - %lld events processed",
fPlayer->GetEventsProcessed());
if (GetRemoteProtocol() > 11) {
// New format
Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.);
} else {
Progress(-1, fPlayer->GetEventsProcessed());
}
Emit("StopProcess(Bool_t)", kFALSE);
}
// Final update of the dialog box
if (GetRemoteProtocol() > 11) {
// New format
EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t,)",
7, (Long64_t)(-1), (Long64_t)(-1), (Long64_t)(-1),
(Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.));
} else {
EmitVA("Progress(Long64_t,Long64_t)", 2, (Long64_t)(-1), (Long64_t)(-1));
}
}
}
break;
case kPROOF_QUERYLIST:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_QUERYLIST: enter");
(*mess) >> fOtherQueries >> fDrawQueries;
if (fQueries) {
fQueries->Delete();
delete fQueries;
fQueries = 0;
}
fQueries = (TList *) mess->ReadObject(TList::Class());
}
break;
case kPROOF_RETRIEVE:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_RETRIEVE: enter");
TQueryResult *pq =
(TQueryResult *) mess->ReadObject(TQueryResult::Class());
if (pq) {
fPlayer->AddQueryResult(pq);
// Notify the GUI that the result arrived
QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName()));
} else {
PDB(kGlobal,2)
Info("CollectInputFrom","kPROOF_RETRIEVE: query result missing");
}
}
break;
case kPROOF_MAXQUERIES:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_MAXQUERIES: enter");
Int_t max = 0;
(*mess) >> max;
Printf("Number of queries fully kept remotely: %d", max);
}
break;
case kPROOF_SERVERSTARTED:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_SERVERSTARTED: enter");
UInt_t tot = 0, done = 0;
TString action;
Bool_t st = kTRUE;
(*mess) >> action >> tot >> done >> st;
if (!IsMaster()) {
if (tot) {
TString type = (action.Contains("submas")) ? "submasters"
: "workers";
Int_t frac = (Int_t) (done*100.)/tot;
if (frac >= 100) {
fprintf(stderr,"%s: OK (%d %s) \n",
action.Data(),tot, type.Data());
} else {
fprintf(stderr,"%s: %d out of %d (%d %%)\r",
action.Data(), done, tot, frac);
}
}
// Notify GUIs
StartupMessage(action.Data(), st, (Int_t)done, (Int_t)tot);
} else {
// Just send the message one level up
TMessage m(kPROOF_SERVERSTARTED);
m << action << tot << done << st;
gProofServ->GetSocket()->Send(m);
}
}
break;
case kPROOF_DATASET_STATUS:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_DATASET_STATUS: enter");
UInt_t tot = 0, done = 0;
TString action;
Bool_t st = kTRUE;
(*mess) >> action >> tot >> done >> st;
if (!IsMaster()) {
if (tot) {
TString type = "files";
Int_t frac = (Int_t) (done*100.)/tot;
if (frac >= 100) {
fprintf(stderr,"%s: OK (%d %s) \n",
action.Data(),tot, type.Data());
} else {
fprintf(stderr,"%s: %d out of %d (%d %%)\r",
action.Data(), done, tot, frac);
}
}
// Notify GUIs
DataSetStatus(action.Data(), st, (Int_t)done, (Int_t)tot);
} else {
// Just send the message one level up
TMessage m(kPROOF_DATASET_STATUS);
m << action << tot << done << st;
gProofServ->GetSocket()->Send(m);
}
}
break;
case kPROOF_STARTPROCESS:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_STARTPROCESS: enter");
fIdle = kFALSE;
TString selec;
Int_t dsz = -1;
Long64_t first = -1, nent = -1;
(*mess) >> selec >> dsz >> first >> nent;
// Start or reset the progress dialog
if (fProgressDialog && !TestBit(kUsingSessionGui)) {
if (!fProgressDialogStarted) {
fProgressDialog->ExecPlugin(5, this,
selec.Data(), dsz, first, nent);
fProgressDialogStarted = kTRUE;
} else {
ResetProgressDialog(selec, dsz, first, nent);
}
}
ResetBit(kUsingSessionGui);
}
break;
case kPROOF_SETIDLE:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_SETIDLE: enter");
// The session is idle
fIdle = kTRUE;
}
break;
case kPROOF_QUERYSUBMITTED:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_QUERYSUBMITTED: enter");
// We have received the sequential number
(*mess) >> fSeqNum;
rc = 1;
}
break;
case kPROOF_SESSIONTAG:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_SESSIONTAG: enter");
// We have received the unique tag and save it as name of this object
TString stag;
(*mess) >> stag;
SetName(stag);
}
break;
case kPROOF_FEEDBACK:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_FEEDBACK: enter");
TList *out = (TList *) mess->ReadObject(TList::Class());
out->SetOwner();
sl = FindSlave(s);
if (fPlayer)
fPlayer->StoreFeedback(sl, out); // Adopts the list
else
// Not yet ready: stop collect asap
rc = 1;
}
break;
case kPROOF_AUTOBIN:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_AUTOBIN: enter");
TString name;
Double_t xmin, xmax, ymin, ymax, zmin, zmax;
(*mess) >> name >> xmin >> xmax >> ymin >> ymax >> zmin >> zmax;
fPlayer->UpdateAutoBin(name,xmin,xmax,ymin,ymax,zmin,zmax);
TMessage answ(kPROOF_AUTOBIN);
answ << name << xmin << xmax << ymin << ymax << zmin << zmax;
s->Send(answ);
}
break;
case kPROOF_PROGRESS:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_PROGRESS: enter");
sl = FindSlave(s);
if (GetRemoteProtocol() > 11) {
// New format
Long64_t total, processed, bytesread;
Float_t initTime, procTime, evtrti, mbrti;
(*mess) >> total >> processed >> bytesread
>> initTime >> procTime
>> evtrti >> mbrti;
fPlayer->Progress(total, processed, bytesread,
initTime, procTime, evtrti, mbrti);
} else {
// Old format
Long64_t total, processed;
(*mess) >> total >> processed;
fPlayer->Progress(sl, total, processed);
}
}
break;
case kPROOF_STOPPROCESS:
{
// answer contains number of processed events;
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_STOPPROCESS: enter");
Long64_t events;
Bool_t abort = kFALSE;
if ((mess->BufferSize() > mess->Length()) && (fProtocol > 8))
(*mess) >> events >> abort;
else
(*mess) >> events;
fPlayer->AddEventsProcessed(events);
if (!IsMaster())
Emit("StopProcess(Bool_t)", abort);
break;
}
case kPROOF_GETSLAVEINFO:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_GETSLAVEINFO: enter");
sl = FindSlave(s);
Bool_t active = (GetListOfActiveSlaves()->FindObject(sl) != 0);
Bool_t bad = (GetListOfBadSlaves()->FindObject(sl) != 0);
TList* tmpinfo = 0;
(*mess) >> tmpinfo;
tmpinfo->SetOwner(kFALSE);
Int_t nentries = tmpinfo->GetSize();
for (Int_t i=0; i<nentries; i++) {
TSlaveInfo* slinfo =
dynamic_cast<TSlaveInfo*>(tmpinfo->At(i));
if (slinfo) {
fSlaveInfo->Add(slinfo);
if (slinfo->fStatus != TSlaveInfo::kBad) {
if (!active) slinfo->SetStatus(TSlaveInfo::kNotActive);
if (bad) slinfo->SetStatus(TSlaveInfo::kBad);
}
if (!sl->GetMsd().IsNull()) slinfo->fMsd = sl->GetMsd();
}
}
delete tmpinfo;
rc = 1;
}
break;
case kPROOF_VALIDATE_DSET:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_VALIDATE_DSET: enter");
TDSet* dset = 0;
(*mess) >> dset;
if (!fDSet)
Error("CollectInputFrom","kPROOF_VALIDATE_DSET: fDSet not set");
else
fDSet->Validate(dset);
delete dset;
}
break;
case kPROOF_DATA_READY:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_DATA_READY: enter");
Bool_t dataready = kFALSE;
Long64_t totalbytes, bytesready;
(*mess) >> dataready >> totalbytes >> bytesready;
fTotalBytes += totalbytes;
fBytesReady += bytesready;
if (dataready == kFALSE) fDataReady = dataready;
}
break;
case kPROOF_PING:
// do nothing (ping is already acknowledged)
break;
case kPROOF_MESSAGE:
{
PDB(kGlobal,2) Info("CollectInputFrom","kPROOF_MESSAGE: enter");
// We have received the unique tag and save it as name of this object
TString msg;
(*mess) >> msg;
Bool_t lfeed = kTRUE;
if ((mess->BufferSize() > mess->Length()))
(*mess) >> lfeed;
if (!IsMaster()) {
// Notify locally taking care of redirection, windows logs, ...
NotifyLogMsg(msg, (lfeed ? "\n" : "\r"));
} else {
// Just send the message one level up
TMessage m(kPROOF_MESSAGE);
m << msg << lfeed;
gProofServ->GetSocket()->Send(m);
}
}
break;
default:
Error("Collect", "unknown command received from slave (what = %d)", what);
break;
}
// Cleanup
if (delete_mess)
delete mess;
// We are done successfully
return rc;
}
//______________________________________________________________________________
void TProof::ActivateAsyncInput()
{
// Activate the a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Add();
}
//______________________________________________________________________________
void TProof::DeActivateAsyncInput()
{
// De-actiate a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Remove();
}
//______________________________________________________________________________
void TProof::HandleAsyncInput(TSocket *sl)
{
// Handle input coming from the master server (when this is a client)
// or from a slave server (when this is a master server). This is mainly
// for a-synchronous communication. Normally when PROOF issues a command
// the (slave) server messages are directly handle by Collect().
TMessage *mess;
Int_t what;
if (sl->Recv(mess) <= 0)
return; // do something more intelligent here
what = mess->What();
switch (what) {
case kPROOF_PING:
// do nothing (ping is already acknowledged)
break;
default:
Error("HandleAsyncInput", "unknown command (what = %d)", what);
break;
}
delete mess;
}
//______________________________________________________________________________
void TProof::MarkBad(TSlave *sl)
{
// Add a bad slave server to the bad slave list and remove it from
// the active list and from the two monitor objects.
fActiveSlaves->Remove(sl);
FindUniqueSlaves();
fBadSlaves->Add(sl);
fAllMonitor->Remove(sl->GetSocket());
fActiveMonitor->Remove(sl->GetSocket());
sl->Close();
fSendGroupView = kTRUE;
// Update session workers files
SaveWorkerInfo();
}
//______________________________________________________________________________
void TProof::MarkBad(TSocket *s)
{
// Add slave with socket s to the bad slave list and remove if from
// the active list and from the two monitor objects.
TSlave *sl = FindSlave(s);
MarkBad(sl);
}
//______________________________________________________________________________
Int_t TProof::Ping()
{
// Ping PROOF. Returns 1 if master server responded.
return Ping(kActive);
}
//______________________________________________________________________________
Int_t TProof::Ping(ESlaves list)
{
// Ping PROOF slaves. Returns the number of slaves that responded.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (list == kAllUnique) slaves = fAllUniqueSlaves;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->Ping() == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
void TProof::Print(Option_t *option) const
{
// Print status of PROOF cluster.
TString secCont;
if (!IsMaster()) {
Printf("Connected to: %s (%s)", GetMaster(),
IsValid() ? "valid" : "invalid");
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
TSlave *sl = (TSlave *)fActiveSlaves->First();
if (sl) {
TString sc;
if (sl->GetSocket()->GetSecContext())
Printf("Security context: %s",
sl->GetSocket()->GetSecContext()->AsString(sc));
Printf("Proofd protocol version: %d", sl->GetSocket()->GetRemoteProtocol());
} else {
Printf("Security context: Error - No connection");
Printf("Proofd protocol version: Error - No connection");
}
Printf("Client protocol version: %d", GetClientProtocol());
Printf("Remote protocol version: %d", GetRemoteProtocol());
Printf("Log level: %d", GetLogLevel());
Printf("Session unique tag: %s", IsValid() ? GetSessionTag() : "");
Printf("Default data pool: %s", IsValid() ? GetDataPoolUrl() : "");
if (IsValid())
const_cast<TProof*>(this)->SendPrint(option);
} else {
const_cast<TProof*>(this)->AskStatistics();
if (IsParallel())
Printf("*** Master server %s (parallel mode, %d slaves):",
gProofServ->GetOrdinal(), GetParallel());
else
Printf("*** Master server %s (sequential mode):",
gProofServ->GetOrdinal());
Printf("Master host name: %s", gSystem->HostName());
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
Printf("Protocol version: %d", GetClientProtocol());
Printf("Image name: %s", GetImage());
Printf("Working directory: %s", gSystem->WorkingDirectory());
Printf("Config directory: %s", GetConfDir());
Printf("Config file: %s", GetConfFile());
Printf("Log level: %d", GetLogLevel());
Printf("Number of workers: %d", GetNumberOfSlaves());
Printf("Number of active workers: %d", GetNumberOfActiveSlaves());
Printf("Number of unique workers: %d", GetNumberOfUniqueSlaves());
Printf("Number of inactive workers: %d", GetNumberOfInactiveSlaves());
Printf("Number of bad workers: %d", GetNumberOfBadSlaves());
Printf("Total MB's processed: %.2f", float(GetBytesRead())/(1024*1024));
Printf("Total real time used (s): %.3f", GetRealTime());
Printf("Total CPU time used (s): %.3f", GetCpuTime());
if (TString(option).Contains("a", TString::kIgnoreCase) && GetNumberOfSlaves()) {
Printf("List of workers:");
TList masters;
TIter nextslave(fSlaves);
while (TSlave* sl = dynamic_cast<TSlave*>(nextslave())) {
if (!sl->IsValid()) continue;
if (sl->GetSlaveType() == TSlave::kSlave) {
sl->Print(option);
} else if (sl->GetSlaveType() == TSlave::kMaster) {
TMessage mess(kPROOF_PRINT);
mess.WriteString(option);
if (sl->GetSocket()->Send(mess) == -1)
const_cast<TProof*>(this)->MarkBad(sl);
else
masters.Add(sl);
} else {
Error("Print", "TSlave is neither Master nor Worker");
R__ASSERT(0);
}
}
const_cast<TProof*>(this)->Collect(&masters);
}
}
}
//______________________________________________________________________________
Long64_t TProof::Process(TDSet *dset, const char *selector, Option_t *option,
Long64_t nentries, Long64_t first, TEventList *evl)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// The return value is -1 in case of error and TSelector::GetStatus() in
// in case of success.
if (!IsValid()) return -1;
// Resolve query mode
fSync = (GetQueryMode(option) == kSync);
if (fSync && !IsIdle()) {
Info("Process","not idle, cannot submit synchronous query");
return -1;
}
// deactivate the default application interrupt handler
// ctrl-c's will be forwarded to PROOF to stop the processing
TSignalHandler *sh = 0;
if (fSync) {
if (gApplication)
sh = gSystem->RemoveSignalHandler(gApplication->GetSignalHandler());
}
Long64_t rv = fPlayer->Process(dset, selector, option, nentries, first, evl);
// // Clear input list
// fPlayer->ClearInput();
if (fSync) {
// reactivate the default application interrupt handler
if (sh)
gSystem->AddSignalHandler(sh);
}
return rv;
}
//______________________________________________________________________________
Int_t TProof::GetQueryReference(Int_t qry, TString &ref)
{
// Get reference for the qry-th query in fQueries (as
// displayed by ShowQueries).
ref = "";
if (qry > 0) {
if (!fQueries)
GetListOfQueries();
if (fQueries) {
TIter nxq(fQueries);
TQueryResult *qr = 0;
while ((qr = (TQueryResult *) nxq()))
if (qr->GetSeqNum() == qry) {
ref = Form("%s:%s", qr->GetTitle(), qr->GetName());
return 0;
}
}
}
return -1;
}
//______________________________________________________________________________
Long64_t TProof::Finalize(Int_t qry, Bool_t force)
{
// Finalize the qry-th query in fQueries.
// If force, force retrieval if the query is found in the local list
// but has already been finalized (default kFALSE).
// If query < 0, finalize current query.
// Return 0 on success, -1 on error
if (fPlayer) {
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0) {
return Finalize(ref, force);
} else {
Info("Finalize", "query #%d not found", qry);
}
} else {
// The last query
return fPlayer->Finalize(force);
}
}
return -1;
}
//______________________________________________________________________________
Long64_t TProof::Finalize(const char *ref, Bool_t force)
{
// Finalize query with reference ref.
// If force, force retrieval if the query is found in the local list
// but has already been finalized (default kFALSE).
// If ref = 0, finalize current query.
// Return 0 on success, -1 on error
if (fPlayer) {
if (ref) {
// Get the pointer to the query
TQueryResult *qr = fPlayer->GetQueryResult(ref);
// If not found, try retrieving it
Bool_t retrieve = kFALSE;
if (!qr) {
retrieve = kTRUE;
} else {
if (qr->IsFinalized()) {
if (force) {
retrieve = kTRUE;
} else {
Info("Finalize","query already finalized:"
" use Finalize(<qry>,kTRUE) to force new retrieval");
qr = 0;
}
}
}
if (retrieve) {
Retrieve(ref);
qr = fPlayer->GetQueryResult(ref);
}
if (qr)
return fPlayer->Finalize(qr);
}
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Retrieve(Int_t qry, const char *path)
{
// Send retrieve request for the qry-th query in fQueries.
// If path is defined save it to path.
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0)
return Retrieve(ref, path);
else
Info("Retrieve", "query #%d not found", qry);
} else {
Info("Retrieve","positive argument required - do nothing");
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Retrieve(const char *ref, const char *path)
{
// Send retrieve request for the query specified by ref.
// If path is defined save it to path.
// Generic method working for all queries known by the server.
if (ref) {
TMessage m(kPROOF_RETRIEVE);
m << TString(ref);
Broadcast(m, kActive);
Collect(kActive);
// Archive ir locally, if required
if (path) {
// Get pointer to query
TQueryResult *qr = fPlayer ? fPlayer->GetQueryResult(ref) : 0;
if (qr) {
TFile *farc = TFile::Open(path,"UPDATE");
if (!(farc->IsOpen())) {
Info("Retrieve", "archive file cannot be open (%s)", path);
return 0;
}
farc->cd();
// Update query status
qr->SetArchived(path);
// Write to file
qr->Write();
farc->Close();
SafeDelete(farc);
} else {
Info("Retrieve", "query not found after retrieve");
return -1;
}
}
return 0;
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Remove(Int_t qry, Bool_t all)
{
// Send remove request for the qry-th query in fQueries.
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0)
return Remove(ref, all);
else
Info("Remove", "query #%d not found", qry);
} else {
Info("Remove","positive argument required - do nothing");
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Remove(const char *ref, Bool_t all)
{
// Send remove request for the query specified by ref.
// If all = TRUE remove also local copies of the query, if any.
// Generic method working for all queries known by the server.
// This method can be also used to reset the list of queries
// waiting to be processed: for that purpose use ref == "cleanupqueue".
if (all) {
// Remove also local copies, if any
if (fPlayer)
fPlayer->RemoveQueryResult(ref);
}
if (ref) {
TMessage m(kPROOF_REMOVE);
m << TString(ref);
Broadcast(m, kActive);
Collect(kActive);
return 0;
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Archive(Int_t qry, const char *path)
{
// Send archive request for the qry-th query in fQueries.
if (qry > 0) {
TString ref;
if (GetQueryReference(qry, ref) == 0)
return Archive(ref, path);
else
Info("Archive", "query #%d not found", qry);
} else {
Info("Archive","positive argument required - do nothing");
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::Archive(const char *ref, const char *path)
{
// Send archive request for the query specified by ref.
// Generic method working for all queries known by the server.
// If ref == "Default", path is understood as a default path for
// archiving.
if (ref) {
TMessage m(kPROOF_ARCHIVE);
m << TString(ref) << TString(path);
Broadcast(m, kActive);
Collect(kActive);
return 0;
}
return -1;
}
//______________________________________________________________________________
Int_t TProof::CleanupSession(const char *sessiontag)
{
// Send cleanup request for the session specified by tag.
if (sessiontag) {
TMessage m(kPROOF_CLEANUPSESSION);
m << TString(sessiontag);
Broadcast(m, kActive);
Collect(kActive);
return 0;
}
return -1;
}
//_____________________________________________________________________________
void TProof::SetQueryMode(EQueryMode mode)
{
// Change query running mode to the one specified by 'mode'.
fQueryMode = mode;
if (gDebug > 0)
Info("SetQueryMode","query mode is set to: %s", fQueryMode == kSync ?
"Sync" : "Async");
}
//______________________________________________________________________________
TProof::EQueryMode TProof::GetQueryMode(Option_t *mode) const
{
// Find out the query mode based on the current setting and 'mode'.
EQueryMode qmode = fQueryMode;
if (mode && (strlen(mode) > 0)) {
TString m(mode);
m.ToUpper();
if (m.Contains("ASYN")) {
qmode = kAsync;
} else if (m.Contains("SYNC")) {
qmode = kSync;
}
}
if (gDebug > 0)
Info("GetQueryMode","query mode is set to: %s", qmode == kSync ?
"Sync" : "Async");
return qmode;
}
//______________________________________________________________________________
Long64_t TProof::DrawSelect(TDSet *dset, const char *varexp, const char *selection, Option_t *option,
Long64_t nentries, Long64_t first)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error or number of selected events in case of success.
if (!IsValid()) return -1;
// Make sure that asynchronous processing is not active
if (!IsIdle()) {
Info("DrawSelect","not idle, asynchronous Draw not supported");
return -1;
}
TString opt(option);
Int_t idx = opt.Index("ASYN", 0, TString::kIgnoreCase);
if (idx != kNPOS)
opt.Replace(idx,4,"");
return fPlayer->DrawSelect(dset, varexp, selection, opt, nentries, first);
}
//______________________________________________________________________________
void TProof::StopProcess(Bool_t abort, Int_t timeout)
{
// Send STOPPROCESS message to master and workers.
PDB(kGlobal,2)
Info("StopProcess","enter %d", abort);
if (!IsValid())
return;
if (fPlayer)
fPlayer->StopProcess(abort, timeout);
// Stop any blocking 'Collect' request
if (!IsMaster())
InterruptCurrentMonitor();
if (fSlaves->GetSize() == 0)
return;
// Notify the remote counterpart
TSlave *sl;
TIter next(fSlaves);
while ((sl = (TSlave *)next()))
if (sl->IsValid())
// Ask slave to progate the stop/abort request
sl->StopProcess(abort, timeout);
}
//______________________________________________________________________________
void TProof::RecvLogFile(TSocket *s, Int_t size)
{
// Receive the log file of the slave with socket s.
const Int_t kMAXBUF = 16384; //32768 //16384 //65536;
char buf[kMAXBUF];
// Append messages to active logging unit
Int_t fdout = -1;
if (!fLogToWindowOnly) {
fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout);
if (fdout < 0) {
Warning("RecvLogFile", "file descriptor for outputs undefined (%d):"
" will not log msgs", fdout);
return;
}
lseek(fdout, (off_t) 0, SEEK_END);
}
Int_t left, rec, r;
Long_t filesize = 0;
while (filesize < size) {
left = Int_t(size - filesize);
if (left > kMAXBUF)
left = kMAXBUF;
rec = s->RecvRaw(&buf, left);
filesize = (rec > 0) ? (filesize + rec) : filesize;
if (!fLogToWindowOnly) {
if (rec > 0) {
char *p = buf;
r = rec;
while (r) {
Int_t w;
w = write(fdout, p, r);
if (w < 0) {
SysError("RecvLogFile", "error writing to unit: %d", fdout);
break;
}
r -= w;
p += w;
}
} else if (rec < 0) {
Error("RecvLogFile", "error during receiving log file");
break;
}
}
if (rec > 0) {
buf[rec] = 0;
EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE);
}
}
// If idle restore logs to main session window
if (fRedirLog && IsIdle())
fRedirLog = kFALSE;
}
//______________________________________________________________________________
void TProof::NotifyLogMsg(const char *msg, const char *sfx)
{
// Notify locally 'msg' to the appropriate units (file, stdout, window)
// If defined, 'sfx' is added after 'msg' (typically a line-feed);
// Must have somenthing to notify
Int_t len = 0;
if (!msg || (len = strlen(msg)) <= 0)
return;
// Get suffix length if any
Int_t lsfx = (sfx) ? strlen(sfx) : 0;
// Append messages to active logging unit
Int_t fdout = -1;
if (!fLogToWindowOnly) {
fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout);
if (fdout < 0) {
Warning("NotifyLogMsg", "file descriptor for outputs undefined (%d):"
" will not notify msgs", fdout);
return;
}
lseek(fdout, (off_t) 0, SEEK_END);
}
if (!fLogToWindowOnly) {
// Write to output unit (stdout or a log file)
if (len > 0) {
char *p = (char *)msg;
Int_t r = len;
while (r) {
Int_t w = write(fdout, p, r);
if (w < 0) {
SysError("NotifyLogMsg", "error writing to unit: %d", fdout);
break;
}
r -= w;
p += w;
}
// Add a suffix, if requested
if (lsfx > 0)
write(fdout, sfx, lsfx);
}
}
if (len > 0) {
// Publish the message to the separate window (if the latter is missing
// the message will just get lost)
EmitVA("LogMessage(const char*,Bool_t)", 2, msg, kFALSE);
}
// If idle restore logs to main session window
if (fRedirLog && IsIdle())
fRedirLog = kFALSE;
}
//______________________________________________________________________________
void TProof::LogMessage(const char *msg, Bool_t all)
{
// Log a message into the appropriate window by emitting a signal.
PDB(kGlobal,1)
Info("LogMessage","Enter ... %s, 'all: %s", msg ? msg : "",
all ? "true" : "false");
if (gROOT->IsBatch()) {
PDB(kGlobal,1) Info("LogMessage","GUI not started - use TProof::ShowLog()");
return;
}
if (msg)
EmitVA("LogMessage(const char*,Bool_t)", 2, msg, all);
// Re-position at the beginning of the file, if requested.
// This is used by the dialog when it re-opens the log window to
// provide all the session messages
if (all)
lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET);
const Int_t kMAXBUF = 32768;
char buf[kMAXBUF];
Int_t len;
do {
while ((len = read(fileno(fLogFileR), buf, kMAXBUF-1)) < 0 &&
TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
Error("LogMessage", "error reading log file");
break;
}
if (len > 0) {
buf[len] = 0;
EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE);
}
} while (len > 0);
}
//______________________________________________________________________________
Int_t TProof::SendGroupView()
{
// Send to all active slaves servers the current slave group size
// and their unique id. Returns number of active slaves.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (!IsMaster()) return 0;
if (!fSendGroupView) return 0;
fSendGroupView = kFALSE;
TIter next(fActiveSlaves);
TSlave *sl;
int bad = 0, cnt = 0, size = GetNumberOfActiveSlaves();
char str[32];
while ((sl = (TSlave *)next())) {
sprintf(str, "%d %d", cnt, size);
if (sl->GetSocket()->Send(str, kPROOF_GROUPVIEW) == -1) {
MarkBad(sl);
bad++;
} else
cnt++;
}
// Send the group view again in case there was a change in the
// group size due to a bad slave
if (bad) SendGroupView();
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Int_t TProof::Exec(const char *cmd, Bool_t plusMaster)
{
// Send command to be executed on the PROOF master and/or slaves.
// If plusMaster is kTRUE then exeucte on slaves and master too.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
return Exec(cmd, kActive, plusMaster);
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::Exec(const char *cmd, ESlaves list, Bool_t plusMaster)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
if (!IsValid()) return -1;
TString s = cmd;
s = s.Strip(TString::kBoth);
if (!s.Length()) return 0;
// check for macro file and make sure the file is available on all slaves
if (s.BeginsWith(".L") || s.BeginsWith(".x") || s.BeginsWith(".X")) {
TString file = s(2, s.Length());
TString acm, arg, io;
TString filename = gSystem->SplitAclicMode(file, acm, arg, io);
char *fn = gSystem->Which(TROOT::GetMacroPath(), filename, kReadPermission);
if (fn) {
if (GetNumberOfUniqueSlaves() > 0) {
if (SendFile(fn, kAscii | kForward) < 0) {
Error("Exec", "file %s could not be transfered", fn);
delete [] fn;
return -1;
}
} else {
TString scmd = s(0,3) + fn;
Int_t n = SendCommand(scmd, list);
delete [] fn;
return n;
}
} else {
Error("Exec", "macro %s not found", file.Data());
return -1;
}
delete [] fn;
}
if (plusMaster) {
Int_t n = GetParallel();
SetParallelSilent(0);
Int_t res = SendCommand(cmd, list);
SetParallelSilent(n);
if (res < 0)
return res;
}
return SendCommand(cmd, list);
}
//______________________________________________________________________________
Int_t TProof::SendCommand(const char *cmd, ESlaves list)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command, however commands
// like ".x file.C" or ".L file.C" will not cause the file.C to be
// transfered to the PROOF cluster. In that case use TProof::Exec().
// Returns the status send by the remote server as part of the
// kPROOF_LOGDONE message. Typically this is the return code of the
// command on the remote side. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(cmd, kMESS_CINT, list);
Collect(list);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::SendCurrentState(ESlaves list)
{
// Transfer the current state of the master to the active slave servers.
// The current state includes: the current working directory, etc.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// Go to the new directory, reset the interpreter environment and
// tell slave to delete all objects from its new current directory.
Broadcast(gDirectory->GetPath(), kPROOF_RESET, list);
return GetParallel();
}
//______________________________________________________________________________
Int_t TProof::SendInitialState()
{
// Transfer the initial (i.e. current) state of the master to all
// slave servers. Currently the initial state includes: log level.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
SetLogLevel(fLogLevel, gProofDebugMask);
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Bool_t TProof::CheckFile(const char *file, TSlave *slave, Long_t modtime)
{
// Check if a file needs to be send to the slave. Use the following
// algorithm:
// - check if file appears in file map
// - if yes, get file's modtime and check against time in map,
// if modtime not same get md5 and compare against md5 in map,
// if not same return kTRUE.
// - if no, get file's md5 and modtime and store in file map, ask
// slave if file exists with specific md5, if yes return kFALSE,
// if no return kTRUE.
// Returns kTRUE in case file needs to be send, returns kFALSE in case
// file is already on remote node.
Bool_t sendto = kFALSE;
// create slave based filename
TString sn = slave->GetName();
sn += ":";
sn += slave->GetOrdinal();
sn += ":";
sn += gSystem->BaseName(file);
// check if file is in map
FileMap_t::const_iterator it;
if ((it = fFileMap.find(sn)) != fFileMap.end()) {
// file in map
MD5Mod_t md = (*it).second;
if (md.fModtime != modtime) {
TMD5 *md5 = TMD5::FileChecksum(file);
if (md5) {
if ((*md5) != md.fMD5) {
sendto = kTRUE;
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
// When on the master, the master and/or slaves may share
// their file systems and cache. Therefore always make a
// check for the file. If the file already exists with the
// expected md5 the kPROOF_CHECKFILE command will cause the
// file to be copied from cache to slave sandbox.
if (IsMaster()) {
sendto = kFALSE;
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
}
delete md5;
} else {
Error("CheckFile", "could not calculate local MD5 check sum - dont send");
return kFALSE;
}
}
} else {
// file not in map
TMD5 *md5 = TMD5::FileChecksum(file);
MD5Mod_t md;
if (md5) {
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
delete md5;
} else {
Error("CheckFile", "could not calculate local MD5 check sum - dont send");
return kFALSE;
}
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
return sendto;
}
//______________________________________________________________________________
Int_t TProof::SendFile(const char *file, Int_t opt, const char *rfile, TSlave *wrk)
{
// Send a file to master or slave servers. Returns number of slaves
// the file was sent to, maybe 0 in case master and slaves have the same
// file system image, -1 in case of error.
// If defined, send to worker 'wrk' only.
// If defined, the full path of the remote path will be rfile.
// The mask 'opt' is an or of ESendFileOpt:
//
// kAscii (0x0) if set true ascii file transfer is used
// kBinary (0x1) if set true binary file transfer is used
// kForce (0x2) if not set an attempt is done to find out
// whether the file really needs to be downloaded
// (a valid copy may already exist in the cache
// from a previous run); the bit is set by
// UploadPackage, since the check is done elsewhere.
// kForward (0x4) if set, ask server to forward the file to slave
// or submaster (meaningless for slave servers).
//
if (!IsValid()) return -1;
// Use the active slaves list ...
TList *slaves = fActiveSlaves;
// ... or the specified slave, if any
if (wrk) {
slaves = new TList();
slaves->Add(wrk);
}
if (slaves->GetSize() == 0) return 0;
#ifndef R__WIN32
Int_t fd = open(file, O_RDONLY);
#else
Int_t fd = open(file, O_RDONLY | O_BINARY);
#endif
if (fd < 0) {
SysError("SendFile", "cannot open file %s", file);
return -1;
}
// Get info about the file
Long64_t size;
Long_t id, flags, modtime;
if (gSystem->GetPathInfo(file, &id, &size, &flags, &modtime) == 1) {
Error("SendFile", "cannot stat file %s", file);
return -1;
}
if (size == 0) {
Error("SendFile", "empty file %s", file);
return -1;
}
// Decode options
Bool_t bin = (opt & kBinary) ? kTRUE : kFALSE;
Bool_t force = (opt & kForce) ? kTRUE : kFALSE;
Bool_t fw = (opt & kForward) ? kTRUE : kFALSE;
const Int_t kMAXBUF = 32768; //16384 //65536;
char buf[kMAXBUF];
Int_t nsl = 0;
TIter next(slaves);
TSlave *sl;
const char *fnam = (rfile) ? rfile : gSystem->BaseName(file);
while ((sl = (TSlave *)next())) {
if (!sl->IsValid())
continue;
Bool_t sendto = force ? kTRUE : CheckFile(file, sl, modtime);
// Don't send the kPROOF_SENDFILE command to real slaves when sendto
// is false. Masters might still need to send the file to newly added
// slaves.
if (sl->fSlaveType == TSlave::kSlave && !sendto)
continue;
// The value of 'size' is used as flag remotely, so we need to
// reset it to 0 if we are not going to send the file
size = sendto ? size : 0;
PDB(kPackage,2)
if (size > 0) {
if (!nsl)
Info("SendFile", "sending file %s to:", file);
printf(" slave = %s:%s\n", sl->GetName(), sl->GetOrdinal());
}
sprintf(buf, "%s %d %lld %d", fnam, bin, size, fw);
if (sl->GetSocket()->Send(buf, kPROOF_SENDFILE) == -1) {
MarkBad(sl);
continue;
}
if (!sendto)
continue;
lseek(fd, 0, SEEK_SET);
Int_t len;
do {
while ((len = read(fd, buf, kMAXBUF)) < 0 && TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
SysError("SendFile", "error reading from file %s", file);
Interrupt(kSoftInterrupt, kActive);
close(fd);
return -1;
}
if (len > 0 && sl->GetSocket()->SendRaw(buf, len) == -1) {
SysError("SendFile", "error writing to slave %s:%s (now offline)",
sl->GetName(), sl->GetOrdinal());
MarkBad(sl);
break;
}
} while (len > 0);
nsl++;
}
close(fd);
// Cleanup temporary list, if any
if (slaves != fActiveSlaves)
SafeDelete(slaves);
return nsl;
}
//______________________________________________________________________________
Int_t TProof::SendObject(const TObject *obj, ESlaves list)
{
// Send object to master or slave servers. Returns number of slaves object
// was sent to, -1 in case of error.
if (!IsValid() || !obj) return -1;
TMessage mess(kMESS_OBJECT);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::SendPrint(Option_t *option)
{
// Send print command to master server. Returns number of slaves message
// was sent to. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(option, kPROOF_PRINT, kActive);
return Collect(kActive);
}
//______________________________________________________________________________
void TProof::SetLogLevel(Int_t level, UInt_t mask)
{
// Set server logging level.
char str[32];
fLogLevel = level;
gProofDebugLevel = level;
gProofDebugMask = (TProofDebug::EProofDebugMask) mask;
sprintf(str, "%d %u", level, mask);
Broadcast(str, kPROOF_LOGLEVEL, kAll);
}
//______________________________________________________________________________
void TProof::SetRealTimeLog(Bool_t on)
{
// Switch ON/OFF the real-time logging facility. When this option is
// ON, log messages from processing are sent back as they come, instead of
// being sent back at the end in one go. This may help debugging or monitoring
// in some cases, but, depending on the amount of log, it may have significant
// consequencies on the load over the network, so it must be used with care.
if (IsValid()) {
TMessage mess(kPROOF_REALTIMELOG);
mess << on;
Broadcast(mess);
} else {
Warning("SetRealTimeLog","session is invalid - do nothing");
}
}
//______________________________________________________________________________
Int_t TProof::SetParallelSilent(Int_t nodes, Bool_t random)
{
// Tell RPOOF how many slaves to use in parallel. If random is TRUE a random
// selection is done (if nodes is less than the available nodes).
// Returns the number of parallel slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
if (IsMaster()) {
GoParallel(nodes, kFALSE, random);
return SendCurrentState();
} else {
PDB(kGlobal,1) Info("SetParallelSilent", "request %d node%s", nodes,
nodes == 1 ? "" : "s");
TMessage mess(kPROOF_PARALLEL);
mess << nodes << random;
Broadcast(mess);
Collect();
Int_t n = GetParallel();
PDB(kGlobal,1) Info("SetParallelSilent", "got %d node%s", n, n == 1 ? "" : "s");
return n;
}
}
//______________________________________________________________________________
Int_t TProof::SetParallel(Int_t nodes, Bool_t random)
{
// Tell PROOF how many slaves to use in parallel. Returns the number of
// parallel slaves. Returns -1 in case of error.
Int_t n = SetParallelSilent(nodes, random);
if (!IsMaster()) {
if (n < 1) {
Printf("PROOF set to sequential mode");
} else {
TString subfix = (n == 1) ? "" : "s";
if (random)
subfix += ", randomly selected";
Printf("PROOF set to parallel mode (%d worker%s)", n, subfix.Data());
}
}
return n;
}
//______________________________________________________________________________
Int_t TProof::GoParallel(Int_t nodes, Bool_t attach, Bool_t random)
{
// Go in parallel mode with at most "nodes" slaves. Since the fSlaves
// list is sorted by slave performace the active list will contain first
// the most performant nodes. Returns the number of active slaves.
// If random is TRUE, and nodes is less than the number of available workers,
// a random selection is done.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (nodes < 0) nodes = 0;
fActiveSlaves->Clear();
fActiveMonitor->RemoveAll();
// Prepare the list of candidates first.
// Algorithm depends on random option.
TSlave *sl = 0;
TList *wlst = new TList;
TIter nxt(fSlaves);
fInactiveSlaves->Clear();
while ((sl = (TSlave *)nxt())) {
if (sl->IsValid() && !fBadSlaves->FindObject(sl)) {
if (strcmp("IGNORE", sl->GetImage()) == 0) continue;
if ((sl->GetSlaveType() != TSlave::kSlave) &&
(sl->GetSlaveType() != TSlave::kMaster)) {
Error("GoParallel", "TSlave is neither Master nor Slave");
R__ASSERT(0);
}
// Good candidate
wlst->Add(sl);
// Set it inactive
fInactiveSlaves->Add(sl);
sl->SetStatus(TSlave::kInactive);
}
}
Int_t nwrks = (nodes > wlst->GetSize()) ? wlst->GetSize() : nodes;
int cnt = 0;
fEndMaster = IsMaster() ? kTRUE : kFALSE;
while (cnt < nwrks) {
// Random choice, if requested
if (random) {
Int_t iwrk = (Int_t) (gRandom->Rndm() * wlst->GetSize());
sl = (TSlave *) wlst->At(iwrk);
} else {
// The first available
sl = (TSlave *) wlst->First();
}
if (!sl) {
Error("GoParallel", "attaching to candidate!");
break;
}
Int_t slavenodes = 0;
if (sl->GetSlaveType() == TSlave::kSlave) {
sl->SetStatus(TSlave::kActive);
fActiveSlaves->Add(sl);
fInactiveSlaves->Remove(sl);
fActiveMonitor->Add(sl->GetSocket());
slavenodes = 1;
} else if (sl->GetSlaveType() == TSlave::kMaster) {
fEndMaster = kFALSE;
TMessage mess(kPROOF_PARALLEL);
if (!attach) {
mess << nodes-cnt;
} else {
// To get the number of slaves
mess.SetWhat(kPROOF_LOGFILE);
mess << -1 << -1;
}
if (sl->GetSocket()->Send(mess) == -1) {
MarkBad(sl);
slavenodes = 0;
} else {
Collect(sl);
sl->SetStatus(TSlave::kActive);
fActiveSlaves->Add(sl);
fInactiveSlaves->Remove(sl);
fActiveMonitor->Add(sl->GetSocket());
if (sl->GetParallel() > 0) {
slavenodes = sl->GetParallel();
} else {
slavenodes = 0;
}
}
}
// Remove from the list
wlst->Remove(sl);
cnt += slavenodes;
}
// Cleanup list
wlst->SetOwner(0);
SafeDelete(wlst);
// Get slave status (will set the slaves fWorkDir correctly)
AskStatistics();
// Find active slaves with unique image
FindUniqueSlaves();
// Send new group-view to slaves
if (!attach)
SendGroupView();
Int_t n = GetParallel();
if (!IsMaster()) {
if (n < 1)
printf("PROOF set to sequential mode\n");
else
printf("PROOF set to parallel mode (%d worker%s)\n",
n, n == 1 ? "" : "s");
}
PDB(kGlobal,1) Info("GoParallel", "got %d node%s", n, n == 1 ? "" : "s");
return n;
}
//______________________________________________________________________________
void TProof::ShowCache(Bool_t all)
{
// List contents of file cache. If all is true show all caches also on
// slaves. If everything is ok all caches are to be the same.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowCache) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubCache) << all;
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ClearCache()
{
// Remove files from all file caches.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kClearCache);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kClearSubCache);
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
// clear file map so files get send again to remote nodes
fFileMap.clear();
}
//______________________________________________________________________________
void TProof::ShowPackages(Bool_t all)
{
// List contents of package directory. If all is true show all package
// directries also on slaves. If everything is ok all package directories
// should be the same.
if (!IsValid()) return;
if (!IsMaster()) {
printf("*** Package cache client:%s ***\n", fPackageDir.Data());
fflush(stdout);
gSystem->Exec(Form("%s %s", kLS, fPackageDir.Data()));
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowPackages) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubPackages) << all;
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ShowEnabledPackages(Bool_t all)
{
// List which packages are enabled. If all is true show enabled packages
// for all active slaves. If everything is ok all active slaves should
// have the same packages enabled.
if (!IsValid()) return;
if (!IsMaster()) {
printf("*** Enabled packages on client on %s\n", gSystem->HostName());
TIter next(fEnabledPackagesOnClient);
while (TObjString *str = (TObjString*) next())
printf("%s\n", str->GetName());
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowEnabledPackages) << all;
Broadcast(mess);
Collect();
}
//______________________________________________________________________________
Int_t TProof::ClearPackages()
{
// Remove all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (UnloadPackages() == -1)
return -1;
if (DisablePackages() == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::ClearPackage(const char *package)
{
// Remove a specific package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("ClearPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (UnloadPackage(pac) == -1)
return -1;
if (DisablePackage(pac) == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::DisablePackage(const char *package)
{
// Remove a specific package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("DisablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (DisablePackageOnClient(pac) == -1)
return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::DisablePackageOnClient(const char *package)
{
// Remove a specific package from the client.
// Returns 0 in case of success and -1 in case of error.
if (!IsMaster()) {
// remove package directory and par file
fPackageLock->Lock();
gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(), package));
gSystem->Exec(Form("%s %s/%s.par", kRM, fPackageDir.Data(), package));
fPackageLock->Unlock();
}
return 0;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::DisablePackages()
{
// Remove all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
// remove all packages on client
if (!IsMaster()) {
fPackageLock->Lock();
gSystem->Exec(Form("%s %s/*", kRM, fPackageDir.Data()));
fPackageLock->Unlock();
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackages);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackages);
Broadcast(mess2, fNonUniqueMasters);
Collect(kAllUnique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::BuildPackage(const char *package, EBuildPackageOpt opt)
{
// Build specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists on all unique nodes. If opt is -1
// then submit build command to slaves, but don't wait
// for results. If opt is 1 then collect result from slaves.
// To be used on the master.
// If opt = 0 (default) then submit and wait for results
// (to be used on the client).
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("BuildPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
Bool_t buildOnClient = kTRUE;
if (opt == kDontBuildOnClient) {
buildOnClient = kFALSE;
opt = kBuildAll;
}
if (opt <= 0) {
TMessage mess(kPROOF_CACHE);
mess << Int_t(kBuildPackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kBuildSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
}
if (opt >= 0) {
// by first forwarding the build commands to the master and slaves
// and only then building locally we build in parallel
Int_t st = 0;
if (buildOnClient)
st = BuildPackageOnClient(pac);
Collect(kAllUnique);
if (fStatus < 0 || st < 0)
return -1;
}
return 0;
}
//______________________________________________________________________________
Int_t TProof::BuildPackageOnClient(const TString &package)
{
// Build specified package on the client. Executes the PROOF-INF/BUILD.sh
// script if it exists on the client.
// Returns 0 in case of success and -1 in case of error.
// The code is equivalent to the one in TProofServ.cxx (TProof::kBuildPackage
// case). Keep in sync in case of changes.
if (!IsMaster()) {
Int_t status = 0;
TString pdir, ocwd;
fPackageLock->Lock();
// check that package and PROOF-INF directory exists
pdir = fPackageDir + "/" + package;
if (gSystem->AccessPathName(pdir)) {
Error("BuildPackageOnClient", "package %s does not exist",
package.Data());
fPackageLock->Unlock();
return -1;
} else if (gSystem->AccessPathName(pdir + "/PROOF-INF")) {
Error("BuildPackageOnClient", "package %s does not have a PROOF-INF directory",
package.Data());
fPackageLock->Unlock();
return -1;
}
PDB(kPackage, 1)
Info("BuildPackageOnCLient",
"package %s exists and has PROOF-INF directory", package.Data());
ocwd = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(pdir);
// check for BUILD.sh and execute
if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
// read version from file proofvers.txt, and if current version is
// not the same do a "BUILD.sh clean"
FILE *f = fopen("PROOF-INF/proofvers.txt", "r");
if (f) {
TString v;
v.Gets(f);
fclose(f);
if (v != gROOT->GetVersion()) {
if (gSystem->Exec("PROOF-INF/BUILD.sh clean")) {
Error("BuildPackageOnClient", "cleaning package %s on the client failed", package.Data());
status = -1;
}
}
}
if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
Error("BuildPackageOnClient", "building package %s on the client failed", package.Data());
status = -1;
}
f = fopen("PROOF-INF/proofvers.txt", "w");
if (f) {
fputs(gROOT->GetVersion(), f);
fclose(f);
}
} else {
PDB(kPackage, 1)
Info("BuildPackageOnCLient",
"package %s exists but has no PROOF-INF/BUILD.sh script", package.Data());
}
gSystem->ChangeDirectory(ocwd);
fPackageLock->Unlock();
return status;
}
return 0;
}
//______________________________________________________________________________
Int_t TProof::LoadPackage(const char *package, Bool_t notOnClient)
{
// Load specified package. Executes the PROOF-INF/SETUP.C script
// on all active nodes. If notOnClient = true, don't load package
// on the client. The default is to load the package also on the client.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("LoadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (!notOnClient)
if (LoadPackageOnClient(pac) == -1)
return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kLoadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::LoadPackageOnClient(const TString &package)
{
// Load specified package in the client. Executes the PROOF-INF/SETUP.C
// script on the client. Returns 0 in case of success and -1 in case of error.
// The code is equivalent to the one in TProofServ.cxx (TProof::kLoadPackage
// case). Keep in sync in case of changes.
if (!IsMaster()) {
Int_t status = 0;
TString pdir, ocwd;
// If already loaded don't do it again
if (fEnabledPackagesOnClient->FindObject(package)) {
Info("LoadPackageOnClient",
"package %s already loaded", package.Data());
return 0;
}
// always follows BuildPackage so no need to check for PROOF-INF
pdir = fPackageDir + "/" + package;
ocwd = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(pdir);
// check for SETUP.C and execute
if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
Int_t err = 0;
Int_t errm = gROOT->Macro("PROOF-INF/SETUP.C", &err);
if (errm < 0)
status = -1;
if (err > TInterpreter::kNoError && err <= TInterpreter::kFatal)
status = -1;
} else {
PDB(kPackage, 1)
Info("LoadPackageOnCLient",
"package %s exists but has no PROOF-INF/SETUP.C script", package.Data());
}
gSystem->ChangeDirectory(ocwd);
if (!status) {
// create link to package in working directory
fPackageLock->Lock();
FileStat_t stat;
Int_t st = gSystem->GetPathInfo(package, stat);
// check if symlink, if so unlink, if not give error
// NOTE: GetPathnfo() returns 1 in case of symlink that does not point to
// existing file or to a directory, but if fIsLink is true the symlink exists
if (stat.fIsLink)
gSystem->Unlink(package);
else if (st == 0) {
Error("LoadPackageOnClient", "cannot create symlink %s in %s on client, "
"another item with same name already exists", package.Data(), ocwd.Data());
fPackageLock->Unlock();
return -1;
}
gSystem->Symlink(pdir, package);
fPackageLock->Unlock();
// add package to list of include directories to be searched by ACliC
gSystem->AddIncludePath(TString("-I") + package);
// add package to list of include directories to be searched by CINT
gROOT->ProcessLine(TString(".include ") + package);
fEnabledPackagesOnClient->Add(new TObjString(package));
PDB(kPackage, 1)
Info("LoadPackageOnClient",
"package %s successfully loaded", package.Data());
} else
Error("LoadPackageOnClient", "loading package %s on client failed", package.Data());
return status;
}
return 0;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::UnloadPackage(const char *package)
{
// Unload specified package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("UnloadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (UnloadPackageOnClient(pac) == -1)
return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::UnloadPackageOnClient(const char *package)
{
// Unload a specific package on the client.
// Returns 0 in case of success and -1 in case of error.
// The code is equivalent to the one in TProofServ.cxx (TProof::UnloadPackage
// case). Keep in sync in case of changes.
if (!IsMaster()) {
TObjString *pack = (TObjString *) fEnabledPackagesOnClient->FindObject(package);
if (pack) {
// Remove entry from include path
TString aclicincpath = gSystem->GetIncludePath();
TString cintincpath = gInterpreter->GetIncludePath();
// remove interpreter part of gSystem->GetIncludePath()
aclicincpath.Remove(aclicincpath.Length() - cintincpath.Length() - 1);
// remove package's include path
aclicincpath.ReplaceAll(TString(" -I") + package, "");
gSystem->SetIncludePath(aclicincpath);
//TODO reset interpreter include path
// remove entry from enabled packages list
delete fEnabledPackagesOnClient->Remove(pack);
}
// cleanup the link
if (!gSystem->AccessPathName(package))
if (gSystem->Unlink(package) != 0)
Warning("UnloadPackageOnClient", "unable to remove symlink to %s", package);
}
return 0;
}
//______________________________________________________________________________
R__HIDDEN Int_t TProof::UnloadPackages()
{
// Unload all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!IsMaster()) {
// Iterate over packages on the client and remove each package
TIter nextpackage(fEnabledPackagesOnClient);
while (TObjString *objstr = dynamic_cast<TObjString*>(nextpackage()))
if (UnloadPackageOnClient(objstr->String()) == -1 )
return -1;
}
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackages);
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::EnablePackage(const char *package, Bool_t notOnClient)
{
// Enable specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists followed by the PROOF-INF/SETUP.C script.
// In case notOnClient = true, don't enable the package on the client.
// The default is to enable packages also on the client.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("EnablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
EBuildPackageOpt opt = kBuildAll;
if (notOnClient)
opt = kDontBuildOnClient;
if (BuildPackage(pac, opt) == -1)
return -1;
if (LoadPackage(pac, notOnClient) == -1)
return -1;
return 0;
}
//______________________________________________________________________________
Int_t TProof::UploadPackage(const char *tpar, EUploadPackageOpt opt)
{
// Upload a PROOF archive (PAR file). A PAR file is a compressed
// tar file with one special additional directory, PROOF-INF
// (blatantly copied from Java's jar format). It must have the extension
// .par. A PAR file can be directly a binary or a source with a build
// procedure. In the PROOF-INF directory there can be a build script:
// BUILD.sh to be called to build the package, in case of a binary PAR
// file don't specify a build script or make it a no-op. Then there is
// SETUP.C which sets the right environment variables to use the package,
// like LD_LIBRARY_PATH, etc.
// The 'opt' allows to specify whether the .PAR should be just unpacked
// in the existing dir (opt = kUntar, default) or a remove of the existing
// directory should be executed (opt = kRemoveOld), so triggering a full
// re-build. The option if effective only for PROOF protocol > 8 .
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
TString par = tpar;
if (!par.EndsWith(".par")) {
Error("UploadPackage", "package %s must have extension .par", tpar);
return -1;
}
gSystem->ExpandPathName(par);
if (gSystem->AccessPathName(par, kReadPermission)) {
Error("UploadPackage", "package %s does not exist", par.Data());
return -1;
}
// Strategy:
// On the client:
// get md5 of package and check if it is different
// from the one stored in the local package directory. If it is lock
// the package directory and copy the package, unlock the directory.
// On the masters:
// get md5 of package and check if it is different from the
// one stored on the remote node. If it is different lock the remote
// package directory and use TFTP or SendFile to ftp the package to the
// remote node, unlock the directory.
TMD5 *md5 = TMD5::FileChecksum(par);
if (UploadPackageOnClient(par, opt, md5) == -1) {
delete md5;
return -1;
}
TMessage mess(kPROOF_CHECKFILE);
mess << TString("+")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess2(kPROOF_CHECKFILE);
mess2 << TString("-")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess3(kPROOF_CHECKFILE);
mess3 << TString("=")+TString(gSystem->BaseName(par)) << (*md5);
delete md5;
if (fProtocol > 8) {
// Send also the option
mess << (UInt_t) opt;
mess2 << (UInt_t) opt;
mess3 << (UInt_t) opt;
}
// loop over all selected nodes
TIter next(fUniqueSlaves);
TSlave *sl = 0;
while ((sl = (TSlave *) next())) {
if (!sl->IsValid())
continue;
sl->GetSocket()->Send(mess);
TMessage *reply;
sl->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
if (fProtocol > 5) {
// remote directory is locked, upload file over the open channel
if (SendFile(par, (kBinary | kForce), Form("%s/%s/%s",
sl->GetProofWorkDir(), kPROOF_PackDir,
gSystem->BaseName(par)), sl) < 0) {
Error("UploadPackage", "problems uploading file %s", par.Data());
SafeDelete(reply);
return -1;
}
} else {
// old servers receive it via TFTP
TFTP ftp(TString("root://")+sl->GetName(), 1);
if (!ftp.IsZombie()) {
ftp.cd(Form("%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir));
ftp.put(par, gSystem->BaseName(par));
}
}
// install package and unlock dir
sl->GetSocket()->Send(mess2);
SafeDelete(reply);
sl->GetSocket()->Recv(reply);
if (!reply || reply->What() != kPROOF_CHECKFILE) {
Error("UploadPackage", "unpacking of package %s failed", par.Data());
SafeDelete(reply);
return -1;
}
}
SafeDelete(reply);
}
// loop over all other master nodes
TIter nextmaster(fNonUniqueMasters);
TSlave *ma;
while ((ma = (TSlave *) nextmaster())) {
if (!ma->IsValid())
continue;
ma->GetSocket()->Send(mess3);
TMessage *reply = 0;
ma->GetSocket()->Recv(reply);
if (!reply || reply->What() != kPROOF_CHECKFILE) {
// error -> package should have been found
Error("UploadPackage", "package %s did not exist on submaster %s",
par.Data(), ma->GetOrdinal());
SafeDelete(reply);
return -1;
}
SafeDelete(reply);
}
return 0;
}
//______________________________________________________________________________
Int_t TProof::UploadPackageOnClient(const TString &par, EUploadPackageOpt opt, TMD5 *md5)
{
// Upload a package on the client in ~/proof/packages.
// The 'opt' allows to specify whether the .PAR should be just unpacked
// in the existing dir (opt = kUntar, default) or a remove of the existing
// directory should be executed (opt = kRemoveOld), thereby triggering a full
// re-build. The option if effective only for PROOF protocol > 8 .
// Returns 0 in case of success and -1 in case of error.
// Strategy:
// get md5 of package and check if it is different
// from the one stored in the local package directory. If it is lock
// the package directory and copy the package, unlock the directory.
Int_t status = 0;
if (!IsMaster()) {
// the fPackageDir directory exists (has been created in Init())
// create symlink to the par file in the fPackageDir (needed by
// master in case we run on the localhost)
fPackageLock->Lock();
TString lpar = fPackageDir + "/" + gSystem->BaseName(par);
FileStat_t stat;
Int_t st = gSystem->GetPathInfo(lpar, stat);
// check if symlink, if so unlink, if not give error
// NOTE: GetPathInfo() returns 1 in case of symlink that does not point to
// existing file, but if fIsLink is true the symlink exists
if (stat.fIsLink)
gSystem->Unlink(lpar);
else if (st == 0) {
Error("UploadPackageOnClient", "cannot create symlink %s on client, "
"another item with same name already exists",
lpar.Data());
fPackageLock->Unlock();
return -1;
}
if (!gSystem->IsAbsoluteFileName(par)) {
TString fpar = par;
gSystem->Symlink(gSystem->PrependPathName(gSystem->WorkingDirectory(), fpar), lpar);
} else
gSystem->Symlink(par, lpar);
// TODO: On Windows need to copy instead of symlink
// compare md5
TString packnam = par(0, par.Length() - 4); // strip off ".par"
packnam = gSystem->BaseName(packnam); // strip off path
TString md5f = fPackageDir + "/" + packnam + "/PROOF-INF/md5.txt";
TMD5 *md5local = TMD5::ReadChecksum(md5f);
if (!md5local || (*md5) != (*md5local)) {
// if not, unzip and untar package in package directory
Int_t st = 0;
if ((opt & TProof::kRemoveOld)) {
// remove any previous package directory with same name
st = gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(),
packnam.Data()));
if (st)
Error("UploadPackageOnClient", "failure executing: %s %s/%s",
kRM, fPackageDir.Data(), packnam.Data());
}
// find gunzip
char *gunzip = gSystem->Which(gSystem->Getenv("PATH"), kGUNZIP,
kExecutePermission);
if (gunzip) {
// untar package
st = gSystem->Exec(Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data()));
if (st)
Error("Uploadpackage", "failure executing: %s",
Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data()));
delete [] gunzip;
} else
Error("UploadPackageOnClient", "%s not found", kGUNZIP);
// check that fPackageDir/packnam now exists
if (gSystem->AccessPathName(fPackageDir + "/" + packnam, kWritePermission)) {
// par file did not unpack itself in the expected directory, failure
Error("UploadPackageOnClient",
"package %s did not unpack into %s/%s", par.Data(), fPackageDir.Data(),
packnam.Data());
status = -1;
} else {
// store md5 in package/PROOF-INF/md5.txt
TMD5::WriteChecksum(md5f, md5);
}
}
fPackageLock->Unlock();
delete md5local;
}
return status;
}
//______________________________________________________________________________
Int_t TProof::AddDynamicPath(const char *libpath)
{
// Add 'libpath' to the lib path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!libpath || !strlen(libpath))) {
if (gDebug > 0)
Info("AddDynamicPath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("lib") << (Bool_t)kTRUE;
// Add paths
if (libpath && strlen(libpath))
m << TString(libpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
Int_t TProof::AddIncludePath(const char *incpath)
{
// Add 'incpath' to the inc path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!incpath || !strlen(incpath))) {
if (gDebug > 0)
Info("AddIncludePath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("inc") << (Bool_t)kTRUE;
// Add paths
if (incpath && strlen(incpath))
m << TString(incpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
Int_t TProof::RemoveDynamicPath(const char *libpath)
{
// Remove 'libpath' from the lib path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!libpath || !strlen(libpath))) {
if (gDebug > 0)
Info("AddDynamicPath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("lib") <<(Bool_t)kFALSE;
// Add paths
if (libpath && strlen(libpath))
m << TString(libpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
Int_t TProof::RemoveIncludePath(const char *incpath)
{
// Remove 'incpath' from the inc path search.
// Multiple paths can be specified at once separating them with a comma or
// a blank.
// Return 0 on success, -1 otherwise
if ((!incpath || !strlen(incpath))) {
if (gDebug > 0)
Info("RemoveIncludePath", "list is empty - nothing to do");
return 0;
}
TMessage m(kPROOF_LIB_INC_PATH);
m << TString("inc") << (Bool_t)kFALSE;
// Add paths
if (incpath && strlen(incpath))
m << TString(incpath);
else
m << TString("-");
// Forward the request
Broadcast(m);
Collect();
return 0;
}
//______________________________________________________________________________
TList *TProof::GetListOfPackages()
{
// Get from the master the list of names of the packages available.
if (!IsValid())
return (TList *)0;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kListPackages);
Broadcast(mess);
Collect();
return fAvailablePackages;
}
//______________________________________________________________________________
TList *TProof::GetListOfEnabledPackages()
{
// Get from the master the list of names of the packages enabled.
if (!IsValid())
return (TList *)0;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kListEnabledPackages);
Broadcast(mess);
Collect();
return fEnabledPackages;
}
//______________________________________________________________________________
void TProof::PrintProgress(Long64_t total, Long64_t processed, Float_t procTime)
{
// Print a progress bar on stderr. Used in batch mode.
fprintf(stderr, "[TProof::Progress] Total %lld events\t|", total);
for (int l = 0; l < 20; l++) {
if (total > 0) {
if (l < 20*processed/total)
fprintf(stderr, "=");
else if (l == 20*processed/total)
fprintf(stderr, ">");
else if (l > 20*processed/total)
fprintf(stderr, ".");
} else
fprintf(stderr, "=");
}
Float_t evtrti = (procTime > 0. && processed > 0) ? processed / procTime : -1.;
if (evtrti > 0.)
fprintf(stderr, "| %.02f %% [%.1f evts/s]\r",
100.0*(total ? (processed/total) : 1), evtrti);
else
fprintf(stderr, "| %.02f %%\r",
100.0*(total ? (processed/total) : 1));
if (processed >= total)
fprintf(stderr, "\n");
}
//______________________________________________________________________________
void TProof::Progress(Long64_t total, Long64_t processed)
{
// Get query progress information. Connect a slot to this signal
// to track progress.
PDB(kGlobal,1)
Info("Progress","%2f (%lld/%lld)", 100.*processed/total, processed, total);
if (gROOT->IsBatch()) {
// Simple progress bar
PrintProgress(total, processed);
} else {
EmitVA("Progress(Long64_t,Long64_t)", 2, total, processed);
}
}
//______________________________________________________________________________
void TProof::Progress(Long64_t total, Long64_t processed, Long64_t bytesread,
Float_t initTime, Float_t procTime,
Float_t evtrti, Float_t mbrti)
{
// Get query progress information. Connect a slot to this signal
// to track progress.
PDB(kGlobal,1)
Info("Progress","%lld %lld %lld %f %f %f %f", total, processed, bytesread,
initTime, procTime, evtrti, mbrti);
if (gROOT->IsBatch()) {
// Simple progress bar
PrintProgress(total, processed, procTime);
} else {
EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
7, total, processed, bytesread, initTime, procTime, evtrti, mbrti);
}
}
//______________________________________________________________________________
void TProof::Feedback(TList *objs)
{
// Get list of feedback objects. Connect a slot to this signal
// to monitor the feedback object.
PDB(kGlobal,1)
Info("Feedback","%d objects", objs->GetSize());
PDB(kFeedback,1) {
Info("Feedback","%d objects", objs->GetSize());
objs->ls();
}
Emit("Feedback(TList *objs)", (Long_t) objs);
}
//______________________________________________________________________________
void TProof::CloseProgressDialog()
{
// Close progress dialog.
PDB(kGlobal,1)
Info("CloseProgressDialog",
"called: have progress dialog: %d", fProgressDialogStarted);
// Nothing to do if not there
if (!fProgressDialogStarted)
return;
Emit("CloseProgressDialog()");
}
//______________________________________________________________________________
void TProof::ResetProgressDialog(const char *sel, Int_t sz, Long64_t fst,
Long64_t ent)
{
// Reset progress dialog.
PDB(kGlobal,1)
Info("ResetProgressDialog","(%s,%d,%lld,%lld)", sel, sz, fst, ent);
EmitVA("ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)",
4, sel, sz, fst, ent);
}
//______________________________________________________________________________
void TProof::StartupMessage(const char *msg, Bool_t st, Int_t done, Int_t total)
{
// Send startup message.
PDB(kGlobal,1)
Info("StartupMessage","(%s,%d,%d,%d)", msg, st, done, total);
EmitVA("StartupMessage(const char*,Bool_t,Int_t,Int_t)",
4, msg, st, done, total);
}
//______________________________________________________________________________
void TProof::DataSetStatus(const char *msg, Bool_t st, Int_t done, Int_t total)
{
// Send dataset preparation status.
PDB(kGlobal,1)
Info("DataSetStatus","(%s,%d,%d,%d)", msg, st, done, total);
EmitVA("DataSetStatus(const char*,Bool_t,Int_t,Int_t)",
4, msg, st, done, total);
}
//______________________________________________________________________________
void TProof::SendDataSetStatus(const char *msg, UInt_t n,
UInt_t tot, Bool_t st)
{
// Send data set status
if (IsMaster()) {
TMessage mess(kPROOF_DATASET_STATUS);
mess << TString(msg) << tot << n << st;
gProofServ->GetSocket()->Send(mess);
}
}
//______________________________________________________________________________
void TProof::QueryResultReady(const char *ref)
{
// Notify availability of a query result.
PDB(kGlobal,1)
Info("QueryResultReady","ref: %s", ref);
Emit("QueryResultReady(const char*)",ref);
}
//______________________________________________________________________________
void TProof::ValidateDSet(TDSet *dset)
{
// Validate a TDSet.
if (dset->ElementsValid()) return;
TList nodes;
nodes.SetOwner();
TList slholder;
slholder.SetOwner();
TList elemholder;
elemholder.SetOwner();
// build nodelist with slaves and elements
TIter nextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) {
TList *sllist = 0;
TPair *p = dynamic_cast<TPair*>(nodes.FindObject(sl->GetName()));
if (!p) {
sllist = new TList;
sllist->SetName(sl->GetName());
slholder.Add(sllist);
TList *elemlist = new TList;
elemlist->SetName(TString(sl->GetName())+"_elem");
elemholder.Add(elemlist);
nodes.Add(new TPair(sllist, elemlist));
} else {
sllist = dynamic_cast<TList*>(p->Key());
}
sllist->Add(sl);
}
// add local elements to nodes
TList nonLocal; // list of nonlocal elements
// make two iterations - first add local elements - then distribute nonlocals
for (Int_t i = 0; i < 2; i++) {
Bool_t local = i>0?kFALSE:kTRUE;
TIter nextElem(local ? dset->GetListOfElements() : &nonLocal);
while (TDSetElement *elem = dynamic_cast<TDSetElement*>(nextElem())) {
if (elem->GetValid()) continue;
TPair *p = dynamic_cast<TPair*>(local?nodes.FindObject(TUrl(elem->GetFileName()).GetHost()):nodes.At(0));
if (p) {
TList *eli = dynamic_cast<TList*>(p->Value());
TList *sli = dynamic_cast<TList*>(p->Key());
eli->Add(elem);
// order list by elements/slave
TPair *p2 = p;
Bool_t stop = kFALSE;
while (!stop) {
TPair *p3 = dynamic_cast<TPair*>(nodes.After(p2->Key()));
if (p3) {
Int_t nelem = dynamic_cast<TList*>(p3->Value())->GetSize();
Int_t nsl = dynamic_cast<TList*>(p3->Key())->GetSize();
if (nelem*sli->GetSize() < eli->GetSize()*nsl) p2 = p3;
else stop = kTRUE;
} else {
stop = kTRUE;
}
}
if (p2!=p) {
nodes.Remove(p->Key());
nodes.AddAfter(p2->Key(), p);
}
} else {
if (local) {
nonLocal.Add(elem);
} else {
Error("ValidateDSet", "No Node to allocate TDSetElement to");
R__ASSERT(0);
}
}
}
}
// send to slaves
TList usedslaves;
TIter nextNode(&nodes);
SetDSet(dset); // set dset to be validated in Collect()
while (TPair *node = dynamic_cast<TPair*>(nextNode())) {
TList *slaves = dynamic_cast<TList*>(node->Key());
TList *setelements = dynamic_cast<TList*>(node->Value());
// distribute elements over the slaves
Int_t nslaves = slaves->GetSize();
Int_t nelements = setelements->GetSize();
for (Int_t i=0; i<nslaves; i++) {
TDSet copyset(dset->GetType(), dset->GetObjName(),
dset->GetDirectory());
for (Int_t j = (i*nelements)/nslaves;
j < ((i+1)*nelements)/nslaves;
j++) {
TDSetElement *elem =
dynamic_cast<TDSetElement*>(setelements->At(j));
copyset.Add(elem->GetFileName(), elem->GetObjName(),
elem->GetDirectory(), elem->GetFirst(),
elem->GetNum(), elem->GetMsd());
}
if (copyset.GetListOfElements()->GetSize()>0) {
TMessage mesg(kPROOF_VALIDATE_DSET);
mesg << ©set;
TSlave *sl = dynamic_cast<TSlave*>(slaves->At(i));
PDB(kGlobal,1) Info("ValidateDSet",
"Sending TDSet with %d elements to slave %s"
" to be validated",
copyset.GetListOfElements()->GetSize(),
sl->GetOrdinal());
sl->GetSocket()->Send(mesg);
usedslaves.Add(sl);
}
}
}
PDB(kGlobal,1) Info("ValidateDSet","Calling Collect");
Collect(&usedslaves);
SetDSet(0);
}
//______________________________________________________________________________
void TProof::AddInput(TObject *obj)
{
// Add objects that might be needed during the processing of
// the selector (see Process()).
fPlayer->AddInput(obj);
}
//______________________________________________________________________________
void TProof::ClearInput()
{
// Clear input object list.
fPlayer->ClearInput();
// the system feedback list is always in the input list
AddInput(fFeedback);
}
//______________________________________________________________________________
TObject *TProof::GetOutput(const char *name)
{
// Get specified object that has been produced during the processing
// (see Process()).
return fPlayer->GetOutput(name);
}
//______________________________________________________________________________
TList *TProof::GetOutputList()
{
// Get list with all object created during processing (see Process()).
return fPlayer->GetOutputList();
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, const char *value)
{
// Set input list parameter. If the parameter is already
// set it will be set to the new value.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TNamed(par, value));
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, Long_t value)
{
// Set an input list parameter.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TParameter<Long_t>(par, value));
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, Long64_t value)
{
// Set an input list parameter.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TParameter<Long64_t>(par, value));
}
//______________________________________________________________________________
void TProof::SetParameter(const char *par, Double_t value)
{
// Set an input list parameter.
TList *il = fPlayer->GetInputList();
TObject *item = il->FindObject(par);
if (item) {
il->Remove(item);
delete item;
}
il->Add(new TParameter<Double_t>(par, value));
}
//______________________________________________________________________________
TObject *TProof::GetParameter(const char *par) const
{
// Get specified parameter. A parameter set via SetParameter() is either
// a TParameter or a TNamed or 0 in case par is not defined.
TList *il = fPlayer->GetInputList();
return il->FindObject(par);
}
//______________________________________________________________________________
void TProof::DeleteParameters(const char *wildcard)
{
// Delete the input list parameters specified by a wildcard (e.g. PROOF_*)
// or exact name (e.g. PROOF_MaxSlavesPerNode).
if (!wildcard) wildcard = "";
TRegexp re(wildcard, kTRUE);
Int_t nch = strlen(wildcard);
TList *il = fPlayer->GetInputList();
TObject *p;
TIter next(il);
while ((p = next())) {
TString s = p->GetName();
if (nch && s != wildcard && s.Index(re) == kNPOS) continue;
il->Remove(p);
delete p;
}
}
//______________________________________________________________________________
void TProof::ShowParameters(const char *wildcard) const
{
// Show the input list parameters specified by the wildcard.
// Default is the special PROOF control parameters (PROOF_*).
if (!wildcard) wildcard = "";
TRegexp re(wildcard, kTRUE);
Int_t nch = strlen(wildcard);
TList *il = fPlayer->GetInputList();
TObject *p;
TIter next(il);
while ((p = next())) {
TString s = p->GetName();
if (nch && s != wildcard && s.Index(re) == kNPOS) continue;
if (p->IsA() == TNamed::Class()) {
Printf("%s\t\t\t%s", s.Data(), p->GetTitle());
} else if (p->IsA() == TParameter<Long_t>::Class()) {
Printf("%s\t\t\t%ld", s.Data(), dynamic_cast<TParameter<Long_t>*>(p)->GetVal());
} else if (p->IsA() == TParameter<Long64_t>::Class()) {
Printf("%s\t\t\t%lld", s.Data(), dynamic_cast<TParameter<Long64_t>*>(p)->GetVal());
} else if (p->IsA() == TParameter<Double_t>::Class()) {
Printf("%s\t\t\t%f", s.Data(), dynamic_cast<TParameter<Double_t>*>(p)->GetVal());
} else {
Printf("%s\t\t\t%s", s.Data(), p->GetTitle());
}
}
}
//______________________________________________________________________________
void TProof::AddFeedback(const char *name)
{
// Add object to feedback list.
PDB(kFeedback, 3)
Info("AddFeedback", "Adding object \"%s\" to feedback", name);
if (fFeedback->FindObject(name) == 0)
fFeedback->Add(new TObjString(name));
}
//______________________________________________________________________________
void TProof::RemoveFeedback(const char *name)
{
// Remove object from feedback list.
TObject *obj = fFeedback->FindObject(name);
if (obj != 0) {
fFeedback->Remove(obj);
delete obj;
}
}
//______________________________________________________________________________
void TProof::ClearFeedback()
{
// Clear feedback list.
fFeedback->Delete();
}
//______________________________________________________________________________
void TProof::ShowFeedback() const
{
// Show items in feedback list.
if (fFeedback->GetSize() == 0) {
Info("","no feedback requested");
return;
}
fFeedback->Print();
}
//______________________________________________________________________________
TList *TProof::GetFeedbackList() const
{
// Return feedback list.
return fFeedback;
}
//______________________________________________________________________________
TTree *TProof::GetTreeHeader(TDSet *dset)
{
// Creates a tree header (a tree with nonexisting files) object for
// the DataSet.
TList *l = GetListOfActiveSlaves();
TSlave *sl = (TSlave*) l->First();
if (sl == 0) {
Error("GetTreeHeader", "No connection");
return 0;
}
TSocket *soc = sl->GetSocket();
TMessage msg(kPROOF_GETTREEHEADER);
msg << dset;
soc->Send(msg);
TMessage *reply;
Int_t d = soc->Recv(reply);
if (reply <= 0) {
Error("GetTreeHeader", "Error getting a replay from the master.Result %d", (int) d);
return 0;
}
TString s1;
TTree * t;
(*reply) >> s1;
(*reply) >> t;
PDB(kGlobal, 1)
if (t)
Info("GetTreeHeader", Form("%s, message size: %d, entries: %d\n",
s1.Data(), reply->BufferSize(), (int) t->GetMaxEntryLoop()));
else
Info("GetTreeHeader", Form("%s, message size: %d\n", s1.Data(), reply->BufferSize()));
delete reply;
return t;
}
//______________________________________________________________________________
TDrawFeedback *TProof::CreateDrawFeedback()
{
// Draw feedback creation proxy. When accessed via TProof avoids
// link dependency on libProofPlayer.
return fPlayer->CreateDrawFeedback(this);
}
//______________________________________________________________________________
void TProof::SetDrawFeedbackOption(TDrawFeedback *f, Option_t *opt)
{
// Set draw feedback option.
fPlayer->SetDrawFeedbackOption(f, opt);
}
//______________________________________________________________________________
void TProof::DeleteDrawFeedback(TDrawFeedback *f)
{
// Delete draw feedback object.
fPlayer->DeleteDrawFeedback(f);
}
//______________________________________________________________________________
TList *TProof::GetOutputNames()
{
// FIXME: to be written
return 0;
/*
TMessage msg(kPROOF_GETOUTPUTLIST);
TList* slaves = fActiveSlaves;
Broadcast(msg, slaves);
TMonitor mon;
TList* outputList = new TList();
TIter si(slaves);
TSlave *slave;
while ((slave = (TSlave*)si.Next()) != 0) {
PDB(kGlobal,4) Info("GetOutputNames","Socket added to monitor: %p (%s)",
slave->GetSocket(), slave->GetName());
mon.Add(slave->GetSocket());
}
mon.ActivateAll();
((TProof*)gProof)->DeActivateAsyncInput();
((TProof*)gProof)->fCurrentMonitor = &mon;
while (mon.GetActive() != 0) {
TSocket *sock = mon.Select();
if (!sock) {
Error("GetOutputList","TMonitor::.Select failed!");
break;
}
mon.DeActivate(sock);
TMessage *reply;
if (sock->Recv(reply) <= 0) {
MarkBad(slave);
// Error("GetOutputList","Recv failed! for slave-%d (%s)",
// slave->GetOrdinal(), slave->GetName());
continue;
}
if (reply->What() != kPROOF_GETOUTPUTNAMES ) {
// Error("GetOutputList","unexpected message %d from slawe-%d (%s)", reply->What(),
// slave->GetOrdinal(), slave->GetName());
MarkBad(slave);
continue;
}
TList* l;
(*reply) >> l;
TIter next(l);
TNamed *n;
while ( (n = dynamic_cast<TNamed*> (next())) ) {
if (!outputList->FindObject(n->GetName()))
outputList->Add(n);
}
delete reply;
}
((TProof*)gProof)->fCurrentMonitor = 0;
return outputList;
*/
}
//______________________________________________________________________________
void TProof::Browse(TBrowser *b)
{
// Build the PROOF's structure in the browser.
b->Add(fActiveSlaves, fActiveSlaves->Class(), "fActiveSlaves");
b->Add(&fMaster, fMaster.Class(), "fMaster");
b->Add(fFeedback, fFeedback->Class(), "fFeedback");
b->Add(fChains, fChains->Class(), "fChains");
b->Add(fPlayer->GetInputList(), fPlayer->GetInputList()->Class(), "InputList");
if (fPlayer->GetOutputList())
b->Add(fPlayer->GetOutputList(), fPlayer->GetOutputList()->Class(), "OutputList");
if (fPlayer->GetListOfResults())
b->Add(fPlayer->GetListOfResults(),
fPlayer->GetListOfResults()->Class(), "ListOfResults");
}
//______________________________________________________________________________
void TProof::SetPlayer(TVirtualProofPlayer *player)
{
// Set a new PROOF player.
if (fPlayer)
delete fPlayer;
fPlayer = player;
};
//______________________________________________________________________________
TVirtualProofPlayer *TProof::MakePlayer(const char *player, TSocket *s)
{
// Construct a TProofPlayer object. The player string specifies which
// player should be created: remote, slave, sm (supermaster) or base.
// Default is remote. Socket is needed in case a slave player is created.
if (!player)
player = "remote";
SetPlayer(TVirtualProofPlayer::Create(player, this, s));
return GetPlayer();
}
//______________________________________________________________________________
void TProof::AddChain(TChain *chain)
{
// Add chain to data set
fChains->Add(chain);
}
//______________________________________________________________________________
void TProof::RemoveChain(TChain *chain)
{
// Remove chain from data set
fChains->Remove(chain);
}
//_____________________________________________________________________________
void *TProof::SlaveStartupThread(void *arg)
{
// Function executed in the slave startup thread.
if (fgSemaphore) fgSemaphore->Wait();
TProofThreadArg *ta = (TProofThreadArg *)arg;
PDB(kGlobal,1)
::Info("TProof::SlaveStartupThread",
"Starting slave %s on host %s", ta->fOrd.Data(), ta->fUrl->GetHost());
TSlave *sl = 0;
if (ta->fType == TSlave::kSlave) {
// Open the connection
sl = ta->fProof->CreateSlave(ta->fUrl->GetUrl(), ta->fOrd,
ta->fPerf, ta->fImage, ta->fWorkdir);
// Finalize setup of the server
if (sl && sl->IsValid())
sl->SetupServ(TSlave::kSlave, 0);
} else {
// Open the connection
sl = ta->fProof->CreateSubmaster(ta->fUrl->GetUrl(), ta->fOrd,
ta->fImage, ta->fMsd);
// Finalize setup of the server
if (sl && sl->IsValid())
sl->SetupServ(TSlave::kMaster, ta->fWorkdir);
}
if (sl && sl->IsValid()) {
{ R__LOCKGUARD2(gProofMutex);
// Add to the started slaves list
ta->fSlaves->Add(sl);
if (ta->fClaims) { // Condor slave
// Remove from the pending claims list
TCondorSlave *c = ta->fCslave;
ta->fClaims->Remove(c);
}
}
// Notify we are done
PDB(kGlobal,1)
::Info("TProof::SlaveStartupThread",
"slave %s on host %s created and added to list",
ta->fOrd.Data(), ta->fUrl->GetHost());
} else {
// Failure
SafeDelete(sl);
::Error("TProof::SlaveStartupThread",
"slave %s on host %s could not be created",
ta->fOrd.Data(), ta->fUrl->GetHost());
}
if (fgSemaphore) fgSemaphore->Post();
return 0;
}
//______________________________________________________________________________
void TProof::GetLog(Int_t start, Int_t end)
{
// Ask for remote logs in the range [start, end]. If start == -1 all the
// messages not yet received are sent back.
if (!IsValid() || IsMaster()) return;
TMessage msg(kPROOF_LOGFILE);
msg << start << end;
Broadcast(msg, kActive);
Collect(kActive);
}
//______________________________________________________________________________
void TProof::PutLog(TQueryResult *pq)
{
// Display log of query pq into the log window frame
if (!pq) return;
TList *lines = pq->GetLogFile()->GetListOfLines();
if (lines) {
TIter nxl(lines);
TObjString *l = 0;
while ((l = (TObjString *)nxl()))
EmitVA("LogMessage(const char*,Bool_t)", 2, l->GetName(), kFALSE);
}
}
//______________________________________________________________________________
void TProof::ShowLog(const char *queryref)
{
// Display on screen the content of the temporary log file for query
// in reference
// Make sure we have all info (GetListOfQueries retrieves the
// head info only)
Retrieve(queryref);
if (fPlayer) {
if (queryref) {
if (fPlayer->GetListOfResults()) {
TIter nxq(fPlayer->GetListOfResults());
TQueryResult *qr = 0;
while ((qr = (TQueryResult *) nxq()))
if (strstr(queryref, qr->GetTitle()) &&
strstr(queryref, qr->GetName()))
break;
if (qr) {
PutLog(qr);
return;
}
}
}
}
}
//______________________________________________________________________________
void TProof::ShowLog(Int_t qry)
{
// Display on screen the content of the temporary log file.
// If qry == -2 show messages from the last (current) query.
// If qry == -1 all the messages not yet displayed are shown (default).
// If qry == 0, all the messages in the file are shown.
// If qry > 0, only the messages related to query 'qry' are shown.
// For qry != -1 the original file offset is restored at the end
// Save present offset
Int_t nowlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_CUR);
// Get extremes
Int_t startlog = nowlog;
Int_t endlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_END);
lseek(fileno(fLogFileR), (off_t) nowlog, SEEK_SET);
if (qry == 0) {
startlog = 0;
lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET);
} else if (qry != -1) {
TQueryResult *pq = 0;
if (qry == -2) {
// Pickup the last one
pq = (GetQueryResults()) ? ((TQueryResult *)(GetQueryResults()->Last())) : 0;
if (!pq) {
GetListOfQueries();
if (fQueries)
pq = (TQueryResult *)(fQueries->Last());
}
} else if (qry > 0) {
TList *queries = GetQueryResults();
if (queries) {
TIter nxq(queries);
while ((pq = (TQueryResult *)nxq()))
if (qry == pq->GetSeqNum())
break;
}
if (!pq) {
queries = GetListOfQueries();
TIter nxq(queries);
while ((pq = (TQueryResult *)nxq()))
if (qry == pq->GetSeqNum())
break;
}
}
if (pq) {
PutLog(pq);
return;
} else {
if (gDebug > 0)
Info("ShowLog","query %d not found in list", qry);
qry = -1;
}
}
// Number of bytes to log
UInt_t tolog = (UInt_t)(endlog - startlog);
// Perhaps nothing
if (tolog <= 0)
// Set starting point
lseek(fileno(fLogFileR), (off_t) startlog, SEEK_SET);
// Now we go
Int_t np = 0;
char line[2048];
Int_t wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog;
while (fgets(line, wanted, fLogFileR)) {
Int_t r = strlen(line);
if (!SendingLogToWindow()) {
if (line[r-1] != '\n') line[r-1] = '\n';
if (r > 0) {
char *p = line;
while (r) {
Int_t w = write(fileno(stdout), p, r);
if (w < 0) {
SysError("ShowLogFile", "error writing to stdout");
break;
}
r -= w;
p += w;
}
}
tolog -= strlen(line);
np++;
// Ask if more is wanted
if (!(np%10)) {
char *opt = Getline("More (y/n)? [y]");
if (opt[0] == 'n')
break;
}
// We may be over
if (tolog <= 0)
break;
// Update wanted bytes
wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog;
} else {
// Log to window
if (line[r-1] == '\n') line[r-1] = 0;
LogMessage(line, kFALSE);
}
}
if (!SendingLogToWindow()) {
// Avoid screwing up the prompt
write(fileno(stdout), "\n", 1);
}
// Restore original pointer
if (qry > -1)
lseek(fileno(fLogFileR), (off_t) nowlog, SEEK_SET);
}
//______________________________________________________________________________
void TProof::cd(Int_t id)
{
// Set session with 'id' the default one. If 'id' is not found in the list,
// the current session is set as default
if (GetManager()) {
TProofDesc *d = GetManager()->GetProofDesc(id);
if (d) {
if (d->GetProof()) {
gProof = d->GetProof();
return;
}
}
// Id not found or undefined: set as default this session
gProof = this;
}
return;
}
//______________________________________________________________________________
void TProof::Detach(Option_t *opt)
{
// Detach this instance to its proofserv.
// If opt is 'S' or 's' the remote server is shutdown
// Nothing to do if not in contact with proofserv
if (!IsValid()) return;
// Get worker and socket instances
TSlave *sl = (TSlave *) fActiveSlaves->First();
TSocket *s = sl->GetSocket();
if (!sl || !(sl->IsValid()) || !s) {
Error("Detach","corrupted worker instance: wrk:%p, sock:%p", sl, s);
return;
}
Bool_t shutdown = (strchr(opt,'s') || strchr(opt,'S')) ? kTRUE : kFALSE;
// If processing, try to stop processing first
if (shutdown && !IsIdle()) {
// Remove pending requests
Remove("cleanupqueue");
// Do not wait for ever, but al least 20 seconds
Long_t timeout = gEnv->GetValue("Proof.ShutdownTimeout", 60);
timeout = (timeout > 20) ? timeout : 20;
// Send stop signal
StopProcess(kFALSE, (Long_t) (timeout / 2));
// Receive results
Collect(kActive, timeout);
}
// Avoid spurious messages: deactivate new inputs ...
DeActivateAsyncInput();
// ... and discard existing ones
sl->FlushSocket();
// Close session (we always close the connection)
Close(opt);
// Close the progress dialog, if any
if (fProgressDialogStarted)
CloseProgressDialog();
// Update info in the table of our manager, if any
if (GetManager() && GetManager()->QuerySessions("L")) {
TIter nxd(GetManager()->QuerySessions("L"));
TProofDesc *d = 0;
while ((d = (TProofDesc *)nxd())) {
if (d->GetProof() == this) {
d->SetProof(0);
GetManager()->QuerySessions("L")->Remove(d);
break;
}
}
}
// Delete this instance
if (!fProgressDialogStarted)
delete this;
else
// ~TProgressDialog will delete this
fValid = kFALSE;
return;
}
//______________________________________________________________________________
void TProof::SetAlias(const char *alias)
{
// Set an alias for this session. If reconnection is supported, the alias
// will be communicated to the remote coordinator so that it can be recovered
// when reconnecting
// Set it locally
TNamed::SetTitle(alias);
if (IsMaster())
// Set the name at the same value
TNamed::SetName(alias);
// Nothing to do if not in contact with coordinator
if (!IsValid()) return;
if (!IsProofd() && !IsMaster()) {
TSlave *sl = (TSlave *) fActiveSlaves->First();
if (sl)
sl->SetAlias(alias);
}
return;
}
//______________________________________________________________________________
Int_t TProof::UploadDataSet(const char *dataSetName,
TList *files,
const char *desiredDest,
Int_t opt,
TList *skippedFiles)
{
// Upload a set of files and save the list of files by name dataSetName.
// The 'files' argument is a list of TFileInfo objects describing the files
// as first url.
// The mask 'opt' is a combination of EUploadOpt:
// kAppend (0x1) if set true files will be appended to
// the dataset existing by given name
// kOverwriteDataSet (0x2) if dataset with given name exited it
// would be overwritten
// kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists
// kOverwriteAllFiles (0x8) overwrite all files that may exist
// kOverwriteNoFiles (0x10) overwrite none
// kAskUser (0x0) ask user before overwriteng dataset/files
// The default value is kAskUser.
// The user will be asked to confirm overwriting dataset or files unless
// specified opt provides the answer!
// If kOverwriteNoFiles is set, then a pointer to TList must be passed as
// skippedFiles argument. The function will add to this list TFileInfo
// objects describing all files that existed on the cluster and were
// not uploaded.
//
// Communication Summary
// Client Master
// |------------>DataSetName----------->|
// |<-------kMESS_OK/kMESS_NOTOK<-------| (Name OK/file exist)
// (*)|-------> call CreateDataSet ------->|
// (*) - optional
// check if dataSetName is not excluded
if (strchr(dataSetName, '/')) {
if (strstr(dataSetName, "public") != dataSetName) {
Error("UploadDataSet",
"Name of public dataset should start with public/");
return kError;
}
}
if (opt & kOverwriteAllFiles && opt & kOverwriteNoFiles
|| opt & kNoOverwriteDataSet && opt & kAppend
|| opt & kOverwriteDataSet && opt & kAppend
|| opt & kNoOverwriteDataSet && opt & kOverwriteDataSet
|| opt & kAskUser && opt & (kOverwriteDataSet |
kNoOverwriteDataSet |
kAppend |
kOverwriteAllFiles |
kOverwriteNoFiles)) {
Error("UploadDataSet", "you specified contradicting options.");
return kError;
}
// Decode options
Int_t overwriteAll = (opt & kOverwriteAllFiles) ? kTRUE : kFALSE;
Int_t overwriteNone = (opt & kOverwriteNoFiles) ? kTRUE : kFALSE;
Int_t goodName = (opt & (kOverwriteDataSet | kAppend)) ? 1 : -1;
Int_t appendToDataSet = (opt & kAppend) ? kTRUE : kFALSE;
Int_t overwriteNoDataSet = (opt & kNoOverwriteDataSet) ? kTRUE : kFALSE;
//If skippedFiles is not provided we can not return list of skipped files.
if ((!skippedFiles || !&skippedFiles) && overwriteNone) {
Error("UploadDataSet",
"Provide pointer to TList object as skippedFiles argument when using kOverwriteNoFiles option.");
return kError;
}
//If skippedFiles is provided but did not point to a TList the have to STOP
if (skippedFiles && &skippedFiles)
if (skippedFiles->Class() != TList::Class()) {
Error("UploadDataSet",
"Provided skippedFiles argument does not point to a TList object.");
return kError;
}
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("UploadDataSet", "No connection to the master!");
return kError;
}
Int_t fileCount = 0; // return value
TMessage *retMess;
if (goodName == -1) { // -1 for undefined
// First check whether this dataset already exists unless
// kAppend or kOverWriteDataSet
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kCheckDataSetName);
nameMess << TString(dataSetName);
Broadcast(nameMess);
master->Recv(retMess);
Collect(); //after each call to HandleDataSets
if (retMess->What() == kMESS_NOTOK) {
//We ask user to agree on overwriting the dataset name
while (goodName == -1 && !overwriteNoDataSet) {
Printf("Dataset %s already exist. ",
dataSetName);
Printf("Do you want to overwrite it[Yes/No/Append]?");
TString answer;
answer.ReadToken(cin);
if (!strncasecmp(answer.Data(), "y", 1)) {
goodName = 1;
} else if (!strncasecmp(answer.Data(), "n", 1)) {
goodName = 0;
} else if (!strncasecmp(answer.Data(), "a", 1)) {
goodName = 1;
appendToDataSet = kTRUE;
}
}
}
else if (retMess->What() == kMESS_OK)
goodName = 1;
else
Error("UploadDataSet", "unrecongnized message type: %d!",
retMess->What());
delete retMess;
} // if (goodName == -1)
if (goodName == 1) { //must be == 1 as -1 was used for a bad name!
//Code for enforcing writing in user "home dir" only
char *relativeDestDir = Form("%s/%s/",
gSystem->GetUserInfo()->fUser.Data(),
desiredDest?desiredDest:"");
//Consider adding dataSetName to the path
relativeDestDir = CollapseSlashesInPath(relativeDestDir);
TString dest = Form("%s/%s", GetDataPoolUrl(), relativeDestDir);
delete[] relativeDestDir;
// Now we will actually copy files and create the TList object
TList *fileList = new TList();
//rdm fix TFileMerger fileCopier;
TIter next(files);
while (TFileInfo *fileInfo = ((TFileInfo*)next())) {
TUrl *fileUrl = fileInfo->GetFirstUrl();
if (gSystem->AccessPathName(fileUrl->GetUrl()) == kFALSE) {
//matching dir entry
//getting the file name from the path represented by fileUrl
const char *ent = gSystem->BaseName(fileUrl->GetFile());
Int_t goodFileName = 1;
if (!overwriteAll &&
gSystem->AccessPathName(Form("%s/%s", dest.Data(), ent), kFileExists)
== kFALSE) { //Destination file exists
goodFileName = -1;
while (goodFileName == -1 && !overwriteAll && !overwriteNone) {
Printf("File %s already exists. ", Form("%s/%s", dest.Data(), ent));
Printf("Do you want to overwrite it [Yes/No/all/none]?");
TString answer;
answer.ReadToken(cin);
if (!strncasecmp(answer.Data(), "y", 1))
goodFileName = 1;
else if (!strncasecmp(answer.Data(), "all", 3))
overwriteAll = kTRUE;
else if (!strncasecmp(answer.Data(), "none", 4))
overwriteNone = kTRUE;
else if (!strncasecmp(answer.Data(), "n", 1))
goodFileName = 0;
}
} //if file exists
// Copy the file to the redirector indicated
if (goodFileName == 1 || overwriteAll) {
//must be == 1 as -1 was meant for bad name!
Printf("Uploading %s to %s/%s",
fileUrl->GetUrl(), dest.Data(), ent);
#if 0
//rdm fix if (fileCopier.Cp(fileUrl->GetUrl(),
Form("%s/%s", dest.Data(), ent))) {
fileList->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent)));
} else
Error("UploadDataSet", "file %s was not copied", fileUrl->GetUrl());
#endif
} else { // don't overwrite, but file exist and must be included
fileList->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent)));
if (skippedFiles && &skippedFiles) {
// user specified the TList *skippedFiles argument so we create
// the list of skipped files
skippedFiles->Add(new TFileInfo(fileUrl->GetUrl()));
}
}
} //if matching dir entry
} //while
if ((fileCount = fileList->GetSize()) == 0) {
Printf("No files were copied. The dataset will not be saved");
} else {
if (CreateDataSet(dataSetName, fileList,
appendToDataSet?kAppend:kOverwriteDataSet) <= 0) {
Error("UploadDataSet", "Error while saving dataset!");
fileCount = kError;
}
}
fileList->SetOwner();
delete fileList;
} else if (overwriteNoDataSet) {
Printf("Dataset %s already exists", dataSetName);
return kDataSetExists;
} //if(goodName == 1)
return fileCount;
}
//______________________________________________________________________________
Int_t TProof::UploadDataSet(const char *dataSetName,
const char *files,
const char *desiredDest,
Int_t opt,
TList *skippedFiles)
{
// Upload a set of files and save the list of files by name dataSetName.
// The mask 'opt' is a combination of EUploadOpt:
// kAppend (0x1) if set true files will be appended to
// the dataset existing by given name
// kOverwriteDataSet (0x2) if dataset with given name exited it
// would be overwritten
// kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists
// kOverwriteAllFiles (0x8) overwrite all files that may exist
// kOverwriteNoFiles (0x10) overwrite none
// kAskUser (0x0) ask user before overwriteng dataset/files
// The default value is kAskUser.
// The user will be asked to confirm overwriting dataset or files unless
// specified opt provides the answer!
// If kOverwriteNoFiles is set, then a pointer to TList must be passed as
// skippedFiles argument. The function will add to this list TFileInfo
// objects describing all files that existed on the cluster and were
// not uploaded.
//
TList *fileList = new TList();
void *dataSetDir = gSystem->OpenDirectory(gSystem->DirName(files));
const char* ent;
TString filesExp(gSystem->BaseName(files));
filesExp.ReplaceAll("*",".*");
TRegexp rg(filesExp);
while ((ent = gSystem->GetDirEntry(dataSetDir))) {
TString entryString(ent);
if (entryString.Index(rg) != kNPOS) {
//matching dir entry
// Creating the intermediate TUrl with kTRUE flag to make sure
// file:// is added for a local file
TUrl *url = new TUrl(Form("%s/%s",
gSystem->DirName(files), ent), kTRUE);
if (gSystem->AccessPathName(url->GetUrl(), kReadPermission) == kFALSE)
fileList->Add(new TFileInfo(url->GetUrl()));
delete url;
} //if matching dir entry
} //while
Int_t fileCount;
if ((fileCount = fileList->GetSize()) == 0)
Printf("No files match your selection. The dataset will not be saved");
else
fileCount = UploadDataSet(dataSetName, fileList, desiredDest,
opt, skippedFiles);
fileList->SetOwner();
delete fileList;
return fileCount;
}
//______________________________________________________________________________
Int_t TProof::UploadDataSetFromFile(const char *dataset, const char *file,
const char *dest, Int_t opt)
{
// Upload files listed in "file" to PROOF cluster.
// Where file = name of file containing list of files and
// dataset = dataset name and opt is a combination of EUploadOpt bits.
// Each file description (line) can include wildcards.
//TODO: This method should use UploadDataSet(char *dataset, TList *l, ...)
Int_t fileCount = 0;
ifstream f;
f.open(gSystem->ExpandPathName(file), ifstream::out);
if (f.is_open()) {
while (f.good()) {
TString line;
line.ReadToDelim(f);
if (fileCount == 0) {
// when uploading the first file user may have to decide
fileCount += UploadDataSet(dataset, line.Data(), dest, opt);
} else // later - just append
fileCount += UploadDataSet(dataset, line.Data(), dest,
opt | kAppend);
}
f.close();
} else {
Error("UploadDataSetFromFile", "unable to open the specified file");
return -1;
}
return fileCount;
}
//______________________________________________________________________________
Int_t TProof::CreateDataSet(const char *dataSetName,
TList *files,
Int_t opt)
{
// Create a dataSet from files existing on the cluster (listed in files)
// and save it as dataSetName.
// No files are uploaded nor verified to exist on the cluster
// The 'files' argument is a list of TFileInfo objects describing the files
// as first url.
// The mask 'opt' is a combination of EUploadOpt:
// kAppend (0x1) if set true files will be appended to
// the dataset existing by given name
// kOverwriteDataSet (0x2) if dataset with given name exited it
// would be overwritten
// kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists
// kAskUser (0x0) ask user before overwriteng dataset/files
// The default value is kAskUser.
// The user will be asked to confirm overwriting dataset or files unless
// specified opt provides the answer!
//
// Communication Summary
// Client Master
// |------------>DataSetName----------->|
// |<-------kMESS_OK/kMESS_NOTOK<-------| (Name OK/file exist)
// (*)|------->TList of TFileInfo -------->| (dataset to save)
// (*)|<-------kMESS_OK/kMESS_NOTOK<-------| (transaction complete?)
// (*) - optional
// check if dataSetName is not excluded
if (strchr(dataSetName, '/')) {
if (strstr(dataSetName, "public") != dataSetName) {
Error("CreateDataSet",
"Name of public dataset should start with public/");
return kError;
}
}
if (opt & kOverwriteDataSet && opt & kAppend
|| opt & kNoOverwriteDataSet && opt & kAppend
|| opt & kNoOverwriteDataSet && opt & kOverwriteDataSet
|| opt & kAskUser && opt & (kOverwriteDataSet |
kNoOverwriteDataSet |
kAppend)) {
Error("CreateDataSet", "you specified contradicting options.");
return kError;
}
if (opt & kOverwriteAllFiles || opt & kOverwriteNoFiles) {
Error("CreateDataSet", "you specified unsupported options.");
return kError;
}
// Decode options
Int_t goodName = (opt & (kOverwriteDataSet | kAppend)) ? 1 : -1;
Int_t appendToDataSet = (opt & kAppend) ? kTRUE : kFALSE;
Int_t overwriteNoDataSet = (opt & kNoOverwriteDataSet) ? kTRUE : kFALSE;
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("CreateDataSet", "No connection to the master!");
return kError;
}
Int_t fileCount = 0; // return value
//TODO Below if statement is a copy from UploadDataSet
TMessage *retMess;
if (goodName == -1) { // -1 for undefined
// First check whether this dataset already exist unless
// kAppend or kOverWriteDataSet
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kCheckDataSetName);
nameMess << TString(dataSetName);
Broadcast(nameMess);
master->Recv(retMess);
Collect(); //after each call to HandleDataSets
if (retMess->What() == kMESS_NOTOK) {
//We ask user to agree on overwriting the dataset name
while (goodName == -1 && !overwriteNoDataSet) {
Printf("Dataset %s already exists. ",
dataSetName);
Printf("Do you want to overwrite it[Yes/No/Append]?");
TString answer;
answer.ReadToken(cin);
if (!strncasecmp(answer.Data(), "y", 1)) {
goodName = 1;
} else if (!strncasecmp(answer.Data(), "n", 1)) {
goodName = 0;
} else if (!strncasecmp(answer.Data(), "a", 1)) {
goodName = 1;
appendToDataSet = kTRUE;
}
}
}
else if (retMess->What() == kMESS_OK)
goodName = 1;
else
Error("CreateDataSet", "unrecongnized message type: %d!",
retMess->What());
delete retMess;
} // if (goodName == -1)
if (goodName == 1) {
if ((fileCount = files->GetSize()) == 0) {
Printf("No files specified!");
} else {
TMessage mess(kPROOF_DATASETS);
if (appendToDataSet)
mess << Int_t(kAppendDataSet);
else
mess << Int_t(kCreateDataSet);
mess << TString(dataSetName);
mess.WriteObject(files);
Broadcast(mess);
//Reusing the retMess.
if (master->Recv(retMess) <= 0) {
Error("CreateDataSet", "No response form the master");
fileCount = -1;
} else {
if (retMess->What() == kMESS_NOTOK) {
Printf("Dataset was not saved.");
fileCount = -1;
} else if (retMess->What() != kMESS_OK)
Error("CreateDataSet",
"Unexpected message type: %d", retMess->What());
delete retMess;
}
}
} else if (overwriteNoDataSet) {
Printf("Dataset %s already exists", dataSetName);
Collect();
return kDataSetExists;
} //if(goodName == 1)
Collect();
return fileCount;
}
//______________________________________________________________________________
TList *TProof::GetDataSets(const char *dir)
{
// Get TList of TObjStrings with all datasets available on master:
// * with dir undifined - just ls contents of ~/proof/datasets,
// * with dir == "public" - ls ~/proof/datasets/public
// * with dir == "~username/public" - ls ~/username/datasets/public
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("GetDataSets", "No connection to the master!");
return 0;
}
if (dir) {
// check if dir is correct; this check is not exhaustive
if (strstr(dir, "public") != dir && strchr(dir, '~') != dir) {
// dir does not start with "public" nor with '~'
Error("GetDataSets",
"directory should be of form '[~userName/]public'");
return 0;
}
}
TMessage mess(kPROOF_DATASETS);
mess << Int_t(kGetDataSets);
mess << TString(dir?dir:"");
Broadcast(mess);
TMessage *retMess;
master->Recv(retMess);
TList *dataSetList = 0;
if (retMess->What() == kMESS_OBJECT) {
dataSetList = (TList*)(retMess->ReadObject(TList::Class()));
if (!dataSetList)
Error("GetDataSets", "Error receiving list of datasets");
} else
Printf("The dataset directory could not be open");
Collect();
delete retMess;
return dataSetList;
}
//______________________________________________________________________________
void TProof::ShowDataSets(const char *dir)
{
// Show all datasets uploaded to the cluster (just ls contents of
// ~/proof/datasets or user/proof/datasets/public if 'dir' is defined).
// * with dir undifined - just ls contents of ~/proof/datasets,
// * with dir == "public" - ls ~/proof/datasets/public
// * with dir == "~username/public" - ls ~/username/datasets/public
TList *dataSetList;
if ((dataSetList = GetDataSets(dir))) {
if (dir)
Printf("DataSets in %s :", dir);
else
Printf("Existing DataSets:");
TIter next(dataSetList);
while (TObjString *obj = (TObjString*)next())
Printf("%s", obj->GetString().Data());
dataSetList->SetOwner();
delete dataSetList;
} else
Printf("Error getting a list of datasets");
}
//______________________________________________________________________________
TList *TProof::GetDataSet(const char *dataset)
{
// Get a list of TFileInfo objects describing the files of the specified
// dataset.
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("GetDataSet", "No connection to the master!");
return 0;
}
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kGetDataSet);
nameMess << TString(dataset);
if (Broadcast(nameMess) < 0)
Error("GetDataSet", "Sending request failed");
TMessage *retMess;
master->Recv(retMess);
TList *fileList = 0;
if (retMess->What() == kMESS_OK) {
if (!(fileList = (TList*)(retMess->ReadObject(TList::Class()))))
Error("GetDataSet", "Error reading list of files");
} else if (retMess->What() != kMESS_NOTOK)
Error("GetDataSet", "Wrong message type %d", retMess->What());
Collect();
delete retMess;
return fileList;
}
//______________________________________________________________________________
void TProof::ShowDataSet(const char *dataset)
{
//Show content of specific dataset (cat ~/proof/datasets/dataset).
TList *fileList;
if ((fileList = GetDataSet(dataset))) {
if (fileList->GetSize()) {
//printing sorted list
Printf("Files in %s:", dataset);
TIter next(fileList);
while (TFileInfo *obj = (TFileInfo*)next())
Printf("%s", obj->GetFirstUrl()->GetUrl());
} else
Printf("There are no files in %s", dataset);
delete fileList;
}
else
Printf("No such dataset: %s", dataset);
}
//______________________________________________________________________________
Int_t TProof::RemoveDataSet(const char *dataSet)
{
// Remove the specified dataset from the PROOF cluster.
// Files are not deleted.
// check if dataSetName is not excluded
// if (strchr(dataSet, '/')) {
// Error("RemoveDataSet", "Dataset name shall not include '/'");
// return kError;
// }
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("RemoveDataSet", "No connection to the master!");
return kError;
}
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kRemoveDataSet);
nameMess << TString(dataSet);
if (Broadcast(nameMess) < 0)
Error("RemoveDataSet", "Sending request failed");
TMessage *mess;
TString errorMess;
master->Recv(mess);
Collect();
if (mess->What() != kMESS_OK) {
if (mess->What() != kMESS_NOTOK)
Error("RemoveDataSet", "unrecongnized message type: %d!",
mess->What());
delete mess;
return -1;
} else {
delete mess;
return 0;
}
}
//______________________________________________________________________________
Int_t TProof::VerifyDataSet(const char *dataSet)
{
// Verify if all files in the specified dataset are available.
// Print a list and return the number of missing files.
Int_t nMissingFiles = 0;
TSocket *master;
if (fActiveSlaves->GetSize())
master = ((TSlave*)(fActiveSlaves->First()))->GetSocket();
else {
Error("VerifyDataSet", "No connection to the master!");
return kError;
}
TMessage nameMess(kPROOF_DATASETS);
nameMess << Int_t(kVerifyDataSet);
nameMess << TString(dataSet);
if (Broadcast(nameMess) < 0)
Error("VerifyDataSet", "Sending request failed");
TMessage *mess;
master->Recv(mess);
Collect();
if (mess->What() == kMESS_OK) {
TList *missingFiles;
missingFiles = (TList*)(mess->ReadObject(TList::Class()));
nMissingFiles = missingFiles->GetSize();
if (nMissingFiles == 0)
Printf("The files from %s dataset are all present on the cluster",
dataSet);
else {
Printf("The following files are missing from dataset %s ", dataSet);
Printf("at the moment:");
TIter next(missingFiles);
TFileInfo* fileInfo;
while ((fileInfo = (TFileInfo*)next())) {
Printf("\t%s", fileInfo->GetFirstUrl()->GetUrl());
}
}
missingFiles->SetOwner();
delete missingFiles;
} else if (mess->What() == kMESS_NOTOK) {
Printf("ValidateDataSet: no such dataset %s", dataSet);
delete mess;
return -1;
} else
Fatal("ValidateDataSet", "unknown message type %d", mess->What());
delete mess;
return nMissingFiles;
}
//_____________________________________________________________________________
void TProof::InterruptCurrentMonitor()
{
// If in active in a monitor set ready state
if (fCurrentMonitor)
fCurrentMonitor->Interrupt();
}
//_____________________________________________________________________________
void TProof::ActivateWorker(const char *ord)
{
// Make sure that the worker identified by the ordinal number 'ord' is
// in the active list. The request will be forwarded to the master
// in direct contact with the worker. If needed, this master will move
// the worker from the inactive to the active list and rebuild the list
// of unique workers.
// Use ord = "*" to activate all inactive workers.
ModifyWorkerLists(ord, kTRUE);
}
//_____________________________________________________________________________
void TProof::DeactivateWorker(const char *ord)
{
// Remove the worker identified by the ordinal number 'ord' from the
// the active list. The request will be forwarded to the master
// in direct contact with the worker. If needed, this master will move
// the worker from the active to the inactive list and rebuild the list
// of unique workers.
// Use ord = "*" to deactivate all active workers.
ModifyWorkerLists(ord, kFALSE);
}
//_____________________________________________________________________________
void TProof::ModifyWorkerLists(const char *ord, Bool_t add)
{
// Modify the worker active/inactive list by making the worker identified by
// the ordinal number 'ord' active (add == TRUE) or inactive (add == FALSE).
// If needed, the request will be forwarded to the master in direct contact
// with the worker. The end-master will move the worker from one list to the
// other active and rebuild the list of unique active workers.
// Use ord = "*" to deactivate all active workers.
// Make sure the input make sense
if (!ord || strlen(ord) <= 0) {
Info("ModifyWorkerLists",
"An ordinal number - e.g. \"0.4\" or \"*\" for all - is required as input");
return;
}
Bool_t fw = kTRUE; // Whether to forward one step down
Bool_t rs = kFALSE; // Whether to rescan for unique workers
// Appropriate list pointing
TList *in = (add) ? fInactiveSlaves : fActiveSlaves;
TList *out = (add) ? fActiveSlaves : fInactiveSlaves;
if (IsMaster()) {
fw = IsEndMaster() ? kFALSE : kTRUE;
// Look for the worker in the inactive list
if (in->GetSize() > 0) {
TIter nxw(in);
TSlave *wrk = 0;
while ((wrk = (TSlave *) nxw())) {
if (ord[0] == '*' || !strncmp(wrk->GetOrdinal(), ord, strlen(ord))) {
// Add it to the inactive list
if (!out->FindObject(wrk)) {
out->Add(wrk);
if (add)
fActiveMonitor->Add(wrk->GetSocket());
}
// Remove it from the active list
in->Remove(wrk);
if (!add) {
fActiveMonitor->Remove(wrk->GetSocket());
wrk->SetStatus(TSlave::kInactive);
} else
wrk->SetStatus(TSlave::kActive);
// Nothing to forward (ord is unique)
fw = kFALSE;
// Rescan for unique workers (active list modified)
rs = kTRUE;
// We are done, if not option 'all'
if (ord[0] != '*')
break;
}
}
}
}
// Rescan for unique workers
if (rs)
FindUniqueSlaves();
// Forward the request one step down, if needed
Int_t action = (add) ? (Int_t) kActivateWorker : (Int_t) kDeactivateWorker;
if (fw) {
TMessage mess(kPROOF_WORKERLISTS);
mess << action << TString(ord);
Broadcast(mess);
Collect();
}
}
//_____________________________________________________________________________
TProof *TProof::Open(const char *cluster, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Start a PROOF session on a specific cluster. If cluster is 0 (the
// default) then the PROOF Session Viewer GUI pops up and 0 is returned.
// If cluster is "" (empty string) then we connect to a PROOF session
// on the localhost ("proof://localhost"). Via conffile a specific
// PROOF config file in the confir directory can be specified.
// Use loglevel to set the default loging level for debugging.
// The appropriate instance of TProofMgr is created, if not
// yet existing. The instantiated TProof object is returned.
// Use TProof::cd() to switch between PROOF sessions.
// For more info on PROOF see the TProof ctor.
const char *pn = "TProof::Open";
// Make sure libProof and dependents are loaded and TProof can be created,
// dependents are loaded via the information in the [system].rootmap file
if (!cluster) {
TPluginManager *pm = gROOT->GetPluginManager();
if (!pm) {
::Error(pn, "plugin manager not found");
return 0;
}
if (gROOT->IsBatch()) {
::Error(pn, "we are in batch mode, cannot show PROOF Session Viewer");
return 0;
}
// start PROOF Session Viewer
TPluginHandler *sv = pm->FindHandler("TSessionViewer", "");
if (!sv) {
::Error(pn, "no plugin found for TSessionViewer");
return 0;
}
if (sv->LoadPlugin() == -1) {
::Error(pn, "plugin for TSessionViewer could not be loaded");
return 0;
}
sv->ExecPlugin(0);
return 0;
} else {
// Parse input URL
TUrl u(cluster);
// Find out if we are required to attach to a specific session
TString o(u.GetOptions());
Int_t locid = -1;
Bool_t create = kFALSE;
if (o.Length() > 0) {
if (o.BeginsWith("N",TString::kIgnoreCase)) {
create = kTRUE;
} else if (o.IsDigit()) {
locid = o.Atoi();
}
u.SetOptions("");
}
// Attach-to or create the appropriate manager
TProofMgr *mgr = TProofMgr::Create(u.GetUrl());
TProof *proof = 0;
if (mgr && mgr->IsValid()) {
// If XProofd we always attempt an attach first (unless
// explicitely not requested).
Bool_t attach = (create || mgr->IsProofd()) ? kFALSE : kTRUE;
if (attach) {
TProofDesc *d = 0;
if (locid < 0)
// Get the list of sessions
d = (TProofDesc *) mgr->QuerySessions("")->First();
else
d = (TProofDesc *) mgr->GetProofDesc(locid);
if (d) {
proof = (TProof*) mgr->AttachSession(d->GetLocalId());
if (!proof || !proof->IsValid()) {
if (locid)
::Error(pn, "new session could not be attached");
SafeDelete(proof);
}
}
}
// start the PROOF session
if (!proof) {
proof = (TProof*) mgr->CreateSession(conffile, confdir, loglevel);
if (!proof || !proof->IsValid()) {
::Error(pn, "new session could not be created");
SafeDelete(proof);
}
}
}
return proof;
}
}
//_____________________________________________________________________________
TProofMgr *TProof::Mgr(const char *url)
{
// Get instance of the effective manager for 'url'
// Return 0 on failure.
if (!url)
return (TProofMgr *)0;
// Attach or create the relevant instance
return TProofMgr::Create(url);
}
//_____________________________________________________________________________
void TProof::Reset(const char *url)
{
// Wrapper around TProofMgr::Reset().
if (url) {
TProofMgr *mgr = TProof::Mgr(url);
if (mgr && mgr->IsValid())
mgr->Reset();
else
::Error("TProof::Reset",
"unable to initialize a valid manager instance");
}
}
//_____________________________________________________________________________
const TList *TProof::GetEnvVars()
{
// Get environemnt variables.
return fgProofEnvList;
}
//_____________________________________________________________________________
void TProof::AddEnvVar(const char *name, const char *value)
{
// Add an variable to the list of environment variables passed to proofserv
// on the master and slaves
if (gDebug > 0) ::Info("TProof::AddEnvVar","%s=%s", name, value);
if (fgProofEnvList == 0) {
// initialize the list if needed
fgProofEnvList = new TList;
fgProofEnvList->SetOwner();
} else {
// replace old entries with the same name
TObject *o = fgProofEnvList->FindObject(name);
if (o != 0) {
fgProofEnvList->Remove(o);
}
}
fgProofEnvList->Add(new TNamed(name, value));
}
//_____________________________________________________________________________
void TProof::DelEnvVar(const char *name)
{
// Remove an variable from the list of environment variables passed to proofserv
// on the master and slaves
if (fgProofEnvList == 0) return;
TObject *o = fgProofEnvList->FindObject(name);
if (o != 0) {
fgProofEnvList->Remove(o);
}
}
//_____________________________________________________________________________
void TProof::ResetEnvVars()
{
// Clear the list of environment variables passed to proofserv
// on the master and slaves
if (fgProofEnvList == 0) return;
SafeDelete(fgProofEnvList);
}
//______________________________________________________________________________
void TProof::SaveWorkerInfo()
{
// Save informations about the worker set in the file .workers in the working
// dir. Called each time there is a change in the worker setup, e.g. by
// TProof::MarkBad().
// We must be masters
if (!IsMaster())
return;
// We must have a server defined
if (!gProofServ) {
Error("SaveWorkerInfo","gProofServ undefined");
return;
}
// Update info
const_cast<TProof*>(this)->AskStatistics();
// The relevant lists must be defined
if (!fSlaves && !fBadSlaves) {
Warning("SaveWorkerInfo","all relevant worker lists is undefined");
return;
}
// Create or truncate the file first
TString fnwrk = Form("%s/.workers",
gSystem->DirName(gProofServ->GetSessionDir()));
FILE *fwrk = fopen(fnwrk.Data(),"w");
if (!fwrk) {
Error("SaveWorkerInfo",
"cannot open %s for writing (errno: %d)", fnwrk.Data(), errno);
return;
}
// Loop over the list of workers (active is any worker not flagged as bad)
TIter nxa(fSlaves);
TSlave *wrk = 0;
while ((wrk = (TSlave *) nxa())) {
Int_t status = (fBadSlaves && fBadSlaves->FindObject(wrk)) ? 0 : 1;
// Write out record for this worker
fprintf(fwrk,"%s@%s:%d %d %s %s.log\n",
wrk->GetUser(), wrk->GetName(), wrk->GetPort(), status,
wrk->GetOrdinal(), wrk->GetWorkDir());
}
// Close file
fclose(fwrk);
// We are done
return;
}
|
#include "GeoCoordinate.hpp"
#include "builders/MeshContext.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "builders/buildings/BuildingBuilder.hpp"
#include "builders/buildings/facades/CylinderFacadeBuilder.hpp"
#include "builders/buildings/facades/FlatFacadeBuilder.hpp"
#include "builders/buildings/facades/SphereFacadeBuilder.hpp"
#include "builders/buildings/roofs/DomeRoofBuilder.hpp"
#include "builders/buildings/roofs/FlatRoofBuilder.hpp"
#include "builders/buildings/roofs/PyramidalRoofBuilder.hpp"
#include "builders/buildings/roofs/MansardRoofBuilder.hpp"
#include "builders/buildings/roofs/SkillionRoofBuilder.hpp"
#include "builders/buildings/roofs/RoundRoofBuilder.hpp"
using namespace utymap;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::math;
using namespace utymap::index;
using namespace utymap::utils;
namespace {
const std::string MeshNamePrefix = "building:";
const std::string RoofPrefix = "roof-";
const std::string RoofTypeKey = RoofPrefix + StyleConsts::TypeKey();
const std::string RoofHeightKey = RoofPrefix + StyleConsts::HeightKey();
const std::string RoofGradientKey = RoofPrefix + StyleConsts::GradientKey();
const std::string RoofTextureIndexKey = RoofPrefix + StyleConsts::TextureIndexKey();
const std::string RoofTextureTypeKey = RoofPrefix + StyleConsts::TextureTypeKey();
const std::string RoofTextureScaleKey = RoofPrefix + StyleConsts::TextureScaleKey();
const std::string RoofDirectionKey = RoofPrefix + StyleConsts::DirectionKey();
const std::string FacadePrefix = "facade-";
const std::string FacadeTypeKey = FacadePrefix + StyleConsts::TypeKey();
const std::string FacadeGradientKey = FacadePrefix + StyleConsts::GradientKey();
const std::string FacadeTextureIndexKey = FacadePrefix + StyleConsts::TextureIndexKey();
const std::string FacadeTextureTypeKey = FacadePrefix + StyleConsts::TextureTypeKey();
const std::string FacadeTextureScaleKey = FacadePrefix + StyleConsts::TextureScaleKey();
/// Defines roof builder which does nothing.
class EmptyRoofBuilder : public RoofBuilder {
public:
EmptyRoofBuilder(const BuilderContext &bc, MeshContext &mc)
: RoofBuilder(bc, mc) {}
void build(Polygon &) override {}
};
typedef std::function<std::unique_ptr<RoofBuilder>(const BuilderContext &, MeshContext &)> RoofBuilderFactory;
std::unordered_map<std::string, RoofBuilderFactory> RoofBuilderFactoryMap =
{
{
"none",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<EmptyRoofBuilder>(builderContext, meshContext);
}
},
{
"flat",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<FlatRoofBuilder>(builderContext, meshContext);
}
},
{
"dome",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<DomeRoofBuilder>(builderContext, meshContext);
}
},
{
"pyramidal",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<PyramidalRoofBuilder>(builderContext, meshContext);
}
},
{
"mansard",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<MansardRoofBuilder>(builderContext, meshContext);
}
},
{
"skillion",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<SkillionRoofBuilder>(builderContext, meshContext);
}
},
{
"round",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<RoundRoofBuilder>(builderContext, meshContext);
}
}
};
typedef std::function<std::unique_ptr<FacadeBuilder>(const BuilderContext &, MeshContext &)> FacadeBuilderFactory;
std::unordered_map<std::string, FacadeBuilderFactory> FacadeBuilderFactoryMap =
{
{
"flat",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<FlatFacadeBuilder>(builderContext, meshContext);
}
},
{
"cylinder",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<CylinderFacadeBuilder>(builderContext, meshContext);
}
},
{
"sphere",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<SphereFacadeBuilder>(builderContext, meshContext);
}
}
};
/// Creates points for polygon
std::vector<Vector2> toPoints(const std::vector<GeoCoordinate> &coordinates) {
std::vector<Vector2> points;
points.reserve(coordinates.size());
for (const auto &coordinate : coordinates) {
points.push_back(Vector2(coordinate.longitude, coordinate.latitude));
}
return std::move(points);
}
/// NOTE this method exists due to special processing of all buildings parts of the
/// one relation. In general, we want to have ability to render complex building
/// as one game object. If area/relation is already part of relation then we
/// should avoid processing it as independent element. We cannot just delete
/// element from store as it might be a part of other relation.
inline bool shouldBeIgnored(const Element &element) {
return hasIgnore(element.tags);
}
/// Responsible for processing multipolygon relation.
class MultiPolygonVisitor final : public ElementVisitor {
public:
explicit MultiPolygonVisitor(Polygon &polygon) :
polygon_(polygon) {
}
void visitNode(const Node &node) override { fail(node); }
void visitWay(const Way &way) override { fail(way); }
virtual void visitRelation(const Relation &relation) override {
for (const auto &element : relation.elements)
element->accept(*this);
}
void visitArea(const Area &area) override {
if (!utymap::utils::isClockwise(area.coordinates))
polygon_.addContour(toPoints(area.coordinates));
else
polygon_.addHole(toPoints(area.coordinates));
}
private:
static void fail(const utymap::entities::Element &element) {
throw std::domain_error("Unexpected element in multipolygon: " + utymap::utils::toString(element.id));
}
Polygon &polygon_;
};
}
namespace utymap {
namespace builders {
class BuildingBuilder::BuildingBuilderImpl : public ElementBuilder {
public:
explicit BuildingBuilderImpl(const utymap::builders::BuilderContext &context) :
ElementBuilder(context),
id_(0) {
}
void visitNode(const Node &) override {}
void visitWay(const Way &) override {}
void visitArea(const Area &area) override {
Style style = context_.styleProvider.forElement(area, context_.quadKey.levelOfDetail);
// NOTE this might happen if relation contains not a building
if (!isBuilding(style))
return;
bool justCreated = ensureContext(area);
polygon_->addContour(toPoints(area.coordinates));
build(area, style);
completeIfNecessary(justCreated);
}
void visitRelation(const Relation &relation) override {
if (relation.elements.empty())
return;
bool justCreated = ensureContext(relation);
Style style = context_.styleProvider.forElement(relation, context_.quadKey.levelOfDetail);
if (isMultipolygon(style) && isBuilding(style)) {
MultiPolygonVisitor visitor(*polygon_);
for (const auto &element : relation.elements)
element->accept(visitor);
build(relation, style);
} else {
for (const auto &element : relation.elements)
element->accept(*this);
}
completeIfNecessary(justCreated);
}
private:
bool ensureContext(const Element &element) {
if (polygon_==nullptr)
polygon_ = utymap::utils::make_unique<Polygon>(1, 0);
if (mesh_==nullptr) {
mesh_ = utymap::utils::make_unique<Mesh>(utymap::utils::getMeshName(MeshNamePrefix, element));
id_ = element.id;
return true;
}
return false;
}
void completeIfNecessary(bool justCreated) {
if (justCreated) {
context_.meshCallback(*mesh_);
mesh_.reset();
}
}
static bool isBuilding(const Style &style) {
return style.getString("building")=="true";
}
static bool isMultipolygon(const Style &style) {
return style.getString("multipolygon")=="true";
}
void build(const Element &element, const Style &style) {
auto geoCoordinate = GeoCoordinate(polygon_->points[1], polygon_->points[0]);
double height = style.getValue(StyleConsts::HeightKey());
// NOTE do not allow height to be zero. This might happen due to the issues in input osm data.
if (height==0)
height = 10;
double minHeight = style.getValue(StyleConsts::MinHeightKey());
double elevation = context_.eleProvider.getElevation(context_.quadKey, geoCoordinate) + minHeight;
height -= minHeight;
attachRoof(*mesh_, style, elevation, height);
// NOTE so far, attach floors only for buildings with minHeight
if (minHeight > 0)
attachFloors(*mesh_, style, elevation, height);
attachFacade(*mesh_, style, elevation, height);
polygon_.reset();
}
void attachRoof(Mesh &mesh, const Style &style, double elevation, double height) const {
MeshContext roofMeshContext = MeshContext::create(mesh,
style,
context_.styleProvider,
RoofGradientKey,
RoofTextureIndexKey,
RoofTextureTypeKey,
RoofTextureScaleKey,
id_);
auto roofType = roofMeshContext.style.getString(RoofTypeKey);
double roofHeight = roofMeshContext.style.getValue(RoofHeightKey);
auto direction = roofMeshContext.style.getString(RoofDirectionKey);
auto roofBuilder = RoofBuilderFactoryMap.find(roofType)->second(context_, roofMeshContext);
roofBuilder->setHeight(roofHeight);
roofBuilder->setMinHeight(elevation + height);
roofBuilder->setColorNoiseFreq(0);
roofBuilder->setDirection(direction);
roofBuilder->build(*polygon_);
context_.meshBuilder.writeTextureMappingInfo(mesh, roofMeshContext.appearanceOptions);
}
void attachFloors(Mesh &mesh, const Style &style, double elevation, double height) const {
MeshContext floorMeshContext = MeshContext::create(mesh,
style,
context_.styleProvider,
RoofGradientKey,
RoofTextureIndexKey,
RoofTextureTypeKey,
RoofTextureScaleKey,
id_);
FlatRoofBuilder floorBuilder(context_, floorMeshContext);
floorBuilder.setMinHeight(elevation);
floorBuilder.setColorNoiseFreq(0);
floorBuilder.flipSide();
floorBuilder.build(*polygon_);
context_.meshBuilder.writeTextureMappingInfo(mesh, floorMeshContext.appearanceOptions);
}
void attachFacade(Mesh &mesh, const Style &style, double elevation, double height) const {
MeshContext facadeMeshContext = MeshContext::create(mesh,
style,
context_.styleProvider,
FacadeGradientKey,
FacadeTextureIndexKey,
FacadeTextureTypeKey,
FacadeTextureScaleKey,
id_);
auto facadeType = facadeMeshContext.style.getString(FacadeTypeKey);
auto facadeBuilder = FacadeBuilderFactoryMap.find(facadeType)->second(context_, facadeMeshContext);
facadeBuilder->setHeight(height);
facadeBuilder->setMinHeight(elevation);
facadeBuilder->setColorNoiseFreq(0);
facadeBuilder->build(*polygon_);
context_.meshBuilder.writeTextureMappingInfo(mesh, facadeMeshContext.appearanceOptions);
}
std::unique_ptr<Polygon> polygon_;
std::unique_ptr<Mesh> mesh_;
std::uint64_t id_;
};
BuildingBuilder::BuildingBuilder(const BuilderContext &context)
: ElementBuilder(context), pimpl_(utymap::utils::make_unique<BuildingBuilderImpl>(context)) {
}
BuildingBuilder::~BuildingBuilder() {}
void BuildingBuilder::visitArea(const Area &area) {
if (!shouldBeIgnored(area))
area.accept(*pimpl_);
}
void BuildingBuilder::visitRelation(const Relation &relation) {
if (!shouldBeIgnored(relation))
relation.accept(*pimpl_);
}
}
}
core: use mesh bool in building builder
#include "GeoCoordinate.hpp"
#include "builders/MeshContext.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "builders/buildings/BuildingBuilder.hpp"
#include "builders/buildings/facades/CylinderFacadeBuilder.hpp"
#include "builders/buildings/facades/FlatFacadeBuilder.hpp"
#include "builders/buildings/facades/SphereFacadeBuilder.hpp"
#include "builders/buildings/roofs/DomeRoofBuilder.hpp"
#include "builders/buildings/roofs/FlatRoofBuilder.hpp"
#include "builders/buildings/roofs/PyramidalRoofBuilder.hpp"
#include "builders/buildings/roofs/MansardRoofBuilder.hpp"
#include "builders/buildings/roofs/SkillionRoofBuilder.hpp"
#include "builders/buildings/roofs/RoundRoofBuilder.hpp"
using namespace utymap;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::math;
using namespace utymap::index;
using namespace utymap::utils;
namespace {
const std::string MeshNamePrefix = "building:";
const std::string RoofPrefix = "roof-";
const std::string RoofTypeKey = RoofPrefix + StyleConsts::TypeKey();
const std::string RoofHeightKey = RoofPrefix + StyleConsts::HeightKey();
const std::string RoofGradientKey = RoofPrefix + StyleConsts::GradientKey();
const std::string RoofTextureIndexKey = RoofPrefix + StyleConsts::TextureIndexKey();
const std::string RoofTextureTypeKey = RoofPrefix + StyleConsts::TextureTypeKey();
const std::string RoofTextureScaleKey = RoofPrefix + StyleConsts::TextureScaleKey();
const std::string RoofDirectionKey = RoofPrefix + StyleConsts::DirectionKey();
const std::string FacadePrefix = "facade-";
const std::string FacadeTypeKey = FacadePrefix + StyleConsts::TypeKey();
const std::string FacadeGradientKey = FacadePrefix + StyleConsts::GradientKey();
const std::string FacadeTextureIndexKey = FacadePrefix + StyleConsts::TextureIndexKey();
const std::string FacadeTextureTypeKey = FacadePrefix + StyleConsts::TextureTypeKey();
const std::string FacadeTextureScaleKey = FacadePrefix + StyleConsts::TextureScaleKey();
/// Defines roof builder which does nothing.
class EmptyRoofBuilder : public RoofBuilder {
public:
EmptyRoofBuilder(const BuilderContext &bc, MeshContext &mc)
: RoofBuilder(bc, mc) {}
void build(Polygon &) override {}
};
typedef std::function<std::unique_ptr<RoofBuilder>(const BuilderContext &, MeshContext &)> RoofBuilderFactory;
std::unordered_map<std::string, RoofBuilderFactory> RoofBuilderFactoryMap =
{
{
"none",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<EmptyRoofBuilder>(builderContext, meshContext);
}
},
{
"flat",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<FlatRoofBuilder>(builderContext, meshContext);
}
},
{
"dome",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<DomeRoofBuilder>(builderContext, meshContext);
}
},
{
"pyramidal",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<PyramidalRoofBuilder>(builderContext, meshContext);
}
},
{
"mansard",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<MansardRoofBuilder>(builderContext, meshContext);
}
},
{
"skillion",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<SkillionRoofBuilder>(builderContext, meshContext);
}
},
{
"round",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<RoundRoofBuilder>(builderContext, meshContext);
}
}
};
typedef std::function<std::unique_ptr<FacadeBuilder>(const BuilderContext &, MeshContext &)> FacadeBuilderFactory;
std::unordered_map<std::string, FacadeBuilderFactory> FacadeBuilderFactoryMap =
{
{
"flat",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<FlatFacadeBuilder>(builderContext, meshContext);
}
},
{
"cylinder",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<CylinderFacadeBuilder>(builderContext, meshContext);
}
},
{
"sphere",
[](const BuilderContext &builderContext, MeshContext &meshContext) {
return utymap::utils::make_unique<SphereFacadeBuilder>(builderContext, meshContext);
}
}
};
/// Creates points for polygon
std::vector<Vector2> toPoints(const std::vector<GeoCoordinate> &coordinates) {
std::vector<Vector2> points;
points.reserve(coordinates.size());
for (const auto &coordinate : coordinates) {
points.push_back(Vector2(coordinate.longitude, coordinate.latitude));
}
return std::move(points);
}
/// NOTE this method exists due to special processing of all buildings parts of the
/// one relation. In general, we want to have ability to render complex building
/// as one game object. If area/relation is already part of relation then we
/// should avoid processing it as independent element. We cannot just delete
/// element from store as it might be a part of other relation.
inline bool shouldBeIgnored(const Element &element) {
return hasIgnore(element.tags);
}
/// Responsible for processing multipolygon relation.
class MultiPolygonVisitor final : public ElementVisitor {
public:
explicit MultiPolygonVisitor(Polygon &polygon) :
polygon_(polygon) {
}
void visitNode(const Node &node) override { fail(node); }
void visitWay(const Way &way) override { fail(way); }
virtual void visitRelation(const Relation &relation) override {
for (const auto &element : relation.elements)
element->accept(*this);
}
void visitArea(const Area &area) override {
if (!utymap::utils::isClockwise(area.coordinates))
polygon_.addContour(toPoints(area.coordinates));
else
polygon_.addHole(toPoints(area.coordinates));
}
private:
static void fail(const utymap::entities::Element &element) {
throw std::domain_error("Unexpected element in multipolygon: " + utymap::utils::toString(element.id));
}
Polygon &polygon_;
};
}
namespace utymap {
namespace builders {
class BuildingBuilder::BuildingBuilderImpl : public ElementBuilder {
public:
explicit BuildingBuilderImpl(const utymap::builders::BuilderContext &context) :
ElementBuilder(context),
id_(0) {
}
void visitNode(const Node &) override {}
void visitWay(const Way &) override {}
void visitArea(const Area &area) override {
Style style = context_.styleProvider.forElement(area, context_.quadKey.levelOfDetail);
// NOTE this might happen if relation contains not a building
if (!isBuilding(style))
return;
bool justCreated = ensureContext(area);
polygon_->addContour(toPoints(area.coordinates));
build(area, style);
completeIfNecessary(justCreated);
}
void visitRelation(const Relation &relation) override {
if (relation.elements.empty())
return;
bool justCreated = ensureContext(relation);
Style style = context_.styleProvider.forElement(relation, context_.quadKey.levelOfDetail);
if (isMultipolygon(style) && isBuilding(style)) {
MultiPolygonVisitor visitor(*polygon_);
for (const auto &element : relation.elements)
element->accept(visitor);
build(relation, style);
} else {
for (const auto &element : relation.elements)
element->accept(*this);
}
completeIfNecessary(justCreated);
}
private:
bool ensureContext(const Element &element) {
if (polygon_==nullptr)
polygon_ = utymap::utils::make_unique<Polygon>(1, 0);
if (mesh_==nullptr) {
auto mesh = context_.meshPool.getSmall(utymap::utils::getMeshName(MeshNamePrefix, element));
mesh_ = std::unique_ptr<Mesh>(new Mesh(std::move(mesh)));
id_ = element.id;
return true;
}
return false;
}
void completeIfNecessary(bool justCreated) {
if (justCreated) {
context_.meshCallback(*mesh_);
context_.meshPool.release(std::move(*mesh_));
mesh_.reset();
}
}
static bool isBuilding(const Style &style) {
return style.getString("building")=="true";
}
static bool isMultipolygon(const Style &style) {
return style.getString("multipolygon")=="true";
}
void build(const Element &element, const Style &style) {
auto geoCoordinate = GeoCoordinate(polygon_->points[1], polygon_->points[0]);
double height = style.getValue(StyleConsts::HeightKey());
// NOTE do not allow height to be zero. This might happen due to the issues in input osm data.
if (height==0)
height = 10;
double minHeight = style.getValue(StyleConsts::MinHeightKey());
double elevation = context_.eleProvider.getElevation(context_.quadKey, geoCoordinate) + minHeight;
height -= minHeight;
attachRoof(*mesh_, style, elevation, height);
// NOTE so far, attach floors only for buildings with minHeight
if (minHeight > 0)
attachFloors(*mesh_, style, elevation, height);
attachFacade(*mesh_, style, elevation, height);
polygon_.reset();
}
void attachRoof(Mesh &mesh, const Style &style, double elevation, double height) const {
MeshContext roofMeshContext = MeshContext::create(mesh,
style,
context_.styleProvider,
RoofGradientKey,
RoofTextureIndexKey,
RoofTextureTypeKey,
RoofTextureScaleKey,
id_);
auto roofType = roofMeshContext.style.getString(RoofTypeKey);
double roofHeight = roofMeshContext.style.getValue(RoofHeightKey);
auto direction = roofMeshContext.style.getString(RoofDirectionKey);
auto roofBuilder = RoofBuilderFactoryMap.find(roofType)->second(context_, roofMeshContext);
roofBuilder->setHeight(roofHeight);
roofBuilder->setMinHeight(elevation + height);
roofBuilder->setColorNoiseFreq(0);
roofBuilder->setDirection(direction);
roofBuilder->build(*polygon_);
context_.meshBuilder.writeTextureMappingInfo(mesh, roofMeshContext.appearanceOptions);
}
void attachFloors(Mesh &mesh, const Style &style, double elevation, double height) const {
MeshContext floorMeshContext = MeshContext::create(mesh,
style,
context_.styleProvider,
RoofGradientKey,
RoofTextureIndexKey,
RoofTextureTypeKey,
RoofTextureScaleKey,
id_);
FlatRoofBuilder floorBuilder(context_, floorMeshContext);
floorBuilder.setMinHeight(elevation);
floorBuilder.setColorNoiseFreq(0);
floorBuilder.flipSide();
floorBuilder.build(*polygon_);
context_.meshBuilder.writeTextureMappingInfo(mesh, floorMeshContext.appearanceOptions);
}
void attachFacade(Mesh &mesh, const Style &style, double elevation, double height) const {
MeshContext facadeMeshContext = MeshContext::create(mesh,
style,
context_.styleProvider,
FacadeGradientKey,
FacadeTextureIndexKey,
FacadeTextureTypeKey,
FacadeTextureScaleKey,
id_);
auto facadeType = facadeMeshContext.style.getString(FacadeTypeKey);
auto facadeBuilder = FacadeBuilderFactoryMap.find(facadeType)->second(context_, facadeMeshContext);
facadeBuilder->setHeight(height);
facadeBuilder->setMinHeight(elevation);
facadeBuilder->setColorNoiseFreq(0);
facadeBuilder->build(*polygon_);
context_.meshBuilder.writeTextureMappingInfo(mesh, facadeMeshContext.appearanceOptions);
}
std::unique_ptr<Polygon> polygon_;
std::unique_ptr<Mesh> mesh_;
std::uint64_t id_;
};
BuildingBuilder::BuildingBuilder(const BuilderContext &context)
: ElementBuilder(context), pimpl_(utymap::utils::make_unique<BuildingBuilderImpl>(context)) {
}
BuildingBuilder::~BuildingBuilder() {}
void BuildingBuilder::visitArea(const Area &area) {
if (!shouldBeIgnored(area))
area.accept(*pimpl_);
}
void BuildingBuilder::visitRelation(const Relation &relation) {
if (!shouldBeIgnored(relation))
relation.accept(*pimpl_);
}
}
}
|
/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors:
* Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for
* (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* (1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <cstddef> // for offsetof()
#include <exception>
#include <map>
#include <set>
#include <boost/filesystem.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <json/value.h>
#ifdef WITHMPI
#include <mpi.h>
#include "data/RestartData.h" // for defining MPI typemap...
#include "inc/tbc_mpi_constants.h"
#endif
// For managing the floating point environment
#ifdef BSD_FPE
#include <xmmintrin.h> // BSD (OSX)
#endif
#ifdef GNU_FPE
#include <fenv.h> // GNU Linux
#endif
#include "inc/timeconst.h"
#include "../include/ArgHandler.h"
#include "TEMLogger.h"
#include "TEMUtilityFunctions.h"
#include "../include/Runner.h"
#include "data/RestartData.h"
#include <netcdf.h>
/** Quick 'n dirty pretty printer for vector of things
*/
template <typename TYPE>
void ppv(const std::vector<TYPE> &v){
typename std::vector<TYPE>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
}
// draft pretty-printers...
void pp_2dvec(const std::vector<std::vector<int> > & vv);
// draft - generate a netcdf file that can follow CF conventions
void create_new_output();
// draft - reading new-style co2 file
std::vector<float> read_new_co2_file(const std::string &filename);
// draft - reading in a 2D run mask...
std::vector< std::vector<int> > read_run_mask(const std::string &filename);
/** Enables a 'floating point exception' mask that will make the program crash
* when a floating point number is generated (and or operated upon).
*
* Some more info
* http://www.johndcook.com/blog/ieee_exceptions_in_cpp/
* http://stackoverflow.com/questions/247053/enabling-floating-point-interrupts-on-mac-os-x-intel
*
* It might be helpful to add a singal handler at some point that could report
* on what/where the exception is generated?
*/
void enable_floating_point_exceptions() {
std::cout << "Enabling floating point exceptions mask!" << std::endl;
// BSD (OSX)
#ifdef BSD_FPE
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID);
#endif
// GNU Linux
#ifdef GNU_FPE
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
}
ArgHandler* args = new ArgHandler();
extern src::severity_logger< severity_level > glg;
int main(int argc, char* argv[]){
// Read in and parse the command line arguments
args->parse(argc, argv);
if (args->get_help()) {
args->show_help();
return 0;
}
std::cout << "Setting up logging...\n";
setup_logging(args->get_log_level(), args->get_log_scope());
BOOST_LOG_SEV(glg, note) << "Checking command line arguments...";
args->verify(); // stub - doesn't really do anything yet
BOOST_LOG_SEV(glg, note) << "Turn floating point exceptions on?: " << args->get_fpe();
if (args->get_fpe()) { enable_floating_point_exceptions(); }
BOOST_LOG_SEV(glg, note) << "Reading controlfile into main(..) scope...";
Json::Value controldata = temutil::parse_control_file(args->get_ctrl_file());
BOOST_LOG_SEV(glg, note) << "Creating a ModelData object based on settings in the control file";
ModelData modeldata(controldata);
BOOST_LOG_SEV(glg, note) << "Update model settings based on command line flags/options...";
modeldata.update(args);
/*
Someday it may be worth the time/effort to make better use of
boots::program_options here to manage the arguments from config file
and the command line.
*/
BOOST_LOG_SEV(glg, note) << "Running PR stage: " << modeldata.pr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running EQ stage: " << modeldata.eq_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SP stage: " << modeldata.sp_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running TR stage: " << modeldata.tr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SC stage: " << modeldata.sc_yrs << "yrs";
// Turn off buffering...
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Create empty output files now so that later, as the program
// proceeds, there is somewhere to append output data...
// ??? Maybe the type/shape of outputs that we create can, or should, depend on
// ??? some of the settings in the ModelData object?
BOOST_LOG_SEV(glg, info) << "Creating a fresh 'n clean NEW output file...";
create_new_output();
time_t stime;
time_t etime;
stime = time(0);
BOOST_LOG_SEV(glg, note) << "Start dvmdostem @ " << ctime(&stime);
BOOST_LOG_SEV(glg, debug) << "NEW STYLE: Going to run space-major over a 2D area covered by run mask...";
// Open the run mask (spatial mask)
std::vector< std::vector<int> > run_mask = read_run_mask(modeldata.runmask_file);
// Make some convenient handles for later...
std::string eq_restart_fname = modeldata.output_dir + "restart-eq.nc";
std::string sp_restart_fname = modeldata.output_dir + "restart-sp.nc";
std::string tr_restart_fname = modeldata.output_dir + "restart-tr.nc";
std::string sc_restart_fname = modeldata.output_dir + "restart-sc.nc";
// Figure out how big the run_mask is
int num_rows = run_mask.size();
int num_cols = run_mask[0].size();
// Create empty restart files for all stages based on size of run mask
RestartData::create_empty_file(eq_restart_fname, num_rows, num_cols);
RestartData::create_empty_file(sp_restart_fname, num_rows, num_cols);
RestartData::create_empty_file(tr_restart_fname, num_rows, num_cols);
RestartData::create_empty_file(sc_restart_fname, num_rows, num_cols);
if (args->get_loop_order() == "space-major") {
// y <==> row <==> lat
// x <==> col <==> lon
// Loop over a 2D grid of 'cells' (cohorts?),
// run each cell for some number of years.
//
// Processing starts in the lower left corner (0,0).
// Should really look into replacing this loop with
// something like python's map(...) function...
// --> Could this allow us to use a map reduce strategy??
//
// Look into std::transform.
// Use a few type definitions to save some typing.
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
vec2D::const_iterator row;
vec::const_iterator col;
for (row = run_mask.begin(); row != run_mask.end() ; ++row) {
for (col = row->begin(); col != row->end(); ++col) {
bool mask_value = *col;
int rowidx = row - run_mask.begin();
int colidx = col - row->begin();
if (true == mask_value) {
BOOST_LOG_SEV(glg, note) << "Running cell (" << rowidx << ", " << colidx << ")";
//modeldata.initmode = 1; // OBSOLETE?
BOOST_LOG_SEV(glg, info) << "Setup the NEW STYLE RUNNER OBJECT ...";
Runner runner(modeldata, args->get_cal_mode(), rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << runner.cohort.ground.layer_report_string("depth thermal");
// seg fault w/o preparing climate...so prepare year zero...
// this is also called inside run_years(...)
runner.cohort.climate.prepare_daily_driving_data(0, "eq");
runner.cohort.initialize_internal_pointers(); // sets up lots of pointers to various things
runner.cohort.initialize_state_parameters(); // sets data based on values in cohortlookup
BOOST_LOG_SEV(glg, debug) << "right after initialize_internal_pointers() and initialize_state_parameters()"
<< runner.cohort.ground.layer_report_string("depth ptr");
// PRE RUN STAGE (PR)
if (modeldata.pr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("PRE-RUN");
/** Env-only "pre-run" stage.
- should use only the env module
- number of years to run can be controlled on cmd line
- use fixed climate that is averaged over first X years
- use static (fixed) co2 value (first element of co2 file)
- FIX: need to set yrs since dsb ?
- FIX: should ignore calibration directives?
*/
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// turn off everything but env
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_bgcmodule(false);
runner.cohort.md->set_nfeed(false);
runner.cohort.md->set_avlnflg(false);
runner.cohort.md->set_baseline(false);
runner.cohort.md->set_dsbmodule(false);
runner.cohort.md->set_dslmodule(false);
runner.cohort.md->set_dvmmodule(false);
BOOST_LOG_SEV(glg, debug) << "Ground, right before 'pre-run'. "
<< runner.cohort.ground.layer_report_string("depth thermal");
runner.run_years(0, modeldata.pr_yrs, "pre-run"); // climate is prepared w/in here.
BOOST_LOG_SEV(glg, debug) << "Ground, right after 'pre-run'"
<< runner.cohort.ground.layer_report_string("depth thermal");
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("pr");
}
}
// EQUILIBRIUM STAGE (EQ)
if (modeldata.eq_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("EQ");
BOOST_LOG_SEV(glg, fatal) << "Running Equilibrium, " << modeldata.eq_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_dvmmodule(true);
runner.cohort.md->set_bgcmodule(true);
runner.cohort.md->set_dslmodule(true);
runner.cohort.md->set_nfeed(true);
runner.cohort.md->set_avlnflg(true);
runner.cohort.md->set_baseline(true);
runner.cohort.md->set_dsbmodule(false);
if (runner.cohort.md->get_dsbmodule()) {
// The transition to SP must occur at the completion of a
// fire cycle (i.e. a year or two prior to the next fire).
// To ensure this, re-set modeldata's EQ year count to an
// even multiple of the FRI minus 2 (to be safe)
int fri = runner.cohort.fire.getFRI();
int EQ_fire_cycles = modeldata.eq_yrs / fri;
if (modeldata.eq_yrs%fri != 0) {
modeldata.eq_yrs = fri * (EQ_fire_cycles + 1) - 2;
}
}
// Run model
runner.run_years(0, modeldata.eq_yrs, "eq-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData post EQ";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData to: " << eq_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(eq_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("eq");
}
}
// SPINUP STAGE (SP)
if (modeldata.sp_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SP");
BOOST_LOG_SEV(glg, fatal) << "Running Spinup, " << modeldata.sp_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.climate.monthlycontainers2log();
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << eq_restart_fname;
runner.cohort.restartdata.update_from_ncfile(eq_restart_fname, rowidx, colidx);
// FIX: if restart file has -9999, then soil temps can end up
// impossibly low should check for valid values prior to actual use
// Maybe a diffcult to maintain in the future
// when/if more variables are added?
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre SP";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.sp_yrs, "sp-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SP";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sp_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(sp_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sp");
}
}
// TRANSIENT STAGE (TR)
if (modeldata.tr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("TR");
BOOST_LOG_SEV(glg, fatal) << "Running Transient, " << modeldata.tr_yrs << " years";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// update the cohort's restart data object
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << sp_restart_fname;
runner.cohort.restartdata.update_from_ncfile(sp_restart_fname, rowidx, colidx);
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre TR";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.tr_yrs, "tr-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post TR";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << tr_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(tr_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("tr");
}
}
// SCENARIO STAGE (SC)
if (modeldata.sc_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SC");
BOOST_LOG_SEV(glg, fatal) << "Running Scenario, " << modeldata.sc_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// update the cohort's restart data object
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << tr_restart_fname;
runner.cohort.restartdata.update_from_ncfile(tr_restart_fname, rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << "RestartData pre SC";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Loading projected data instead of historic. FIX?
runner.cohort.load_proj_climate(modeldata.proj_climate_file);
// Run model
runner.run_years(0, modeldata.sc_yrs, "sc-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SC";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sc_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(sc_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sc");
}
}
// NOTE: Could have an option to set some time constants based on
// some sizes/dimensions of the input driving data...
/**
eq
- create the climate from the average of the first X years
of the driving climate data.
SIZE: 12 months, 1 year
- set to default module settings to: ??
- run_years( 0 <= iy < MAX_EQ_YEAR )
- act on calibration directives
-
sp
- create the climate from the first X years of the driving
climate dataset.
SIZE: 12 months, X years
- set to default module settings: ??
- run_years( SP_BEG <= iy <= SP_END )
tr
- create climate by loading the driving climate data (historic)
SIZE: 12 months, length of driving dataset? OR number from inc/timeconst.h
- set to default module settings: ??
- run_years( TR_BEG <= iy <= TR_END )
*/
} else {
BOOST_LOG_SEV(glg, debug) << "Skipping cell (" << rowidx << ", " << colidx << ")";
}
}
}
} else if (args->get_loop_order() == "time-major") {
BOOST_LOG_SEV(glg, warn) << "DO NOTHING. NOT IMPLEMENTED YET.";
// for each year
// Read in Climate - all locations, one year/timestep
// Read in Vegetation - all locations
// Read in Drainage - all locations
// Read in Fire - all locations
// for each cohort
// updateMonthly(...)
}
BOOST_LOG_SEV(glg, note) << "DONE WITH NEW STYLE run (" << args->get_loop_order() << ")";
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Total Seconds: " << difftime(etime, stime);
return 0;
} /* End main() */
/** Pretty print a 2D vector of ints */
void pp_2dvec(const std::vector<std::vector<int> > & vv) {
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
for (vec2D::const_iterator row = vv.begin(); row != vv.end(); ++row) {
for (vec::const_iterator col = row->begin(); col != row->end(); ++col) {
std::cout << *col << " ";
}
std::cout << std::endl;
}
}
/** rough draft for reading a run-mask (2D vector of ints)
*/
std::vector< std::vector<int> > read_run_mask(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yD, xD;
size_t yD_len, xD_len;
temutil::nc( nc_inq_dimid(ncid, "Y", &yD) );
temutil::nc( nc_inq_dimlen(ncid, yD, &yD_len) );
temutil::nc( nc_inq_dimid(ncid, "X", &xD) );
temutil::nc( nc_inq_dimlen(ncid, xD, &xD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate a 2D run-mask vector (y,x). Size: (" << yD_len << ", " << xD_len << ")";
std::vector< std::vector<int> > run_mask(yD_len, std::vector<int>(xD_len));
BOOST_LOG_SEV(glg, debug) << "Read the run flag data from the file into the 2D vector...";
int runV;
temutil::nc( nc_inq_varid(ncid, "run", &runV) );
BOOST_LOG_SEV(glg, debug) << "Grab one row at a time";
BOOST_LOG_SEV(glg, debug) << "(need contiguous memory, and vector<vector> are not contiguous)";
std::vector< std::vector<int> >::iterator row;
for (row = run_mask.begin(); row != run_mask.end(); ++row) {
int rowidx = row - run_mask.begin();
// specify start indices for each dimension (y, x)
size_t start[2];
start[0] = rowidx; // Y
start[1] = 0; // X
// specify counts for each dimension
size_t count[2];
count[0] = 1; // one row
count[1] = xD_len; // all data
std::vector<int> rowdata(xD_len);
temutil::nc( nc_get_vara_int(ncid, runV, start, count, &rowdata[0] ) );
run_mask[rowidx] = rowdata;
}
temutil::nc( nc_close(ncid) );
//pp_2dvec(run_mask);
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return run_mask;
}
/** rough draft for reading new-style co2 data
*/
std::vector<float> read_new_co2_file(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yearD;
size_t yearD_len;
temutil::nc( nc_inq_dimid(ncid, "year", &yearD) );
temutil::nc( nc_inq_dimlen(ncid, yearD, &yearD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate vector big enough for " << yearD_len << " years of co2 data...";
std::vector<float> co2data(yearD_len);
BOOST_LOG_SEV(glg, debug) << "Read the co2 data from the file into the vector...";
int co2V;
temutil::nc( nc_inq_varid(ncid, "co2", &co2V) );
temutil::nc( nc_get_var(ncid, co2V, &co2data[0]) );
temutil::nc( nc_close(ncid) );
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return co2data;
}
/** rough draft for new output files
*/
void create_new_output() {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Creating dataset...";
temutil::nc( nc_create("general-outputs-monthly.nc", NC_CLOBBER, &ncid) );
int timeD; // unlimited dimension
int pftD;
int xD;
int yD;
/* Create Dimensions */
BOOST_LOG_SEV(glg, debug) << "Adding dimensions...";
temutil::nc( nc_def_dim(ncid, "time", NC_UNLIMITED, &timeD) );
temutil::nc( nc_def_dim(ncid, "pft", NUM_PFT, &pftD) );
temutil::nc( nc_def_dim(ncid, "y", 10, &yD) );
temutil::nc( nc_def_dim(ncid, "x", 10, &xD) );
/* Create Coordinate Variables?? */
/* Create Data Variables */
// 4D vars
BOOST_LOG_SEV(glg, debug) << "Adding 4D variables...";
int vartypeA_dimids[4];
vartypeA_dimids[0] = timeD;
vartypeA_dimids[1] = pftD;
vartypeA_dimids[2] = yD;
vartypeA_dimids[3] = xD;
int vegcV;
int veg_fractionV;
int growstartV;
temutil::nc( nc_def_var(ncid, "vegc", NC_DOUBLE, 4, vartypeA_dimids, &vegcV) );
temutil::nc( nc_def_var(ncid, "veg_fraction", NC_DOUBLE, 4, vartypeA_dimids, &veg_fractionV) );
temutil::nc( nc_def_var(ncid, "growstart", NC_DOUBLE, 4, vartypeA_dimids, &growstartV) );
// 3D vars
BOOST_LOG_SEV(glg, debug) << "Adding 3D variables...";
int vartypeB_dimids[3];
vartypeB_dimids[0] = timeD;
vartypeB_dimids[1] = yD;
vartypeB_dimids[2] = xD;
int org_shlw_thicknessV;
temutil::nc( nc_def_var(ncid, "org_shlw_thickness", NC_DOUBLE, 3, vartypeB_dimids, &org_shlw_thicknessV) );
/* Create Attributes? */
/* End Define Mode (not scrictly necessary for netcdf 4) */
BOOST_LOG_SEV(glg, debug) << "Leaving 'define mode'...";
temutil::nc( nc_enddef(ncid) );
/* Load coordinate variables?? */
/* Close file. */
BOOST_LOG_SEV(glg, debug) << "Closing new file...";
temutil::nc( nc_close(ncid) );
}
add snippet to create output directory if it doesn;t exist.
This has been a nagging problem: user pull updates from dvmdostem, tries
new dataset and the model won;t run, complaining about missing files.
Turns out that when creating new NetCDF files for the restart files, the
operation will succeed if the directory exists, but if the directory doesn't
exist, then it will fail to create the files. We always forget about it
because usually once you create the directory once, the problem goes away.
/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors:
* Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for
* (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* (1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <cstddef> // for offsetof()
#include <exception>
#include <map>
#include <set>
#include <boost/filesystem.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <json/value.h>
#ifdef WITHMPI
#include <mpi.h>
#include "data/RestartData.h" // for defining MPI typemap...
#include "inc/tbc_mpi_constants.h"
#endif
// For managing the floating point environment
#ifdef BSD_FPE
#include <xmmintrin.h> // BSD (OSX)
#endif
#ifdef GNU_FPE
#include <fenv.h> // GNU Linux
#endif
#include "inc/timeconst.h"
#include "../include/ArgHandler.h"
#include "TEMLogger.h"
#include "TEMUtilityFunctions.h"
#include "../include/Runner.h"
#include "data/RestartData.h"
#include <netcdf.h>
/** Quick 'n dirty pretty printer for vector of things
*/
template <typename TYPE>
void ppv(const std::vector<TYPE> &v){
typename std::vector<TYPE>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
}
// draft pretty-printers...
void pp_2dvec(const std::vector<std::vector<int> > & vv);
// draft - generate a netcdf file that can follow CF conventions
void create_new_output();
// draft - reading new-style co2 file
std::vector<float> read_new_co2_file(const std::string &filename);
// draft - reading in a 2D run mask...
std::vector< std::vector<int> > read_run_mask(const std::string &filename);
/** Enables a 'floating point exception' mask that will make the program crash
* when a floating point number is generated (and or operated upon).
*
* Some more info
* http://www.johndcook.com/blog/ieee_exceptions_in_cpp/
* http://stackoverflow.com/questions/247053/enabling-floating-point-interrupts-on-mac-os-x-intel
*
* It might be helpful to add a singal handler at some point that could report
* on what/where the exception is generated?
*/
void enable_floating_point_exceptions() {
std::cout << "Enabling floating point exceptions mask!" << std::endl;
// BSD (OSX)
#ifdef BSD_FPE
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID);
#endif
// GNU Linux
#ifdef GNU_FPE
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
}
ArgHandler* args = new ArgHandler();
extern src::severity_logger< severity_level > glg;
int main(int argc, char* argv[]){
// Read in and parse the command line arguments
args->parse(argc, argv);
if (args->get_help()) {
args->show_help();
return 0;
}
std::cout << "Setting up logging...\n";
setup_logging(args->get_log_level(), args->get_log_scope());
BOOST_LOG_SEV(glg, note) << "Checking command line arguments...";
args->verify(); // stub - doesn't really do anything yet
BOOST_LOG_SEV(glg, note) << "Turn floating point exceptions on?: " << args->get_fpe();
if (args->get_fpe()) { enable_floating_point_exceptions(); }
BOOST_LOG_SEV(glg, note) << "Reading controlfile into main(..) scope...";
Json::Value controldata = temutil::parse_control_file(args->get_ctrl_file());
BOOST_LOG_SEV(glg, note) << "Creating a ModelData object based on settings in the control file";
ModelData modeldata(controldata);
BOOST_LOG_SEV(glg, note) << "Update model settings based on command line flags/options...";
modeldata.update(args);
/*
Someday it may be worth the time/effort to make better use of
boots::program_options here to manage the arguments from config file
and the command line.
*/
BOOST_LOG_SEV(glg, note) << "Running PR stage: " << modeldata.pr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running EQ stage: " << modeldata.eq_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SP stage: " << modeldata.sp_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running TR stage: " << modeldata.tr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SC stage: " << modeldata.sc_yrs << "yrs";
// Turn off buffering...
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Create empty output files now so that later, as the program
// proceeds, there is somewhere to append output data...
// ??? Maybe the type/shape of outputs that we create can, or should, depend on
// ??? some of the settings in the ModelData object?
BOOST_LOG_SEV(glg, info) << "Creating a fresh 'n clean NEW output file...";
create_new_output();
time_t stime;
time_t etime;
stime = time(0);
BOOST_LOG_SEV(glg, note) << "Start dvmdostem @ " << ctime(&stime);
BOOST_LOG_SEV(glg, debug) << "NEW STYLE: Going to run space-major over a 2D area covered by run mask...";
// Open the run mask (spatial mask)
std::vector< std::vector<int> > run_mask = read_run_mask(modeldata.runmask_file);
// Make some convenient handles for later...
std::string eq_restart_fname = modeldata.output_dir + "restart-eq.nc";
std::string sp_restart_fname = modeldata.output_dir + "restart-sp.nc";
std::string tr_restart_fname = modeldata.output_dir + "restart-tr.nc";
std::string sc_restart_fname = modeldata.output_dir + "restart-sc.nc";
// Figure out how big the run_mask is
int num_rows = run_mask.size();
int num_cols = run_mask[0].size();
// Create empty restart files for all stages based on size of run mask
if (!boost::filesystem::exists(modeldata.output_dir)) {
BOOST_LOG_SEV(glg, info) << "Creating output directory as specified in "
<< "config file: ", modeldata.output_dir;
boost::filesystem::create_directory(modeldata.output_dir);
}
RestartData::create_empty_file(eq_restart_fname, num_rows, num_cols);
RestartData::create_empty_file(sp_restart_fname, num_rows, num_cols);
RestartData::create_empty_file(tr_restart_fname, num_rows, num_cols);
RestartData::create_empty_file(sc_restart_fname, num_rows, num_cols);
if (args->get_loop_order() == "space-major") {
// y <==> row <==> lat
// x <==> col <==> lon
// Loop over a 2D grid of 'cells' (cohorts?),
// run each cell for some number of years.
//
// Processing starts in the lower left corner (0,0).
// Should really look into replacing this loop with
// something like python's map(...) function...
// --> Could this allow us to use a map reduce strategy??
//
// Look into std::transform.
// Use a few type definitions to save some typing.
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
vec2D::const_iterator row;
vec::const_iterator col;
for (row = run_mask.begin(); row != run_mask.end() ; ++row) {
for (col = row->begin(); col != row->end(); ++col) {
bool mask_value = *col;
int rowidx = row - run_mask.begin();
int colidx = col - row->begin();
if (true == mask_value) {
BOOST_LOG_SEV(glg, note) << "Running cell (" << rowidx << ", " << colidx << ")";
//modeldata.initmode = 1; // OBSOLETE?
BOOST_LOG_SEV(glg, info) << "Setup the NEW STYLE RUNNER OBJECT ...";
Runner runner(modeldata, args->get_cal_mode(), rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << runner.cohort.ground.layer_report_string("depth thermal");
// seg fault w/o preparing climate...so prepare year zero...
// this is also called inside run_years(...)
runner.cohort.climate.prepare_daily_driving_data(0, "eq");
runner.cohort.initialize_internal_pointers(); // sets up lots of pointers to various things
runner.cohort.initialize_state_parameters(); // sets data based on values in cohortlookup
BOOST_LOG_SEV(glg, debug) << "right after initialize_internal_pointers() and initialize_state_parameters()"
<< runner.cohort.ground.layer_report_string("depth ptr");
// PRE RUN STAGE (PR)
if (modeldata.pr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("PRE-RUN");
/** Env-only "pre-run" stage.
- should use only the env module
- number of years to run can be controlled on cmd line
- use fixed climate that is averaged over first X years
- use static (fixed) co2 value (first element of co2 file)
- FIX: need to set yrs since dsb ?
- FIX: should ignore calibration directives?
*/
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// turn off everything but env
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_bgcmodule(false);
runner.cohort.md->set_nfeed(false);
runner.cohort.md->set_avlnflg(false);
runner.cohort.md->set_baseline(false);
runner.cohort.md->set_dsbmodule(false);
runner.cohort.md->set_dslmodule(false);
runner.cohort.md->set_dvmmodule(false);
BOOST_LOG_SEV(glg, debug) << "Ground, right before 'pre-run'. "
<< runner.cohort.ground.layer_report_string("depth thermal");
runner.run_years(0, modeldata.pr_yrs, "pre-run"); // climate is prepared w/in here.
BOOST_LOG_SEV(glg, debug) << "Ground, right after 'pre-run'"
<< runner.cohort.ground.layer_report_string("depth thermal");
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("pr");
}
}
// EQUILIBRIUM STAGE (EQ)
if (modeldata.eq_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("EQ");
BOOST_LOG_SEV(glg, fatal) << "Running Equilibrium, " << modeldata.eq_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_dvmmodule(true);
runner.cohort.md->set_bgcmodule(true);
runner.cohort.md->set_dslmodule(true);
runner.cohort.md->set_nfeed(true);
runner.cohort.md->set_avlnflg(true);
runner.cohort.md->set_baseline(true);
runner.cohort.md->set_dsbmodule(false);
if (runner.cohort.md->get_dsbmodule()) {
// The transition to SP must occur at the completion of a
// fire cycle (i.e. a year or two prior to the next fire).
// To ensure this, re-set modeldata's EQ year count to an
// even multiple of the FRI minus 2 (to be safe)
int fri = runner.cohort.fire.getFRI();
int EQ_fire_cycles = modeldata.eq_yrs / fri;
if (modeldata.eq_yrs%fri != 0) {
modeldata.eq_yrs = fri * (EQ_fire_cycles + 1) - 2;
}
}
// Run model
runner.run_years(0, modeldata.eq_yrs, "eq-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData post EQ";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData to: " << eq_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(eq_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("eq");
}
}
// SPINUP STAGE (SP)
if (modeldata.sp_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SP");
BOOST_LOG_SEV(glg, fatal) << "Running Spinup, " << modeldata.sp_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.climate.monthlycontainers2log();
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << eq_restart_fname;
runner.cohort.restartdata.update_from_ncfile(eq_restart_fname, rowidx, colidx);
// FIX: if restart file has -9999, then soil temps can end up
// impossibly low should check for valid values prior to actual use
// Maybe a diffcult to maintain in the future
// when/if more variables are added?
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre SP";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.sp_yrs, "sp-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SP";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sp_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(sp_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sp");
}
}
// TRANSIENT STAGE (TR)
if (modeldata.tr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("TR");
BOOST_LOG_SEV(glg, fatal) << "Running Transient, " << modeldata.tr_yrs << " years";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// update the cohort's restart data object
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << sp_restart_fname;
runner.cohort.restartdata.update_from_ncfile(sp_restart_fname, rowidx, colidx);
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre TR";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.tr_yrs, "tr-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post TR";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << tr_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(tr_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("tr");
}
}
// SCENARIO STAGE (SC)
if (modeldata.sc_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SC");
BOOST_LOG_SEV(glg, fatal) << "Running Scenario, " << modeldata.sc_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// update the cohort's restart data object
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << tr_restart_fname;
runner.cohort.restartdata.update_from_ncfile(tr_restart_fname, rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << "RestartData pre SC";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Loading projected data instead of historic. FIX?
runner.cohort.load_proj_climate(modeldata.proj_climate_file);
// Run model
runner.run_years(0, modeldata.sc_yrs, "sc-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SC";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sc_restart_fname;
runner.cohort.restartdata.write_pixel_to_ncfile(sc_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sc");
}
}
// NOTE: Could have an option to set some time constants based on
// some sizes/dimensions of the input driving data...
/**
eq
- create the climate from the average of the first X years
of the driving climate data.
SIZE: 12 months, 1 year
- set to default module settings to: ??
- run_years( 0 <= iy < MAX_EQ_YEAR )
- act on calibration directives
-
sp
- create the climate from the first X years of the driving
climate dataset.
SIZE: 12 months, X years
- set to default module settings: ??
- run_years( SP_BEG <= iy <= SP_END )
tr
- create climate by loading the driving climate data (historic)
SIZE: 12 months, length of driving dataset? OR number from inc/timeconst.h
- set to default module settings: ??
- run_years( TR_BEG <= iy <= TR_END )
*/
} else {
BOOST_LOG_SEV(glg, debug) << "Skipping cell (" << rowidx << ", " << colidx << ")";
}
}
}
} else if (args->get_loop_order() == "time-major") {
BOOST_LOG_SEV(glg, warn) << "DO NOTHING. NOT IMPLEMENTED YET.";
// for each year
// Read in Climate - all locations, one year/timestep
// Read in Vegetation - all locations
// Read in Drainage - all locations
// Read in Fire - all locations
// for each cohort
// updateMonthly(...)
}
BOOST_LOG_SEV(glg, note) << "DONE WITH NEW STYLE run (" << args->get_loop_order() << ")";
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Total Seconds: " << difftime(etime, stime);
return 0;
} /* End main() */
/** Pretty print a 2D vector of ints */
void pp_2dvec(const std::vector<std::vector<int> > & vv) {
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
for (vec2D::const_iterator row = vv.begin(); row != vv.end(); ++row) {
for (vec::const_iterator col = row->begin(); col != row->end(); ++col) {
std::cout << *col << " ";
}
std::cout << std::endl;
}
}
/** rough draft for reading a run-mask (2D vector of ints)
*/
std::vector< std::vector<int> > read_run_mask(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yD, xD;
size_t yD_len, xD_len;
temutil::nc( nc_inq_dimid(ncid, "Y", &yD) );
temutil::nc( nc_inq_dimlen(ncid, yD, &yD_len) );
temutil::nc( nc_inq_dimid(ncid, "X", &xD) );
temutil::nc( nc_inq_dimlen(ncid, xD, &xD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate a 2D run-mask vector (y,x). Size: (" << yD_len << ", " << xD_len << ")";
std::vector< std::vector<int> > run_mask(yD_len, std::vector<int>(xD_len));
BOOST_LOG_SEV(glg, debug) << "Read the run flag data from the file into the 2D vector...";
int runV;
temutil::nc( nc_inq_varid(ncid, "run", &runV) );
BOOST_LOG_SEV(glg, debug) << "Grab one row at a time";
BOOST_LOG_SEV(glg, debug) << "(need contiguous memory, and vector<vector> are not contiguous)";
std::vector< std::vector<int> >::iterator row;
for (row = run_mask.begin(); row != run_mask.end(); ++row) {
int rowidx = row - run_mask.begin();
// specify start indices for each dimension (y, x)
size_t start[2];
start[0] = rowidx; // Y
start[1] = 0; // X
// specify counts for each dimension
size_t count[2];
count[0] = 1; // one row
count[1] = xD_len; // all data
std::vector<int> rowdata(xD_len);
temutil::nc( nc_get_vara_int(ncid, runV, start, count, &rowdata[0] ) );
run_mask[rowidx] = rowdata;
}
temutil::nc( nc_close(ncid) );
//pp_2dvec(run_mask);
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return run_mask;
}
/** rough draft for reading new-style co2 data
*/
std::vector<float> read_new_co2_file(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yearD;
size_t yearD_len;
temutil::nc( nc_inq_dimid(ncid, "year", &yearD) );
temutil::nc( nc_inq_dimlen(ncid, yearD, &yearD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate vector big enough for " << yearD_len << " years of co2 data...";
std::vector<float> co2data(yearD_len);
BOOST_LOG_SEV(glg, debug) << "Read the co2 data from the file into the vector...";
int co2V;
temutil::nc( nc_inq_varid(ncid, "co2", &co2V) );
temutil::nc( nc_get_var(ncid, co2V, &co2data[0]) );
temutil::nc( nc_close(ncid) );
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return co2data;
}
/** rough draft for new output files
*/
void create_new_output() {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Creating dataset...";
temutil::nc( nc_create("general-outputs-monthly.nc", NC_CLOBBER, &ncid) );
int timeD; // unlimited dimension
int pftD;
int xD;
int yD;
/* Create Dimensions */
BOOST_LOG_SEV(glg, debug) << "Adding dimensions...";
temutil::nc( nc_def_dim(ncid, "time", NC_UNLIMITED, &timeD) );
temutil::nc( nc_def_dim(ncid, "pft", NUM_PFT, &pftD) );
temutil::nc( nc_def_dim(ncid, "y", 10, &yD) );
temutil::nc( nc_def_dim(ncid, "x", 10, &xD) );
/* Create Coordinate Variables?? */
/* Create Data Variables */
// 4D vars
BOOST_LOG_SEV(glg, debug) << "Adding 4D variables...";
int vartypeA_dimids[4];
vartypeA_dimids[0] = timeD;
vartypeA_dimids[1] = pftD;
vartypeA_dimids[2] = yD;
vartypeA_dimids[3] = xD;
int vegcV;
int veg_fractionV;
int growstartV;
temutil::nc( nc_def_var(ncid, "vegc", NC_DOUBLE, 4, vartypeA_dimids, &vegcV) );
temutil::nc( nc_def_var(ncid, "veg_fraction", NC_DOUBLE, 4, vartypeA_dimids, &veg_fractionV) );
temutil::nc( nc_def_var(ncid, "growstart", NC_DOUBLE, 4, vartypeA_dimids, &growstartV) );
// 3D vars
BOOST_LOG_SEV(glg, debug) << "Adding 3D variables...";
int vartypeB_dimids[3];
vartypeB_dimids[0] = timeD;
vartypeB_dimids[1] = yD;
vartypeB_dimids[2] = xD;
int org_shlw_thicknessV;
temutil::nc( nc_def_var(ncid, "org_shlw_thickness", NC_DOUBLE, 3, vartypeB_dimids, &org_shlw_thicknessV) );
/* Create Attributes? */
/* End Define Mode (not scrictly necessary for netcdf 4) */
BOOST_LOG_SEV(glg, debug) << "Leaving 'define mode'...";
temutil::nc( nc_enddef(ncid) );
/* Load coordinate variables?? */
/* Close file. */
BOOST_LOG_SEV(glg, debug) << "Closing new file...";
temutil::nc( nc_close(ncid) );
}
|
// @(#)root/proof:$Name: $:$Id: TProof.cxx,v 1.82 2005/03/17 15:00:47 rdm Exp $
// Author: Fons Rademakers 13/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProof //
// //
// This class controls a Parallel ROOT Facility, PROOF, cluster. //
// It fires the slave servers, it keeps track of how many slaves are //
// running, it keeps track of the slaves running status, it broadcasts //
// messages to all slaves, it collects results, etc. //
// //
//////////////////////////////////////////////////////////////////////////
#include <fcntl.h>
#include <errno.h>
#ifdef WIN32
# include <io.h>
# include <sys/stat.h>
# include <sys/types.h>
#else
# include <unistd.h>
#endif
#include "TProof.h"
#include "TSortedList.h"
#include "TSlave.h"
#include "TMonitor.h"
#include "TMessage.h"
#include "TSystem.h"
#include "TError.h"
#include "TUrl.h"
#include "TFTP.h"
#include "TROOT.h"
#include "TH1.h"
#include "TProofPlayer.h"
#include "TDSet.h"
#include "TEnv.h"
#include "TPluginManager.h"
#include "TCondor.h"
#include "Riostream.h"
#include "TTree.h"
#include "TDrawFeedback.h"
#include "TEventList.h"
#include "TMonitor.h"
#include "TBrowser.h"
#include "TChain.h"
#include "TProofServ.h"
#include "TMap.h"
#include "TTimer.h"
//----- PROOF Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TProofInterruptHandler : public TSignalHandler {
private:
TProof *fProof;
public:
TProofInterruptHandler(TProof *p)
: TSignalHandler(kSigInterrupt, kFALSE), fProof(p) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TProofInterruptHandler::Notify()
{
// TProof interrupt handler.
fProof->Interrupt(TProof::kHardInterrupt);
return kTRUE;
}
//----- Input handler for messages from TProofServ -----------------------------
//______________________________________________________________________________
class TProofInputHandler : public TFileHandler {
private:
TSocket *fSocket;
TProof *fProof;
public:
TProofInputHandler(TProof *p, TSocket *s)
: TFileHandler(s->GetDescriptor(), 1) { fProof = p; fSocket = s; }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TProofInputHandler::Notify()
{
fProof->HandleAsyncInput(fSocket);
return kTRUE;
}
//------------------------------------------------------------------------------
ClassImp(TSlaveInfo)
//______________________________________________________________________________
Int_t TSlaveInfo::Compare(const TObject *obj) const
{
// Used to sort slaveinfos by ordinal.
if (!obj) return 1;
const TSlaveInfo *si = dynamic_cast<const TSlaveInfo*>(obj);
if (!si) return fOrdinal.CompareTo(obj->GetName());
const char *myord = GetOrdinal();
const char *otherord = si->GetOrdinal();
while (myord && otherord) {
Int_t myval = atoi(myord);
Int_t otherval = atoi(otherord);
if (myval < otherval) return 1;
if (myval > otherval) return -1;
myord = strchr(myord, '.');
if (myord) myord++;
otherord = strchr(otherord, '.');
if (otherord) otherord++;
}
if (myord) return -1;
if (otherord) return 1;
return 0;
}
//______________________________________________________________________________
void TSlaveInfo::Print(Option_t *opt) const
{
// Print slave info. If opt = "active" print only the active
// slaves, if opt="notactive" print only the not active slaves,
// if opt = "bad" print only the bad slaves, else
// print all slaves.
TString stat = fStatus == kActive ? "active" :
fStatus == kBad ? "bad" :
"not active";
if (!opt) opt = "";
if (!strcmp(opt, "active") && fStatus != kActive)
return;
if (!strcmp(opt, "notactive") && fStatus != kNotActive)
return;
if (!strcmp(opt, "bad") && fStatus != kBad)
return;
cout << "Slave: " << fOrdinal
<< " hostname: " << fHostName
<< " msd: " << fMsd
<< " perf index: " << fPerfIndex
<< " " << stat
<< endl;
}
//------------------------------------------------------------------------------
ClassImp(TProof)
//______________________________________________________________________________
TProof::TProof(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Create a PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). Masterurl is of
// the form: proof://host[:port] or proofs://host[:port]. Conffile is
// the name of the config file describing the remote PROOF cluster
// (this argument alows you to describe different cluster configurations).
// The default is proof.conf. Confdir is the directory where the config
// file and other PROOF related files are (like motd and noproof files).
// Loglevel is the log level (default = 1).
if (!conffile || strlen(conffile) == 0)
conffile = kPROOF_ConfFile;
if (!confdir || strlen(confdir) == 0)
confdir = kPROOF_ConfDir;
// Can have only one PROOF session open at a time (for the time being).
if (gProof) {
Warning("TProof", "closing currently open PROOF session");
gProof->Close();
}
Init(masterurl, conffile, confdir, loglevel);
gProof = this;
}
//______________________________________________________________________________
TProof::TProof()
{
// Protected constructor to be used by classes deriving from TProof
// (they have to call Init themselves and override StartSlaves
// appropriately).
//
// This constructor simply closes any previous gProof and sets gProof
// to this instance.
// Can have only one PROOF session open at a time (for the time being).
if (gProof) {
Warning("TProof", "closing currently open PROOF session");
gProof->Close();
}
gProof = this;
}
//______________________________________________________________________________
TProof::~TProof()
{
// Clean up PROOF environment.
while (TChain *chain = dynamic_cast<TChain*> (fChains->First()) ) {
// remove "chain" from list
chain->SetProof(0);
}
Close();
SafeDelete(fIntHandler);
SafeDelete(fSlaves);
SafeDelete(fActiveSlaves);
SafeDelete(fUniqueSlaves);
SafeDelete(fNonUniqueMasters);
SafeDelete(fBadSlaves);
SafeDelete(fAllMonitor);
SafeDelete(fActiveMonitor);
SafeDelete(fUniqueMonitor);
SafeDelete(fSlaveInfo);
SafeDelete(fChains);
gROOT->GetListOfSockets()->Remove(this);
if (gProof == this) {
gProof = 0;
}
}
//______________________________________________________________________________
Int_t TProof::Init(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Start the PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). For a description
// of the arguments see the TProof ctor. Returns the number of started
// master or slave servers, returns 0 in case of error, in which case
// fValid remains false.
Assert(gSystem);
fValid = kFALSE;
TUrl *u;
if (!masterurl || !*masterurl)
u = new TUrl("proof://__master__");
else if (strstr(masterurl, "://"))
u = new TUrl(masterurl);
else
u = new TUrl(Form("proof://%s", masterurl));
fUser = u->GetUser();
fMaster = u->GetHost();
fPort = u->GetPort();
fConfDir = confdir;
fConfFile = conffile;
fWorkDir = gSystem->WorkingDirectory();
fLogLevel = loglevel;
fProtocol = kPROOF_Protocol;
fMasterServ = fMaster == "__master__" ? kTRUE : kFALSE;
fSendGroupView = kTRUE;
fImage = fMasterServ ? "" : "<local>";
fIntHandler = 0;
fProgressDialog = 0;
fStatus = 0;
fSlaveInfo = 0;
fSecContext = 0;
fChains = new TList;
fUrlProtocol = u->GetProtocol();
fPlayer = MakePlayer();
fFeedback = new TList;
fFeedback->SetOwner();
fFeedback->SetName("FeedbackList");
AddInput(fFeedback);
delete u;
// global logging
gProofDebugLevel = fLogLevel;
gProofDebugMask = TProofDebug::kAll;
// sort slaves by descending performance index
fSlaves = new TSortedList(kSortDescending);
fActiveSlaves = new TList;
fUniqueSlaves = new TList;
fNonUniqueMasters = new TList;
fBadSlaves = new TList;
fAllMonitor = new TMonitor;
fActiveMonitor = new TMonitor;
fUniqueMonitor = new TMonitor;
if (!StartSlaves()) return 0;
// we are now properly initialized
fValid = kTRUE;
// De-activate monitor (will be activated in Collect)
fAllMonitor->DeActivateAll();
// By default go into parallel mode
GoParallel(9999);
// Send relevant initial state to slaves
SendInitialState();
SetActive(kFALSE);
if (IsValid())
gROOT->GetListOfSockets()->Add(this);
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
Bool_t TProof::StartSlaves()
{
// Start up PROOF slaves.
// If this is a master server, find the config file and start slave
// servers as specified in the config file
if (IsMaster()) {
TString fconf;
fconf.Form("%s/.%s", gSystem->Getenv("HOME"), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
fconf.Form("%s/proof/etc/%s", fConfDir.Data(), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
Error("StartSlaves", "no PROOF config file found");
return kFALSE;
}
}
PDB(kGlobal,1) Info("StartSlaves", "using PROOF config file: %s", fconf.Data());
FILE *pconf;
if ((pconf = fopen(fconf, "r"))) {
fConfFile = fconf;
// read the config file
char line[1024];
TString host = gSystem->GetHostByName(gSystem->HostName()).GetHostName();
int ord = 0;
// check for valid master line
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// see if master may run on this node, accept both old "node"
// and new "master" lines
if (nword >= 2 &&
(!strcmp(word[0], "node") || !strcmp(word[0], "master")) &&
!fImage.Length()) {
TInetAddress a = gSystem->GetHostByName(word[1]);
if (!host.CompareTo(a.GetHostName()) ||
!strcmp(word[1], "localhost")) {
const char *image = word[1];
const char *workdir = kPROOF_WorkDir;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "workdir=", 8))
workdir = word[i]+8;
}
const char* expworkdir = gSystem->ExpandPathName(workdir);
if (!strcmp(expworkdir,gProofServ->GetWorkDir())) {
fImage = image;
}
delete [] (char *) expworkdir;
}
}
}
if (fImage.Length() == 0) {
fclose(pconf);
Error("StartSlaves", "no appropriate master line found in %s", fconf.Data());
return kFALSE;
}
// check for valid slave lines and start slaves
rewind(pconf);
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// find all slave servers, accept both "slave" and "worker" lines
if (nword >= 2 &&
(!strcmp(word[0], "slave") || !strcmp(word[0], "worker"))) {
int perfidx = 100;
int sport = fPort;
const char *image = word[1];
const char *workdir = 0;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "perf=", 5))
perfidx = atoi(word[i]+5);
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "port=", 5))
sport = atoi(word[i]+5);
if (!strncmp(word[i], "workdir=", 8))
workdir = word[i]+8;
}
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)word[1]);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
// create slave server
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
TSlave *slave = CreateSlave(word[1], sport, fullord, perfidx, image, workdir);
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
} else {
fBadSlaves->Add(slave);
}
PDB(kGlobal,3)
Info("StartSlaves","slave on host %s created and added to list", word[1]);
}
}
}
fclose(pconf);
} else {
// create master server
TSlave *slave = CreateSubmaster(fMaster, fPort, "0", "master", fConfFile, 0);
if (slave->IsValid()) {
// check protocol compatability
// protocol 1 is not supported anymore
if (fProtocol == 1) {
Error("StartSlaves", "client and remote protocols not compatible (%d and %d)",
kPROOF_Protocol, fProtocol);
delete slave;
return kFALSE;
}
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
Collect(slave);
if (slave->GetStatus() == -99) {
Error("StartSlaves", "not allowed to connect to PROOF master server");
return 0;
}
if (!slave->IsValid()) {
delete slave;
Error("StartSlaves", "failed to setup connection with PROOF master server");
return kFALSE;
}
fIntHandler = new TProofInterruptHandler(this);
fIntHandler->Add();
if (!gROOT->IsBatch()) {
if ((fProgressDialog = gROOT->GetPluginManager()->FindHandler("TProofProgressDialog")))
if (fProgressDialog->LoadPlugin() == -1)
fProgressDialog = 0;
}
} else {
delete slave;
Error("StartSlaves", "failed to connect to a PROOF master server");
return kFALSE;
}
}
return kTRUE;
}
//______________________________________________________________________________
void TProof::Close(Option_t *)
{
// Close all open slave servers.
if (fSlaves) {
if (fIntHandler)
fIntHandler->Remove();
// If local client ...
if (!IsMaster()) {
// ... tell master and slaves to stop
Interrupt(kShutdownInterrupt, kAll);
}
fActiveSlaves->Clear("nodelete");
fUniqueSlaves->Clear("nodelete");
fNonUniqueMasters->Clear("nodelete");
fBadSlaves->Clear("nodelete");
fSlaves->Delete();
}
}
//______________________________________________________________________________
TSlave *TProof::CreateSlave(const char *host, Int_t port, const char *ord,
Int_t perf, const char *image, const char *workdir)
{
// Create a new TSlave of type TSlave::kSlave.
// Note: constructor of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave* sl = new TSlave(host, port, ord, perf, image,
this, TSlave::kSlave, workdir, 0, 0);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
// must set fParallel to 1 for slaves since they do not
// report their fParallel with a LOG_DONE message
sl->fParallel = 1;
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::CreateSubmaster(const char *host, Int_t port, const char *ord,
const char *image, const char *conffile,
const char *msd)
{
// Create a new TSlave of type TSlave::kMaster.
// Note: constructor of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave *sl = new TSlave(host, port, ord, 100, image, this,
TSlave::kMaster, 0, conffile, msd);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::FindSlave(TSocket *s) const
{
// Find slave that has TSocket s. Returns 0 in case slave is not found.
TSlave *sl;
TIter next(fSlaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid() && sl->GetSocket() == s)
return sl;
}
return 0;
}
//______________________________________________________________________________
void TProof::FindUniqueSlaves()
{
// Add to the fUniqueSlave list the active slaves that have a unique
// (user) file system image. This information is used to transfer files
// only once to nodes that share a file system (an image). Submasters
// which are not in fUniqueSlaves are put in the fNonUniqueMasters
// list. That list is used to trigger the transferring of files to
// the submaster's unique slaves without the need to transfer the file
// to the submaster.
fUniqueSlaves->Clear();
fUniqueMonitor->RemoveAll();
fNonUniqueMasters->Clear();
TIter next(fActiveSlaves);
while (TSlave *sl = dynamic_cast<TSlave*>(next())) {
if (fImage == sl->fImage) {
if (sl->GetSlaveType() == TSlave::kMaster)
fNonUniqueMasters->Add(sl);
continue;
}
TIter next2(fUniqueSlaves);
TSlave *replace_slave = 0;
Bool_t add = kTRUE;
while (TSlave *sl2 = dynamic_cast<TSlave*>(next2())) {
if (sl->fImage == sl2->fImage) {
add = kFALSE;
if (sl->GetSlaveType() == TSlave::kMaster) {
if (sl2->GetSlaveType() == TSlave::kSlave) {
// give preference to master
replace_slave = sl2;
add = kTRUE;
} else if (sl2->GetSlaveType() == TSlave::kMaster) {
fNonUniqueMasters->Add(sl);
} else {
Error("FindUniqueSlaves", "TSlave is neither Master nor Slave");
Assert(0);
}
}
break;
}
}
if (add) {
fUniqueSlaves->Add(sl);
fUniqueMonitor->Add(sl->GetSocket());
if (replace_slave) {
fUniqueSlaves->Remove(replace_slave);
fUniqueMonitor->Remove(replace_slave->GetSocket());
}
}
}
// will be actiavted in Collect()
fUniqueMonitor->DeActivateAll();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfSlaves() const
{
// Return number of slaves as described in the config file.
return fSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfActiveSlaves() const
{
// Return number of active slaves, i.e. slaves that are valid and in
// the current computing group.
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfUniqueSlaves() const
{
// Return number of unique slaves, i.e. active slaves that have each a
// unique different user files system.
return fUniqueSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfBadSlaves() const
{
// Return number of bad slaves. This are slaves that we in the config
// file, but refused to startup or that died during the PROOF session.
return fBadSlaves->GetSize();
}
//______________________________________________________________________________
void TProof::AskStatistics()
{
// Ask the for the statistics of the slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETSTATS, kActive);
Collect(kActive);
}
//______________________________________________________________________________
void TProof::AskParallel()
{
// Ask the for the number of parallel slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETPARALLEL, kActive);
Collect(kActive);
}
//______________________________________________________________________________
Bool_t TProof::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready)
{
// See if the data is ready to be analyzed.
if (!IsValid()) return kFALSE;
TList submasters;
TIter NextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(NextSlave())) {
if (sl->GetSlaveType() == TSlave::kMaster) {
submasters.Add(sl);
}
}
fDataReady = kTRUE; //see if any submasters set it to false
fBytesReady = 0;
fTotalBytes = 0;
//loop over submasters and see if data is ready
if (submasters.GetSize() > 0) {
Broadcast(kPROOF_DATA_READY, &submasters);
Collect(&submasters);
}
bytesready = fBytesReady;
totalbytes = fTotalBytes;
EmitVA("IsDataReady(Long64_t,Long64_t)", 2, totalbytes, bytesready);
//PDB(kGlobal,2)
Info("IsDataReady", "%lld / %lld (%s)", bytesready, totalbytes, fDataReady?"READY":"NOT READY");
return fDataReady;
}
//______________________________________________________________________________
void TProof::Interrupt(EUrgent type, ESlaves list)
{
// Send interrupt OOB byte to master or slave servers.
if (!IsValid()) return;
char oobc = (char) type;
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (slaves->GetSize() == 0) return;
const int kBufSize = 1024;
char waste[kBufSize];
TSlave *sl;
TIter next(slaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
TSocket *s = sl->GetSocket();
// Send one byte out-of-band message to server
if (s->SendRaw(&oobc, 1, kOob) <= 0) {
Error("Interrupt", "error sending oobc to slave %s", sl->GetOrdinal());
continue;
}
if (type == kHardInterrupt) {
char oob_byte;
int n, nch, nbytes = 0, nloop = 0;
// Receive the OOB byte
while ((n = s->RecvRaw(&oob_byte, 1, kOob)) < 0) {
if (n == -2) { // EWOULDBLOCK
//
// The OOB data has not yet arrived: flush the input stream
//
// In some systems (Solaris) regular recv() does not return upon
// receipt of the oob byte, which makes the below call to recv()
// block indefinitely if there are no other data in the queue.
// FIONREAD ioctl can be used to check if there are actually any
// data to be flushed. If not, wait for a while for the oob byte
// to arrive and try to read it again.
//
s->GetOption(kBytesToRead, nch);
if (nch == 0) {
gSystem->Sleep(1000);
continue;
}
if (nch > kBufSize) nch = kBufSize;
n = s->RecvRaw(waste, nch);
if (n <= 0) {
Error("Interrupt", "error receiving waste from slave %s",
sl->GetOrdinal());
break;
}
nbytes += n;
} else if (n == -3) { // EINVAL
//
// The OOB data has not arrived yet
//
gSystem->Sleep(100);
if (++nloop > 100) { // 10 seconds time-out
Error("Interrupt", "server %s does not respond", sl->GetOrdinal());
break;
}
} else {
Error("Interrupt", "error receiving OOB from server %s",
sl->GetOrdinal());
break;
}
}
//
// Continue flushing the input socket stream until the OOB
// mark is reached
//
while (1) {
int atmark;
s->GetOption(kAtMark, atmark);
if (atmark)
break;
// find out number of bytes to read before atmark
s->GetOption(kBytesToRead, nch);
if (nch == 0) {
gSystem->Sleep(1000);
continue;
}
if (nch > kBufSize) nch = kBufSize;
n = s->RecvRaw(waste, nch);
if (n <= 0) {
Error("Interrupt", "error receiving waste (2) from slave %s",
sl->GetOrdinal());
break;
}
nbytes += n;
}
if (nbytes > 0) {
if (IsMaster())
Printf("*** Slave %s:%s synchronized: %d bytes discarded",
sl->GetName(), sl->GetOrdinal(), nbytes);
else
Printf("*** PROOF synchronized: %d bytes discarded", nbytes);
}
// Get log file from master or slave after a hard interrupt
Collect(sl);
} else if (type == kSoftInterrupt) {
// Get log file from master or slave after a soft interrupt
Collect(sl);
} else if (type == kShutdownInterrupt) {
; // nothing expected to be returned
} else {
// Unexpected message, just receive log file
Collect(sl);
}
}
}
}
//______________________________________________________________________________
Int_t TProof::GetParallel() const
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// iterate over active slaves and return total number of slaves
TIter NextSlave(GetListOfActiveSlaves());
Int_t nparallel = 0;
while (TSlave* sl = dynamic_cast<TSlave*>(NextSlave()))
if(sl->GetParallel() >= 0)
nparallel += sl->GetParallel();
return nparallel;
}
//______________________________________________________________________________
TList *TProof::GetSlaveInfo()
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return 0;
if (fSlaveInfo == 0) {
fSlaveInfo = new TSortedList(kSortDescending);
fSlaveInfo->SetOwner();
} else {
fSlaveInfo->Delete();
}
TList masters;
TIter next(GetListOfSlaves());
TSlave *slave;
while((slave = (TSlave *) next()) != 0) {
if (slave->GetSlaveType() == TSlave::kSlave) {
TSlaveInfo *slaveinfo = new TSlaveInfo(slave->GetOrdinal(),
slave->GetName(),
slave->GetPerfIdx());
fSlaveInfo->Add(slaveinfo);
TIter nextactive(GetListOfActiveSlaves());
TSlave *activeslave;
while ((activeslave = (TSlave *) nextactive())) {
if (TString(slaveinfo->GetOrdinal()) == activeslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kActive);
break;
}
}
TIter nextbad(GetListOfBadSlaves());
TSlave *badslave;
while ((badslave = (TSlave *) nextbad())) {
if (TString(slaveinfo->GetOrdinal()) == badslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kBad);
break;
}
}
} else if (slave->GetSlaveType() == TSlave::kMaster) {
if (slave->IsValid()) {
if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1)
MarkBad(slave);
else
masters.Add(slave);
}
} else {
Error("GetSlaveInfo", "TSlave is neither Master nor Slave");
Assert(0);
}
}
if (masters.GetSize() > 0) Collect(&masters);
return fSlaveInfo;
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, TList *slaves)
{
// Broadcast a message to all slaves in the specified list. Returns
// the number of slaves the message was successfully sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->Send(mess) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, ESlaves list)
{
// Broadcast a message to all slaves in the specified list (either
// all slaves or only the active slaves). Returns the number of slaves
// the message was successfully sent to. Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, TList *slaves)
{
// Broadcast a character string buffer to all slaves in the specified
// list. Use kind to set the TMessage what field. Returns the number of
// slaves the message was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, ESlaves list)
{
// Broadcast a character string buffer to all slaves in the specified
// list (either all slaves or only the active slaves). Use kind to
// set the TMessage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, TList *slaves)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, ESlaves list)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, TList *slaves)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->SendRaw(buffer, length) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, ESlaves list)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
return BroadcastRaw(buffer, length, slaves);
}
//______________________________________________________________________________
Int_t TProof::Collect(const TSlave *sl)
{
// Collect responses from slave sl. Returns the number of slaves that
// responded (=1).
if (!sl->IsValid()) return 0;
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
mon->Activate(sl->GetSocket());
return Collect(mon);
}
//______________________________________________________________________________
Int_t TProof::Collect(TList *slaves)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave*) next())) {
if (sl->IsValid())
mon->Activate(sl->GetSocket());
}
return Collect(mon);
}
//______________________________________________________________________________
Int_t TProof::Collect(ESlaves list)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
TMonitor *mon = 0;
if (list == kAll) mon = fAllMonitor;
if (list == kActive) mon = fActiveMonitor;
if (list == kUnique) mon = fUniqueMonitor;
mon->ActivateAll();
return Collect(mon);
}
//______________________________________________________________________________
Int_t TProof::Collect(TMonitor *mon)
{
// Collect responses from the slave servers. Returns the number of messages
// received. Can be 0 if there are no active slaves.
fStatus = 0;
if (!mon->GetActive()) return 0;
DeActivateAsyncInput();
int cnt = 0, loop = 1;
fBytesRead = 0;
fRealTime = 0.0;
fCpuTime = 0.0;
while (loop) {
char str[512];
TMessage *mess;
TSocket *s;
TSlave *sl;
TObject *obj;
Int_t what;
s = mon->Select();
if (s->Recv(mess) < 0) {
MarkBad(s);
continue;
}
if (!mess) {
// we get here in case the remote server died
MarkBad(s);
if (!mon->GetActive()) loop = 0;
continue;
}
what = mess->What();
switch (what) {
case kMESS_OBJECT:
obj = mess->ReadObject(mess->GetClass());
if (obj->InheritsFrom(TH1::Class())) {
TH1 *h = (TH1*)obj;
h->SetDirectory(0);
TH1 *horg = (TH1*)gDirectory->GetList()->FindObject(h->GetName());
if (horg)
horg->Add(h);
else
h->SetDirectory(gDirectory);
}
break;
case kPROOF_FATAL:
MarkBad(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_GETOBJECT:
mess->ReadString(str, sizeof(str));
obj = gDirectory->Get(str);
if (obj)
s->SendObject(obj);
else
s->Send(kMESS_NOTOK);
break;
case kPROOF_GETPACKET:
{
TDSetElement *elem = 0;
sl = FindSlave(s);
elem = fPlayer->GetNextPacket(sl, mess);
TMessage answ(kPROOF_GETPACKET);
if (elem != 0) {
answ << kTRUE
<< TString(elem->GetFileName())
<< TString(elem->GetDirectory())
<< TString(elem->GetObjName());
if (elem->GetEventList())
answ << ((Long64_t)-1) << elem->GetEventList();
else
answ << elem->GetFirst() << elem->GetNum();
} else {
answ << kFALSE;
}
s->Send(answ);
}
break;
case kPROOF_LOGFILE:
{
Int_t size;
(*mess) >> size;
RecvLogFile(s, size);
}
break;
case kPROOF_LOGDONE:
sl = FindSlave(s);
(*mess) >> sl->fStatus >> sl->fParallel;
PDB(kGlobal,2) Info("Collect:kPROOF_LOGDONE","status %d parallel %d",
sl->fStatus, sl->fParallel);
if (sl->fStatus != 0) fStatus = sl->fStatus; //return last nonzero status
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_GETSTATS:
sl = FindSlave(s);
(*mess) >> sl->fBytesRead >> sl->fRealTime >> sl->fCpuTime
>> sl->fWorkDir >> sl->fProofWorkDir;
fBytesRead += sl->fBytesRead;
fRealTime += sl->fRealTime;
fCpuTime += sl->fCpuTime;
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_GETPARALLEL:
sl = FindSlave(s);
(*mess) >> sl->fParallel;
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_OUTPUTLIST:
{
PDB(kGlobal,2) Info("Collect:kPROOF_OUTPUTLIST","Enter");
TList *out = (TList *) mess->ReadObject(TList::Class());
if (out) {
out->SetOwner();
fPlayer->StoreOutput(out); // Adopts the list
}
}
break;
case kPROOF_FEEDBACK:
{
PDB(kGlobal,2) Info("Collect:kPROOF_FEEDBACK","Enter");
TList *out = (TList *) mess->ReadObject(TList::Class());
out->SetOwner();
sl = FindSlave(s);
fPlayer->StoreFeedback(sl, out); // Adopts the list
}
break;
case kPROOF_AUTOBIN:
{
TString name;
Double_t xmin, xmax, ymin, ymax, zmin, zmax;
(*mess) >> name >> xmin >> xmax >> ymin >> ymax >> zmin >> zmax;
fPlayer->UpdateAutoBin(name,xmin,xmax,ymin,ymax,zmin,zmax);
TMessage answ(kPROOF_AUTOBIN);
answ << name << xmin << xmax << ymin << ymax << zmin << zmax;
s->Send(answ);
}
break;
case kPROOF_PROGRESS:
{
PDB(kGlobal,2) Info("Collect:kPROOF_PROGRESS","Enter");
sl = FindSlave(s);
Long64_t total, processed;
(*mess) >> total >> processed;
fPlayer->Progress(sl, total, processed);
}
break;
case kPROOF_GETSLAVEINFO:
{
PDB(kGlobal,2) Info("Collect:kPROOF_GETSLAVEINFO","Enter");
sl = FindSlave(s);
Bool_t active = (GetListOfActiveSlaves()->FindObject(sl) != 0);
Bool_t bad = (GetListOfBadSlaves()->FindObject(sl) != 0);
TList* tmpinfo = 0;
(*mess) >> tmpinfo;
tmpinfo->SetOwner(kFALSE);
Int_t nentries = tmpinfo->GetSize();
for (Int_t i=0; i<nentries; i++) {
TSlaveInfo* slinfo =
dynamic_cast<TSlaveInfo*>(tmpinfo->At(i));
if(slinfo) {
fSlaveInfo->Add(slinfo);
if (slinfo->fStatus != TSlaveInfo::kBad) {
if (!active) slinfo->SetStatus(TSlaveInfo::kNotActive);
if (bad) slinfo->SetStatus(TSlaveInfo::kBad);
}
if (!sl->GetMsd().IsNull()) slinfo->fMsd = sl->GetMsd();
}
}
delete tmpinfo;
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
}
break;
case kPROOF_VALIDATE_DSET:
{
PDB(kGlobal,2) Info("Collect:kPROOF_VALIDATE_DSET","Enter");
TDSet* dset = 0;
(*mess) >> dset;
if (!fDSet)
Error("Collect:kPROOF_VALIDATE_DSET", "fDSet not set");
else
fDSet->Validate(dset);
delete dset;
}
break;
case kPROOF_DATA_READY:
{
PDB(kGlobal,2) Info("Collect:kPROOF_DATA_READY","Enter");
Bool_t dataready = kFALSE;
Long64_t totalbytes, bytesready;
(*mess) >> dataready >> totalbytes >> bytesready;
fTotalBytes += totalbytes;
fBytesReady += bytesready;
if (dataready == kFALSE) fDataReady = dataready;
}
break;
default:
Error("Collect", "unknown command received from slave (%d)", what);
break;
}
cnt++;
delete mess;
}
// make sure group view is up to date
SendGroupView();
ActivateAsyncInput();
return cnt;
}
//______________________________________________________________________________
void TProof::ActivateAsyncInput()
{
// Activate the a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Add();
}
//______________________________________________________________________________
void TProof::DeActivateAsyncInput()
{
// De-actiate a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Remove();
}
//______________________________________________________________________________
void TProof::HandleAsyncInput(TSocket *sl)
{
// Handle input coming from the master server (when this is a client)
// or from a slave server (when this is a master server). This is mainly
// for a-synchronous communication. Normally when PROOF issues a command
// the (slave) server messages are directly handle by Collect().
TMessage *mess;
Int_t what;
if (sl->Recv(mess) <= 0)
return; // do something more intelligent here
what = mess->What();
switch (what) {
case kPROOF_PING:
// do nothing (ping is already acknowledged)
break;
default:
Error("HandleAsyncInput", "unknown command %d", what);
break;
}
delete mess;
}
//______________________________________________________________________________
void TProof::MarkBad(TSlave *sl)
{
// Add a bad slave server to the bad slave list and remove it from
// the active list and from the two monitor objects.
fActiveSlaves->Remove(sl);
FindUniqueSlaves();
fBadSlaves->Add(sl);
fAllMonitor->Remove(sl->GetSocket());
fActiveMonitor->Remove(sl->GetSocket());
sl->Close();
fSendGroupView = kTRUE;
}
//______________________________________________________________________________
void TProof::MarkBad(TSocket *s)
{
// Add slave with socket s to the bad slave list and remove if from
// the active list and from the two monitor objects.
TSlave *sl = FindSlave(s);
MarkBad(sl);
}
//______________________________________________________________________________
Int_t TProof::Ping()
{
// Ping PROOF. Returns 1 if master server responded.
return Ping(kActive);
}
//______________________________________________________________________________
Int_t TProof::Ping(ESlaves list)
{
// Ping PROOF slaves. Returns the number of slaves that responded.
TMessage mess(kPROOF_PING | kMESS_ACK);
return Broadcast(mess, list);
}
//______________________________________________________________________________
void TProof::Print(Option_t *option) const
{
// Print status of PROOF cluster.
if (!IsMaster()) {
Printf("Connected to: %s (%s)", GetMaster(),
IsValid() ? "valid" : "invalid");
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
Printf("Security context: %s", fSecContext->AsString());
TSlave *sl = (TSlave *)fActiveSlaves->First();
if (sl)
Printf("Proofd protocol version: %d", sl->GetSocket()->GetRemoteProtocol());
else
Printf("Proofd protocol version: Error - No connection");
Printf("Client protocol version: %d", GetClientProtocol());
Printf("Remote protocol version: %d", GetRemoteProtocol());
Printf("Log level: %d", GetLogLevel());
if (IsValid())
const_cast<TProof*>(this)->SendPrint(option);
} else {
const_cast<TProof*>(this)->AskStatistics();
if (IsParallel())
Printf("*** Master server %s (parallel mode, %d slaves):",
gProofServ->GetOrdinal(), GetParallel());
else
Printf("*** Master server %s (sequential mode):",
gProofServ->GetOrdinal());
Printf("Master host name: %s", gSystem->HostName());
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
Printf("Protocol version: %d", GetClientProtocol());
Printf("Image name: %s", GetImage());
Printf("Working directory: %s", gSystem->WorkingDirectory());
Printf("Config directory: %s", GetConfDir());
Printf("Config file: %s", GetConfFile());
Printf("Log level: %d", GetLogLevel());
Printf("Number of slaves: %d", GetNumberOfSlaves());
Printf("Number of active slaves: %d", GetNumberOfActiveSlaves());
Printf("Number of unique slaves: %d", GetNumberOfUniqueSlaves());
Printf("Number of bad slaves: %d", GetNumberOfBadSlaves());
Printf("Total MB's processed: %.2f", float(GetBytesRead())/(1024*1024));
Printf("Total real time used (s): %.3f", GetRealTime());
Printf("Total CPU time used (s): %.3f", GetCpuTime());
if (TString(option).Contains("a") && GetNumberOfSlaves()) {
Printf("List of slaves:");
TList masters;
TIter nextslave(fSlaves);
while (TSlave* sl = dynamic_cast<TSlave*>(nextslave())) {
if (!sl->IsValid()) continue;
if (sl->GetSlaveType() == TSlave::kSlave) {
sl->Print(option);
} else if (sl->GetSlaveType() == TSlave::kMaster) {
TMessage mess(kPROOF_PRINT);
mess.WriteString(option);
if (sl->GetSocket()->Send(mess) == -1)
const_cast<TProof*>(this)->MarkBad(sl);
else
masters.Add(sl);
} else {
Error("Print", "TSlave is neither Master nor Slave");
Assert(0);
}
}
const_cast<TProof*>(this)->Collect(&masters);
}
}
}
//______________________________________________________________________________
Int_t TProof::Process(TDSet *set, const char *selector, Option_t *option,
Long64_t nentries, Long64_t first, TEventList *evl)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error, 0 otherwise.
if (!IsValid()) return -1;
if (fProgressDialog)
fProgressDialog->ExecPlugin(5, this, selector, set->GetListOfElements()->GetSize(),
first, nentries);
return fPlayer->Process(set, selector, option, nentries, first, evl);
}
//______________________________________________________________________________
Int_t TProof::DrawSelect(TDSet *set, const char *varexp, const char *selection, Option_t *option,
Long64_t nentries, Long64_t first)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error, 0 otherwise.
if (!IsValid()) return -1;
return fPlayer->DrawSelect(set, varexp, selection, option, nentries, first);
}
//______________________________________________________________________________
void TProof::StopProcess(Bool_t abort)
{
fPlayer->StopProcess(abort);
}
//______________________________________________________________________________
void TProof::AddInput(TObject *obj)
{
// Add objects that might be needed during the processing of
// the selector (see Process()).
fPlayer->AddInput(obj);
}
//______________________________________________________________________________
void TProof::ClearInput()
{
// Clear input object list.
fPlayer->ClearInput();
// the system feedback list is always in the input list
AddInput(fFeedback);
}
//______________________________________________________________________________
TObject *TProof::GetOutput(const char *name)
{
// Get specified object that has been produced during the processing
// (see Process()).
return fPlayer->GetOutput(name);
}
//______________________________________________________________________________
TList *TProof::GetOutputList()
{
// Get list with all object created during processing (see Process()).
return fPlayer->GetOutputList();
}
//______________________________________________________________________________
void TProof::RecvLogFile(TSocket *s, Int_t size)
{
// Receive the log file of the slave with socket s.
const Int_t kMAXBUF = 16384; //32768 //16384 //65536;
char buf[kMAXBUF];
Int_t left, r;
Long_t filesize = 0;
while (filesize < size) {
left = Int_t(size - filesize);
if (left > kMAXBUF)
left = kMAXBUF;
r = s->RecvRaw(&buf, left);
if (r > 0) {
char *p = buf;
filesize += r;
while (r) {
Int_t w;
w = write(fileno(stdout), p, r);
if (w < 0) {
SysError("RecvLogFile", "error writing to stdout");
break;
}
r -= w;
p += w;
}
} else if (r < 0) {
Error("RecvLogFile", "error during receiving log file");
break;
}
}
}
//______________________________________________________________________________
Int_t TProof::SendGroupView()
{
// Send to all active slaves servers the current slave group size
// and their unique id. Returns number of active slaves.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (!IsMaster()) return 0;
if (!fSendGroupView) return 0;
fSendGroupView = kFALSE;
TIter next(fActiveSlaves);
TSlave *sl;
int bad = 0, cnt = 0, size = GetNumberOfActiveSlaves();
char str[32];
while ((sl = (TSlave *)next())) {
sprintf(str, "%d %d", cnt, size);
if (sl->GetSocket()->Send(str, kPROOF_GROUPVIEW) == -1) {
MarkBad(sl);
bad++;
} else
cnt++;
}
// Send the group view again in case there was a change in the
// group size due to a bad slave
if (bad) SendGroupView();
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Int_t TProof::Exec(const char *cmd)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
return Exec(cmd, kActive);
}
//______________________________________________________________________________
Int_t TProof::Exec(const char *cmd, ESlaves list)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
if (!IsValid()) return -1;
TString s = cmd;
s = s.Strip(TString::kBoth);
if (!s.Length()) return 0;
// check for macro file and make sure the file is available on all slaves
if (s.BeginsWith(".L") || s.BeginsWith(".x") || s.BeginsWith(".X")) {
TString file = s(2, s.Length());
TString acm, arg, io;
TString filename = gSystem->SplitAclicMode(file, acm, arg, io);
char *fn = gSystem->Which(TROOT::GetMacroPath(), filename, kReadPermission);
if (fn) {
if (GetNumberOfUniqueSlaves() > 0) {
if (SendFile(fn, kFALSE) < 0) {
Error("Exec", "file %s could not be transfered", fn);
delete [] fn;
return -1;
}
} else {
TString scmd = s(0,3) + fn;
Int_t n = SendCommand(scmd, list);
delete [] fn;
return n;
}
} else {
Error("Exec", "macro %s not found", file.Data());
return -1;
}
delete [] fn;
}
return SendCommand(cmd, list);
}
//______________________________________________________________________________
Int_t TProof::SendCommand(const char *cmd, ESlaves list)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command, however commands
// like ".x file.C" or ".L file.C" will not cause the file.C to be
// transfered to the PROOF cluster. In that case use TProof::Exec().
// Returns the status send by the remote server as part of the
// kPROOF_LOGDONE message. Typically this is the return code of the
// command on the remote side. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(cmd, kMESS_CINT, list);
Collect(list);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::SendCurrentState(ESlaves list)
{
// Transfer the current state of the master to the active slave servers.
// The current state includes: the current working directory, etc.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// Go to the new directory, reset the interpreter environment and
// tell slave to delete all objects from its new current directory.
Broadcast(gDirectory->GetPath(), kPROOF_RESET, list);
return GetParallel();
}
//______________________________________________________________________________
Int_t TProof::SendInitialState()
{
// Transfer the initial (i.e. current) state of the master to all
// slave servers. Currently the initial state includes: log level.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
SetLogLevel(fLogLevel, gProofDebugMask);
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Long_t TProof::CheckFile(const char *file, TSlave *slave)
{
// Check if a file needs to be send to the slave. Use the following
// algorithm:
// - check if file appears in file map
// - if yes, get file's modtime and check against time in map,
// if modtime not same get md5 and compare against md5 in map,
// if not same return size
// - if no, get file's md5 and modtime and store in file map, ask
// slave if file exists with specific md5, if yes return 0,
// if no return file's size
// Returns size of file in case file needs to be send, returns 0 in case
// file is already on remote and -1 in case of error.
Long64_t size;
Long_t id, flags, modtime;
if (gSystem->GetPathInfo(file, &id, &size, &flags, &modtime) == 1) {
Error("CheckFile", "cannot stat file %s", file);
return -1;
}
if (size == 0) {
Error("CheckFile", "empty file %s", file);
return -1;
}
Bool_t sendto = kFALSE;
// create slave based filename
TString sn = slave->GetName();
sn += ":";
sn += slave->GetOrdinal();
sn += ":";
sn += gSystem->BaseName(file);
// check if file is in map
FileMap_t::const_iterator it;
if ((it = fFileMap.find(sn)) != fFileMap.end()) {
// file in map
MD5Mod_t md = (*it).second;
if (md.fModtime != modtime) {
TMD5 *md5 = TMD5::FileChecksum(file);
if ((*md5) != md.fMD5) {
sendto = kTRUE;
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
// When on the master, the master and/or slaves may share
// their file systems and cache. Therefore always make a
// check for the file. If the file already exists with the
// expected md5 the kPROOF_CHECKFILE command will cause the
// file to be copied from cache to slave sandbox.
if (IsMaster()) {
sendto = kFALSE;
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
}
delete md5;
}
} else {
// file not in map
TMD5 *md5 = TMD5::FileChecksum(file);
MD5Mod_t md;
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
delete md5;
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
if (sendto)
return size;
return 0;
}
//______________________________________________________________________________
Int_t TProof::SendFile(const char *file, Bool_t bin)
{
// Send a file to master or slave servers. Returns number of slaves
// the file was sent to, maybe 0 in case master and slaves have the same
// file system image, -1 in case of error. If bin is true binary
// file transfer is used, otherwise ASCII mode.
if (!IsValid()) return -1;
TList *slaves = fActiveSlaves;
if (slaves->GetSize() == 0) return 0;
#ifndef R__WIN32
Int_t fd = open(file, O_RDONLY);
#else
Int_t fd = open(file, O_RDONLY | O_BINARY);
#endif
if (fd < 0) {
SysError("SendFile", "cannot open file %s", file);
return -1;
}
const Int_t kMAXBUF = 32768; //16384 //65536;
char buf[kMAXBUF];
Int_t nsl = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (!sl->IsValid())
continue;
Long_t size = CheckFile(file, sl);
// Don't send the kPROOF_SENDFILE command to real slaves when size=0.
// Masters might still need to send the file to newly added slaves.
if (sl->fSlaveType == TSlave::kSlave && size == 0)
continue;
PDB(kPackage,2)
if (size > 0) {
if (!nsl)
Info("SendFile", "sending file %s to:", file);
printf(" slave = %s:%s\n", sl->GetName(), sl->GetOrdinal());
}
sprintf(buf, "%s %d %ld", gSystem->BaseName(file), bin, size);
if (sl->GetSocket()->Send(buf, kPROOF_SENDFILE) == -1) {
MarkBad(sl);
continue;
}
if (size == 0)
continue;
lseek(fd, 0, SEEK_SET);
Int_t len;
do {
while ((len = read(fd, buf, kMAXBUF)) < 0 && TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
SysError("SendFile", "error reading from file %s", file);
Interrupt(kSoftInterrupt, kActive);
close(fd);
return -1;
}
if (sl->GetSocket()->SendRaw(buf, len) == -1) {
SysError("SendFile", "error writing to slave %s:%s (now offline)",
sl->GetName(), sl->GetOrdinal());
MarkBad(sl);
break;
}
} while (len > 0);
nsl++;
}
close(fd);
return nsl;
}
//______________________________________________________________________________
Int_t TProof::SendObject(const TObject *obj, ESlaves list)
{
// Send object to master or slave servers. Returns number of slaves object
// was sent to, -1 in case of error.
if (!IsValid() || !obj) return -1;
TMessage mess(kMESS_OBJECT);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::SendPrint(Option_t *option)
{
// Send print command to master server. Returns number of slaves message
// was sent to. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(option, kPROOF_PRINT, kActive);
return Collect(kActive);
}
//______________________________________________________________________________
void TProof::SetLogLevel(Int_t level, UInt_t mask)
{
// Set server logging level.
char str[32];
fLogLevel = level;
gProofDebugLevel = level;
gProofDebugMask = (TProofDebug::EProofDebugMask) mask;
sprintf(str, "%d %u", level, mask);
Broadcast(str, kPROOF_LOGLEVEL, kAll);
}
//______________________________________________________________________________
Int_t TProof::SetParallel(Int_t nodes)
{
// Tell RPOOF how many slaves to use in parallel. Returns the number of
// parallel slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
if (IsMaster()) {
GoParallel(nodes);
return SendCurrentState();
} else {
PDB(kGlobal,1) Info("SetParallel", "request %d node%s", nodes,
nodes == 1 ? "" : "s");
TMessage mess(kPROOF_PARALLEL);
mess << nodes;
Broadcast(mess);
Collect();
Int_t parallel = GetParallel();
PDB(kGlobal,1) Info("SetParallel", "got %d node%s", parallel,
parallel == 1 ? "" : "s");
if (parallel > 0) printf("PROOF set to parallel mode (%d slaves)\n", parallel);
return parallel;
}
}
//______________________________________________________________________________
Int_t TProof::GoParallel(Int_t nodes)
{
// Go in parallel mode with at most "nodes" slaves. Since the fSlaves
// list is sorted by slave performace the active list will contain first
// the most performant nodes. Returns the number of active slaves.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (nodes < 0) nodes = 0;
fActiveSlaves->Clear();
fActiveMonitor->RemoveAll();
TIter next(fSlaves);
//Simple algorithm for going parallel - fill up first nodes
int cnt = 0;
TSlave *sl;
while (cnt < nodes && (sl = (TSlave *)next())) {
if (sl->IsValid()) {
Int_t slavenodes = 0;
if (sl->GetSlaveType() == TSlave::kSlave) {
fActiveSlaves->Add(sl);
fActiveMonitor->Add(sl->GetSocket());
slavenodes = 1;
} else if (sl->GetSlaveType() == TSlave::kMaster) {
TMessage mess(kPROOF_PARALLEL);
mess << nodes-cnt;
if (sl->GetSocket()->Send(mess) == -1) {
MarkBad(sl);
slavenodes = 0;
} else {
Collect(sl);
fActiveSlaves->Add(sl);
fActiveMonitor->Add(sl->GetSocket());
if (sl->GetParallel()>0) {
slavenodes = sl->GetParallel();
} else {
slavenodes = 0;
}
}
} else {
Error("GoParallel", "TSlave is neither Master nor Slave");
Assert(0);
}
cnt += slavenodes;
}
}
// Get slave status (will set the slaves fWorkDir correctly)
AskStatistics();
// Find active slaves with unique image
FindUniqueSlaves();
// Send new group-view to slaves
SendGroupView();
Int_t n = GetParallel();
if (IsMaster()) {
if (n < 1)
printf("PROOF set to sequential mode\n");
} else {
printf("PROOF set to parallel mode (%d slaves)\n", n);
}
PDB(kGlobal,1) Info("GoParallel", "got %d node%s", n, n == 1 ? "" : "s");
return n;
}
//______________________________________________________________________________
void TProof::ShowCache(Bool_t all)
{
// List contents of file cache. If all is true show all caches also on
// slaves. If everything is ok all caches are to be the same.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowCache) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubCache) << all;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ClearCache()
{
// Remove files from all file caches.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kClearCache);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kClearSubCache);
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters
TList allunique;
Int_t i;
for (i = 0; i<fUniqueSlaves->GetSize(); i++) {
TSlave* sl =
dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i<fNonUniqueMasters->GetSize(); i++) {
TSlave* sl =
dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
// clear file map so files get send again to remote nodes
fFileMap.clear();
}
//______________________________________________________________________________
void TProof::ShowPackages(Bool_t all)
{
// List contents of package directory. If all is true show all package
// directries also on slaves. If everything is ok all package directories
// should be the same.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowPackages) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubPackages) << all;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ShowEnabledPackages(Bool_t all)
{
// List which packages are enabled. If all is true show enabled packages
// for all active slaves. If everything is ok all active slaves should
// have the same packages enabled.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowEnabledPackages) << all;
Broadcast(mess);
Collect();
}
//______________________________________________________________________________
Int_t TProof::ClearPackages()
{
// Remove all packages.
if (!IsValid()) return -1;
if (UnloadPackages() == -1)
return -1;
if (DisablePackages() == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::ClearPackage(const char *package)
{
// Remove a specific package.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("ClearPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (UnloadPackage(pac) == -1)
return -1;
if (DisablePackage(pac) == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::DisablePackage(const char *package)
{
// Remove a specific package.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("DisablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::DisablePackages()
{
// Remove all packages.
if (!IsValid()) return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackages);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackages);
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::BuildPackage(const char *package)
{
// Build specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists on all unique nodes.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("BuildPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kBuildPackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kBuildSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::LoadPackage(const char *package)
{
// Load specified package. Executes the PROOF-INF/SETUP.C script
// on all active nodes.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("LoadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kLoadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::UnloadPackage(const char *package)
{
// Unload specified package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("UnloadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::UnloadPackages()
{
// Unload all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackages);
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::EnablePackage(const char *package)
{
// Enable specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists followed by the PROOF-INF/SETUP.C script.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("EnablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (BuildPackage(pac) == -1)
return -1;
if (LoadPackage(pac) == -1)
return -1;
return 0;
}
//______________________________________________________________________________
Int_t TProof::UploadPackage(const char *tpar, Int_t parallel)
{
// Upload a PROOF archive (PAR file). A PAR file is a compressed
// tar file with one special additional directory, PROOF-INF
// (blatantly copied from Java's jar format). It must have the extension
// .par. A PAR file can be directly a binary or a source with a build
// procedure. In the PROOF-INF directory there can be a build script:
// BUILD.sh to be called to build the package, in case of a binary PAR
// file don't specify a build script or make it a no-op. Then there is
// SETUP.C which sets the right environment variables to use the package,
// like LD_LIBRARY_PATH, etc. Parallel is the number of parallel streams
// that can be used to upload the package to the master server.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
TString par = tpar;
if (!par.EndsWith(".par")) {
Error("UploadPackage", "package %s must have extension .par", tpar);
return -1;
}
gSystem->ExpandPathName(par);
if (gSystem->AccessPathName(par, kReadPermission)) {
Error("UploadPackage", "package %s does not exist", par.Data());
return -1;
}
// Strategy: get md5 of package and check if it is different from the
// one stored on the remote node. If it is different lock the remote
// package directory and use TFTP to ftp the package to the remote node,
// unlock the directory.
TMD5 *md5 = TMD5::FileChecksum(par);
TMessage mess(kPROOF_CHECKFILE);
mess << TString("+")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess2(kPROOF_CHECKFILE);
mess2 << TString("-")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess3(kPROOF_CHECKFILE);
mess3 << TString("=")+TString(gSystem->BaseName(par)) << (*md5);
delete md5;
// loop over all unique nodes
TIter next(fUniqueSlaves);
TSlave *sl;
while ((sl = (TSlave *) next())) {
if (!sl->IsValid())
continue;
sl->GetSocket()->Send(mess);
TMessage *reply;
sl->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
// remote directory is locked, upload file via TFTP
if (IsMaster())
parallel = 1; // assume LAN
{
TFTP ftp(TString("root://")+sl->GetName(), parallel);
if (!ftp.IsZombie()) {
ftp.cd(Form("%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir));
ftp.put(par, gSystem->BaseName(par));
}
}
// install package and unlock dir
sl->GetSocket()->Send(mess2);
delete reply;
sl->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
Error("UploadPackage", "unpacking of package %s failed", par.Data());
delete reply;
return -1;
}
}
delete reply;
}
// loop over all other master nodes
TIter nextmaster(fNonUniqueMasters);
TSlave *ma;
while ((ma = (TSlave *) nextmaster())) {
if (!ma->IsValid())
continue;
ma->GetSocket()->Send(mess3);
TMessage *reply;
ma->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
// error -> package should have been found
Error("UploadPackage", "package %s did not exist on submaster %s",
par.Data(), ma->GetOrdinal());
delete reply;
return -1;
}
delete reply;
}
return 0;
}
//______________________________________________________________________________
void TProof::Progress(Long64_t total, Long64_t processed)
{
// Get query progress information. Connect a slot to this signal
// to track progress.
PDB(kGlobal,1)
Info("Progress","%2f (%lld/%lld)", 100.*processed/total, processed, total);
EmitVA("Progress(Long64_t,Long64_t)", 2, total, processed);
}
//______________________________________________________________________________
void TProof::Feedback(TList *objs)
{
// Get list of feedback objects. Connect a slot to this signal
// to monitor the feedback object.
PDB(kGlobal,1) Info("Feedback","%d Objects", objs->GetSize());
PDB(kFeedback,1) {
Info("Feedback","%d objects", objs->GetSize());
objs->ls();
}
Emit("Feedback(TList *objs)", (Long_t) objs);
}
//______________________________________________________________________________
void TProof::ValidateDSet(TDSet *dset)
{
// Validate a TDSet.
if (dset->ElementsValid()) return;
THashList nodes;
nodes.SetOwner();
TList slholder;
slholder.SetOwner();
TList elemholder;
elemholder.SetOwner();
// build nodelist with slaves and elements
TIter NextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(NextSlave())) {
TList *sllist = 0;
TPair *p = dynamic_cast<TPair*>(nodes.FindObject(sl->GetName()));
if (!p) {
sllist = new TList;
sllist->SetName(sl->GetName());
slholder.Add(sllist);
TList *elemlist = new TList;
elemlist->SetName(TString(sl->GetName())+"_elem");
elemholder.Add(elemlist);
nodes.Add(new TPair(sllist, elemlist));
} else {
sllist = dynamic_cast<TList*>(p->Key());
}
sllist->Add(sl);
}
// add local elements to nodes
TList NonLocal; // list of nonlocal elements
// make two iterations - first add local elements - then distribute nonlocals
for (Int_t i = 0; i < 2; i++) {
Bool_t local = i>0?kFALSE:kTRUE;
TIter NextElem(local?dset->GetListOfElements():&NonLocal);
while (TDSetElement *elem = dynamic_cast<TDSetElement*>(NextElem())) {
if (elem->GetValid()) continue;
TPair *p = dynamic_cast<TPair*>(local?nodes.FindObject(TUrl(elem->GetFileName()).GetHost()):nodes.At(0));
if (p) {
TList *eli = dynamic_cast<TList*>(p->Value());
TList *sli = dynamic_cast<TList*>(p->Key());
eli->Add(elem);
// order list by elements/slave
TPair *p2 = p;
Bool_t stop = kFALSE;
while (!stop) {
TPair *p3 = dynamic_cast<TPair*>(nodes.After(p2->Key()));
if (p3) {
Int_t nelem = dynamic_cast<TList*>(p3->Value())->GetSize();
Int_t nsl = dynamic_cast<TList*>(p3->Key())->GetSize();
if (nelem*sli->GetSize() < eli->GetSize()*nsl) p2 = p3;
else stop = kTRUE;
} else {
stop = kTRUE;
}
}
if (p2!=p) {
nodes.Remove(p->Key());
nodes.AddAfter(p2->Key(), p);
}
} else {
if (local) {
NonLocal.Add(elem);
} else {
Error("ValidateDSet", "No Node to allocate TDSetElement to");
Assert(0);
}
}
}
}
// send to slaves
TList usedslaves;
TIter NextNode(&nodes);
SetDSet(dset); // set dset to be validated in Collect()
while (TPair *node = dynamic_cast<TPair*>(NextNode())) {
TList *slaves = dynamic_cast<TList*>(node->Key());
TList *setelements = dynamic_cast<TList*>(node->Value());
// distribute elements over the slaves
Int_t nslaves = slaves->GetSize();
Int_t nelements = setelements->GetSize();
for (Int_t i=0; i<nslaves; i++) {
TDSet set(dset->GetType(), dset->GetObjName(),
dset->GetDirectory());
for (Int_t j = (i*nelements)/nslaves;
j < ((i+1)*nelements)/nslaves;
j++) {
TDSetElement *elem =
dynamic_cast<TDSetElement*>(setelements->At(j));
set.Add(elem->GetFileName(), elem->GetObjName(),
elem->GetDirectory(), elem->GetFirst(),
elem->GetNum(), elem->GetMsd());
}
if (set.GetListOfElements()->GetSize()>0) {
TMessage mesg(kPROOF_VALIDATE_DSET);
mesg << &set;
TSlave *sl = dynamic_cast<TSlave*>(slaves->At(i));
PDB(kGlobal,1) Info("ValidateDSet",
"Sending TDSet with %d elements to slave %s"
" to be validated",
set.GetListOfElements()->GetSize(),
sl->GetOrdinal());
sl->GetSocket()->Send(mesg);
usedslaves.Add(sl);
}
}
}
PDB(kGlobal,1) Info("ValidateDSet","Calling Collect");
Collect(&usedslaves);
SetDSet(0);
}
//______________________________________________________________________________
void TProof::AddFeedback(const char *name)
{
// Add object to feedback list.
PDB(kFeedback, 3) Info("AddFeedback", "Adding object \"%s\" to feedback", name);
if (fFeedback->FindObject(name) == 0) fFeedback->Add(new TObjString(name));
}
//______________________________________________________________________________
void TProof::RemoveFeedback(const char *name)
{
// Remove object from feedback list.
TObject *obj = fFeedback->FindObject(name);
if (obj != 0) {
fFeedback->Remove(obj);
delete obj;
}
}
//______________________________________________________________________________
void TProof::ClearFeedback()
{
// Clear feedback list.
fFeedback->Delete();
}
//______________________________________________________________________________
void TProof::ShowFeedback() const
{
// Show items in feedback list.
if (fFeedback->GetSize() == 0) {
Info("","no feedback requested");
return;
}
fFeedback->Print();
}
//______________________________________________________________________________
TList *TProof::GetFeedbackList() const
{
// Return feedback list.
return fFeedback;
}
//______________________________________________________________________________
TTree *TProof::GetTreeHeader(TDSet *dset)
{
// Creates a tree header (a tree with nonexisting files) object for
// the DataSet.
TList *l = GetListOfActiveSlaves();
TSlave *sl = (TSlave*) l->First();
if (sl == 0) {
Error("GetTreeHeader", "No connection");
return 0;
}
TSocket *soc = sl->GetSocket();
TMessage msg(kPROOF_GETTREEHEADER);
msg << dset;
soc->Send(msg);
TMessage *reply;
Int_t d = soc->Recv(reply);
if (reply <= 0) {
Error("GetTreeHeader", "Error getting a replay from the master.Result %d", (int) d);
return 0;
}
TString s1;
TTree * t;
(*reply) >> s1;
(*reply) >> t;
PDB(kGlobal, 1)
if (t)
Info("GetTreeHeader", Form("%s, message size: %d, entries: %d\n",
s1.Data(), reply->BufferSize(), (int) t->GetMaxEntryLoop()));
else
Info("GetTreeHeader", Form("%s, message size: %d\n", s1.Data(), reply->BufferSize()));
delete reply;
return t;
}
//______________________________________________________________________________
TDrawFeedback *TProof::CreateDrawFeedback()
{
// Draw feedback creation proxy. When accessed via TVirtualProof avoids
// link dependency on libProof.
return new TDrawFeedback(this);
}
//______________________________________________________________________________
void TProof::SetDrawFeedbackOption(TDrawFeedback *f, Option_t *opt)
{
// Set draw feedback option.
if (f)
f->SetOption(opt);
}
//______________________________________________________________________________
void TProof::DeleteDrawFeedback(TDrawFeedback *f)
{
// Delete draw feedback object.
if (f)
delete f;
}
//______________________________________________________________________________
TList *TProof::GetOutputNames()
{
// FIXME: to be written
return 0;
/*
TMessage msg(kPROOF_GETOUTPUTLIST);
TList* slaves = fActiveSlaves;
Broadcast(msg, slaves);
TMonitor mon;
TList* outputList = new TList();
TIter si(slaves);
TSlave *slave;
while ((slave = (TSlave*)si.Next()) != 0) {
PDB(kGlobal,4) Info("GetOutputNames","Socket added to monitor: %p (%s)",
slave->GetSocket(), slave->GetName());
mon.Add(slave->GetSocket());
}
mon.ActivateAll();
((TProof*)gProof)->DeActivateAsyncInput();
while (mon.GetActive() != 0) {
TSocket *sock = mon.Select();
if (!sock) {
Error("GetOutputList","TMonitor::.Select failed!");
break;
}
mon.DeActivate(sock);
TMessage *reply;
if (sock->Recv(reply) <= 0) {
MarkBad(slave);
// Error("GetOutputList","Recv failed! for slave-%d (%s)",
// slave->GetOrdinal(), slave->GetName());
continue;
}
if (reply->What() != kPROOF_GETOUTPUTNAMES ) {
// Error("GetOutputList","unexpected message %d from slawe-%d (%s)", reply->What(),
// slave->GetOrdinal(), slave->GetName());
MarkBad(slave);
continue;
}
TList* l;
(*reply) >> l;
TIter next(l);
TNamed *n;
while ( (n = dynamic_cast<TNamed*> (next())) ) {
if (!outputList->FindObject(n->GetName()))
outputList->Add(n);
}
delete reply;
}
return outputList;
*/
}
//______________________________________________________________________________
void TProof::Browse(TBrowser *b)
{
// Build the proof's structure in the browser.
b->Add(fActiveSlaves, fActiveSlaves->Class(), "fActiveSlaves");
b->Add(&fMaster, fMaster.Class(), "fMaster");
b->Add(fFeedback, fFeedback->Class(), "fFeedback");
b->Add(fChains, fChains->Class(), "fChains");
b->Add(fPlayer->GetInputList(), fPlayer->GetInputList()->Class(), "InputList");
if (fPlayer->GetOutputList())
b->Add(fPlayer->GetOutputList(), fPlayer->GetOutputList()->Class(), "OutputList");
}
//______________________________________________________________________________
TProofPlayer *TProof::MakePlayer()
{
// Construct a TProofPlayer object.
SetPlayer(new TProofPlayerRemote(this));
return GetPlayer();
}
//______________________________________________________________________________
void TProof::AddChain(TChain *chain)
{
fChains->Add(chain);
}
//______________________________________________________________________________
void TProof::RemoveChain(TChain *chain)
{
fChains->Remove(chain);
}
//------------------------------------------------------------------------------
ClassImp(TProofCondor)
//______________________________________________________________________________
TProofCondor::TProofCondor(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
: fCondor(0), fTimer(0)
{
// Start proof using condor
if (!conffile || strlen(conffile) == 0) {
conffile = kPROOF_ConfFile;
} else if (!strncasecmp(conffile, "condor:", 7)) {
conffile+=7;
}
if (!confdir || strlen(confdir) == 0) {
confdir = kPROOF_ConfDir;
}
Init(masterurl, conffile, confdir, loglevel);
}
//______________________________________________________________________________
TProofCondor::~TProofCondor()
{
// Clean up Condor PROOF environment.
SafeDelete(fCondor);
SafeDelete(fTimer);
}
//______________________________________________________________________________
Bool_t TProofCondor::StartSlaves()
{
// non static config
fCondor = new TCondor;
TString jobad = GetJobAd();
fImage = fCondor->GetImage(gSystem->HostName());
if (fImage.Length() == 0) {
Error("StartSlaves", "Empty Condor image found for system %s",
gSystem->HostName());
return kFALSE;
}
TList claims;
if (fConfFile.IsNull()) {
// startup all slaves if no config file given
TList *condorclaims = fCondor->Claim(9999, jobad);
TIter nextclaim(condorclaims);
while (TObject *o = nextclaim()) claims.Add(o);
} else {
// parse config file
TString fconf;
fconf.Form("%s/.%s", gSystem->Getenv("HOME"), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
fconf.Form("%s/proof/etc/%s", fConfDir.Data(), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
Error("StartSlaves", "no PROOF config file found");
return kFALSE;
}
}
PDB(kGlobal,1) Info("StartSlaves", "using PROOF config file: %s", fconf.Data());
FILE *pconf;
if ((pconf = fopen(fconf, "r"))) {
fConfFile = fconf;
// check for valid slave lines and claim condor nodes
char line[1024];
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// find all slave servers, accept both "slave" and "worker" lines
if (nword >= 2 &&
(!strcmp(word[0], "condorslave") || !strcmp(word[0], "condorworker"))) {
int perfidx = 100;
const char *stripvm = strchr(word[1], '@');
const char *image = stripvm ? stripvm+1 : word[1];
const char *workdir = 0;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "perf=", 5))
perfidx = atoi(word[i]+5);
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "workdir=", 8))
workdir = word[i]+8;
}
TCondorSlave* csl = fCondor->Claim(word[1], jobad);
if (csl) {
csl->fPerfIdx = perfidx;
csl->fImage = image;
csl->fWorkDir = workdir;
claims.Add(csl);
}
}
}
}
fclose(pconf);
}
Long_t delay = 500; // timer delay 0.5s
Int_t ntries = 20; // allow 20 tries (must be > 1 for algorithm to work)
Int_t trial = 1;
Int_t idx = 0;
Int_t ord = 0;
while (claims.GetSize() > 0) {
// Get Condor Slave
TCondorSlave* c = 0;
if (trial == 1) {
c = dynamic_cast<TCondorSlave*>(claims.At(idx));
c->fOrdinal = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
} else {
TPair *p = dynamic_cast<TPair*>(claims.At(idx));
TTimer *t = dynamic_cast<TTimer*>(p->Value());
// wait remaining time
Long_t wait = (Long_t) (t->GetAbsTime()-gSystem->Now());
if (wait>0) gSystem->Sleep(wait);
c = dynamic_cast<TCondorSlave*>(p->Key());
}
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)c->fHostname);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
// create slave
TSlave *slave = CreateSlave(c->fHostname, c->fPort, c->fOrdinal,
c->fPerfIdx, c->fImage, c->fWorkDir);
// add slave to appropriate list
if (trial<ntries) {
if (slave->IsValid()) {
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
if (trial == 1) {
claims.Remove(c);
} else {
TPair *p = dynamic_cast<TPair*>(claims.Remove(c));
delete dynamic_cast<TTimer*>(p->Value());
delete p;
}
} else {
if (trial == 1) {
TTimer* timer = new TTimer(delay);
TPair *p = new TPair(c, timer);
claims.RemoveAt(idx);
claims.AddAt(p, idx);
} else {
TPair *p = dynamic_cast<TPair*>(claims.At(idx));
dynamic_cast<TTimer*>(p->Value())->Reset();
}
delete slave;
idx++;
}
} else {
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
} else {
fBadSlaves->Add(slave);
}
TPair *p = dynamic_cast<TPair*>(claims.Remove(c));
delete dynamic_cast<TTimer*>(p->Value());
delete p;
}
if (idx>=claims.GetSize()) {
trial++;
idx = 0;
}
}
return kTRUE;
}
//______________________________________________________________________________
void TProofCondor::SetActive(Bool_t active)
{
// Suspend or resume PROOF via Condor.
if (fTimer == 0) {
fTimer = new TTimer();
}
if (active) {
PDB(kCondor,1) Info("SetActive","-- Condor Resume --");
fTimer->Stop();
if (fCondor->GetState() == TCondor::kSuspended)
fCondor->Resume();
} else {
Int_t delay = 10000; // milli seconds
PDB(kCondor,1) Info("SetActive","-- Delayed Condor Suspend (%d msec) --", delay);
fTimer->Connect("Timeout()", "TCondor", fCondor, "Suspend()");
fTimer->Start(10000, kTRUE); // single shot
}
}
//______________________________________________________________________________
TString TProofCondor::GetJobAd()
{
TString ad;
ad = "JobUniverse = 5\n"; // vanilla
ad += Form("Cmd = \"%s/bin/proofd\"\n", GetConfDir());
ad += "Iwd = \"/tmp\"\n";
ad += "In = \"/dev/null\"\n";
ad += "Out = \"/tmp/proofd.out.$(Port)\"\n";
ad += "Err = \"/tmp/proofd.err.$(Port)\"\n";
ad += Form("Args = \"-f -p $(Port) -d %d %s\"\n", GetLogLevel(), GetConfDir());
return ad;
}
//______________________________________________________________________________
ClassImp(TProofSuperMaster)
//______________________________________________________________________________
TProofSuperMaster::TProofSuperMaster(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Start super master PROOF session.
if (!conffile || strlen(conffile) == 0)
conffile = kPROOF_ConfFile;
else if (!strncasecmp(conffile, "sm:", 3))
conffile+=3;
if (!confdir || strlen(confdir) == 0)
confdir = kPROOF_ConfDir;
Init(masterurl, conffile, confdir, loglevel);
}
//______________________________________________________________________________
Bool_t TProofSuperMaster::StartSlaves()
{
// Start up PROOF submasters.
// If this is a supermaster server, find the config file and start
// submaster servers as specified in the config file.
// There is a difference in startup between a slave and a submaster
// in which the submaster will issue a kPROOF_LOGFILE and
// then a kPROOF_LOGDONE message (which must be collected)
// while slaves do not.
TString fconf;
fconf.Form("%s/.%s", gSystem->Getenv("HOME"), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
fconf.Form("%s/proof/etc/%s", fConfDir.Data(), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
Error("StartSlaves", "no PROOF config file found");
return kFALSE;
}
}
PDB(kGlobal,1) Info("StartSlaves", "using PROOF config file: %s", fconf.Data());
TList validSlaves;
FILE *pconf;
if ((pconf = fopen(fconf, "r"))) {
TString fconfname = fConfFile;
fConfFile = fconf;
// read the config file
char line[1024];
TString host = gSystem->GetHostByName(gSystem->HostName()).GetHostName();
int ord = 0;
// check for valid master line
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// see if master may run on this node, accept both old "node"
// and new "master" lines
if (nword >= 2 &&
(!strcmp(word[0], "node") || !strcmp(word[0], "master")) &&
!fImage.Length()) {
TInetAddress a = gSystem->GetHostByName(word[1]);
if (!host.CompareTo(a.GetHostName()) ||
!strcmp(word[1], "localhost")) {
const char *image = word[1];
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
}
fImage = image;
}
}
}
if (fImage.Length() == 0) {
fclose(pconf);
Error("StartSlaves", "no appropriate master line found in %s", fconf.Data());
return kFALSE;
}
// check for valid submaster lines and start them
rewind(pconf);
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// find all submaster servers
if (nword >= 2 &&
!strcmp(word[0], "submaster")) {
int sport = fPort;
const char *conffile = 0;
const char *image = word[1];
const char *msd = 0;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "port=", 5))
sport = atoi(word[i]+5);
if (!strncmp(word[i], "config=", 7))
conffile = word[i]+7;
if (!strncmp(word[i], "msd=", 4))
msd = word[i]+4;
}
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)word[1]);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
// create submaster server
TSlave *slave = CreateSubmaster(word[1], sport, fullord, image, conffile, msd);
fSlaves->Add(slave);
if (slave->IsValid()) {
// check protocol compatability
// protocol 1 is not supported anymore
if (fProtocol == 1) {
Error("StartSlaves", "master and submaster protocols not compatible (%d and %d)",
kPROOF_Protocol, fProtocol);
fBadSlaves->Add(slave);
}
else {
fAllMonitor->Add(slave->GetSocket());
validSlaves.Add(slave);
}
} else {
fBadSlaves->Add(slave);
}
PDB(kGlobal,3)
Info("StartSlaves","slave on host %s created and added to list", word[1]);
}
}
}
fclose(pconf);
Collect(kAll); //Get kPROOF_LOGFILE and kPROOF_LOGDONE messages
TIter NextSlave(&validSlaves);
while (TSlave* sl = dynamic_cast<TSlave*>(NextSlave())){
if (sl->GetStatus() == -99) {
Error("StartSlaves", "not allowed to connect to PROOF master server");
fBadSlaves->Add(sl);
continue;
}
if (!sl->IsValid()) {
Error("StartSlaves", "failed to setup connection with PROOF master server");
fBadSlaves->Add(sl);
continue;
}
}
return kTRUE;
}
//______________________________________________________________________________
Int_t TProofSuperMaster::Process(TDSet *set, const char *selector, Option_t *option,
Long64_t nentries, Long64_t first, TEventList *evl)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error, 0 otherwise.
if (!IsValid()) return -1;
if (!GetPlayer())
SetPlayer(new TProofPlayerSuperMaster(this));
if (GetProgressDialog())
GetProgressDialog()->ExecPlugin(5, this, selector, set->GetListOfElements()->GetSize(),
first, nentries);
return GetPlayer()->Process(set, selector, option, nentries, first, evl);
}
//______________________________________________________________________________
void TProofSuperMaster::ValidateDSet(TDSet *dset)
{
// Validate a TDSet.
if (dset->ElementsValid()) return;
THashList msds;
msds.SetOwner();
TList smholder;
smholder.SetOwner();
TList elemholder;
elemholder.SetOwner();
// build nodelist with slaves and elements
TIter NextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(NextSlave())) {
TList *smlist = 0;
TPair *p = dynamic_cast<TPair*>(msds.FindObject(sl->GetMsd()));
if (!p) {
smlist = new TList;
smlist->SetName(sl->GetMsd());
smholder.Add(smlist);
TList *elemlist = new TSortedList(kSortDescending);
elemlist->SetName(TString(sl->GetMsd())+"_elem");
elemholder.Add(elemlist);
msds.Add(new TPair(smlist, elemlist));
} else {
smlist = dynamic_cast<TList*>(p->Key());
}
smlist->Add(sl);
}
TIter NextElem(dset->GetListOfElements());
while (TDSetElement *elem = dynamic_cast<TDSetElement*>(NextElem())) {
if (elem->GetValid()) continue;
TPair *p = dynamic_cast<TPair*>(msds.FindObject(elem->GetMsd()));
if (p) {
dynamic_cast<TList*>(p->Value())->Add(elem);
} else {
Error("ValidateDSet", "no mass storage domain '%s' associated"
" with available submasters",
elem->GetMsd());
return;
}
}
// send to slaves
TList usedsms;
TIter NextSM(&msds);
SetDSet(dset); // set dset to be validated in Collect()
while (TPair *msd = dynamic_cast<TPair*>(NextSM())) {
TList *sms = dynamic_cast<TList*>(msd->Key());
TList *setelements = dynamic_cast<TList*>(msd->Value());
// distribute elements over the slaves
Int_t nsms = sms->GetSize();
Int_t nelements = setelements->GetSize();
for (Int_t i=0; i<nsms; i++) {
TDSet set(dset->GetType(), dset->GetObjName(),
dset->GetDirectory());
for (Int_t j = (i*nelements)/nsms;
j < ((i+1)*nelements)/nsms;
j++) {
TDSetElement *elem =
dynamic_cast<TDSetElement*>(setelements->At(j));
set.Add(elem->GetFileName(), elem->GetObjName(),
elem->GetDirectory(), elem->GetFirst(),
elem->GetNum(), elem->GetMsd());
}
if (set.GetListOfElements()->GetSize()>0) {
TMessage mesg(kPROOF_VALIDATE_DSET);
mesg << &set;
TSlave *sl = dynamic_cast<TSlave*>(sms->At(i));
PDB(kGlobal,1) Info("ValidateDSet",
"Sending TDSet with %d elements to slave %s"
" to be validated",
set.GetListOfElements()->GetSize(),
sl->GetOrdinal());
sl->GetSocket()->Send(mesg);
usedsms.Add(sl);
}
}
}
PDB(kGlobal,1) Info("ValidateDSet","Calling Collect");
Collect(&usedsms);
SetDSet(0);
}
//______________________________________________________________________________
TProofPlayer *TProofSuperMaster::MakePlayer()
{
// Construct a TProofPlayer object.
SetPlayer(new TProofPlayerSuperMaster(this));
return GetPlayer();
}
from Maarten:
Condor related improvement.
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@11475 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/proof:$Name: $:$Id: TProof.cxx,v 1.83 2005/03/18 22:41:27 rdm Exp $
// Author: Fons Rademakers 13/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProof //
// //
// This class controls a Parallel ROOT Facility, PROOF, cluster. //
// It fires the slave servers, it keeps track of how many slaves are //
// running, it keeps track of the slaves running status, it broadcasts //
// messages to all slaves, it collects results, etc. //
// //
//////////////////////////////////////////////////////////////////////////
#include <fcntl.h>
#include <errno.h>
#ifdef WIN32
# include <io.h>
# include <sys/stat.h>
# include <sys/types.h>
#else
# include <unistd.h>
#endif
#include "TProof.h"
#include "TSortedList.h"
#include "TSlave.h"
#include "TMonitor.h"
#include "TMessage.h"
#include "TSystem.h"
#include "TError.h"
#include "TUrl.h"
#include "TFTP.h"
#include "TROOT.h"
#include "TH1.h"
#include "TProofPlayer.h"
#include "TDSet.h"
#include "TEnv.h"
#include "TPluginManager.h"
#include "TCondor.h"
#include "Riostream.h"
#include "TTree.h"
#include "TDrawFeedback.h"
#include "TEventList.h"
#include "TMonitor.h"
#include "TBrowser.h"
#include "TChain.h"
#include "TProofServ.h"
#include "TMap.h"
#include "TTimer.h"
//----- PROOF Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TProofInterruptHandler : public TSignalHandler {
private:
TProof *fProof;
public:
TProofInterruptHandler(TProof *p)
: TSignalHandler(kSigInterrupt, kFALSE), fProof(p) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TProofInterruptHandler::Notify()
{
// TProof interrupt handler.
fProof->Interrupt(TProof::kHardInterrupt);
return kTRUE;
}
//----- Input handler for messages from TProofServ -----------------------------
//______________________________________________________________________________
class TProofInputHandler : public TFileHandler {
private:
TSocket *fSocket;
TProof *fProof;
public:
TProofInputHandler(TProof *p, TSocket *s)
: TFileHandler(s->GetDescriptor(), 1) { fProof = p; fSocket = s; }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TProofInputHandler::Notify()
{
fProof->HandleAsyncInput(fSocket);
return kTRUE;
}
//------------------------------------------------------------------------------
ClassImp(TSlaveInfo)
//______________________________________________________________________________
Int_t TSlaveInfo::Compare(const TObject *obj) const
{
// Used to sort slaveinfos by ordinal.
if (!obj) return 1;
const TSlaveInfo *si = dynamic_cast<const TSlaveInfo*>(obj);
if (!si) return fOrdinal.CompareTo(obj->GetName());
const char *myord = GetOrdinal();
const char *otherord = si->GetOrdinal();
while (myord && otherord) {
Int_t myval = atoi(myord);
Int_t otherval = atoi(otherord);
if (myval < otherval) return 1;
if (myval > otherval) return -1;
myord = strchr(myord, '.');
if (myord) myord++;
otherord = strchr(otherord, '.');
if (otherord) otherord++;
}
if (myord) return -1;
if (otherord) return 1;
return 0;
}
//______________________________________________________________________________
void TSlaveInfo::Print(Option_t *opt) const
{
// Print slave info. If opt = "active" print only the active
// slaves, if opt="notactive" print only the not active slaves,
// if opt = "bad" print only the bad slaves, else
// print all slaves.
TString stat = fStatus == kActive ? "active" :
fStatus == kBad ? "bad" :
"not active";
if (!opt) opt = "";
if (!strcmp(opt, "active") && fStatus != kActive)
return;
if (!strcmp(opt, "notactive") && fStatus != kNotActive)
return;
if (!strcmp(opt, "bad") && fStatus != kBad)
return;
cout << "Slave: " << fOrdinal
<< " hostname: " << fHostName
<< " msd: " << fMsd
<< " perf index: " << fPerfIndex
<< " " << stat
<< endl;
}
//------------------------------------------------------------------------------
ClassImp(TProof)
//______________________________________________________________________________
TProof::TProof(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Create a PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). Masterurl is of
// the form: proof://host[:port] or proofs://host[:port]. Conffile is
// the name of the config file describing the remote PROOF cluster
// (this argument alows you to describe different cluster configurations).
// The default is proof.conf. Confdir is the directory where the config
// file and other PROOF related files are (like motd and noproof files).
// Loglevel is the log level (default = 1).
if (!conffile || strlen(conffile) == 0)
conffile = kPROOF_ConfFile;
if (!confdir || strlen(confdir) == 0)
confdir = kPROOF_ConfDir;
// Can have only one PROOF session open at a time (for the time being).
if (gProof) {
Warning("TProof", "closing currently open PROOF session");
gProof->Close();
}
Init(masterurl, conffile, confdir, loglevel);
gProof = this;
}
//______________________________________________________________________________
TProof::TProof()
{
// Protected constructor to be used by classes deriving from TProof
// (they have to call Init themselves and override StartSlaves
// appropriately).
//
// This constructor simply closes any previous gProof and sets gProof
// to this instance.
// Can have only one PROOF session open at a time (for the time being).
if (gProof) {
Warning("TProof", "closing currently open PROOF session");
gProof->Close();
}
gProof = this;
}
//______________________________________________________________________________
TProof::~TProof()
{
// Clean up PROOF environment.
while (TChain *chain = dynamic_cast<TChain*> (fChains->First()) ) {
// remove "chain" from list
chain->SetProof(0);
}
Close();
SafeDelete(fIntHandler);
SafeDelete(fSlaves);
SafeDelete(fActiveSlaves);
SafeDelete(fUniqueSlaves);
SafeDelete(fNonUniqueMasters);
SafeDelete(fBadSlaves);
SafeDelete(fAllMonitor);
SafeDelete(fActiveMonitor);
SafeDelete(fUniqueMonitor);
SafeDelete(fSlaveInfo);
SafeDelete(fChains);
gROOT->GetListOfSockets()->Remove(this);
if (gProof == this) {
gProof = 0;
}
}
//______________________________________________________________________________
Int_t TProof::Init(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Start the PROOF environment. Starting PROOF involves either connecting
// to a master server, which in turn will start a set of slave servers, or
// directly starting as master server (if master = ""). For a description
// of the arguments see the TProof ctor. Returns the number of started
// master or slave servers, returns 0 in case of error, in which case
// fValid remains false.
Assert(gSystem);
fValid = kFALSE;
TUrl *u;
if (!masterurl || !*masterurl)
u = new TUrl("proof://__master__");
else if (strstr(masterurl, "://"))
u = new TUrl(masterurl);
else
u = new TUrl(Form("proof://%s", masterurl));
fUser = u->GetUser();
fMaster = u->GetHost();
fPort = u->GetPort();
fConfDir = confdir;
fConfFile = conffile;
fWorkDir = gSystem->WorkingDirectory();
fLogLevel = loglevel;
fProtocol = kPROOF_Protocol;
fMasterServ = fMaster == "__master__" ? kTRUE : kFALSE;
fSendGroupView = kTRUE;
fImage = fMasterServ ? "" : "<local>";
fIntHandler = 0;
fProgressDialog = 0;
fStatus = 0;
fSlaveInfo = 0;
fSecContext = 0;
fChains = new TList;
fUrlProtocol = u->GetProtocol();
fPlayer = MakePlayer();
fFeedback = new TList;
fFeedback->SetOwner();
fFeedback->SetName("FeedbackList");
AddInput(fFeedback);
delete u;
// global logging
gProofDebugLevel = fLogLevel;
gProofDebugMask = TProofDebug::kAll;
// sort slaves by descending performance index
fSlaves = new TSortedList(kSortDescending);
fActiveSlaves = new TList;
fUniqueSlaves = new TList;
fNonUniqueMasters = new TList;
fBadSlaves = new TList;
fAllMonitor = new TMonitor;
fActiveMonitor = new TMonitor;
fUniqueMonitor = new TMonitor;
if (!StartSlaves()) return 0;
// we are now properly initialized
fValid = kTRUE;
// De-activate monitor (will be activated in Collect)
fAllMonitor->DeActivateAll();
// By default go into parallel mode
GoParallel(9999);
// Send relevant initial state to slaves
SendInitialState();
SetActive(kFALSE);
if (IsValid())
gROOT->GetListOfSockets()->Add(this);
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
Bool_t TProof::StartSlaves()
{
// Start up PROOF slaves.
// If this is a master server, find the config file and start slave
// servers as specified in the config file
if (IsMaster()) {
TString fconf;
fconf.Form("%s/.%s", gSystem->Getenv("HOME"), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
fconf.Form("%s/proof/etc/%s", fConfDir.Data(), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
Error("StartSlaves", "no PROOF config file found");
return kFALSE;
}
}
PDB(kGlobal,1) Info("StartSlaves", "using PROOF config file: %s", fconf.Data());
FILE *pconf;
if ((pconf = fopen(fconf, "r"))) {
fConfFile = fconf;
// read the config file
char line[1024];
TString host = gSystem->GetHostByName(gSystem->HostName()).GetHostName();
int ord = 0;
// check for valid master line
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// see if master may run on this node, accept both old "node"
// and new "master" lines
if (nword >= 2 &&
(!strcmp(word[0], "node") || !strcmp(word[0], "master")) &&
!fImage.Length()) {
TInetAddress a = gSystem->GetHostByName(word[1]);
if (!host.CompareTo(a.GetHostName()) ||
!strcmp(word[1], "localhost")) {
const char *image = word[1];
const char *workdir = kPROOF_WorkDir;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "workdir=", 8))
workdir = word[i]+8;
}
const char* expworkdir = gSystem->ExpandPathName(workdir);
if (!strcmp(expworkdir,gProofServ->GetWorkDir())) {
fImage = image;
}
delete [] (char *) expworkdir;
}
}
}
if (fImage.Length() == 0) {
fclose(pconf);
Error("StartSlaves", "no appropriate master line found in %s", fconf.Data());
return kFALSE;
}
// check for valid slave lines and start slaves
rewind(pconf);
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// find all slave servers, accept both "slave" and "worker" lines
if (nword >= 2 &&
(!strcmp(word[0], "slave") || !strcmp(word[0], "worker"))) {
int perfidx = 100;
int sport = fPort;
const char *image = word[1];
const char *workdir = 0;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "perf=", 5))
perfidx = atoi(word[i]+5);
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "port=", 5))
sport = atoi(word[i]+5);
if (!strncmp(word[i], "workdir=", 8))
workdir = word[i]+8;
}
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)word[1]);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
// create slave server
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
TSlave *slave = CreateSlave(word[1], sport, fullord, perfidx, image, workdir);
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
} else {
fBadSlaves->Add(slave);
}
PDB(kGlobal,3)
Info("StartSlaves","slave on host %s created and added to list", word[1]);
}
}
}
fclose(pconf);
} else {
// create master server
TSlave *slave = CreateSubmaster(fMaster, fPort, "0", "master", fConfFile, 0);
if (slave->IsValid()) {
// check protocol compatability
// protocol 1 is not supported anymore
if (fProtocol == 1) {
Error("StartSlaves", "client and remote protocols not compatible (%d and %d)",
kPROOF_Protocol, fProtocol);
delete slave;
return kFALSE;
}
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
Collect(slave);
if (slave->GetStatus() == -99) {
Error("StartSlaves", "not allowed to connect to PROOF master server");
return 0;
}
if (!slave->IsValid()) {
delete slave;
Error("StartSlaves", "failed to setup connection with PROOF master server");
return kFALSE;
}
fIntHandler = new TProofInterruptHandler(this);
fIntHandler->Add();
if (!gROOT->IsBatch()) {
if ((fProgressDialog = gROOT->GetPluginManager()->FindHandler("TProofProgressDialog")))
if (fProgressDialog->LoadPlugin() == -1)
fProgressDialog = 0;
}
} else {
delete slave;
Error("StartSlaves", "failed to connect to a PROOF master server");
return kFALSE;
}
}
return kTRUE;
}
//______________________________________________________________________________
void TProof::Close(Option_t *)
{
// Close all open slave servers.
if (fSlaves) {
if (fIntHandler)
fIntHandler->Remove();
// If local client ...
if (!IsMaster()) {
// ... tell master and slaves to stop
Interrupt(kShutdownInterrupt, kAll);
}
fActiveSlaves->Clear("nodelete");
fUniqueSlaves->Clear("nodelete");
fNonUniqueMasters->Clear("nodelete");
fBadSlaves->Clear("nodelete");
fSlaves->Delete();
}
}
//______________________________________________________________________________
TSlave *TProof::CreateSlave(const char *host, Int_t port, const char *ord,
Int_t perf, const char *image, const char *workdir)
{
// Create a new TSlave of type TSlave::kSlave.
// Note: constructor of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave* sl = new TSlave(host, port, ord, perf, image,
this, TSlave::kSlave, workdir, 0, 0);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
// must set fParallel to 1 for slaves since they do not
// report their fParallel with a LOG_DONE message
sl->fParallel = 1;
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::CreateSubmaster(const char *host, Int_t port, const char *ord,
const char *image, const char *conffile,
const char *msd)
{
// Create a new TSlave of type TSlave::kMaster.
// Note: constructor of TSlave is private with TProof as a friend.
// Derived classes must use this function to create slaves.
TSlave *sl = new TSlave(host, port, ord, 100, image, this,
TSlave::kMaster, 0, conffile, msd);
if (sl->IsValid()) {
sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket()));
}
return sl;
}
//______________________________________________________________________________
TSlave *TProof::FindSlave(TSocket *s) const
{
// Find slave that has TSocket s. Returns 0 in case slave is not found.
TSlave *sl;
TIter next(fSlaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid() && sl->GetSocket() == s)
return sl;
}
return 0;
}
//______________________________________________________________________________
void TProof::FindUniqueSlaves()
{
// Add to the fUniqueSlave list the active slaves that have a unique
// (user) file system image. This information is used to transfer files
// only once to nodes that share a file system (an image). Submasters
// which are not in fUniqueSlaves are put in the fNonUniqueMasters
// list. That list is used to trigger the transferring of files to
// the submaster's unique slaves without the need to transfer the file
// to the submaster.
fUniqueSlaves->Clear();
fUniqueMonitor->RemoveAll();
fNonUniqueMasters->Clear();
TIter next(fActiveSlaves);
while (TSlave *sl = dynamic_cast<TSlave*>(next())) {
if (fImage == sl->fImage) {
if (sl->GetSlaveType() == TSlave::kMaster)
fNonUniqueMasters->Add(sl);
continue;
}
TIter next2(fUniqueSlaves);
TSlave *replace_slave = 0;
Bool_t add = kTRUE;
while (TSlave *sl2 = dynamic_cast<TSlave*>(next2())) {
if (sl->fImage == sl2->fImage) {
add = kFALSE;
if (sl->GetSlaveType() == TSlave::kMaster) {
if (sl2->GetSlaveType() == TSlave::kSlave) {
// give preference to master
replace_slave = sl2;
add = kTRUE;
} else if (sl2->GetSlaveType() == TSlave::kMaster) {
fNonUniqueMasters->Add(sl);
} else {
Error("FindUniqueSlaves", "TSlave is neither Master nor Slave");
Assert(0);
}
}
break;
}
}
if (add) {
fUniqueSlaves->Add(sl);
fUniqueMonitor->Add(sl->GetSocket());
if (replace_slave) {
fUniqueSlaves->Remove(replace_slave);
fUniqueMonitor->Remove(replace_slave->GetSocket());
}
}
}
// will be actiavted in Collect()
fUniqueMonitor->DeActivateAll();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfSlaves() const
{
// Return number of slaves as described in the config file.
return fSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfActiveSlaves() const
{
// Return number of active slaves, i.e. slaves that are valid and in
// the current computing group.
return fActiveSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfUniqueSlaves() const
{
// Return number of unique slaves, i.e. active slaves that have each a
// unique different user files system.
return fUniqueSlaves->GetSize();
}
//______________________________________________________________________________
Int_t TProof::GetNumberOfBadSlaves() const
{
// Return number of bad slaves. This are slaves that we in the config
// file, but refused to startup or that died during the PROOF session.
return fBadSlaves->GetSize();
}
//______________________________________________________________________________
void TProof::AskStatistics()
{
// Ask the for the statistics of the slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETSTATS, kActive);
Collect(kActive);
}
//______________________________________________________________________________
void TProof::AskParallel()
{
// Ask the for the number of parallel slaves.
if (!IsValid()) return;
Broadcast(kPROOF_GETPARALLEL, kActive);
Collect(kActive);
}
//______________________________________________________________________________
Bool_t TProof::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready)
{
// See if the data is ready to be analyzed.
if (!IsValid()) return kFALSE;
TList submasters;
TIter NextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(NextSlave())) {
if (sl->GetSlaveType() == TSlave::kMaster) {
submasters.Add(sl);
}
}
fDataReady = kTRUE; //see if any submasters set it to false
fBytesReady = 0;
fTotalBytes = 0;
//loop over submasters and see if data is ready
if (submasters.GetSize() > 0) {
Broadcast(kPROOF_DATA_READY, &submasters);
Collect(&submasters);
}
bytesready = fBytesReady;
totalbytes = fTotalBytes;
EmitVA("IsDataReady(Long64_t,Long64_t)", 2, totalbytes, bytesready);
//PDB(kGlobal,2)
Info("IsDataReady", "%lld / %lld (%s)", bytesready, totalbytes, fDataReady?"READY":"NOT READY");
return fDataReady;
}
//______________________________________________________________________________
void TProof::Interrupt(EUrgent type, ESlaves list)
{
// Send interrupt OOB byte to master or slave servers.
if (!IsValid()) return;
char oobc = (char) type;
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
if (slaves->GetSize() == 0) return;
const int kBufSize = 1024;
char waste[kBufSize];
TSlave *sl;
TIter next(slaves);
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
TSocket *s = sl->GetSocket();
// Send one byte out-of-band message to server
if (s->SendRaw(&oobc, 1, kOob) <= 0) {
Error("Interrupt", "error sending oobc to slave %s", sl->GetOrdinal());
continue;
}
if (type == kHardInterrupt) {
char oob_byte;
int n, nch, nbytes = 0, nloop = 0;
// Receive the OOB byte
while ((n = s->RecvRaw(&oob_byte, 1, kOob)) < 0) {
if (n == -2) { // EWOULDBLOCK
//
// The OOB data has not yet arrived: flush the input stream
//
// In some systems (Solaris) regular recv() does not return upon
// receipt of the oob byte, which makes the below call to recv()
// block indefinitely if there are no other data in the queue.
// FIONREAD ioctl can be used to check if there are actually any
// data to be flushed. If not, wait for a while for the oob byte
// to arrive and try to read it again.
//
s->GetOption(kBytesToRead, nch);
if (nch == 0) {
gSystem->Sleep(1000);
continue;
}
if (nch > kBufSize) nch = kBufSize;
n = s->RecvRaw(waste, nch);
if (n <= 0) {
Error("Interrupt", "error receiving waste from slave %s",
sl->GetOrdinal());
break;
}
nbytes += n;
} else if (n == -3) { // EINVAL
//
// The OOB data has not arrived yet
//
gSystem->Sleep(100);
if (++nloop > 100) { // 10 seconds time-out
Error("Interrupt", "server %s does not respond", sl->GetOrdinal());
break;
}
} else {
Error("Interrupt", "error receiving OOB from server %s",
sl->GetOrdinal());
break;
}
}
//
// Continue flushing the input socket stream until the OOB
// mark is reached
//
while (1) {
int atmark;
s->GetOption(kAtMark, atmark);
if (atmark)
break;
// find out number of bytes to read before atmark
s->GetOption(kBytesToRead, nch);
if (nch == 0) {
gSystem->Sleep(1000);
continue;
}
if (nch > kBufSize) nch = kBufSize;
n = s->RecvRaw(waste, nch);
if (n <= 0) {
Error("Interrupt", "error receiving waste (2) from slave %s",
sl->GetOrdinal());
break;
}
nbytes += n;
}
if (nbytes > 0) {
if (IsMaster())
Printf("*** Slave %s:%s synchronized: %d bytes discarded",
sl->GetName(), sl->GetOrdinal(), nbytes);
else
Printf("*** PROOF synchronized: %d bytes discarded", nbytes);
}
// Get log file from master or slave after a hard interrupt
Collect(sl);
} else if (type == kSoftInterrupt) {
// Get log file from master or slave after a soft interrupt
Collect(sl);
} else if (type == kShutdownInterrupt) {
; // nothing expected to be returned
} else {
// Unexpected message, just receive log file
Collect(sl);
}
}
}
}
//______________________________________________________________________________
Int_t TProof::GetParallel() const
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// iterate over active slaves and return total number of slaves
TIter NextSlave(GetListOfActiveSlaves());
Int_t nparallel = 0;
while (TSlave* sl = dynamic_cast<TSlave*>(NextSlave()))
if(sl->GetParallel() >= 0)
nparallel += sl->GetParallel();
return nparallel;
}
//______________________________________________________________________________
TList *TProof::GetSlaveInfo()
{
// Returns number of slaves active in parallel mode. Returns 0 in case
// there are no active slaves. Returns -1 in case of error.
if (!IsValid()) return 0;
if (fSlaveInfo == 0) {
fSlaveInfo = new TSortedList(kSortDescending);
fSlaveInfo->SetOwner();
} else {
fSlaveInfo->Delete();
}
TList masters;
TIter next(GetListOfSlaves());
TSlave *slave;
while((slave = (TSlave *) next()) != 0) {
if (slave->GetSlaveType() == TSlave::kSlave) {
TSlaveInfo *slaveinfo = new TSlaveInfo(slave->GetOrdinal(),
slave->GetName(),
slave->GetPerfIdx());
fSlaveInfo->Add(slaveinfo);
TIter nextactive(GetListOfActiveSlaves());
TSlave *activeslave;
while ((activeslave = (TSlave *) nextactive())) {
if (TString(slaveinfo->GetOrdinal()) == activeslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kActive);
break;
}
}
TIter nextbad(GetListOfBadSlaves());
TSlave *badslave;
while ((badslave = (TSlave *) nextbad())) {
if (TString(slaveinfo->GetOrdinal()) == badslave->GetOrdinal()) {
slaveinfo->SetStatus(TSlaveInfo::kBad);
break;
}
}
} else if (slave->GetSlaveType() == TSlave::kMaster) {
if (slave->IsValid()) {
if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1)
MarkBad(slave);
else
masters.Add(slave);
}
} else {
Error("GetSlaveInfo", "TSlave is neither Master nor Slave");
Assert(0);
}
}
if (masters.GetSize() > 0) Collect(&masters);
return fSlaveInfo;
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, TList *slaves)
{
// Broadcast a message to all slaves in the specified list. Returns
// the number of slaves the message was successfully sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->Send(mess) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const TMessage &mess, ESlaves list)
{
// Broadcast a message to all slaves in the specified list (either
// all slaves or only the active slaves). Returns the number of slaves
// the message was successfully sent to. Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, TList *slaves)
{
// Broadcast a character string buffer to all slaves in the specified
// list. Use kind to set the TMessage what field. Returns the number of
// slaves the message was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::Broadcast(const char *str, Int_t kind, ESlaves list)
{
// Broadcast a character string buffer to all slaves in the specified
// list (either all slaves or only the active slaves). Use kind to
// set the TMessage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
if (str) mess.WriteString(str);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, TList *slaves)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, slaves);
}
//______________________________________________________________________________
Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, ESlaves list)
{
// Broadcast an object to all slaves in the specified list. Use kind to
// set the TMEssage what field. Returns the number of slaves the message
// was sent to. Returns -1 in case of error.
TMessage mess(kind);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, TList *slaves)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (slaves->GetSize() == 0) return 0;
int nsent = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (sl->IsValid()) {
if (sl->GetSocket()->SendRaw(buffer, length) == -1)
MarkBad(sl);
else
nsent++;
}
}
return nsent;
}
//______________________________________________________________________________
Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, ESlaves list)
{
// Broadcast a raw buffer of specified length to all slaves in the
// specified list. Returns the number of slaves the buffer was sent to.
// Returns -1 in case of error.
TList *slaves = 0;
if (list == kAll) slaves = fSlaves;
if (list == kActive) slaves = fActiveSlaves;
if (list == kUnique) slaves = fUniqueSlaves;
return BroadcastRaw(buffer, length, slaves);
}
//______________________________________________________________________________
Int_t TProof::Collect(const TSlave *sl)
{
// Collect responses from slave sl. Returns the number of slaves that
// responded (=1).
if (!sl->IsValid()) return 0;
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
mon->Activate(sl->GetSocket());
return Collect(mon);
}
//______________________________________________________________________________
Int_t TProof::Collect(TList *slaves)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
TMonitor *mon = fAllMonitor;
mon->DeActivateAll();
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave*) next())) {
if (sl->IsValid())
mon->Activate(sl->GetSocket());
}
return Collect(mon);
}
//______________________________________________________________________________
Int_t TProof::Collect(ESlaves list)
{
// Collect responses from the slave servers. Returns the number of slaves
// that responded.
TMonitor *mon = 0;
if (list == kAll) mon = fAllMonitor;
if (list == kActive) mon = fActiveMonitor;
if (list == kUnique) mon = fUniqueMonitor;
mon->ActivateAll();
return Collect(mon);
}
//______________________________________________________________________________
Int_t TProof::Collect(TMonitor *mon)
{
// Collect responses from the slave servers. Returns the number of messages
// received. Can be 0 if there are no active slaves.
fStatus = 0;
if (!mon->GetActive()) return 0;
DeActivateAsyncInput();
int cnt = 0, loop = 1;
fBytesRead = 0;
fRealTime = 0.0;
fCpuTime = 0.0;
while (loop) {
char str[512];
TMessage *mess;
TSocket *s;
TSlave *sl;
TObject *obj;
Int_t what;
s = mon->Select();
if (s->Recv(mess) < 0) {
MarkBad(s);
continue;
}
if (!mess) {
// we get here in case the remote server died
MarkBad(s);
if (!mon->GetActive()) loop = 0;
continue;
}
what = mess->What();
switch (what) {
case kMESS_OBJECT:
obj = mess->ReadObject(mess->GetClass());
if (obj->InheritsFrom(TH1::Class())) {
TH1 *h = (TH1*)obj;
h->SetDirectory(0);
TH1 *horg = (TH1*)gDirectory->GetList()->FindObject(h->GetName());
if (horg)
horg->Add(h);
else
h->SetDirectory(gDirectory);
}
break;
case kPROOF_FATAL:
MarkBad(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_GETOBJECT:
mess->ReadString(str, sizeof(str));
obj = gDirectory->Get(str);
if (obj)
s->SendObject(obj);
else
s->Send(kMESS_NOTOK);
break;
case kPROOF_GETPACKET:
{
TDSetElement *elem = 0;
sl = FindSlave(s);
elem = fPlayer->GetNextPacket(sl, mess);
TMessage answ(kPROOF_GETPACKET);
if (elem != 0) {
answ << kTRUE
<< TString(elem->GetFileName())
<< TString(elem->GetDirectory())
<< TString(elem->GetObjName());
if (elem->GetEventList())
answ << ((Long64_t)-1) << elem->GetEventList();
else
answ << elem->GetFirst() << elem->GetNum();
} else {
answ << kFALSE;
}
s->Send(answ);
}
break;
case kPROOF_LOGFILE:
{
Int_t size;
(*mess) >> size;
RecvLogFile(s, size);
}
break;
case kPROOF_LOGDONE:
sl = FindSlave(s);
(*mess) >> sl->fStatus >> sl->fParallel;
PDB(kGlobal,2) Info("Collect:kPROOF_LOGDONE","status %d parallel %d",
sl->fStatus, sl->fParallel);
if (sl->fStatus != 0) fStatus = sl->fStatus; //return last nonzero status
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_GETSTATS:
sl = FindSlave(s);
(*mess) >> sl->fBytesRead >> sl->fRealTime >> sl->fCpuTime
>> sl->fWorkDir >> sl->fProofWorkDir;
fBytesRead += sl->fBytesRead;
fRealTime += sl->fRealTime;
fCpuTime += sl->fCpuTime;
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_GETPARALLEL:
sl = FindSlave(s);
(*mess) >> sl->fParallel;
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
break;
case kPROOF_OUTPUTLIST:
{
PDB(kGlobal,2) Info("Collect:kPROOF_OUTPUTLIST","Enter");
TList *out = (TList *) mess->ReadObject(TList::Class());
if (out) {
out->SetOwner();
fPlayer->StoreOutput(out); // Adopts the list
}
}
break;
case kPROOF_FEEDBACK:
{
PDB(kGlobal,2) Info("Collect:kPROOF_FEEDBACK","Enter");
TList *out = (TList *) mess->ReadObject(TList::Class());
out->SetOwner();
sl = FindSlave(s);
fPlayer->StoreFeedback(sl, out); // Adopts the list
}
break;
case kPROOF_AUTOBIN:
{
TString name;
Double_t xmin, xmax, ymin, ymax, zmin, zmax;
(*mess) >> name >> xmin >> xmax >> ymin >> ymax >> zmin >> zmax;
fPlayer->UpdateAutoBin(name,xmin,xmax,ymin,ymax,zmin,zmax);
TMessage answ(kPROOF_AUTOBIN);
answ << name << xmin << xmax << ymin << ymax << zmin << zmax;
s->Send(answ);
}
break;
case kPROOF_PROGRESS:
{
PDB(kGlobal,2) Info("Collect:kPROOF_PROGRESS","Enter");
sl = FindSlave(s);
Long64_t total, processed;
(*mess) >> total >> processed;
fPlayer->Progress(sl, total, processed);
}
break;
case kPROOF_GETSLAVEINFO:
{
PDB(kGlobal,2) Info("Collect:kPROOF_GETSLAVEINFO","Enter");
sl = FindSlave(s);
Bool_t active = (GetListOfActiveSlaves()->FindObject(sl) != 0);
Bool_t bad = (GetListOfBadSlaves()->FindObject(sl) != 0);
TList* tmpinfo = 0;
(*mess) >> tmpinfo;
tmpinfo->SetOwner(kFALSE);
Int_t nentries = tmpinfo->GetSize();
for (Int_t i=0; i<nentries; i++) {
TSlaveInfo* slinfo =
dynamic_cast<TSlaveInfo*>(tmpinfo->At(i));
if(slinfo) {
fSlaveInfo->Add(slinfo);
if (slinfo->fStatus != TSlaveInfo::kBad) {
if (!active) slinfo->SetStatus(TSlaveInfo::kNotActive);
if (bad) slinfo->SetStatus(TSlaveInfo::kBad);
}
if (!sl->GetMsd().IsNull()) slinfo->fMsd = sl->GetMsd();
}
}
delete tmpinfo;
mon->DeActivate(s);
if (!mon->GetActive()) loop = 0;
}
break;
case kPROOF_VALIDATE_DSET:
{
PDB(kGlobal,2) Info("Collect:kPROOF_VALIDATE_DSET","Enter");
TDSet* dset = 0;
(*mess) >> dset;
if (!fDSet)
Error("Collect:kPROOF_VALIDATE_DSET", "fDSet not set");
else
fDSet->Validate(dset);
delete dset;
}
break;
case kPROOF_DATA_READY:
{
PDB(kGlobal,2) Info("Collect:kPROOF_DATA_READY","Enter");
Bool_t dataready = kFALSE;
Long64_t totalbytes, bytesready;
(*mess) >> dataready >> totalbytes >> bytesready;
fTotalBytes += totalbytes;
fBytesReady += bytesready;
if (dataready == kFALSE) fDataReady = dataready;
}
break;
default:
Error("Collect", "unknown command received from slave (%d)", what);
break;
}
cnt++;
delete mess;
}
// make sure group view is up to date
SendGroupView();
ActivateAsyncInput();
return cnt;
}
//______________________________________________________________________________
void TProof::ActivateAsyncInput()
{
// Activate the a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Add();
}
//______________________________________________________________________________
void TProof::DeActivateAsyncInput()
{
// De-actiate a-sync input handler.
TIter next(fSlaves);
TSlave *sl;
while ((sl = (TSlave*) next()))
if (sl->GetInputHandler())
sl->GetInputHandler()->Remove();
}
//______________________________________________________________________________
void TProof::HandleAsyncInput(TSocket *sl)
{
// Handle input coming from the master server (when this is a client)
// or from a slave server (when this is a master server). This is mainly
// for a-synchronous communication. Normally when PROOF issues a command
// the (slave) server messages are directly handle by Collect().
TMessage *mess;
Int_t what;
if (sl->Recv(mess) <= 0)
return; // do something more intelligent here
what = mess->What();
switch (what) {
case kPROOF_PING:
// do nothing (ping is already acknowledged)
break;
default:
Error("HandleAsyncInput", "unknown command %d", what);
break;
}
delete mess;
}
//______________________________________________________________________________
void TProof::MarkBad(TSlave *sl)
{
// Add a bad slave server to the bad slave list and remove it from
// the active list and from the two monitor objects.
fActiveSlaves->Remove(sl);
FindUniqueSlaves();
fBadSlaves->Add(sl);
fAllMonitor->Remove(sl->GetSocket());
fActiveMonitor->Remove(sl->GetSocket());
sl->Close();
fSendGroupView = kTRUE;
}
//______________________________________________________________________________
void TProof::MarkBad(TSocket *s)
{
// Add slave with socket s to the bad slave list and remove if from
// the active list and from the two monitor objects.
TSlave *sl = FindSlave(s);
MarkBad(sl);
}
//______________________________________________________________________________
Int_t TProof::Ping()
{
// Ping PROOF. Returns 1 if master server responded.
return Ping(kActive);
}
//______________________________________________________________________________
Int_t TProof::Ping(ESlaves list)
{
// Ping PROOF slaves. Returns the number of slaves that responded.
TMessage mess(kPROOF_PING | kMESS_ACK);
return Broadcast(mess, list);
}
//______________________________________________________________________________
void TProof::Print(Option_t *option) const
{
// Print status of PROOF cluster.
if (!IsMaster()) {
Printf("Connected to: %s (%s)", GetMaster(),
IsValid() ? "valid" : "invalid");
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
Printf("Security context: %s", fSecContext->AsString());
TSlave *sl = (TSlave *)fActiveSlaves->First();
if (sl)
Printf("Proofd protocol version: %d", sl->GetSocket()->GetRemoteProtocol());
else
Printf("Proofd protocol version: Error - No connection");
Printf("Client protocol version: %d", GetClientProtocol());
Printf("Remote protocol version: %d", GetRemoteProtocol());
Printf("Log level: %d", GetLogLevel());
if (IsValid())
const_cast<TProof*>(this)->SendPrint(option);
} else {
const_cast<TProof*>(this)->AskStatistics();
if (IsParallel())
Printf("*** Master server %s (parallel mode, %d slaves):",
gProofServ->GetOrdinal(), GetParallel());
else
Printf("*** Master server %s (sequential mode):",
gProofServ->GetOrdinal());
Printf("Master host name: %s", gSystem->HostName());
Printf("Port number: %d", GetPort());
Printf("User: %s", GetUser());
Printf("Protocol version: %d", GetClientProtocol());
Printf("Image name: %s", GetImage());
Printf("Working directory: %s", gSystem->WorkingDirectory());
Printf("Config directory: %s", GetConfDir());
Printf("Config file: %s", GetConfFile());
Printf("Log level: %d", GetLogLevel());
Printf("Number of slaves: %d", GetNumberOfSlaves());
Printf("Number of active slaves: %d", GetNumberOfActiveSlaves());
Printf("Number of unique slaves: %d", GetNumberOfUniqueSlaves());
Printf("Number of bad slaves: %d", GetNumberOfBadSlaves());
Printf("Total MB's processed: %.2f", float(GetBytesRead())/(1024*1024));
Printf("Total real time used (s): %.3f", GetRealTime());
Printf("Total CPU time used (s): %.3f", GetCpuTime());
if (TString(option).Contains("a") && GetNumberOfSlaves()) {
Printf("List of slaves:");
TList masters;
TIter nextslave(fSlaves);
while (TSlave* sl = dynamic_cast<TSlave*>(nextslave())) {
if (!sl->IsValid()) continue;
if (sl->GetSlaveType() == TSlave::kSlave) {
sl->Print(option);
} else if (sl->GetSlaveType() == TSlave::kMaster) {
TMessage mess(kPROOF_PRINT);
mess.WriteString(option);
if (sl->GetSocket()->Send(mess) == -1)
const_cast<TProof*>(this)->MarkBad(sl);
else
masters.Add(sl);
} else {
Error("Print", "TSlave is neither Master nor Slave");
Assert(0);
}
}
const_cast<TProof*>(this)->Collect(&masters);
}
}
}
//______________________________________________________________________________
Int_t TProof::Process(TDSet *set, const char *selector, Option_t *option,
Long64_t nentries, Long64_t first, TEventList *evl)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error, 0 otherwise.
if (!IsValid()) return -1;
if (fProgressDialog)
fProgressDialog->ExecPlugin(5, this, selector, set->GetListOfElements()->GetSize(),
first, nentries);
return fPlayer->Process(set, selector, option, nentries, first, evl);
}
//______________________________________________________________________________
Int_t TProof::DrawSelect(TDSet *set, const char *varexp, const char *selection, Option_t *option,
Long64_t nentries, Long64_t first)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error, 0 otherwise.
if (!IsValid()) return -1;
return fPlayer->DrawSelect(set, varexp, selection, option, nentries, first);
}
//______________________________________________________________________________
void TProof::StopProcess(Bool_t abort)
{
fPlayer->StopProcess(abort);
}
//______________________________________________________________________________
void TProof::AddInput(TObject *obj)
{
// Add objects that might be needed during the processing of
// the selector (see Process()).
fPlayer->AddInput(obj);
}
//______________________________________________________________________________
void TProof::ClearInput()
{
// Clear input object list.
fPlayer->ClearInput();
// the system feedback list is always in the input list
AddInput(fFeedback);
}
//______________________________________________________________________________
TObject *TProof::GetOutput(const char *name)
{
// Get specified object that has been produced during the processing
// (see Process()).
return fPlayer->GetOutput(name);
}
//______________________________________________________________________________
TList *TProof::GetOutputList()
{
// Get list with all object created during processing (see Process()).
return fPlayer->GetOutputList();
}
//______________________________________________________________________________
void TProof::RecvLogFile(TSocket *s, Int_t size)
{
// Receive the log file of the slave with socket s.
const Int_t kMAXBUF = 16384; //32768 //16384 //65536;
char buf[kMAXBUF];
Int_t left, r;
Long_t filesize = 0;
while (filesize < size) {
left = Int_t(size - filesize);
if (left > kMAXBUF)
left = kMAXBUF;
r = s->RecvRaw(&buf, left);
if (r > 0) {
char *p = buf;
filesize += r;
while (r) {
Int_t w;
w = write(fileno(stdout), p, r);
if (w < 0) {
SysError("RecvLogFile", "error writing to stdout");
break;
}
r -= w;
p += w;
}
} else if (r < 0) {
Error("RecvLogFile", "error during receiving log file");
break;
}
}
}
//______________________________________________________________________________
Int_t TProof::SendGroupView()
{
// Send to all active slaves servers the current slave group size
// and their unique id. Returns number of active slaves.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (!IsMaster()) return 0;
if (!fSendGroupView) return 0;
fSendGroupView = kFALSE;
TIter next(fActiveSlaves);
TSlave *sl;
int bad = 0, cnt = 0, size = GetNumberOfActiveSlaves();
char str[32];
while ((sl = (TSlave *)next())) {
sprintf(str, "%d %d", cnt, size);
if (sl->GetSocket()->Send(str, kPROOF_GROUPVIEW) == -1) {
MarkBad(sl);
bad++;
} else
cnt++;
}
// Send the group view again in case there was a change in the
// group size due to a bad slave
if (bad) SendGroupView();
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Int_t TProof::Exec(const char *cmd)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
return Exec(cmd, kActive);
}
//______________________________________________________________________________
Int_t TProof::Exec(const char *cmd, ESlaves list)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command. Commands like
// ".x file.C" or ".L file.C" will cause the file file.C to be send
// to the PROOF cluster. Returns -1 in case of error, >=0 in case of
// succes.
if (!IsValid()) return -1;
TString s = cmd;
s = s.Strip(TString::kBoth);
if (!s.Length()) return 0;
// check for macro file and make sure the file is available on all slaves
if (s.BeginsWith(".L") || s.BeginsWith(".x") || s.BeginsWith(".X")) {
TString file = s(2, s.Length());
TString acm, arg, io;
TString filename = gSystem->SplitAclicMode(file, acm, arg, io);
char *fn = gSystem->Which(TROOT::GetMacroPath(), filename, kReadPermission);
if (fn) {
if (GetNumberOfUniqueSlaves() > 0) {
if (SendFile(fn, kFALSE) < 0) {
Error("Exec", "file %s could not be transfered", fn);
delete [] fn;
return -1;
}
} else {
TString scmd = s(0,3) + fn;
Int_t n = SendCommand(scmd, list);
delete [] fn;
return n;
}
} else {
Error("Exec", "macro %s not found", file.Data());
return -1;
}
delete [] fn;
}
return SendCommand(cmd, list);
}
//______________________________________________________________________________
Int_t TProof::SendCommand(const char *cmd, ESlaves list)
{
// Send command to be executed on the PROOF master and/or slaves.
// Command can be any legal command line command, however commands
// like ".x file.C" or ".L file.C" will not cause the file.C to be
// transfered to the PROOF cluster. In that case use TProof::Exec().
// Returns the status send by the remote server as part of the
// kPROOF_LOGDONE message. Typically this is the return code of the
// command on the remote side. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(cmd, kMESS_CINT, list);
Collect(list);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::SendCurrentState(ESlaves list)
{
// Transfer the current state of the master to the active slave servers.
// The current state includes: the current working directory, etc.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
// Go to the new directory, reset the interpreter environment and
// tell slave to delete all objects from its new current directory.
Broadcast(gDirectory->GetPath(), kPROOF_RESET, list);
return GetParallel();
}
//______________________________________________________________________________
Int_t TProof::SendInitialState()
{
// Transfer the initial (i.e. current) state of the master to all
// slave servers. Currently the initial state includes: log level.
// Returns the number of active slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
SetLogLevel(fLogLevel, gProofDebugMask);
return GetNumberOfActiveSlaves();
}
//______________________________________________________________________________
Long_t TProof::CheckFile(const char *file, TSlave *slave)
{
// Check if a file needs to be send to the slave. Use the following
// algorithm:
// - check if file appears in file map
// - if yes, get file's modtime and check against time in map,
// if modtime not same get md5 and compare against md5 in map,
// if not same return size
// - if no, get file's md5 and modtime and store in file map, ask
// slave if file exists with specific md5, if yes return 0,
// if no return file's size
// Returns size of file in case file needs to be send, returns 0 in case
// file is already on remote and -1 in case of error.
Long64_t size;
Long_t id, flags, modtime;
if (gSystem->GetPathInfo(file, &id, &size, &flags, &modtime) == 1) {
Error("CheckFile", "cannot stat file %s", file);
return -1;
}
if (size == 0) {
Error("CheckFile", "empty file %s", file);
return -1;
}
Bool_t sendto = kFALSE;
// create slave based filename
TString sn = slave->GetName();
sn += ":";
sn += slave->GetOrdinal();
sn += ":";
sn += gSystem->BaseName(file);
// check if file is in map
FileMap_t::const_iterator it;
if ((it = fFileMap.find(sn)) != fFileMap.end()) {
// file in map
MD5Mod_t md = (*it).second;
if (md.fModtime != modtime) {
TMD5 *md5 = TMD5::FileChecksum(file);
if ((*md5) != md.fMD5) {
sendto = kTRUE;
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
// When on the master, the master and/or slaves may share
// their file systems and cache. Therefore always make a
// check for the file. If the file already exists with the
// expected md5 the kPROOF_CHECKFILE command will cause the
// file to be copied from cache to slave sandbox.
if (IsMaster()) {
sendto = kFALSE;
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
}
delete md5;
}
} else {
// file not in map
TMD5 *md5 = TMD5::FileChecksum(file);
MD5Mod_t md;
md.fMD5 = *md5;
md.fModtime = modtime;
fFileMap[sn] = md;
delete md5;
TMessage mess(kPROOF_CHECKFILE);
mess << TString(gSystem->BaseName(file)) << md.fMD5;
slave->GetSocket()->Send(mess);
TMessage *reply;
slave->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE)
sendto = kTRUE;
delete reply;
}
if (sendto)
return size;
return 0;
}
//______________________________________________________________________________
Int_t TProof::SendFile(const char *file, Bool_t bin)
{
// Send a file to master or slave servers. Returns number of slaves
// the file was sent to, maybe 0 in case master and slaves have the same
// file system image, -1 in case of error. If bin is true binary
// file transfer is used, otherwise ASCII mode.
if (!IsValid()) return -1;
TList *slaves = fActiveSlaves;
if (slaves->GetSize() == 0) return 0;
#ifndef R__WIN32
Int_t fd = open(file, O_RDONLY);
#else
Int_t fd = open(file, O_RDONLY | O_BINARY);
#endif
if (fd < 0) {
SysError("SendFile", "cannot open file %s", file);
return -1;
}
const Int_t kMAXBUF = 32768; //16384 //65536;
char buf[kMAXBUF];
Int_t nsl = 0;
TIter next(slaves);
TSlave *sl;
while ((sl = (TSlave *)next())) {
if (!sl->IsValid())
continue;
Long_t size = CheckFile(file, sl);
// Don't send the kPROOF_SENDFILE command to real slaves when size=0.
// Masters might still need to send the file to newly added slaves.
if (sl->fSlaveType == TSlave::kSlave && size == 0)
continue;
PDB(kPackage,2)
if (size > 0) {
if (!nsl)
Info("SendFile", "sending file %s to:", file);
printf(" slave = %s:%s\n", sl->GetName(), sl->GetOrdinal());
}
sprintf(buf, "%s %d %ld", gSystem->BaseName(file), bin, size);
if (sl->GetSocket()->Send(buf, kPROOF_SENDFILE) == -1) {
MarkBad(sl);
continue;
}
if (size == 0)
continue;
lseek(fd, 0, SEEK_SET);
Int_t len;
do {
while ((len = read(fd, buf, kMAXBUF)) < 0 && TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
SysError("SendFile", "error reading from file %s", file);
Interrupt(kSoftInterrupt, kActive);
close(fd);
return -1;
}
if (sl->GetSocket()->SendRaw(buf, len) == -1) {
SysError("SendFile", "error writing to slave %s:%s (now offline)",
sl->GetName(), sl->GetOrdinal());
MarkBad(sl);
break;
}
} while (len > 0);
nsl++;
}
close(fd);
return nsl;
}
//______________________________________________________________________________
Int_t TProof::SendObject(const TObject *obj, ESlaves list)
{
// Send object to master or slave servers. Returns number of slaves object
// was sent to, -1 in case of error.
if (!IsValid() || !obj) return -1;
TMessage mess(kMESS_OBJECT);
mess.WriteObject(obj);
return Broadcast(mess, list);
}
//______________________________________________________________________________
Int_t TProof::SendPrint(Option_t *option)
{
// Send print command to master server. Returns number of slaves message
// was sent to. Returns -1 in case of error.
if (!IsValid()) return -1;
Broadcast(option, kPROOF_PRINT, kActive);
return Collect(kActive);
}
//______________________________________________________________________________
void TProof::SetLogLevel(Int_t level, UInt_t mask)
{
// Set server logging level.
char str[32];
fLogLevel = level;
gProofDebugLevel = level;
gProofDebugMask = (TProofDebug::EProofDebugMask) mask;
sprintf(str, "%d %u", level, mask);
Broadcast(str, kPROOF_LOGLEVEL, kAll);
}
//______________________________________________________________________________
Int_t TProof::SetParallel(Int_t nodes)
{
// Tell RPOOF how many slaves to use in parallel. Returns the number of
// parallel slaves. Returns -1 in case of error.
if (!IsValid()) return -1;
if (IsMaster()) {
GoParallel(nodes);
return SendCurrentState();
} else {
PDB(kGlobal,1) Info("SetParallel", "request %d node%s", nodes,
nodes == 1 ? "" : "s");
TMessage mess(kPROOF_PARALLEL);
mess << nodes;
Broadcast(mess);
Collect();
Int_t parallel = GetParallel();
PDB(kGlobal,1) Info("SetParallel", "got %d node%s", parallel,
parallel == 1 ? "" : "s");
if (parallel > 0) printf("PROOF set to parallel mode (%d slaves)\n", parallel);
return parallel;
}
}
//______________________________________________________________________________
Int_t TProof::GoParallel(Int_t nodes)
{
// Go in parallel mode with at most "nodes" slaves. Since the fSlaves
// list is sorted by slave performace the active list will contain first
// the most performant nodes. Returns the number of active slaves.
// Returns -1 in case of error.
if (!IsValid()) return -1;
if (nodes < 0) nodes = 0;
fActiveSlaves->Clear();
fActiveMonitor->RemoveAll();
TIter next(fSlaves);
//Simple algorithm for going parallel - fill up first nodes
int cnt = 0;
TSlave *sl;
while (cnt < nodes && (sl = (TSlave *)next())) {
if (sl->IsValid()) {
if ( strcmp("IGNORE", sl->GetImage()) == 0 ) continue;
Int_t slavenodes = 0;
if (sl->GetSlaveType() == TSlave::kSlave) {
fActiveSlaves->Add(sl);
fActiveMonitor->Add(sl->GetSocket());
slavenodes = 1;
} else if (sl->GetSlaveType() == TSlave::kMaster) {
TMessage mess(kPROOF_PARALLEL);
mess << nodes-cnt;
if (sl->GetSocket()->Send(mess) == -1) {
MarkBad(sl);
slavenodes = 0;
} else {
Collect(sl);
fActiveSlaves->Add(sl);
fActiveMonitor->Add(sl->GetSocket());
if (sl->GetParallel()>0) {
slavenodes = sl->GetParallel();
} else {
slavenodes = 0;
}
}
} else {
Error("GoParallel", "TSlave is neither Master nor Slave");
Assert(0);
}
cnt += slavenodes;
}
}
// Get slave status (will set the slaves fWorkDir correctly)
AskStatistics();
// Find active slaves with unique image
FindUniqueSlaves();
// Send new group-view to slaves
SendGroupView();
Int_t n = GetParallel();
if (IsMaster()) {
if (n < 1)
printf("PROOF set to sequential mode\n");
} else {
printf("PROOF set to parallel mode (%d slaves)\n", n);
}
PDB(kGlobal,1) Info("GoParallel", "got %d node%s", n, n == 1 ? "" : "s");
return n;
}
//______________________________________________________________________________
void TProof::ShowCache(Bool_t all)
{
// List contents of file cache. If all is true show all caches also on
// slaves. If everything is ok all caches are to be the same.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowCache) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubCache) << all;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ClearCache()
{
// Remove files from all file caches.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kClearCache);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kClearSubCache);
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters
TList allunique;
Int_t i;
for (i = 0; i<fUniqueSlaves->GetSize(); i++) {
TSlave* sl =
dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i<fNonUniqueMasters->GetSize(); i++) {
TSlave* sl =
dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
// clear file map so files get send again to remote nodes
fFileMap.clear();
}
//______________________________________________________________________________
void TProof::ShowPackages(Bool_t all)
{
// List contents of package directory. If all is true show all package
// directries also on slaves. If everything is ok all package directories
// should be the same.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowPackages) << all;
Broadcast(mess, kUnique);
if (all) {
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kShowSubPackages) << all;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
} else {
Collect(kUnique);
}
}
//______________________________________________________________________________
void TProof::ShowEnabledPackages(Bool_t all)
{
// List which packages are enabled. If all is true show enabled packages
// for all active slaves. If everything is ok all active slaves should
// have the same packages enabled.
if (!IsValid()) return;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kShowEnabledPackages) << all;
Broadcast(mess);
Collect();
}
//______________________________________________________________________________
Int_t TProof::ClearPackages()
{
// Remove all packages.
if (!IsValid()) return -1;
if (UnloadPackages() == -1)
return -1;
if (DisablePackages() == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::ClearPackage(const char *package)
{
// Remove a specific package.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("ClearPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (UnloadPackage(pac) == -1)
return -1;
if (DisablePackage(pac) == -1)
return -1;
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::DisablePackage(const char *package)
{
// Remove a specific package.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("DisablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::DisablePackages()
{
// Remove all packages.
if (!IsValid()) return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kDisablePackages);
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kDisableSubPackages);
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::BuildPackage(const char *package)
{
// Build specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists on all unique nodes.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("BuildPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kBuildPackage) << pac;
Broadcast(mess, kUnique);
TMessage mess2(kPROOF_CACHE);
mess2 << Int_t(kBuildSubPackage) << pac;
Broadcast(mess2, fNonUniqueMasters);
// make list of unique slaves (which will include
// unique slave on submasters)
TList allunique;
Int_t i;
for (i = 0; i < fUniqueSlaves->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fUniqueSlaves->At(i));
if (sl) allunique.Add(sl);
}
for (i = 0; i < fNonUniqueMasters->GetSize(); i++) {
TSlave* sl = dynamic_cast<TSlave*>(fNonUniqueMasters->At(i));
if (sl) allunique.Add(sl);
}
Collect(&allunique);
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::LoadPackage(const char *package)
{
// Load specified package. Executes the PROOF-INF/SETUP.C script
// on all active nodes.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("LoadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kLoadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::UnloadPackage(const char *package)
{
// Unload specified package.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("UnloadPackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackage) << pac;
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::UnloadPackages()
{
// Unload all packages.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
TMessage mess(kPROOF_CACHE);
mess << Int_t(kUnloadPackages);
Broadcast(mess);
Collect();
return fStatus;
}
//______________________________________________________________________________
Int_t TProof::EnablePackage(const char *package)
{
// Enable specified package. Executes the PROOF-INF/BUILD.sh
// script if it exists followed by the PROOF-INF/SETUP.C script.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
if (!package || !strlen(package)) {
Error("EnablePackage", "need to specify a package name");
return -1;
}
// if name, erroneously, is a par pathname strip off .par and path
TString pac = package;
if (pac.EndsWith(".par"))
pac.Remove(pac.Length()-4);
pac = gSystem->BaseName(pac);
if (BuildPackage(pac) == -1)
return -1;
if (LoadPackage(pac) == -1)
return -1;
return 0;
}
//______________________________________________________________________________
Int_t TProof::UploadPackage(const char *tpar, Int_t parallel)
{
// Upload a PROOF archive (PAR file). A PAR file is a compressed
// tar file with one special additional directory, PROOF-INF
// (blatantly copied from Java's jar format). It must have the extension
// .par. A PAR file can be directly a binary or a source with a build
// procedure. In the PROOF-INF directory there can be a build script:
// BUILD.sh to be called to build the package, in case of a binary PAR
// file don't specify a build script or make it a no-op. Then there is
// SETUP.C which sets the right environment variables to use the package,
// like LD_LIBRARY_PATH, etc. Parallel is the number of parallel streams
// that can be used to upload the package to the master server.
// Returns 0 in case of success and -1 in case of error.
if (!IsValid()) return -1;
TString par = tpar;
if (!par.EndsWith(".par")) {
Error("UploadPackage", "package %s must have extension .par", tpar);
return -1;
}
gSystem->ExpandPathName(par);
if (gSystem->AccessPathName(par, kReadPermission)) {
Error("UploadPackage", "package %s does not exist", par.Data());
return -1;
}
// Strategy: get md5 of package and check if it is different from the
// one stored on the remote node. If it is different lock the remote
// package directory and use TFTP to ftp the package to the remote node,
// unlock the directory.
TMD5 *md5 = TMD5::FileChecksum(par);
TMessage mess(kPROOF_CHECKFILE);
mess << TString("+")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess2(kPROOF_CHECKFILE);
mess2 << TString("-")+TString(gSystem->BaseName(par)) << (*md5);
TMessage mess3(kPROOF_CHECKFILE);
mess3 << TString("=")+TString(gSystem->BaseName(par)) << (*md5);
delete md5;
// loop over all unique nodes
TIter next(fUniqueSlaves);
TSlave *sl;
while ((sl = (TSlave *) next())) {
if (!sl->IsValid())
continue;
sl->GetSocket()->Send(mess);
TMessage *reply;
sl->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
// remote directory is locked, upload file via TFTP
if (IsMaster())
parallel = 1; // assume LAN
{
TFTP ftp(TString("root://")+sl->GetName(), parallel);
if (!ftp.IsZombie()) {
ftp.cd(Form("%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir));
ftp.put(par, gSystem->BaseName(par));
}
}
// install package and unlock dir
sl->GetSocket()->Send(mess2);
delete reply;
sl->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
Error("UploadPackage", "unpacking of package %s failed", par.Data());
delete reply;
return -1;
}
}
delete reply;
}
// loop over all other master nodes
TIter nextmaster(fNonUniqueMasters);
TSlave *ma;
while ((ma = (TSlave *) nextmaster())) {
if (!ma->IsValid())
continue;
ma->GetSocket()->Send(mess3);
TMessage *reply;
ma->GetSocket()->Recv(reply);
if (reply->What() != kPROOF_CHECKFILE) {
// error -> package should have been found
Error("UploadPackage", "package %s did not exist on submaster %s",
par.Data(), ma->GetOrdinal());
delete reply;
return -1;
}
delete reply;
}
return 0;
}
//______________________________________________________________________________
void TProof::Progress(Long64_t total, Long64_t processed)
{
// Get query progress information. Connect a slot to this signal
// to track progress.
PDB(kGlobal,1)
Info("Progress","%2f (%lld/%lld)", 100.*processed/total, processed, total);
EmitVA("Progress(Long64_t,Long64_t)", 2, total, processed);
}
//______________________________________________________________________________
void TProof::Feedback(TList *objs)
{
// Get list of feedback objects. Connect a slot to this signal
// to monitor the feedback object.
PDB(kGlobal,1) Info("Feedback","%d Objects", objs->GetSize());
PDB(kFeedback,1) {
Info("Feedback","%d objects", objs->GetSize());
objs->ls();
}
Emit("Feedback(TList *objs)", (Long_t) objs);
}
//______________________________________________________________________________
void TProof::ValidateDSet(TDSet *dset)
{
// Validate a TDSet.
if (dset->ElementsValid()) return;
THashList nodes;
nodes.SetOwner();
TList slholder;
slholder.SetOwner();
TList elemholder;
elemholder.SetOwner();
// build nodelist with slaves and elements
TIter NextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(NextSlave())) {
TList *sllist = 0;
TPair *p = dynamic_cast<TPair*>(nodes.FindObject(sl->GetName()));
if (!p) {
sllist = new TList;
sllist->SetName(sl->GetName());
slholder.Add(sllist);
TList *elemlist = new TList;
elemlist->SetName(TString(sl->GetName())+"_elem");
elemholder.Add(elemlist);
nodes.Add(new TPair(sllist, elemlist));
} else {
sllist = dynamic_cast<TList*>(p->Key());
}
sllist->Add(sl);
}
// add local elements to nodes
TList NonLocal; // list of nonlocal elements
// make two iterations - first add local elements - then distribute nonlocals
for (Int_t i = 0; i < 2; i++) {
Bool_t local = i>0?kFALSE:kTRUE;
TIter NextElem(local?dset->GetListOfElements():&NonLocal);
while (TDSetElement *elem = dynamic_cast<TDSetElement*>(NextElem())) {
if (elem->GetValid()) continue;
TPair *p = dynamic_cast<TPair*>(local?nodes.FindObject(TUrl(elem->GetFileName()).GetHost()):nodes.At(0));
if (p) {
TList *eli = dynamic_cast<TList*>(p->Value());
TList *sli = dynamic_cast<TList*>(p->Key());
eli->Add(elem);
// order list by elements/slave
TPair *p2 = p;
Bool_t stop = kFALSE;
while (!stop) {
TPair *p3 = dynamic_cast<TPair*>(nodes.After(p2->Key()));
if (p3) {
Int_t nelem = dynamic_cast<TList*>(p3->Value())->GetSize();
Int_t nsl = dynamic_cast<TList*>(p3->Key())->GetSize();
if (nelem*sli->GetSize() < eli->GetSize()*nsl) p2 = p3;
else stop = kTRUE;
} else {
stop = kTRUE;
}
}
if (p2!=p) {
nodes.Remove(p->Key());
nodes.AddAfter(p2->Key(), p);
}
} else {
if (local) {
NonLocal.Add(elem);
} else {
Error("ValidateDSet", "No Node to allocate TDSetElement to");
Assert(0);
}
}
}
}
// send to slaves
TList usedslaves;
TIter NextNode(&nodes);
SetDSet(dset); // set dset to be validated in Collect()
while (TPair *node = dynamic_cast<TPair*>(NextNode())) {
TList *slaves = dynamic_cast<TList*>(node->Key());
TList *setelements = dynamic_cast<TList*>(node->Value());
// distribute elements over the slaves
Int_t nslaves = slaves->GetSize();
Int_t nelements = setelements->GetSize();
for (Int_t i=0; i<nslaves; i++) {
TDSet set(dset->GetType(), dset->GetObjName(),
dset->GetDirectory());
for (Int_t j = (i*nelements)/nslaves;
j < ((i+1)*nelements)/nslaves;
j++) {
TDSetElement *elem =
dynamic_cast<TDSetElement*>(setelements->At(j));
set.Add(elem->GetFileName(), elem->GetObjName(),
elem->GetDirectory(), elem->GetFirst(),
elem->GetNum(), elem->GetMsd());
}
if (set.GetListOfElements()->GetSize()>0) {
TMessage mesg(kPROOF_VALIDATE_DSET);
mesg << &set;
TSlave *sl = dynamic_cast<TSlave*>(slaves->At(i));
PDB(kGlobal,1) Info("ValidateDSet",
"Sending TDSet with %d elements to slave %s"
" to be validated",
set.GetListOfElements()->GetSize(),
sl->GetOrdinal());
sl->GetSocket()->Send(mesg);
usedslaves.Add(sl);
}
}
}
PDB(kGlobal,1) Info("ValidateDSet","Calling Collect");
Collect(&usedslaves);
SetDSet(0);
}
//______________________________________________________________________________
void TProof::AddFeedback(const char *name)
{
// Add object to feedback list.
PDB(kFeedback, 3) Info("AddFeedback", "Adding object \"%s\" to feedback", name);
if (fFeedback->FindObject(name) == 0) fFeedback->Add(new TObjString(name));
}
//______________________________________________________________________________
void TProof::RemoveFeedback(const char *name)
{
// Remove object from feedback list.
TObject *obj = fFeedback->FindObject(name);
if (obj != 0) {
fFeedback->Remove(obj);
delete obj;
}
}
//______________________________________________________________________________
void TProof::ClearFeedback()
{
// Clear feedback list.
fFeedback->Delete();
}
//______________________________________________________________________________
void TProof::ShowFeedback() const
{
// Show items in feedback list.
if (fFeedback->GetSize() == 0) {
Info("","no feedback requested");
return;
}
fFeedback->Print();
}
//______________________________________________________________________________
TList *TProof::GetFeedbackList() const
{
// Return feedback list.
return fFeedback;
}
//______________________________________________________________________________
TTree *TProof::GetTreeHeader(TDSet *dset)
{
// Creates a tree header (a tree with nonexisting files) object for
// the DataSet.
TList *l = GetListOfActiveSlaves();
TSlave *sl = (TSlave*) l->First();
if (sl == 0) {
Error("GetTreeHeader", "No connection");
return 0;
}
TSocket *soc = sl->GetSocket();
TMessage msg(kPROOF_GETTREEHEADER);
msg << dset;
soc->Send(msg);
TMessage *reply;
Int_t d = soc->Recv(reply);
if (reply <= 0) {
Error("GetTreeHeader", "Error getting a replay from the master.Result %d", (int) d);
return 0;
}
TString s1;
TTree * t;
(*reply) >> s1;
(*reply) >> t;
PDB(kGlobal, 1)
if (t)
Info("GetTreeHeader", Form("%s, message size: %d, entries: %d\n",
s1.Data(), reply->BufferSize(), (int) t->GetMaxEntryLoop()));
else
Info("GetTreeHeader", Form("%s, message size: %d\n", s1.Data(), reply->BufferSize()));
delete reply;
return t;
}
//______________________________________________________________________________
TDrawFeedback *TProof::CreateDrawFeedback()
{
// Draw feedback creation proxy. When accessed via TVirtualProof avoids
// link dependency on libProof.
return new TDrawFeedback(this);
}
//______________________________________________________________________________
void TProof::SetDrawFeedbackOption(TDrawFeedback *f, Option_t *opt)
{
// Set draw feedback option.
if (f)
f->SetOption(opt);
}
//______________________________________________________________________________
void TProof::DeleteDrawFeedback(TDrawFeedback *f)
{
// Delete draw feedback object.
if (f)
delete f;
}
//______________________________________________________________________________
TList *TProof::GetOutputNames()
{
// FIXME: to be written
return 0;
/*
TMessage msg(kPROOF_GETOUTPUTLIST);
TList* slaves = fActiveSlaves;
Broadcast(msg, slaves);
TMonitor mon;
TList* outputList = new TList();
TIter si(slaves);
TSlave *slave;
while ((slave = (TSlave*)si.Next()) != 0) {
PDB(kGlobal,4) Info("GetOutputNames","Socket added to monitor: %p (%s)",
slave->GetSocket(), slave->GetName());
mon.Add(slave->GetSocket());
}
mon.ActivateAll();
((TProof*)gProof)->DeActivateAsyncInput();
while (mon.GetActive() != 0) {
TSocket *sock = mon.Select();
if (!sock) {
Error("GetOutputList","TMonitor::.Select failed!");
break;
}
mon.DeActivate(sock);
TMessage *reply;
if (sock->Recv(reply) <= 0) {
MarkBad(slave);
// Error("GetOutputList","Recv failed! for slave-%d (%s)",
// slave->GetOrdinal(), slave->GetName());
continue;
}
if (reply->What() != kPROOF_GETOUTPUTNAMES ) {
// Error("GetOutputList","unexpected message %d from slawe-%d (%s)", reply->What(),
// slave->GetOrdinal(), slave->GetName());
MarkBad(slave);
continue;
}
TList* l;
(*reply) >> l;
TIter next(l);
TNamed *n;
while ( (n = dynamic_cast<TNamed*> (next())) ) {
if (!outputList->FindObject(n->GetName()))
outputList->Add(n);
}
delete reply;
}
return outputList;
*/
}
//______________________________________________________________________________
void TProof::Browse(TBrowser *b)
{
// Build the proof's structure in the browser.
b->Add(fActiveSlaves, fActiveSlaves->Class(), "fActiveSlaves");
b->Add(&fMaster, fMaster.Class(), "fMaster");
b->Add(fFeedback, fFeedback->Class(), "fFeedback");
b->Add(fChains, fChains->Class(), "fChains");
b->Add(fPlayer->GetInputList(), fPlayer->GetInputList()->Class(), "InputList");
if (fPlayer->GetOutputList())
b->Add(fPlayer->GetOutputList(), fPlayer->GetOutputList()->Class(), "OutputList");
}
//______________________________________________________________________________
TProofPlayer *TProof::MakePlayer()
{
// Construct a TProofPlayer object.
SetPlayer(new TProofPlayerRemote(this));
return GetPlayer();
}
//______________________________________________________________________________
void TProof::AddChain(TChain *chain)
{
fChains->Add(chain);
}
//______________________________________________________________________________
void TProof::RemoveChain(TChain *chain)
{
fChains->Remove(chain);
}
//------------------------------------------------------------------------------
ClassImp(TProofCondor)
//______________________________________________________________________________
TProofCondor::TProofCondor(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
: fCondor(0), fTimer(0)
{
// Start proof using condor
if (!conffile || strlen(conffile) == 0) {
conffile = kPROOF_ConfFile;
} else if (!strncasecmp(conffile, "condor:", 7)) {
conffile+=7;
}
if (!confdir || strlen(confdir) == 0) {
confdir = kPROOF_ConfDir;
}
Init(masterurl, conffile, confdir, loglevel);
}
//______________________________________________________________________________
TProofCondor::~TProofCondor()
{
// Clean up Condor PROOF environment.
SafeDelete(fCondor);
SafeDelete(fTimer);
}
//______________________________________________________________________________
Bool_t TProofCondor::StartSlaves()
{
// non static config
fCondor = new TCondor;
TString jobad = GetJobAd();
fImage = fCondor->GetImage(gSystem->HostName());
if (fImage.Length() == 0) {
Error("StartSlaves", "Empty Condor image found for system %s",
gSystem->HostName());
return kFALSE;
}
TList claims;
if (fConfFile.IsNull()) {
// startup all slaves if no config file given
TList *condorclaims = fCondor->Claim(9999, jobad);
TIter nextclaim(condorclaims);
while (TObject *o = nextclaim()) claims.Add(o);
} else {
// parse config file
TString fconf;
fconf.Form("%s/.%s", gSystem->Getenv("HOME"), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
fconf.Form("%s/proof/etc/%s", fConfDir.Data(), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
Error("StartSlaves", "no PROOF config file found");
return kFALSE;
}
}
PDB(kGlobal,1) Info("StartSlaves", "using PROOF config file: %s", fconf.Data());
FILE *pconf;
if ((pconf = fopen(fconf, "r"))) {
fConfFile = fconf;
// check for valid slave lines and claim condor nodes
char line[1024];
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// find all slave servers, accept both "slave" and "worker" lines
if (nword >= 2 &&
(!strcmp(word[0], "condorslave") || !strcmp(word[0], "condorworker"))) {
int perfidx = 100;
const char *stripvm = strchr(word[1], '@');
const char *image = stripvm ? stripvm+1 : word[1];
const char *workdir = 0;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "perf=", 5))
perfidx = atoi(word[i]+5);
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "workdir=", 8))
workdir = word[i]+8;
}
TCondorSlave* csl = fCondor->Claim(word[1], jobad);
if (csl) {
csl->fPerfIdx = perfidx;
csl->fImage = image;
csl->fWorkDir = workdir;
claims.Add(csl);
}
}
}
}
fclose(pconf);
}
Long_t delay = 500; // timer delay 0.5s
Int_t ntries = 20; // allow 20 tries (must be > 1 for algorithm to work)
Int_t trial = 1;
Int_t idx = 0;
Int_t ord = 0;
while (claims.GetSize() > 0) {
// Get Condor Slave
TCondorSlave* c = 0;
if (trial == 1) {
c = dynamic_cast<TCondorSlave*>(claims.At(idx));
c->fOrdinal = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
} else {
TPair *p = dynamic_cast<TPair*>(claims.At(idx));
TTimer *t = dynamic_cast<TTimer*>(p->Value());
// wait remaining time
Long_t wait = (Long_t) (t->GetAbsTime()-gSystem->Now());
if (wait>0) gSystem->Sleep(wait);
c = dynamic_cast<TCondorSlave*>(p->Key());
}
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)c->fHostname);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
// create slave
TSlave *slave = CreateSlave(c->fHostname, c->fPort, c->fOrdinal,
c->fPerfIdx, c->fImage, c->fWorkDir);
// add slave to appropriate list
if (trial<ntries) {
if (slave->IsValid()) {
fSlaves->Add(slave);
fAllMonitor->Add(slave->GetSocket());
if (trial == 1) {
claims.Remove(c);
} else {
TPair *p = dynamic_cast<TPair*>(claims.Remove(c));
delete dynamic_cast<TTimer*>(p->Value());
delete p;
}
} else {
if (trial == 1) {
TTimer* timer = new TTimer(delay);
TPair *p = new TPair(c, timer);
claims.RemoveAt(idx);
claims.AddAt(p, idx);
} else {
TPair *p = dynamic_cast<TPair*>(claims.At(idx));
dynamic_cast<TTimer*>(p->Value())->Reset();
}
delete slave;
idx++;
}
} else {
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
} else {
fBadSlaves->Add(slave);
}
TPair *p = dynamic_cast<TPair*>(claims.Remove(c));
delete dynamic_cast<TTimer*>(p->Value());
delete p;
}
if (idx>=claims.GetSize()) {
trial++;
idx = 0;
}
}
return kTRUE;
}
//______________________________________________________________________________
void TProofCondor::SetActive(Bool_t active)
{
// Suspend or resume PROOF via Condor.
if (fTimer == 0) {
fTimer = new TTimer();
}
if (active) {
PDB(kCondor,1) Info("SetActive","-- Condor Resume --");
fTimer->Stop();
if (fCondor->GetState() == TCondor::kSuspended)
fCondor->Resume();
} else {
Int_t delay = 60000; // milli seconds
PDB(kCondor,1) Info("SetActive","-- Delayed Condor Suspend (%d msec / to %ld) --",
delay, delay + long(gSystem->Now()));
fTimer->Connect("Timeout()", "TCondor", fCondor, "Suspend()");
fTimer->Start(10000, kTRUE); // single shot
}
}
//______________________________________________________________________________
TString TProofCondor::GetJobAd()
{
TString ad;
ad = "JobUniverse = 5\n"; // vanilla
ad += Form("Cmd = \"%s/bin/proofd\"\n", GetConfDir());
ad += "Iwd = \"/tmp\"\n";
ad += "In = \"/dev/null\"\n";
ad += "Out = \"/tmp/proofd.out.$(Port)\"\n";
ad += "Err = \"/tmp/proofd.err.$(Port)\"\n";
ad += Form("Args = \"-f -p $(Port) -d %d %s\"\n", GetLogLevel(), GetConfDir());
return ad;
}
//______________________________________________________________________________
ClassImp(TProofSuperMaster)
//______________________________________________________________________________
TProofSuperMaster::TProofSuperMaster(const char *masterurl, const char *conffile,
const char *confdir, Int_t loglevel)
{
// Start super master PROOF session.
if (!conffile || strlen(conffile) == 0)
conffile = kPROOF_ConfFile;
else if (!strncasecmp(conffile, "sm:", 3))
conffile+=3;
if (!confdir || strlen(confdir) == 0)
confdir = kPROOF_ConfDir;
Init(masterurl, conffile, confdir, loglevel);
}
//______________________________________________________________________________
Bool_t TProofSuperMaster::StartSlaves()
{
// Start up PROOF submasters.
// If this is a supermaster server, find the config file and start
// submaster servers as specified in the config file.
// There is a difference in startup between a slave and a submaster
// in which the submaster will issue a kPROOF_LOGFILE and
// then a kPROOF_LOGDONE message (which must be collected)
// while slaves do not.
TString fconf;
fconf.Form("%s/.%s", gSystem->Getenv("HOME"), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
fconf.Form("%s/proof/etc/%s", fConfDir.Data(), fConfFile.Data());
PDB(kGlobal,2) Info("StartSlaves", "checking PROOF config file %s", fconf.Data());
if (gSystem->AccessPathName(fconf, kReadPermission)) {
Error("StartSlaves", "no PROOF config file found");
return kFALSE;
}
}
PDB(kGlobal,1) Info("StartSlaves", "using PROOF config file: %s", fconf.Data());
TList validSlaves;
FILE *pconf;
if ((pconf = fopen(fconf, "r"))) {
TString fconfname = fConfFile;
fConfFile = fconf;
// read the config file
char line[1024];
TString host = gSystem->GetHostByName(gSystem->HostName()).GetHostName();
int ord = 0;
// check for valid master line
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// see if master may run on this node, accept both old "node"
// and new "master" lines
if (nword >= 2 &&
(!strcmp(word[0], "node") || !strcmp(word[0], "master")) &&
!fImage.Length()) {
TInetAddress a = gSystem->GetHostByName(word[1]);
if (!host.CompareTo(a.GetHostName()) ||
!strcmp(word[1], "localhost")) {
const char *image = word[1];
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
}
fImage = image;
}
}
}
if (fImage.Length() == 0) {
fclose(pconf);
Error("StartSlaves", "no appropriate master line found in %s", fconf.Data());
return kFALSE;
}
// check for valid submaster lines and start them
rewind(pconf);
while (fgets(line, sizeof(line), pconf)) {
char word[12][128];
if (line[0] == '#') continue; // skip comment lines
int nword = sscanf(line, "%s %s %s %s %s %s %s %s %s %s %s %s", word[0], word[1],
word[2], word[3], word[4], word[5], word[6],
word[7], word[8], word[9], word[10], word[11]);
// find all submaster servers
if (nword >= 2 &&
!strcmp(word[0], "submaster")) {
int sport = fPort;
const char *conffile = 0;
const char *image = word[1];
const char *msd = 0;
for (int i = 2; i < nword; i++) {
if (!strncmp(word[i], "image=", 6))
image = word[i]+6;
if (!strncmp(word[i], "port=", 5))
sport = atoi(word[i]+5);
if (!strncmp(word[i], "config=", 7))
conffile = word[i]+7;
if (!strncmp(word[i], "msd=", 4))
msd = word[i]+4;
}
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)word[1]);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
// create submaster server
TSlave *slave = CreateSubmaster(word[1], sport, fullord, image, conffile, msd);
fSlaves->Add(slave);
if (slave->IsValid()) {
// check protocol compatability
// protocol 1 is not supported anymore
if (fProtocol == 1) {
Error("StartSlaves", "master and submaster protocols not compatible (%d and %d)",
kPROOF_Protocol, fProtocol);
fBadSlaves->Add(slave);
}
else {
fAllMonitor->Add(slave->GetSocket());
validSlaves.Add(slave);
}
} else {
fBadSlaves->Add(slave);
}
PDB(kGlobal,3)
Info("StartSlaves","slave on host %s created and added to list", word[1]);
}
}
}
fclose(pconf);
Collect(kAll); //Get kPROOF_LOGFILE and kPROOF_LOGDONE messages
TIter NextSlave(&validSlaves);
while (TSlave* sl = dynamic_cast<TSlave*>(NextSlave())){
if (sl->GetStatus() == -99) {
Error("StartSlaves", "not allowed to connect to PROOF master server");
fBadSlaves->Add(sl);
continue;
}
if (!sl->IsValid()) {
Error("StartSlaves", "failed to setup connection with PROOF master server");
fBadSlaves->Add(sl);
continue;
}
}
return kTRUE;
}
//______________________________________________________________________________
Int_t TProofSuperMaster::Process(TDSet *set, const char *selector, Option_t *option,
Long64_t nentries, Long64_t first, TEventList *evl)
{
// Process a data set (TDSet) using the specified selector (.C) file.
// Returns -1 in case of error, 0 otherwise.
if (!IsValid()) return -1;
if (!GetPlayer())
SetPlayer(new TProofPlayerSuperMaster(this));
if (GetProgressDialog())
GetProgressDialog()->ExecPlugin(5, this, selector, set->GetListOfElements()->GetSize(),
first, nentries);
return GetPlayer()->Process(set, selector, option, nentries, first, evl);
}
//______________________________________________________________________________
void TProofSuperMaster::ValidateDSet(TDSet *dset)
{
// Validate a TDSet.
if (dset->ElementsValid()) return;
THashList msds;
msds.SetOwner();
TList smholder;
smholder.SetOwner();
TList elemholder;
elemholder.SetOwner();
// build nodelist with slaves and elements
TIter NextSlave(GetListOfActiveSlaves());
while (TSlave *sl = dynamic_cast<TSlave*>(NextSlave())) {
TList *smlist = 0;
TPair *p = dynamic_cast<TPair*>(msds.FindObject(sl->GetMsd()));
if (!p) {
smlist = new TList;
smlist->SetName(sl->GetMsd());
smholder.Add(smlist);
TList *elemlist = new TSortedList(kSortDescending);
elemlist->SetName(TString(sl->GetMsd())+"_elem");
elemholder.Add(elemlist);
msds.Add(new TPair(smlist, elemlist));
} else {
smlist = dynamic_cast<TList*>(p->Key());
}
smlist->Add(sl);
}
TIter NextElem(dset->GetListOfElements());
while (TDSetElement *elem = dynamic_cast<TDSetElement*>(NextElem())) {
if (elem->GetValid()) continue;
TPair *p = dynamic_cast<TPair*>(msds.FindObject(elem->GetMsd()));
if (p) {
dynamic_cast<TList*>(p->Value())->Add(elem);
} else {
Error("ValidateDSet", "no mass storage domain '%s' associated"
" with available submasters",
elem->GetMsd());
return;
}
}
// send to slaves
TList usedsms;
TIter NextSM(&msds);
SetDSet(dset); // set dset to be validated in Collect()
while (TPair *msd = dynamic_cast<TPair*>(NextSM())) {
TList *sms = dynamic_cast<TList*>(msd->Key());
TList *setelements = dynamic_cast<TList*>(msd->Value());
// distribute elements over the slaves
Int_t nsms = sms->GetSize();
Int_t nelements = setelements->GetSize();
for (Int_t i=0; i<nsms; i++) {
TDSet set(dset->GetType(), dset->GetObjName(),
dset->GetDirectory());
for (Int_t j = (i*nelements)/nsms;
j < ((i+1)*nelements)/nsms;
j++) {
TDSetElement *elem =
dynamic_cast<TDSetElement*>(setelements->At(j));
set.Add(elem->GetFileName(), elem->GetObjName(),
elem->GetDirectory(), elem->GetFirst(),
elem->GetNum(), elem->GetMsd());
}
if (set.GetListOfElements()->GetSize()>0) {
TMessage mesg(kPROOF_VALIDATE_DSET);
mesg << &set;
TSlave *sl = dynamic_cast<TSlave*>(sms->At(i));
PDB(kGlobal,1) Info("ValidateDSet",
"Sending TDSet with %d elements to slave %s"
" to be validated",
set.GetListOfElements()->GetSize(),
sl->GetOrdinal());
sl->GetSocket()->Send(mesg);
usedsms.Add(sl);
}
}
}
PDB(kGlobal,1) Info("ValidateDSet","Calling Collect");
Collect(&usedsms);
SetDSet(0);
}
//______________________________________________________________________________
TProofPlayer *TProofSuperMaster::MakePlayer()
{
// Construct a TProofPlayer object.
SetPlayer(new TProofPlayerSuperMaster(this));
return GetPlayer();
}
|
#include "callwindow.h"
#include "ui_callwindow.h"
#include "ui_about.h"
#include "statisticswindow.h"
#include "videoviewfactory.h"
#include "common.h"
#include "settingskeys.h"
#include <QCloseEvent>
#include <QTimer>
#include <QMetaType>
#include <QDebug>
#include <QDir>
CallWindow::CallWindow(QWidget *parent):
QMainWindow(parent),
ui_(new Ui::CallWindow),
viewFactory_(std::shared_ptr<VideoviewFactory>(new VideoviewFactory)),
settingsView_(this),
statsWindow_(nullptr),
conference_(this),
partInt_(nullptr),
timer_(new QTimer(this))
{
ui_->setupUi(this);
}
CallWindow::~CallWindow()
{
timer_->stop();
delete timer_;
if(statsWindow_)
{
statsWindow_->close();
delete statsWindow_;
}
delete ui_;
}
void CallWindow::init(ParticipantInterface *partInt)
{
partInt_ = partInt;
ui_->Add_contact_widget->setVisible(false);
viewFactory_->setSelfview(ui_->SelfView, ui_->SelfView);
setWindowTitle("Kvazzup");
contacts_.initializeList(ui_->contactList, partInt_);
aboutWidget_ = new Ui::AboutWidget;
aboutWidget_->setupUi(&about_);
// I don't know why this is required.
qRegisterMetaType<QVector<int> >("QVector<int>");
QObject::connect(&settingsView_, &Settings::updateCallSettings,
this, &CallWindow::updateCallSettings);
QObject::connect(&settingsView_, &Settings::updateVideoSettings,
this, &CallWindow::updateVideoSettings);
QObject::connect(&settingsView_, &Settings::updateAudioSettings,
this, &CallWindow::updateAudioSettings);
QObject::connect(ui_->mic, &QPushButton::clicked,
this, &CallWindow::micButton);
QObject::connect(ui_->camera, &QPushButton::clicked,
this, &CallWindow::cameraButton);
QObject::connect(ui_->EndCallButton, SIGNAL(clicked()),
this, SIGNAL(endCall()));
QObject::connect(ui_->actionClose, SIGNAL(triggered()),
this, SIGNAL(closed()));
QObject::connect(ui_->address, &QLineEdit::textChanged,
this, &CallWindow::changedSIPText);
QObject::connect(ui_->username, &QLineEdit::textChanged,
this, &CallWindow::changedSIPText);
QObject::connect(ui_->screen_share, &QPushButton::clicked,
this, &CallWindow::screensShareButton);
QMainWindow::show();
QObject::connect(&conference_, &ConferenceView::acceptCall, this, &CallWindow::callAccepted);
QObject::connect(&conference_, &ConferenceView::rejectCall, this, &CallWindow::callRejected);
QObject::connect(&conference_, &ConferenceView::cancelCall, this, &CallWindow::callCancelled);
conference_.init(ui_->participantLayout, ui_->participants);
initButton(QDir::currentPath() + "/icons/add_contact.svg", QSize(60,60), QSize(35,35), ui_->addContact);
initButton(QDir::currentPath() + "/icons/settings.svg", QSize(60,60), QSize(35,35), ui_->settings_button);
initButton(QDir::currentPath() + "/icons/video_on.svg", QSize(60,60), QSize(35,35), ui_->camera);
initButton(QDir::currentPath() + "/icons/mic_on.svg", QSize(60,60), QSize(35,35), ui_->mic);
initButton(QDir::currentPath() + "/icons/end_call.svg", QSize(60,60), QSize(35,35), ui_->EndCallButton);
initButton(QDir::currentPath() + "/icons/screen_share.svg", QSize(60,60), QSize(35,35), ui_->screen_share);
ui_->buttonContainer->layout()->setAlignment(ui_->endcallHolder, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->settings_button, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->mic, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->camera, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->SelfView, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->screen_share, Qt::AlignBottom);
ui_->contactListContainer->layout()->setAlignment(ui_->addContact, Qt::AlignHCenter);
ui_->EndCallButton->hide();
settingsView_.init();
// set button icons to correct states
setMicState(settingEnabled(SettingsKey::micStatus));
setCameraState(settingEnabled(SettingsKey::cameraStatus));
setScreenShareState(settingEnabled(SettingsKey::screenShareStatus));
}
void CallWindow::initButton(QString iconPath, QSize size, QSize iconSize,
QPushButton* button)
{
QPixmap pixmap(iconPath);
if(!pixmap.isNull())
{
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setText("");
button->setMaximumSize(size);
button->setMinimumSize(size);
button->setIconSize(iconSize);
}
else
{
qDebug() << "WARNING," << metaObject()->className() << ": Could not find icon:" << iconPath;
}
}
StatisticsInterface* CallWindow::createStatsWindow()
{
printNormal(this,"Initiating, CallWindow: Creating statistics window");
statsWindow_ = new StatisticsWindow(this);
// Stats GUI updates are handled solely by timer
timer_->setInterval(200);
timer_->setSingleShot(false);
timer_->start();
connect(timer_, SIGNAL(timeout()), statsWindow_, SLOT(update()));
return statsWindow_;
}
void CallWindow::on_addContact_clicked()
{
printNormal(this, "Clicked");
QString serverAddress = settingString(SettingsKey::sipServerAddress);
ui_->address->setText(serverAddress);
ui_->username->setText("username");
changedSIPText(serverAddress);
}
void CallWindow::addContact()
{
// TODO: support dns
QRegularExpression re_ip ("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b");
QRegularExpressionMatch ip_match = re_ip.match(ui_->address->text());
// has the user inputted correct information
if (!ip_match.hasMatch())
{
ui_->addressLabel->setText("Please set an IP address!");
ui_->addressLabel->setStyleSheet("QLabel { color : red; }");
}
else if (ui_->username->text() == "")
{
ui_->usernameLabel->setText("Please set username!");
ui_->usernameLabel->setStyleSheet("QLabel { color : red; }");
}
else
{
contacts_.addContact(partInt_, ui_->peerName->text(), ui_->username->text(), ui_->address->text());
// Clean the add menu after successful add
ui_->peerName->clear();
ui_->username->clear();
ui_->address->clear();
ui_->addressLabel->setText("Address");
ui_->addressLabel->setStyleSheet("QLabel { color : black; }");
ui_->usernameLabel->setText("Username");
ui_->usernameLabel->setStyleSheet("QLabel { color : black; }");
ui_->Add_contact_widget->hide();
ui_->addContact->show();
}
}
void CallWindow::displayOutgoingCall(uint32_t sessionID, QString name)
{
contacts_.turnAllItemsToPlus();
conference_.callingTo(sessionID, name); // TODO get name from contact list
}
void CallWindow::displayIncomingCall(uint32_t sessionID, QString caller)
{
conference_.incomingCall(sessionID, caller);
}
void CallWindow::displayRinging(uint32_t sessionID)
{
conference_.ringing(sessionID);
}
void CallWindow::openStatistics()
{
if(statsWindow_)
{
statsWindow_->show();
}
else
{
qDebug() << "WARNING," << metaObject()->className()
<< ": No stats window class initiated";
}
}
void CallWindow::closeEvent(QCloseEvent *event)
{
emit closed();
statsWindow_->hide();
statsWindow_->finished(0);
QMainWindow::closeEvent(event);
}
void CallWindow::addVideoStream(uint32_t sessionID)
{
ui_->EndCallButton->setEnabled(true);
ui_->EndCallButton->show();
conference_.addVideoStream(sessionID, viewFactory_);
}
void CallWindow::setMicState(bool on)
{
if(on)
{
initButton(QDir::currentPath() + "/icons/mic_on.svg", QSize(60,60), QSize(35,35), ui_->mic);
//ui_->mic->setText("Mic off");
}
else
{
initButton(QDir::currentPath() + "/icons/mic_off.svg", QSize(60,60), QSize(35,35), ui_->mic);
//ui_->mic->setText("Mic on");
}
}
void CallWindow::setCameraState(bool on)
{
if(on)
{
initButton(QDir::currentPath() + "/icons/video_on.svg",
QSize(60,60), QSize(35,35), ui_->camera);
}
else
{
initButton(QDir::currentPath() + "/icons/video_off.svg",
QSize(60,60), QSize(35,35), ui_->camera);
}
}
void CallWindow::setScreenShareState(bool on)
{
Q_UNUSED(on)
// TODO: Change screen share icon
}
void CallWindow::removeParticipant(uint32_t sessionID)
{
Q_ASSERT(sessionID != 0);
if (sessionID == 0)
{
//printDebug();
return;
}
if(!conference_.removeCaller(sessionID))
{
ui_->EndCallButton->setEnabled(false);
ui_->EndCallButton->hide();
contacts_.setAccessibleAll();
}
contacts_.setAccessible(sessionID);
viewFactory_->clearWidgets(sessionID);
}
void CallWindow::removeWithMessage(uint32_t sessionID, QString message, bool temporaryMessage)
{
removeParticipant(sessionID);
conference_.attachMessageWidget(message, temporaryMessage);
}
void CallWindow::on_settings_button_clicked()
{
settingsView_.show();
}
void CallWindow::screensShareButton()
{
printNormal(this, "Changing state of screen share");
// we change the state of screensharestatus setting here
settingsView_.setScreenShareState(!settingEnabled(SettingsKey::screenShareStatus));
emit updateVideoSettings();
}
void CallWindow::micButton(bool checked)
{
Q_UNUSED(checked);
bool currentState = settingEnabled(SettingsKey::micStatus);
setMicState(!currentState);
settingsView_.setMicState(!currentState);
emit updateAudioSettings();
}
void CallWindow::cameraButton(bool checked)
{
Q_UNUSED(checked);
bool currentState = settingEnabled(SettingsKey::cameraStatus);
setCameraState(!currentState);
settingsView_.setCameraState(!currentState);
emit updateVideoSettings();
}
void CallWindow::on_about_clicked()
{
about_.show();
}
void CallWindow::changedSIPText(const QString &text)
{
Q_UNUSED(text);
ui_->sipAddress->setText("sip:" + ui_->username->text() + "@" + ui_->address->text());
}
void CallWindow::showICEFailedMessage()
{
mesg_.showError("Error: ICE Failed",
"ICE did not succeed to find a connection. "
"You may try again. If the issue persists, "
"please report the issue to Github if you are connected to the internet "
"and describe your network setup.");
}
void CallWindow::showCryptoMissingMessage()
{
mesg_.showWarning("Warning: Encryption not possible",
"Crypto++ has not been included in both Kvazzup and uvgRTP.");
}
void CallWindow::showZRTPFailedMessage(QString sessionID)
{
mesg_.showError("Error: ZRTP handshake has failed for session " + sessionID,
"Could not exchange encryption keys.");
}
fix(GUI): Close the GUI message when exiting application
It is annoying that the message has to be closed separately.
#include "callwindow.h"
#include "ui_callwindow.h"
#include "ui_about.h"
#include "statisticswindow.h"
#include "videoviewfactory.h"
#include "common.h"
#include "settingskeys.h"
#include <QCloseEvent>
#include <QTimer>
#include <QMetaType>
#include <QDebug>
#include <QDir>
CallWindow::CallWindow(QWidget *parent):
QMainWindow(parent),
ui_(new Ui::CallWindow),
viewFactory_(std::shared_ptr<VideoviewFactory>(new VideoviewFactory)),
settingsView_(this),
statsWindow_(nullptr),
conference_(this),
partInt_(nullptr),
timer_(new QTimer(this))
{
ui_->setupUi(this);
}
CallWindow::~CallWindow()
{
timer_->stop();
delete timer_;
if(statsWindow_)
{
statsWindow_->close();
delete statsWindow_;
}
delete ui_;
}
void CallWindow::init(ParticipantInterface *partInt)
{
partInt_ = partInt;
ui_->Add_contact_widget->setVisible(false);
viewFactory_->setSelfview(ui_->SelfView, ui_->SelfView);
setWindowTitle("Kvazzup");
contacts_.initializeList(ui_->contactList, partInt_);
aboutWidget_ = new Ui::AboutWidget;
aboutWidget_->setupUi(&about_);
// I don't know why this is required.
qRegisterMetaType<QVector<int> >("QVector<int>");
QObject::connect(&settingsView_, &Settings::updateCallSettings,
this, &CallWindow::updateCallSettings);
QObject::connect(&settingsView_, &Settings::updateVideoSettings,
this, &CallWindow::updateVideoSettings);
QObject::connect(&settingsView_, &Settings::updateAudioSettings,
this, &CallWindow::updateAudioSettings);
QObject::connect(ui_->mic, &QPushButton::clicked,
this, &CallWindow::micButton);
QObject::connect(ui_->camera, &QPushButton::clicked,
this, &CallWindow::cameraButton);
QObject::connect(ui_->EndCallButton, SIGNAL(clicked()),
this, SIGNAL(endCall()));
QObject::connect(ui_->actionClose, SIGNAL(triggered()),
this, SIGNAL(closed()));
QObject::connect(ui_->address, &QLineEdit::textChanged,
this, &CallWindow::changedSIPText);
QObject::connect(ui_->username, &QLineEdit::textChanged,
this, &CallWindow::changedSIPText);
QObject::connect(ui_->screen_share, &QPushButton::clicked,
this, &CallWindow::screensShareButton);
QMainWindow::show();
QObject::connect(&conference_, &ConferenceView::acceptCall, this, &CallWindow::callAccepted);
QObject::connect(&conference_, &ConferenceView::rejectCall, this, &CallWindow::callRejected);
QObject::connect(&conference_, &ConferenceView::cancelCall, this, &CallWindow::callCancelled);
conference_.init(ui_->participantLayout, ui_->participants);
initButton(QDir::currentPath() + "/icons/add_contact.svg", QSize(60,60), QSize(35,35), ui_->addContact);
initButton(QDir::currentPath() + "/icons/settings.svg", QSize(60,60), QSize(35,35), ui_->settings_button);
initButton(QDir::currentPath() + "/icons/video_on.svg", QSize(60,60), QSize(35,35), ui_->camera);
initButton(QDir::currentPath() + "/icons/mic_on.svg", QSize(60,60), QSize(35,35), ui_->mic);
initButton(QDir::currentPath() + "/icons/end_call.svg", QSize(60,60), QSize(35,35), ui_->EndCallButton);
initButton(QDir::currentPath() + "/icons/screen_share.svg", QSize(60,60), QSize(35,35), ui_->screen_share);
ui_->buttonContainer->layout()->setAlignment(ui_->endcallHolder, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->settings_button, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->mic, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->camera, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->SelfView, Qt::AlignBottom);
ui_->buttonContainer->layout()->setAlignment(ui_->screen_share, Qt::AlignBottom);
ui_->contactListContainer->layout()->setAlignment(ui_->addContact, Qt::AlignHCenter);
ui_->EndCallButton->hide();
settingsView_.init();
// set button icons to correct states
setMicState(settingEnabled(SettingsKey::micStatus));
setCameraState(settingEnabled(SettingsKey::cameraStatus));
setScreenShareState(settingEnabled(SettingsKey::screenShareStatus));
}
void CallWindow::initButton(QString iconPath, QSize size, QSize iconSize,
QPushButton* button)
{
QPixmap pixmap(iconPath);
if(!pixmap.isNull())
{
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setText("");
button->setMaximumSize(size);
button->setMinimumSize(size);
button->setIconSize(iconSize);
}
else
{
qDebug() << "WARNING," << metaObject()->className() << ": Could not find icon:" << iconPath;
}
}
StatisticsInterface* CallWindow::createStatsWindow()
{
printNormal(this,"Initiating, CallWindow: Creating statistics window");
statsWindow_ = new StatisticsWindow(this);
// Stats GUI updates are handled solely by timer
timer_->setInterval(200);
timer_->setSingleShot(false);
timer_->start();
connect(timer_, SIGNAL(timeout()), statsWindow_, SLOT(update()));
return statsWindow_;
}
void CallWindow::on_addContact_clicked()
{
printNormal(this, "Clicked");
QString serverAddress = settingString(SettingsKey::sipServerAddress);
ui_->address->setText(serverAddress);
ui_->username->setText("username");
changedSIPText(serverAddress);
}
void CallWindow::addContact()
{
// TODO: support dns
QRegularExpression re_ip ("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b");
QRegularExpressionMatch ip_match = re_ip.match(ui_->address->text());
// has the user inputted correct information
if (!ip_match.hasMatch())
{
ui_->addressLabel->setText("Please set an IP address!");
ui_->addressLabel->setStyleSheet("QLabel { color : red; }");
}
else if (ui_->username->text() == "")
{
ui_->usernameLabel->setText("Please set username!");
ui_->usernameLabel->setStyleSheet("QLabel { color : red; }");
}
else
{
contacts_.addContact(partInt_, ui_->peerName->text(), ui_->username->text(), ui_->address->text());
// Clean the add menu after successful add
ui_->peerName->clear();
ui_->username->clear();
ui_->address->clear();
ui_->addressLabel->setText("Address");
ui_->addressLabel->setStyleSheet("QLabel { color : black; }");
ui_->usernameLabel->setText("Username");
ui_->usernameLabel->setStyleSheet("QLabel { color : black; }");
ui_->Add_contact_widget->hide();
ui_->addContact->show();
}
}
void CallWindow::displayOutgoingCall(uint32_t sessionID, QString name)
{
contacts_.turnAllItemsToPlus();
conference_.callingTo(sessionID, name); // TODO get name from contact list
}
void CallWindow::displayIncomingCall(uint32_t sessionID, QString caller)
{
conference_.incomingCall(sessionID, caller);
}
void CallWindow::displayRinging(uint32_t sessionID)
{
conference_.ringing(sessionID);
}
void CallWindow::openStatistics()
{
if(statsWindow_)
{
statsWindow_->show();
}
else
{
qDebug() << "WARNING," << metaObject()->className()
<< ": No stats window class initiated";
}
}
void CallWindow::closeEvent(QCloseEvent *event)
{
emit closed();
statsWindow_->hide();
mesg_.hide();
QMainWindow::closeEvent(event);
}
void CallWindow::addVideoStream(uint32_t sessionID)
{
ui_->EndCallButton->setEnabled(true);
ui_->EndCallButton->show();
conference_.addVideoStream(sessionID, viewFactory_);
}
void CallWindow::setMicState(bool on)
{
if(on)
{
initButton(QDir::currentPath() + "/icons/mic_on.svg", QSize(60,60), QSize(35,35), ui_->mic);
//ui_->mic->setText("Mic off");
}
else
{
initButton(QDir::currentPath() + "/icons/mic_off.svg", QSize(60,60), QSize(35,35), ui_->mic);
//ui_->mic->setText("Mic on");
}
}
void CallWindow::setCameraState(bool on)
{
if(on)
{
initButton(QDir::currentPath() + "/icons/video_on.svg",
QSize(60,60), QSize(35,35), ui_->camera);
}
else
{
initButton(QDir::currentPath() + "/icons/video_off.svg",
QSize(60,60), QSize(35,35), ui_->camera);
}
}
void CallWindow::setScreenShareState(bool on)
{
Q_UNUSED(on)
// TODO: Change screen share icon
}
void CallWindow::removeParticipant(uint32_t sessionID)
{
Q_ASSERT(sessionID != 0);
if (sessionID == 0)
{
//printDebug();
return;
}
if(!conference_.removeCaller(sessionID))
{
ui_->EndCallButton->setEnabled(false);
ui_->EndCallButton->hide();
contacts_.setAccessibleAll();
}
contacts_.setAccessible(sessionID);
viewFactory_->clearWidgets(sessionID);
}
void CallWindow::removeWithMessage(uint32_t sessionID, QString message, bool temporaryMessage)
{
removeParticipant(sessionID);
conference_.attachMessageWidget(message, temporaryMessage);
}
void CallWindow::on_settings_button_clicked()
{
settingsView_.show();
}
void CallWindow::screensShareButton()
{
printNormal(this, "Changing state of screen share");
// we change the state of screensharestatus setting here
settingsView_.setScreenShareState(!settingEnabled(SettingsKey::screenShareStatus));
emit updateVideoSettings();
}
void CallWindow::micButton(bool checked)
{
Q_UNUSED(checked);
bool currentState = settingEnabled(SettingsKey::micStatus);
setMicState(!currentState);
settingsView_.setMicState(!currentState);
emit updateAudioSettings();
}
void CallWindow::cameraButton(bool checked)
{
Q_UNUSED(checked);
bool currentState = settingEnabled(SettingsKey::cameraStatus);
setCameraState(!currentState);
settingsView_.setCameraState(!currentState);
emit updateVideoSettings();
}
void CallWindow::on_about_clicked()
{
about_.show();
}
void CallWindow::changedSIPText(const QString &text)
{
Q_UNUSED(text);
ui_->sipAddress->setText("sip:" + ui_->username->text() + "@" + ui_->address->text());
}
void CallWindow::showICEFailedMessage()
{
mesg_.showError("Error: ICE Failed",
"ICE did not succeed to find a connection. "
"You may try again. If the issue persists, "
"please report the issue to Github if you are connected to the internet "
"and describe your network setup.");
}
void CallWindow::showCryptoMissingMessage()
{
mesg_.showWarning("Warning: Encryption not possible",
"Crypto++ has not been included in both Kvazzup and uvgRTP.");
}
void CallWindow::showZRTPFailedMessage(QString sessionID)
{
mesg_.showError("Error: ZRTP handshake has failed for session " + sessionID,
"Could not exchange encryption keys.");
}
|
#include <Asynchrony.h>
#ifndef NULL
#define NULL 0
#endif
namespace Asynchrony {
void Asynchrony::loop() {
bool destructFlag = false;
ForwardList<ListenerItem>::Iterator itPrev = listeners.beforeBegin(),
itNext = itPrev;
++itNext;
while(true) {
if(itNext == NULL) {
break;
} else {
if((*itNext).listener->check(&destructFlag))
(*itNext).callback();
if(destructFlag) {
delete (*itNext).listener;
itPrev.eraseAfter();
destructFlag = false;
itNext = itPrev;
} else {
itPrev = itNext;
}
++itNext;
}
}
}
identificator Asynchrony::add(Listener* listener, void (*callback)(), int priority) {
ListenerItem item;
item.listener = listener;
item.callback = callback;
item.priority = priority;
item.id = getIdentificator();
ForwardList<ListenerItem>::Iterator itPrev = listeners.beforeBegin(),
itNext = itPrev;
++itNext;
while(true) {
if(itNext == NULL || priority > (*itNext).priority) {
itPrev.insertAfter(item);
break;
} else {
itPrev = itNext;
++itNext;
}
}
return item.id;
}
void Asynchrony::remove(identificator id, bool deleteListener) {
ForwardList<ListenerItem>::Iterator itPrev = listeners.beforeBegin(),
itNext = itPrev;
++itNext;
while(true) {
if(itNext == NULL) {
break;
} else if(id == (*itNext).id) {
if(deleteListener)
delete (*itNext).listener;
itPrev.eraseAfter();
break;
} {
itPrev = itNext;
++itNext;
}
}
}
identificator Asynchrony::getIdentificator() {
return ++lastIdentificator;
}
#if defined(ARDUINO)
identificator Asynchrony::click(void (*callback)(), int pin, bool eventState, char mode, unsigned long bounce) {
return add(new Click(pin, eventState, mode, bounce), callback);
}
identificator Asynchrony::interval(void (*callback)(), unsigned long time, char timeUnit) {
return add(new Interval(time, timeUnit), callback);
}
identificator Asynchrony::timeout(void (*callback)(), unsigned long time, char timeUnit) {
return add(new Timeout(time, timeUnit), callback);
}
#endif
}
Asynchrony::Asynchrony Asyn;
Awfull bug fix
#include <Asynchrony.h>
#ifndef NULL
#define NULL 0
#endif
namespace Asynchrony {
void Asynchrony::loop() {
bool destructFlag = false;
ForwardList<ListenerItem>::Iterator itPrev = listeners.beforeBegin(),
itNext = itPrev;
++itNext;
while(true) {
if(itNext == NULL) {
break;
} else {
if((*itNext).listener->check(&destructFlag))
(*itNext).callback();
if(destructFlag) {
delete (*itNext).listener;
itPrev.eraseAfter();
destructFlag = false;
itNext = itPrev;
} else {
itPrev = itNext;
}
++itNext;
}
}
}
identificator Asynchrony::add(Listener* listener, void (*callback)(), int priority) {
ListenerItem item;
item.listener = listener;
item.callback = callback;
item.priority = priority;
item.id = getIdentificator();
ForwardList<ListenerItem>::Iterator itPrev = listeners.beforeBegin(),
itNext = itPrev;
++itNext;
while(true) {
if(itNext == NULL || priority > (*itNext).priority) {
itPrev.insertAfter(item);
break;
} else {
itPrev = itNext;
++itNext;
}
}
return item.id;
}
void Asynchrony::remove(identificator id, bool deleteListener) {
ForwardList<ListenerItem>::Iterator itPrev = listeners.beforeBegin(),
itNext = itPrev;
++itNext;
while(true) {
if(itNext == NULL) {
break;
} else if(id == (*itNext).id) {
if(deleteListener)
delete (*itNext).listener;
itPrev.eraseAfter();
break;
} else {
itPrev = itNext;
++itNext;
}
}
}
identificator Asynchrony::getIdentificator() {
return ++lastIdentificator;
}
#if defined(ARDUINO)
identificator Asynchrony::click(void (*callback)(), int pin, bool eventState, char mode, unsigned long bounce) {
return add(new Click(pin, eventState, mode, bounce), callback);
}
identificator Asynchrony::interval(void (*callback)(), unsigned long time, char timeUnit) {
return add(new Interval(time, timeUnit), callback);
}
identificator Asynchrony::timeout(void (*callback)(), unsigned long time, char timeUnit) {
return add(new Timeout(time, timeUnit), callback);
}
#endif
}
Asynchrony::Asynchrony Asyn; |
/*
* Copyright (C) 2015 midnightBITS
*
* 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 "pch.h"
#include <assert.h>
#include <cctype>
#include <languages.hpp>
#include <streams.hpp>
#include <strings.hpp>
namespace locale {
std::string warp(const std::string& s)
{
auto w = utf::widen(s);
for (auto& c : w) {
switch (c) {
case L'a': c = 0x0227; break; // 'ȧ'
case L'b': c = 0x018b; break; // 'Ƌ'
case L'c': c = 0x00e7; break; // 'ç'
case L'd': c = 0x0111; break; // 'đ'
case L'e': c = 0x00ea; break; // 'ê'
case L'f': c = 0x0192; break; // 'ƒ'
case L'g': c = 0x011f; break; // 'ğ'
case L'h': c = 0x0125; break; // 'ĥ'
case L'i': c = 0x00ef; break; // 'ï'
case L'j': c = 0x0135; break; // 'ĵ'
case L'k': c = 0x0137; break; // 'ķ'
case L'l': c = 0x013a; break; // 'ĺ'
case L'n': c = 0x00f1; break; // 'ñ'
case L'o': c = 0x00f4; break; // 'ô'
case L'r': c = 0x0213; break; // 'ȓ'
case L's': c = 0x015f; break; // 'ş'
case L't': c = 0x0167; break; // 'ŧ'
case L'u': c = 0x0169; break; // 'ũ'
case L'w': c = 0x0175; break; // 'ŵ'
case L'y': c = 0x00ff; break; // 'ÿ'
case L'z': c = 0x0225; break; // 'ȥ'
case L'A': c = 0x00c4; break; // 'Ä'
case L'B': c = 0x00df; break; // 'ß'
case L'C': c = 0x00c7; break; // 'Ç'
case L'D': c = 0x00d0; break; // 'Ð'
case L'E': c = 0x0204; break; // 'Ȅ'
case L'F': c = 0x0191; break; // 'Ƒ'
case L'G': c = 0x0120; break; // 'Ġ'
case L'H': c = 0x0126; break; // 'Ħ'
case L'I': c = 0x00cd; break; // 'Í'
case L'J': c = 0x0134; break; // 'Ĵ'
case L'K': c = 0x0136; break; // 'Ķ'
case L'L': c = 0x023d; break; // 'Ƚ'
case L'N': c = 0x00d1; break; // 'Ñ'
case L'O': c = 0x00d6; break; // 'Ö'
case L'R': c = 0x0154; break; // 'Ŕ'
case L'S': c = 0x015e; break; // 'Ş'
case L'T': c = 0x023e; break; // 'Ⱦ'
case L'U': c = 0x00d9; break; // 'Ù'
case L'W': c = 0x0174; break; // 'Ŵ'
case L'Y': c = 0x00dd; break; // 'Ý'
case L'Z': c = 0x0224; break; // 'Ȥ'
case L'"': c = L'?'; break; // '?'
};
}
return utf::narrowed(w);
}
std::vector<string> translations(const std::map<std::string, std::string>& gtt, const std::vector<locale::String>& strings, bool warp_missing, bool verbose)
{
std::vector<string> out;
out.reserve(gtt.empty() ? 0 : gtt.size() - 1);
for (auto& str : strings) {
auto it = gtt.find(str.key);
if (it == gtt.end()) {
if (verbose)
printf("warning: translation for `%s' missing.\n", str.key.c_str());
if (warp_missing)
out.emplace_back(str.id, warp(str.value));
continue;
}
out.emplace_back(str.id, it->second);
}
return std::move(out);
}
std::map<std::string, std::string> attrGTT(const std::string& attrs)
{
std::map<std::string, std::string> out;
auto c = std::begin(attrs);
auto e = std::end(attrs);
while (c != e) {
while (c != e && std::isspace((uint8_t)*c)) ++c;
auto s_name = c;
while (c != e && !std::isspace((uint8_t)*c)) {
if (*c == ':')
break;
++c;
}
auto name = std::string{ s_name, c };
while (c != e && std::isspace((uint8_t)*c)) ++c;
if (c == e || *c != ':')
continue;
++c;
while (c != e && std::isspace((uint8_t)*c) && *c != '\n') ++c;
auto s_value = c;
while (c != e && *c != '\n') ++c;
if (c != e) ++c;
auto e_value = c;
while (s_value != e_value && std::isspace((uint8_t)e_value[-1])) --e_value;
out[name] = { s_value, e_value };
}
return out;
}
std::vector<string> attributes(const std::map<std::string, std::string>& gtt)
{
std::vector<string> props;
auto it = gtt.find("");
auto attrs = attrGTT(it == gtt.end() ? std::string{ } : it->second);
props.push_back({ ATTR_CULTURE, attrs["Language"] });
auto attr = attrs.find("Plural-Forms");
if (attr != attrs.end())
props.push_back({ ATTR_PLURALS, attr->second });
// TODO: ATTR_LANGUAGE
return std::move(props);
}
char nextc(locale::instream& is)
{
char c;
is.read(&c, 1);
return c;
}
bool ll_code(locale::instream& is, std::string& code, std::string& name, const std::string& fname, bool ret)
{
code.clear();
name.clear();
while (!is.eof() && std::isspace((uint8_t)is.peek()))
nextc(is);
if (is.eof())
return false;
while (!is.eof() && !std::isspace((uint8_t)is.peek()))
code.push_back(nextc(is));
while (!is.eof() && std::isspace((uint8_t)is.peek())) {
auto c = nextc(is);
if (c == '\n') {
fprintf(stderr, "error: `%s' does not contain name in %s\n", code.c_str(), fname.c_str());
ret = false;
return false;
}
}
while (!is.eof() && is.peek() != '\n')
name.push_back(nextc(is));
if (!is.eof())
nextc(is);
auto len = name.length();
while (len > 0 && std::isspace((uint8_t)name[len - 1]))
--len;
if (len != name.length())
name = name.substr(0, len);
return true;
}
bool ll_CC(const fs::path& in, std::map<std::string, std::string>& langs)
{
auto inname = in;
inname.make_preferred();
std::unique_ptr<FILE, decltype(&fclose)> inf{ fs::fopen(in, "rb"), fclose };
if (!inf) {
fprintf(stderr, "could not open `%s'", inname.string().c_str());
return false;
}
locale::finstream is{ inf.get() };
std::string code, name;
bool ret = true;
while (ll_code(is, code, name, inname.string(), ret) && ret)
langs[code] = name;
return ret;
}
#define WRITE(os, I) if (!os.write(I)) return -1;
#define WRITESTR(os, S) if (os.write(S) != (S).length()) return -1;
#define CARRY(ex) do { auto ret = (ex); if (ret) return ret; } while (0)
namespace {
int header(locale::outstream& os, uint32_t& next_offset, std::vector<string>& block)
{
if (block.empty())
return 0;
WRITE(os, (uint32_t)block.size());
WRITE(os, next_offset);
next_offset += (uint32_t)(sizeof(string_key) * block.size());
return 0;
}
void update_offsets(uint32_t& next_offset, std::vector<string>& block)
{
for (auto& str : block) {
str.key.offset = next_offset;
next_offset += str.key.length;
++next_offset;
}
}
int list(locale::outstream& os, std::vector<string>& block)
{
if (block.empty())
return 0;
for (auto& str : block)
WRITE(os, str.key);
return 0;
}
int data(locale::outstream& os, std::vector<string>& block)
{
if (block.empty())
return 0;
for (auto& str : block) {
WRITESTR(os, str.value);
WRITE(os, '\0');
}
return 0;
}
int section(locale::outstream& os, uint32_t section_id, std::vector<string>& block)
{
if (block.empty())
return 0;
uint32_t key_size = sizeof(string_key) / sizeof(uint32_t);
key_size *= (uint32_t)block.size();
string_header hdr;
hdr.id = section_id;
hdr.string_offset = key_size + sizeof(string_header) / sizeof(uint32_t);
hdr.ints = hdr.string_offset - sizeof(section_header) / sizeof(uint32_t);
hdr.string_count = (uint32_t)block.size();
uint32_t offset = 0;
update_offsets(offset, block);
uint32_t padding = (((offset + 3) >> 2) << 2) - offset;
offset += padding;
offset /= sizeof(uint32_t);
hdr.ints += offset;
WRITE(os, hdr);
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
CARRY(list(os, block));
CARRY(data(os, block));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
while (padding--) {
WRITE(os, '\0');
}
return 0;
}
}
int file::write(locale::outstream& os)
{
constexpr uint32_t header_size = 3 * sizeof(uint32_t);
file_header hdr;
hdr.id = hdrtext_tag;
hdr.ints = (sizeof(file_header) - sizeof(section_header)) / sizeof(uint32_t);
hdr.version = v1_0::version;
hdr.serial = serial;
WRITE(os, langtext_tag);
WRITE(os, hdr);
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
CARRY(section(os, attrtext_tag, attrs));
CARRY(section(os, strstext_tag, strings));
CARRY(section(os, keystext_tag, keys));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
WRITE(os, lasttext_tag);
WRITE(os, (size_t)0);
return 0;
}
#undef WRITE
#undef WRITESTR
#undef CARRY
}
Switching fomr GNU ll_CC to ISO ll-CC
/*
* Copyright (C) 2015 midnightBITS
*
* 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 "pch.h"
#include <assert.h>
#include <cctype>
#include <languages.hpp>
#include <streams.hpp>
#include <strings.hpp>
namespace locale {
std::string warp(const std::string& s)
{
auto w = utf::widen(s);
for (auto& c : w) {
switch (c) {
case L'a': c = 0x0227; break; // 'ȧ'
case L'b': c = 0x018b; break; // 'Ƌ'
case L'c': c = 0x00e7; break; // 'ç'
case L'd': c = 0x0111; break; // 'đ'
case L'e': c = 0x00ea; break; // 'ê'
case L'f': c = 0x0192; break; // 'ƒ'
case L'g': c = 0x011f; break; // 'ğ'
case L'h': c = 0x0125; break; // 'ĥ'
case L'i': c = 0x00ef; break; // 'ï'
case L'j': c = 0x0135; break; // 'ĵ'
case L'k': c = 0x0137; break; // 'ķ'
case L'l': c = 0x013a; break; // 'ĺ'
case L'n': c = 0x00f1; break; // 'ñ'
case L'o': c = 0x00f4; break; // 'ô'
case L'r': c = 0x0213; break; // 'ȓ'
case L's': c = 0x015f; break; // 'ş'
case L't': c = 0x0167; break; // 'ŧ'
case L'u': c = 0x0169; break; // 'ũ'
case L'w': c = 0x0175; break; // 'ŵ'
case L'y': c = 0x00ff; break; // 'ÿ'
case L'z': c = 0x0225; break; // 'ȥ'
case L'A': c = 0x00c4; break; // 'Ä'
case L'B': c = 0x00df; break; // 'ß'
case L'C': c = 0x00c7; break; // 'Ç'
case L'D': c = 0x00d0; break; // 'Ð'
case L'E': c = 0x0204; break; // 'Ȅ'
case L'F': c = 0x0191; break; // 'Ƒ'
case L'G': c = 0x0120; break; // 'Ġ'
case L'H': c = 0x0126; break; // 'Ħ'
case L'I': c = 0x00cd; break; // 'Í'
case L'J': c = 0x0134; break; // 'Ĵ'
case L'K': c = 0x0136; break; // 'Ķ'
case L'L': c = 0x023d; break; // 'Ƚ'
case L'N': c = 0x00d1; break; // 'Ñ'
case L'O': c = 0x00d6; break; // 'Ö'
case L'R': c = 0x0154; break; // 'Ŕ'
case L'S': c = 0x015e; break; // 'Ş'
case L'T': c = 0x023e; break; // 'Ⱦ'
case L'U': c = 0x00d9; break; // 'Ù'
case L'W': c = 0x0174; break; // 'Ŵ'
case L'Y': c = 0x00dd; break; // 'Ý'
case L'Z': c = 0x0224; break; // 'Ȥ'
case L'"': c = L'?'; break; // '?'
};
}
return utf::narrowed(w);
}
std::vector<string> translations(const std::map<std::string, std::string>& gtt, const std::vector<locale::String>& strings, bool warp_missing, bool verbose)
{
std::vector<string> out;
out.reserve(gtt.empty() ? 0 : gtt.size() - 1);
for (auto& str : strings) {
auto it = gtt.find(str.key);
if (it == gtt.end()) {
if (verbose)
printf("warning: translation for `%s' missing.\n", str.key.c_str());
if (warp_missing)
out.emplace_back(str.id, warp(str.value));
continue;
}
out.emplace_back(str.id, it->second);
}
return std::move(out);
}
std::map<std::string, std::string> attrGTT(const std::string& attrs)
{
std::map<std::string, std::string> out;
auto c = std::begin(attrs);
auto e = std::end(attrs);
while (c != e) {
while (c != e && std::isspace((uint8_t)*c)) ++c;
auto s_name = c;
while (c != e && !std::isspace((uint8_t)*c)) {
if (*c == ':')
break;
++c;
}
auto name = std::string{ s_name, c };
while (c != e && std::isspace((uint8_t)*c)) ++c;
if (c == e || *c != ':')
continue;
++c;
while (c != e && std::isspace((uint8_t)*c) && *c != '\n') ++c;
auto s_value = c;
while (c != e && *c != '\n') ++c;
if (c != e) ++c;
auto e_value = c;
while (s_value != e_value && std::isspace((uint8_t)e_value[-1])) --e_value;
out[name] = { s_value, e_value };
}
return out;
}
static std::string gnu2iso(std::string s)
{
size_t i = 0;
for (auto& c : s) {
if (c == '_') {
c = '.';
} else if (c == '.') { // ll_CC.code?
s = s.substr(0, i);
break;
}
++i;
}
return s;
}
std::vector<string> attributes(const std::map<std::string, std::string>& gtt)
{
std::vector<string> props;
auto it = gtt.find("");
auto attrs = attrGTT(it == gtt.end() ? std::string{ } : it->second);
props.push_back({ ATTR_CULTURE, gnu2iso(attrs["Language"]) });
auto attr = attrs.find("Plural-Forms");
if (attr != attrs.end())
props.push_back({ ATTR_PLURALS, attr->second });
// TODO: ATTR_LANGUAGE
return std::move(props);
}
char nextc(locale::instream& is)
{
char c;
is.read(&c, 1);
return c;
}
bool ll_code(locale::instream& is, std::string& code, std::string& name, const std::string& fname, bool ret)
{
code.clear();
name.clear();
while (!is.eof() && std::isspace((uint8_t)is.peek()))
nextc(is);
if (is.eof())
return false;
while (!is.eof() && !std::isspace((uint8_t)is.peek()))
code.push_back(nextc(is));
while (!is.eof() && std::isspace((uint8_t)is.peek())) {
auto c = nextc(is);
if (c == '\n') {
fprintf(stderr, "error: `%s' does not contain name in %s\n", code.c_str(), fname.c_str());
ret = false;
return false;
}
}
while (!is.eof() && is.peek() != '\n')
name.push_back(nextc(is));
if (!is.eof())
nextc(is);
auto len = name.length();
while (len > 0 && std::isspace((uint8_t)name[len - 1]))
--len;
if (len != name.length())
name = name.substr(0, len);
return true;
}
bool ll_CC(const fs::path& in, std::map<std::string, std::string>& langs)
{
auto inname = in;
inname.make_preferred();
std::unique_ptr<FILE, decltype(&fclose)> inf{ fs::fopen(in, "rb"), fclose };
if (!inf) {
fprintf(stderr, "could not open `%s'", inname.string().c_str());
return false;
}
locale::finstream is{ inf.get() };
std::string code, name;
bool ret = true;
while (ll_code(is, code, name, inname.string(), ret) && ret)
langs[code] = name;
return ret;
}
#define WRITE(os, I) if (!os.write(I)) return -1;
#define WRITESTR(os, S) if (os.write(S) != (S).length()) return -1;
#define CARRY(ex) do { auto ret = (ex); if (ret) return ret; } while (0)
namespace {
int header(locale::outstream& os, uint32_t& next_offset, std::vector<string>& block)
{
if (block.empty())
return 0;
WRITE(os, (uint32_t)block.size());
WRITE(os, next_offset);
next_offset += (uint32_t)(sizeof(string_key) * block.size());
return 0;
}
void update_offsets(uint32_t& next_offset, std::vector<string>& block)
{
for (auto& str : block) {
str.key.offset = next_offset;
next_offset += str.key.length;
++next_offset;
}
}
int list(locale::outstream& os, std::vector<string>& block)
{
if (block.empty())
return 0;
for (auto& str : block)
WRITE(os, str.key);
return 0;
}
int data(locale::outstream& os, std::vector<string>& block)
{
if (block.empty())
return 0;
for (auto& str : block) {
WRITESTR(os, str.value);
WRITE(os, '\0');
}
return 0;
}
int section(locale::outstream& os, uint32_t section_id, std::vector<string>& block)
{
if (block.empty())
return 0;
uint32_t key_size = sizeof(string_key) / sizeof(uint32_t);
key_size *= (uint32_t)block.size();
string_header hdr;
hdr.id = section_id;
hdr.string_offset = key_size + sizeof(string_header) / sizeof(uint32_t);
hdr.ints = hdr.string_offset - sizeof(section_header) / sizeof(uint32_t);
hdr.string_count = (uint32_t)block.size();
uint32_t offset = 0;
update_offsets(offset, block);
uint32_t padding = (((offset + 3) >> 2) << 2) - offset;
offset += padding;
offset /= sizeof(uint32_t);
hdr.ints += offset;
WRITE(os, hdr);
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
CARRY(list(os, block));
CARRY(data(os, block));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
while (padding--) {
WRITE(os, '\0');
}
return 0;
}
}
int file::write(locale::outstream& os)
{
constexpr uint32_t header_size = 3 * sizeof(uint32_t);
file_header hdr;
hdr.id = hdrtext_tag;
hdr.ints = (sizeof(file_header) - sizeof(section_header)) / sizeof(uint32_t);
hdr.version = v1_0::version;
hdr.serial = serial;
WRITE(os, langtext_tag);
WRITE(os, hdr);
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
CARRY(section(os, attrtext_tag, attrs));
CARRY(section(os, strstext_tag, strings));
CARRY(section(os, keystext_tag, keys));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
WRITE(os, lasttext_tag);
WRITE(os, (size_t)0);
return 0;
}
#undef WRITE
#undef WRITESTR
#undef CARRY
}
|
/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors:
* Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for
* (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* (1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <cstddef> // for offsetof()
#include <exception>
#include <map>
#include <set>
#include <boost/filesystem.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <json/value.h>
#ifdef WITHMPI
#include <mpi.h>
#include "data/RestartData.h" // for defining MPI typemap...
#include "inc/tbc_mpi_constants.h"
#endif
// For managing the floating point environment
#ifdef BSD_FPE
#include <xmmintrin.h> // BSD (OSX)
#endif
#ifdef GNU_FPE
#include <fenv.h> // GNU Linux
#endif
#include "inc/timeconst.h"
#include "../include/ArgHandler.h"
#include "TEMLogger.h"
#include "TEMUtilityFunctions.h"
#include "../include/Runner.h"
#include <netcdf.h>
/** Quick 'n dirty pretty printer for vector of things
*/
template <typename TYPE>
void ppv(const std::vector<TYPE> &v){
typename std::vector<TYPE>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
}
// draft pretty-printers...
void pp_2dvec(const std::vector<std::vector<int> > & vv);
// draft - generate a netcdf file that can follow CF conventions
void create_new_output();
// draft - reading new-style co2 file
std::vector<float> read_new_co2_file(const std::string &filename);
// draft - reading in a 2D run mask...
std::vector< std::vector<int> > read_run_mask(const std::string &filename);
/** Enables a 'floating point exception' mask that will make the program crash
* when a floating point number is generated (and or operated upon).
*
* Some more info
* http://www.johndcook.com/blog/ieee_exceptions_in_cpp/
* http://stackoverflow.com/questions/247053/enabling-floating-point-interrupts-on-mac-os-x-intel
*
* It might be helpful to add a singal handler at some point that could report
* on what/where the exception is generated?
*/
void enable_floating_point_exceptions() {
std::cout << "Enabling floating point exceptions mask!" << std::endl;
// BSD (OSX)
#ifdef BSD_FPE
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID);
#endif
// GNU Linux
#ifdef GNU_FPE
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
}
ArgHandler* args = new ArgHandler();
extern src::severity_logger< severity_level > glg;
int main(int argc, char* argv[]){
// Read in and parse the command line arguments
args->parse(argc, argv);
if (args->get_help()) {
args->show_help();
return 0;
}
std::cout << "Setting up logging...\n";
setup_logging(args->get_log_level(), args->get_log_scope());
BOOST_LOG_SEV(glg, note) << "Checking command line arguments...";
args->verify(); // stub - doesn't really do anything yet
BOOST_LOG_SEV(glg, note) << "Turn floating point exceptions on?: " << args->get_fpe();
if (args->get_fpe()) { enable_floating_point_exceptions(); }
BOOST_LOG_SEV(glg, note) << "Reading controlfile into main(..) scope...";
Json::Value controldata = temutil::parse_control_file(args->get_ctrl_file());
BOOST_LOG_SEV(glg, note) << "Creating a ModelData object based on settings in the control file";
ModelData modeldata(controldata);
BOOST_LOG_SEV(glg, note) << "Update model settings based on command line flags/options...";
modeldata.update(args);
/*
Someday it may be worth the time/effort to make better use of
boots::program_options here to manage the arguments from config file
and the command line.
*/
BOOST_LOG_SEV(glg, note) << "Running PR stage: " << modeldata.pr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running EQ stage: " << modeldata.eq_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SP stage: " << modeldata.sp_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running TR stage: " << modeldata.tr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SC stage: " << modeldata.sc_yrs << "yrs";
// Turn off buffering...
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Create empty output files now so that later, as the program
// proceeds, there is somewhere to append output data...
// ??? Maybe the type/shape of outputs that we create can, or should, depend on
// ??? some of the settings in the ModelData object?
BOOST_LOG_SEV(glg, info) << "Creating a fresh 'n clean NEW output file...";
create_new_output();
time_t stime;
time_t etime;
stime = time(0);
BOOST_LOG_SEV(glg, note) << "Start dvmdostem @ " << ctime(&stime);
BOOST_LOG_SEV(glg, debug) << "NEW STYLE: Going to run space-major over a 2D area covered by run mask...";
// Open the run mask (spatial mask)
std::vector< std::vector<int> > run_mask = read_run_mask(modeldata.runmask_file);
if (args->get_loop_order() == "space-major") {
// y <==> row <==> lat
// x <==> col <==> lon
/*
Loop over a 2D grid of 'cells' (cohorts?),
run each cell for some number of years.
Processing starts in the lower left corner (0,0).
Should really look into replacing this loop with
something like python's map(...) function...
--> Could this allow us to use a map reduce strategy??
Look into std::transform.
*/
// Use a few type definitions to save some typing.
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
vec2D::const_iterator row;
vec::const_iterator col;
for (row = run_mask.begin(); row != run_mask.end() ; ++row) {
for (col = row->begin(); col != row->end(); ++col) {
bool mask_value = *col;
int rowidx = row - run_mask.begin();
int colidx = col - row->begin();
if (true == mask_value) {
BOOST_LOG_SEV(glg, note) << "Running cell (" << rowidx << ", " << colidx << ")";
//modeldata.initmode = 1; // OBSOLETE?
BOOST_LOG_SEV(glg, info) << "Setup the NEW STYLE RUNNER OBJECT ...";
Runner runner(modeldata, args->get_cal_mode(), rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << runner.cohort.ground.layer_report_string("depth thermal");
// seg fault w/o preparing climate...so prepare year zero...
// this is also called inside run_years(...)
runner.cohort.climate.prepare_daily_driving_data(0, "eq");
runner.cohort.initialize_internal_pointers(); // sets up lots of pointers to various things
runner.cohort.initialize_state_parameters(); // sets data based on values in cohortlookup
BOOST_LOG_SEV(glg, debug) << "right after initialize_internal_pointers() and initialize_state_parameters()"
<< runner.cohort.ground.layer_report_string("depth ptr");
// PRE RUN STAGE (PR)
if (modeldata.pr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("PRE-RUN");
/** Env-only "pre-run" stage.
- should use only the env module
- number of years to run can be controlled on cmd line
- use fixed climate that is averaged over first X years
- use static (fixed) co2 value (first element of co2 file)
- FIX: need to set yrs since dsb ?
- FIX: should ignore calibration directives?
*/
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// turn off everything but env
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_bgcmodule(false);
runner.cohort.md->set_nfeed(false);
runner.cohort.md->set_avlnflg(false);
runner.cohort.md->set_baseline(false);
runner.cohort.md->set_dsbmodule(false);
runner.cohort.md->set_dslmodule(false);
runner.cohort.md->set_dvmmodule(false);
BOOST_LOG_SEV(glg, debug) << "Ground, right before 'pre-run'. "
<< runner.cohort.ground.layer_report_string("depth thermal");
runner.run_years(0, modeldata.pr_yrs, "pre-run"); // climate is prepared w/in here.
BOOST_LOG_SEV(glg, debug) << "Ground, right after 'pre-run'"
<< runner.cohort.ground.layer_report_string("depth thermal");
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("pr");
}
}
// EQULIBRIUM STAGE (EQ)
if (modeldata.eq_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("EQ");
BOOST_LOG_SEV(glg, fatal) << "Running Equlibrium, " << modeldata.sp_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_dvmmodule(true);
runner.cohort.md->set_bgcmodule(true);
runner.cohort.md->set_dslmodule(true);
runner.cohort.md->set_nfeed(true);
runner.cohort.md->set_avlnflg(true);
runner.cohort.md->set_baseline(true);
runner.cohort.md->set_dsbmodule(false);
if (runner.cohort.md->get_dsbmodule()) {
// The transition to SP must occur at the completion of a
// fire cycle (i.e. a year or two prior to the next fire).
// To ensure this, re-set modeldata's EQ year count to an
// even multiple of the FRI minus 2 (to be safe)
int fri = runner.cohort.fire.getFRI();
int EQ_fire_cycles = modeldata.eq_yrs / fri;
if (modeldata.eq_yrs%fri != 0) {
modeldata.eq_yrs = fri * (EQ_fire_cycles + 1) - 2;
}
}
// Run model
// Check for the existence of a restart file to output to
// prior to running.
std::string restart_fname = modeldata.output_dir + "restart-eq.nc";
if( !boost::filesystem::exists(restart_fname) ) {
BOOST_LOG_SEV(glg, fatal) << "Restart file " << restart_fname
<< " does not exist";
return 1;
}
runner.run_years(0, modeldata.eq_yrs, "eq-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData post EQ";
runner.cohort.restartdata.restartdata_to_log();
// Write out EQ restart file
runner.cohort.restartdata.append_to_ncfile(restart_fname, rowidx, colidx); /* cohort id/key ???*/
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("eq");
}
}
// SPINUP STAGE (SP)
if (modeldata.sp_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SP");
BOOST_LOG_SEV(glg, fatal) << "Running Spinup, " << modeldata.sp_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// Check for the existence of a restart file to output to
// prior to running.
std::string restart_fname = modeldata.output_dir + "restart-sp.nc";
if(!boost::filesystem::exists(restart_fname)){
BOOST_LOG_SEV(glg, fatal) << "Restart file " << restart_fname
<< " does not exist";
return 1;
}
runner.cohort.climate.monthlycontainers2log();
// FIX: if restart file has -9999, then soil temps can end up impossibly low
// look for and read in restart-eq.nc (if it exists)
// should check for valid values prior to actual use
std::string eq_restart_fname = modeldata.output_dir + "restart-eq.nc";
if (boost::filesystem::exists(eq_restart_fname)) {
BOOST_LOG_SEV(glg, debug) << "Loading data from the restart file for spinup";
// update the cohort's restart data object
runner.cohort.restartdata.update_from_ncfile(eq_restart_fname, rowidx, colidx);
runner.cohort.restartdata.verify_logical_values();
// The above may be a bad idea. Separating reading
// and validation will confuse things when variables
// are added in the future - possibility for a disconnect.
BOOST_LOG_SEV(glg, debug) << "RestartData pre SP";
runner.cohort.restartdata.restartdata_to_log();
// copy values from the (updated) restart data to cohort
// and cd. this should overwrite some things that were
// previously just set in initialize_state_parameters(...)
runner.cohort.set_state_from_restartdata();
// run model
runner.run_years(0, modeldata.sp_yrs, "sp-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SP";
runner.cohort.restartdata.restartdata_to_log();
// Save status to spinup restart file
runner.cohort.restartdata.append_to_ncfile(restart_fname, rowidx, colidx);
if(runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sp");
}
} else {
BOOST_LOG_SEV(glg, err) << "No restart file from EQ.";
}
}
// TRANSIENT STAGE (TR)
if (modeldata.tr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("TR");
BOOST_LOG_SEV(glg, fatal) << "Running Transient, " << modeldata.tr_yrs << " years";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// Check for the existence of a restart file to output to
// prior to running.
std::string restart_fname = modeldata.output_dir + "restart-tr.nc";
if(!boost::filesystem::exists(restart_fname)){
BOOST_LOG_SEV(glg, fatal) << "Restart file " << restart_fname
<< " does not exist.";
return 1;
}
std::string sp_restart_fname = modeldata.output_dir + "restart-sp.nc";
if (boost::filesystem::exists(sp_restart_fname)) {
BOOST_LOG_SEV(glg, debug) << "Loading data from the restart file for transient";
// Update the cohort's restart data object
runner.cohort.restartdata.update_from_ncfile(sp_restart_fname, rowidx, colidx);
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre TR";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort
// and cd.
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.tr_yrs, "tr-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post TR";
runner.cohort.restartdata.restartdata_to_log();
// Save status to transient restart file
runner.cohort.restartdata.append_to_ncfile(restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("tr");
}
} else {
BOOST_LOG_SEV(glg, fatal) << "No restart file from SP.";
}
}
// SCENARIO STAGE (SC)
if (modeldata.sc_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SC");
BOOST_LOG_SEV(glg, fatal) << "Running Scenario, " << modeldata.sc_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// Check for the existence of a restart file to output to
// prior to running.
std::string restart_fname = modeldata.output_dir + "restart-sc.nc";
if (!boost::filesystem::exists(restart_fname)) {
BOOST_LOG_SEV(glg, fatal) << "Restart file " << restart_fname
<< " does not exist.";
return 1;
}
std::string tr_restart_fname = modeldata.output_dir
+ "restart-tr.nc";
if (boost::filesystem::exists(tr_restart_fname)) {
BOOST_LOG_SEV(glg, debug) << "Loading data from the transient restart file for a scenario run";
// Update the cohort's restart data object
runner.cohort.restartdata.update_from_ncfile(tr_restart_fname, rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << "RestartData pre SC";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort
// and cd.
runner.cohort.set_state_from_restartdata();
// Loading projected data instead of historic. FIX?
runner.cohort.load_proj_climate(modeldata.proj_climate_file);
// Run model
runner.run_years(0, modeldata.sc_yrs, "sc-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SC";
runner.cohort.restartdata.restartdata_to_log();
// Save status to scenario restart file
// This may be unnecessary, but will provide a possibly
// interesting snapshot of the data structure
// following a scenario run.
runner.cohort.restartdata.append_to_ncfile(restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sc");
}
} else { // No TR restart file
BOOST_LOG_SEV(glg, fatal) << "No restart file from TR.";
}
}
// NOTE: Could have an option to set some time constants based on
// some sizes/dimensions of the input driving data...
/**
eq
- create the climate from the average of the first X years
of the driving climate data.
SIZE: 12 months, 1 year
- set to default module settings to: ??
- run_years( 0 <= iy < MAX_EQ_YEAR )
- act on calibration directives
-
sp
- create the climate from the first X years of the driving
climate dataset.
SIZE: 12 months, X years
- set to default module settings: ??
- run_years( SP_BEG <= iy <= SP_END )
tr
- create climate by loading the driving climate data (historic)
SIZE: 12 months, length of driving dataset? OR number from inc/timeconst.h
- set to default module settings: ??
- run_years( TR_BEG <= iy <= TR_END )
*/
} else {
BOOST_LOG_SEV(glg, debug) << "Skipping cell (" << rowidx << ", " << colidx << ")";
}
}
}
} else if(args->get_loop_order() == "time-major") {
BOOST_LOG_SEV(glg, warn) << "DO NOTHING. NOT IMPLEMENTED YET.";
// for each year
// Read in Climate - all locations, one year/timestep
// Read in Vegetation - all locations
// Read in Drainage - all locations
// Read in Fire - all locations
// for each cohort
// updateMonthly(...)
}
BOOST_LOG_SEV(glg, note) << "DONE WITH NEW STYLE run (" << args->get_loop_order() << ")";
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Total Seconds: " << difftime(etime, stime);
return 0;
} /* End main() */
/** Pretty print a 2D vector of ints */
void pp_2dvec(const std::vector<std::vector<int> > & vv) {
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
for (vec2D::const_iterator row = vv.begin(); row != vv.end(); ++row) {
for (vec::const_iterator col = row->begin(); col != row->end(); ++col) {
std::cout << *col << " ";
}
std::cout << std::endl;
}
}
/** rough draft for reading a run-mask (2D vector of ints)
*/
std::vector< std::vector<int> > read_run_mask(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yD, xD;
size_t yD_len, xD_len;
temutil::nc( nc_inq_dimid(ncid, "Y", &yD) );
temutil::nc( nc_inq_dimlen(ncid, yD, &yD_len) );
temutil::nc( nc_inq_dimid(ncid, "X", &xD) );
temutil::nc( nc_inq_dimlen(ncid, xD, &xD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate a 2D run-mask vector (y,x). Size: (" << yD_len << ", " << xD_len << ")";
std::vector< std::vector<int> > run_mask(yD_len, std::vector<int>(xD_len));
BOOST_LOG_SEV(glg, debug) << "Read the run flag data from the file into the 2D vector...";
int runV;
temutil::nc( nc_inq_varid(ncid, "run", &runV) );
BOOST_LOG_SEV(glg, debug) << "Grab one row at a time";
BOOST_LOG_SEV(glg, debug) << "(need contiguous memory, and vector<vector> are not contiguous)";
std::vector< std::vector<int> >::iterator row;
for (row = run_mask.begin(); row != run_mask.end(); ++row) {
int rowidx = row - run_mask.begin();
// specify start indices for each dimension (y, x)
size_t start[2];
start[0] = rowidx; // Y
start[1] = 0; // X
// specify counts for each dimension
size_t count[2];
count[0] = 1; // one row
count[1] = xD_len; // all data
std::vector<int> rowdata(xD_len);
temutil::nc( nc_get_vara_int(ncid, runV, start, count, &rowdata[0] ) );
run_mask[rowidx] = rowdata;
}
temutil::nc( nc_close(ncid) );
//pp_2dvec(run_mask);
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return run_mask;
}
/** rough draft for reading new-style co2 data
*/
std::vector<float> read_new_co2_file(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yearD;
size_t yearD_len;
temutil::nc( nc_inq_dimid(ncid, "year", &yearD) );
temutil::nc( nc_inq_dimlen(ncid, yearD, &yearD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate vector big enough for " << yearD_len << " years of co2 data...";
std::vector<float> co2data(yearD_len);
BOOST_LOG_SEV(glg, debug) << "Read the co2 data from the file into the vector...";
int co2V;
temutil::nc( nc_inq_varid(ncid, "co2", &co2V) );
temutil::nc( nc_get_var(ncid, co2V, &co2data[0]) );
temutil::nc( nc_close(ncid) );
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return co2data;
}
/** rough draft for new output files
*/
void create_new_output() {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Creating dataset...";
temutil::nc( nc_create("general-outputs-monthly.nc", NC_CLOBBER, &ncid) );
int timeD; // unlimited dimension
int pftD;
int xD;
int yD;
/* Create Dimensions */
BOOST_LOG_SEV(glg, debug) << "Adding dimensions...";
temutil::nc( nc_def_dim(ncid, "time", NC_UNLIMITED, &timeD) );
temutil::nc( nc_def_dim(ncid, "pft", NUM_PFT, &pftD) );
temutil::nc( nc_def_dim(ncid, "y", 10, &yD) );
temutil::nc( nc_def_dim(ncid, "x", 10, &xD) );
/* Create Coordinate Variables?? */
/* Create Data Variables */
// 4D vars
BOOST_LOG_SEV(glg, debug) << "Adding 4D variables...";
int vartypeA_dimids[4];
vartypeA_dimids[0] = timeD;
vartypeA_dimids[1] = pftD;
vartypeA_dimids[2] = yD;
vartypeA_dimids[3] = xD;
int vegcV;
int veg_fractionV;
int growstartV;
temutil::nc( nc_def_var(ncid, "vegc", NC_DOUBLE, 4, vartypeA_dimids, &vegcV) );
temutil::nc( nc_def_var(ncid, "veg_fraction", NC_DOUBLE, 4, vartypeA_dimids, &veg_fractionV) );
temutil::nc( nc_def_var(ncid, "growstart", NC_DOUBLE, 4, vartypeA_dimids, &growstartV) );
// 3D vars
BOOST_LOG_SEV(glg, debug) << "Adding 3D variables...";
int vartypeB_dimids[3];
vartypeB_dimids[0] = timeD;
vartypeB_dimids[1] = yD;
vartypeB_dimids[2] = xD;
int org_shlw_thicknessV;
temutil::nc( nc_def_var(ncid, "org_shlw_thickness", NC_DOUBLE, 3, vartypeB_dimids, &org_shlw_thicknessV) );
/* Create Attributes? */
/* End Define Mode (not scrictly necessary for netcdf 4) */
BOOST_LOG_SEV(glg, debug) << "Leaving 'define mode'...";
temutil::nc( nc_enddef(ncid) );
/* Load coordinate variables?? */
/* Close file. */
BOOST_LOG_SEV(glg, debug) << "Closing new file...";
temutil::nc( nc_close(ncid) );
}
Refactor TEM.cpp main() run stage code to use new RestartData scheme.
Diff is hard to read because much of the refactoring changed the
indentation, so while much of the code is the same, it shows up as modified.
Previously, there was some convoluted logic that checked for the
existence of the various restart files. The checks were implemented slightly
differently for each stage. Now with a static member function
added to RestartData, we can create the empty files before looping over
any of the run mask and then during the stage, we can be assured that the
files already exist, therfore obviating all the need to check for the files.
Also the current scheme comes much closer to standardizing the
the code for each stage.
/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors:
* Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for
* (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* (1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <cstddef> // for offsetof()
#include <exception>
#include <map>
#include <set>
#include <boost/filesystem.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <json/value.h>
#ifdef WITHMPI
#include <mpi.h>
#include "data/RestartData.h" // for defining MPI typemap...
#include "inc/tbc_mpi_constants.h"
#endif
// For managing the floating point environment
#ifdef BSD_FPE
#include <xmmintrin.h> // BSD (OSX)
#endif
#ifdef GNU_FPE
#include <fenv.h> // GNU Linux
#endif
#include "inc/timeconst.h"
#include "../include/ArgHandler.h"
#include "TEMLogger.h"
#include "TEMUtilityFunctions.h"
#include "../include/Runner.h"
#include "data/RestartData.h"
#include <netcdf.h>
/** Quick 'n dirty pretty printer for vector of things
*/
template <typename TYPE>
void ppv(const std::vector<TYPE> &v){
typename std::vector<TYPE>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
}
// draft pretty-printers...
void pp_2dvec(const std::vector<std::vector<int> > & vv);
// draft - generate a netcdf file that can follow CF conventions
void create_new_output();
// draft - reading new-style co2 file
std::vector<float> read_new_co2_file(const std::string &filename);
// draft - reading in a 2D run mask...
std::vector< std::vector<int> > read_run_mask(const std::string &filename);
/** Enables a 'floating point exception' mask that will make the program crash
* when a floating point number is generated (and or operated upon).
*
* Some more info
* http://www.johndcook.com/blog/ieee_exceptions_in_cpp/
* http://stackoverflow.com/questions/247053/enabling-floating-point-interrupts-on-mac-os-x-intel
*
* It might be helpful to add a singal handler at some point that could report
* on what/where the exception is generated?
*/
void enable_floating_point_exceptions() {
std::cout << "Enabling floating point exceptions mask!" << std::endl;
// BSD (OSX)
#ifdef BSD_FPE
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID);
#endif
// GNU Linux
#ifdef GNU_FPE
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
}
ArgHandler* args = new ArgHandler();
extern src::severity_logger< severity_level > glg;
int main(int argc, char* argv[]){
// Read in and parse the command line arguments
args->parse(argc, argv);
if (args->get_help()) {
args->show_help();
return 0;
}
std::cout << "Setting up logging...\n";
setup_logging(args->get_log_level(), args->get_log_scope());
BOOST_LOG_SEV(glg, note) << "Checking command line arguments...";
args->verify(); // stub - doesn't really do anything yet
BOOST_LOG_SEV(glg, note) << "Turn floating point exceptions on?: " << args->get_fpe();
if (args->get_fpe()) { enable_floating_point_exceptions(); }
BOOST_LOG_SEV(glg, note) << "Reading controlfile into main(..) scope...";
Json::Value controldata = temutil::parse_control_file(args->get_ctrl_file());
BOOST_LOG_SEV(glg, note) << "Creating a ModelData object based on settings in the control file";
ModelData modeldata(controldata);
BOOST_LOG_SEV(glg, note) << "Update model settings based on command line flags/options...";
modeldata.update(args);
/*
Someday it may be worth the time/effort to make better use of
boots::program_options here to manage the arguments from config file
and the command line.
*/
BOOST_LOG_SEV(glg, note) << "Running PR stage: " << modeldata.pr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running EQ stage: " << modeldata.eq_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SP stage: " << modeldata.sp_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running TR stage: " << modeldata.tr_yrs << "yrs";
BOOST_LOG_SEV(glg, note) << "Running SC stage: " << modeldata.sc_yrs << "yrs";
// Turn off buffering...
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Create empty output files now so that later, as the program
// proceeds, there is somewhere to append output data...
// ??? Maybe the type/shape of outputs that we create can, or should, depend on
// ??? some of the settings in the ModelData object?
BOOST_LOG_SEV(glg, info) << "Creating a fresh 'n clean NEW output file...";
create_new_output();
time_t stime;
time_t etime;
stime = time(0);
BOOST_LOG_SEV(glg, note) << "Start dvmdostem @ " << ctime(&stime);
BOOST_LOG_SEV(glg, debug) << "NEW STYLE: Going to run space-major over a 2D area covered by run mask...";
// Open the run mask (spatial mask)
std::vector< std::vector<int> > run_mask = read_run_mask(modeldata.runmask_file);
// Create empty restart files for all stages based on size of run mask
RestartData::create_empty_file(modeldata.output_dir + "restart-eq.nc", 10, 10);
RestartData::create_empty_file(modeldata.output_dir + "restart-sp.nc", 10, 10);
RestartData::create_empty_file(modeldata.output_dir + "restart-tr.nc", 10, 10);
RestartData::create_empty_file(modeldata.output_dir + "restart-sc.nc", 10, 10);
// Make some convenient handles for later...
std::string eq_restart_fname = modeldata.output_dir + "restart-eq.nc";
std::string sp_restart_fname = modeldata.output_dir + "restart-sp.nc";
std::string tr_restart_fname = modeldata.output_dir + "restart-tr.nc";
std::string sc_restart_fname = modeldata.output_dir + "restart-sc.nc";
if (args->get_loop_order() == "space-major") {
// y <==> row <==> lat
// x <==> col <==> lon
/*
Loop over a 2D grid of 'cells' (cohorts?),
run each cell for some number of years.
Processing starts in the lower left corner (0,0).
Should really look into replacing this loop with
something like python's map(...) function...
--> Could this allow us to use a map reduce strategy??
Look into std::transform.
*/
// Use a few type definitions to save some typing.
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
vec2D::const_iterator row;
vec::const_iterator col;
for (row = run_mask.begin(); row != run_mask.end() ; ++row) {
for (col = row->begin(); col != row->end(); ++col) {
bool mask_value = *col;
int rowidx = row - run_mask.begin();
int colidx = col - row->begin();
if (true == mask_value) {
BOOST_LOG_SEV(glg, note) << "Running cell (" << rowidx << ", " << colidx << ")";
//modeldata.initmode = 1; // OBSOLETE?
BOOST_LOG_SEV(glg, info) << "Setup the NEW STYLE RUNNER OBJECT ...";
Runner runner(modeldata, args->get_cal_mode(), rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << runner.cohort.ground.layer_report_string("depth thermal");
// seg fault w/o preparing climate...so prepare year zero...
// this is also called inside run_years(...)
runner.cohort.climate.prepare_daily_driving_data(0, "eq");
runner.cohort.initialize_internal_pointers(); // sets up lots of pointers to various things
runner.cohort.initialize_state_parameters(); // sets data based on values in cohortlookup
BOOST_LOG_SEV(glg, debug) << "right after initialize_internal_pointers() and initialize_state_parameters()"
<< runner.cohort.ground.layer_report_string("depth ptr");
// PRE RUN STAGE (PR)
if (modeldata.pr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("PRE-RUN");
/** Env-only "pre-run" stage.
- should use only the env module
- number of years to run can be controlled on cmd line
- use fixed climate that is averaged over first X years
- use static (fixed) co2 value (first element of co2 file)
- FIX: need to set yrs since dsb ?
- FIX: should ignore calibration directives?
*/
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// turn off everything but env
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_bgcmodule(false);
runner.cohort.md->set_nfeed(false);
runner.cohort.md->set_avlnflg(false);
runner.cohort.md->set_baseline(false);
runner.cohort.md->set_dsbmodule(false);
runner.cohort.md->set_dslmodule(false);
runner.cohort.md->set_dvmmodule(false);
BOOST_LOG_SEV(glg, debug) << "Ground, right before 'pre-run'. "
<< runner.cohort.ground.layer_report_string("depth thermal");
runner.run_years(0, modeldata.pr_yrs, "pre-run"); // climate is prepared w/in here.
BOOST_LOG_SEV(glg, debug) << "Ground, right after 'pre-run'"
<< runner.cohort.ground.layer_report_string("depth thermal");
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("pr");
}
}
// EQULIBRIUM STAGE (EQ)
if (modeldata.eq_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("EQ");
BOOST_LOG_SEV(glg, fatal) << "Running Equlibrium, " << modeldata.sp_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.md->set_envmodule(true);
runner.cohort.md->set_dvmmodule(true);
runner.cohort.md->set_bgcmodule(true);
runner.cohort.md->set_dslmodule(true);
runner.cohort.md->set_nfeed(true);
runner.cohort.md->set_avlnflg(true);
runner.cohort.md->set_baseline(true);
runner.cohort.md->set_dsbmodule(false);
if (runner.cohort.md->get_dsbmodule()) {
// The transition to SP must occur at the completion of a
// fire cycle (i.e. a year or two prior to the next fire).
// To ensure this, re-set modeldata's EQ year count to an
// even multiple of the FRI minus 2 (to be safe)
int fri = runner.cohort.fire.getFRI();
int EQ_fire_cycles = modeldata.eq_yrs / fri;
if (modeldata.eq_yrs%fri != 0) {
modeldata.eq_yrs = fri * (EQ_fire_cycles + 1) - 2;
}
}
// Run model
runner.run_years(0, modeldata.eq_yrs, "eq-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData post EQ";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData to: " << eq_restart_fname;
runner.cohort.restartdata.append_to_ncfile(eq_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("eq");
}
}
// SPINUP STAGE (SP)
if (modeldata.sp_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SP");
BOOST_LOG_SEV(glg, fatal) << "Running Spinup, " << modeldata.sp_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
runner.cohort.climate.monthlycontainers2log();
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << eq_restart_fname;
runner.cohort.restartdata.update_from_ncfile(eq_restart_fname, rowidx, colidx);
// FIX: if restart file has -9999, then soil temps can end up
// impossibly low should check for valid values prior to actual use
// Maybe a diffcult to maintain in the future
// when/if more variables are added?
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre SP";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.sp_yrs, "sp-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SP";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sp_restart_fname;
runner.cohort.restartdata.append_to_ncfile(sp_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sp");
}
}
// TRANSIENT STAGE (TR)
if (modeldata.tr_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("TR");
BOOST_LOG_SEV(glg, fatal) << "Running Transient, " << modeldata.tr_yrs << " years";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// update the cohort's restart data object
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << sp_restart_fname;
runner.cohort.restartdata.update_from_ncfile(sp_restart_fname, rowidx, colidx);
runner.cohort.restartdata.verify_logical_values();
BOOST_LOG_SEV(glg, debug) << "RestartData pre TR";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Run model
runner.run_years(0, modeldata.tr_yrs, "tr-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post TR";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << tr_restart_fname;
runner.cohort.restartdata.append_to_ncfile(tr_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("tr");
}
}
// SCENARIO STAGE (SC)
if (modeldata.sc_yrs > 0) {
BOOST_LOG_NAMED_SCOPE("SC");
BOOST_LOG_SEV(glg, fatal) << "Running Scenario, " << modeldata.sc_yrs << " years.";
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_start();
}
// update the cohort's restart data object
BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << tr_restart_fname;
runner.cohort.restartdata.update_from_ncfile(tr_restart_fname, rowidx, colidx);
BOOST_LOG_SEV(glg, debug) << "RestartData pre SC";
runner.cohort.restartdata.restartdata_to_log();
// Copy values from the updated restart data to cohort and cd
runner.cohort.set_state_from_restartdata();
// Loading projected data instead of historic. FIX?
runner.cohort.load_proj_climate(modeldata.proj_climate_file);
// Run model
runner.run_years(0, modeldata.sc_yrs, "sc-run");
// Update restartdata structure from the running state
runner.cohort.set_restartdata_from_state();
BOOST_LOG_SEV(glg, debug) << "RestartData post SC";
runner.cohort.restartdata.restartdata_to_log();
BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sc_restart_fname;
runner.cohort.restartdata.append_to_ncfile(sc_restart_fname, rowidx, colidx);
if (runner.calcontroller_ptr) {
runner.calcontroller_ptr->handle_stage_end("sc");
}
}
// NOTE: Could have an option to set some time constants based on
// some sizes/dimensions of the input driving data...
/**
eq
- create the climate from the average of the first X years
of the driving climate data.
SIZE: 12 months, 1 year
- set to default module settings to: ??
- run_years( 0 <= iy < MAX_EQ_YEAR )
- act on calibration directives
-
sp
- create the climate from the first X years of the driving
climate dataset.
SIZE: 12 months, X years
- set to default module settings: ??
- run_years( SP_BEG <= iy <= SP_END )
tr
- create climate by loading the driving climate data (historic)
SIZE: 12 months, length of driving dataset? OR number from inc/timeconst.h
- set to default module settings: ??
- run_years( TR_BEG <= iy <= TR_END )
*/
} else {
BOOST_LOG_SEV(glg, debug) << "Skipping cell (" << rowidx << ", " << colidx << ")";
}
}
}
} else if(args->get_loop_order() == "time-major") {
BOOST_LOG_SEV(glg, warn) << "DO NOTHING. NOT IMPLEMENTED YET.";
// for each year
// Read in Climate - all locations, one year/timestep
// Read in Vegetation - all locations
// Read in Drainage - all locations
// Read in Fire - all locations
// for each cohort
// updateMonthly(...)
}
BOOST_LOG_SEV(glg, note) << "DONE WITH NEW STYLE run (" << args->get_loop_order() << ")";
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Total Seconds: " << difftime(etime, stime);
return 0;
} /* End main() */
/** Pretty print a 2D vector of ints */
void pp_2dvec(const std::vector<std::vector<int> > & vv) {
typedef std::vector<int> vec;
typedef std::vector<vec> vec2D;
for (vec2D::const_iterator row = vv.begin(); row != vv.end(); ++row) {
for (vec::const_iterator col = row->begin(); col != row->end(); ++col) {
std::cout << *col << " ";
}
std::cout << std::endl;
}
}
/** rough draft for reading a run-mask (2D vector of ints)
*/
std::vector< std::vector<int> > read_run_mask(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yD, xD;
size_t yD_len, xD_len;
temutil::nc( nc_inq_dimid(ncid, "Y", &yD) );
temutil::nc( nc_inq_dimlen(ncid, yD, &yD_len) );
temutil::nc( nc_inq_dimid(ncid, "X", &xD) );
temutil::nc( nc_inq_dimlen(ncid, xD, &xD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate a 2D run-mask vector (y,x). Size: (" << yD_len << ", " << xD_len << ")";
std::vector< std::vector<int> > run_mask(yD_len, std::vector<int>(xD_len));
BOOST_LOG_SEV(glg, debug) << "Read the run flag data from the file into the 2D vector...";
int runV;
temutil::nc( nc_inq_varid(ncid, "run", &runV) );
BOOST_LOG_SEV(glg, debug) << "Grab one row at a time";
BOOST_LOG_SEV(glg, debug) << "(need contiguous memory, and vector<vector> are not contiguous)";
std::vector< std::vector<int> >::iterator row;
for (row = run_mask.begin(); row != run_mask.end(); ++row) {
int rowidx = row - run_mask.begin();
// specify start indices for each dimension (y, x)
size_t start[2];
start[0] = rowidx; // Y
start[1] = 0; // X
// specify counts for each dimension
size_t count[2];
count[0] = 1; // one row
count[1] = xD_len; // all data
std::vector<int> rowdata(xD_len);
temutil::nc( nc_get_vara_int(ncid, runV, start, count, &rowdata[0] ) );
run_mask[rowidx] = rowdata;
}
temutil::nc( nc_close(ncid) );
//pp_2dvec(run_mask);
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return run_mask;
}
/** rough draft for reading new-style co2 data
*/
std::vector<float> read_new_co2_file(const std::string &filename) {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename;
temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );
BOOST_LOG_SEV(glg, debug) << "Find out how much data there is...";
int yearD;
size_t yearD_len;
temutil::nc( nc_inq_dimid(ncid, "year", &yearD) );
temutil::nc( nc_inq_dimlen(ncid, yearD, &yearD_len) );
BOOST_LOG_SEV(glg, debug) << "Allocate vector big enough for " << yearD_len << " years of co2 data...";
std::vector<float> co2data(yearD_len);
BOOST_LOG_SEV(glg, debug) << "Read the co2 data from the file into the vector...";
int co2V;
temutil::nc( nc_inq_varid(ncid, "co2", &co2V) );
temutil::nc( nc_get_var(ncid, co2V, &co2data[0]) );
temutil::nc( nc_close(ncid) );
BOOST_LOG_SEV(glg, debug) << "Return the vector...";
return co2data;
}
/** rough draft for new output files
*/
void create_new_output() {
int ncid;
BOOST_LOG_SEV(glg, debug) << "Creating dataset...";
temutil::nc( nc_create("general-outputs-monthly.nc", NC_CLOBBER, &ncid) );
int timeD; // unlimited dimension
int pftD;
int xD;
int yD;
/* Create Dimensions */
BOOST_LOG_SEV(glg, debug) << "Adding dimensions...";
temutil::nc( nc_def_dim(ncid, "time", NC_UNLIMITED, &timeD) );
temutil::nc( nc_def_dim(ncid, "pft", NUM_PFT, &pftD) );
temutil::nc( nc_def_dim(ncid, "y", 10, &yD) );
temutil::nc( nc_def_dim(ncid, "x", 10, &xD) );
/* Create Coordinate Variables?? */
/* Create Data Variables */
// 4D vars
BOOST_LOG_SEV(glg, debug) << "Adding 4D variables...";
int vartypeA_dimids[4];
vartypeA_dimids[0] = timeD;
vartypeA_dimids[1] = pftD;
vartypeA_dimids[2] = yD;
vartypeA_dimids[3] = xD;
int vegcV;
int veg_fractionV;
int growstartV;
temutil::nc( nc_def_var(ncid, "vegc", NC_DOUBLE, 4, vartypeA_dimids, &vegcV) );
temutil::nc( nc_def_var(ncid, "veg_fraction", NC_DOUBLE, 4, vartypeA_dimids, &veg_fractionV) );
temutil::nc( nc_def_var(ncid, "growstart", NC_DOUBLE, 4, vartypeA_dimids, &growstartV) );
// 3D vars
BOOST_LOG_SEV(glg, debug) << "Adding 3D variables...";
int vartypeB_dimids[3];
vartypeB_dimids[0] = timeD;
vartypeB_dimids[1] = yD;
vartypeB_dimids[2] = xD;
int org_shlw_thicknessV;
temutil::nc( nc_def_var(ncid, "org_shlw_thickness", NC_DOUBLE, 3, vartypeB_dimids, &org_shlw_thicknessV) );
/* Create Attributes? */
/* End Define Mode (not scrictly necessary for netcdf 4) */
BOOST_LOG_SEV(glg, debug) << "Leaving 'define mode'...";
temutil::nc( nc_enddef(ncid) );
/* Load coordinate variables?? */
/* Close file. */
BOOST_LOG_SEV(glg, debug) << "Closing new file...";
temutil::nc( nc_close(ncid) );
}
|
#include "stdafx.h"
BDD representState(const Cudd& manager, const std::vector<bool>& values) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(values); it != std::end(values); ++it) {
BDD var = manager.bddVar(i);
if (!*it) {
var = !var;
}
bdd = var * bdd;
i++;
}
return bdd;
}
BDD representClause(const Cudd& manager, const std::vector<int>& clause) {
BDD bdd = manager.bddZero();
for (auto it = std::begin(clause); it != std::end(clause); ++it) {
BDD var = manager.bddVar(abs(*it));
if (*it < 0) {
var = !var;
}
bdd = var + bdd;
}
return bdd;
}
BDD representUpdateFunction(const Cudd& manager, const std::vector<std::vector<int>>& cnf) {
BDD bdd = manager.bddOne();
for (auto it = std::begin(cnf); it != std::end(cnf); ++it) {
bdd = bdd * representClause(manager, *it);
}
return bdd;
}
BDD implication(const BDD& a, const BDD& b) {
return !a + b;
}
BDD logicalEquivalence(const BDD& a, const BDD& b) {
return implication(a, b) * implication(b, a);
}
BDD representSyncTransitionRelation(const Cudd& manager, const std::vector<std::vector<std::vector<int>>>& network) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD f = representUpdateFunction(manager, *it);
BDD vPrime = manager.bddVar(network.size() + i);
BDD transition = logicalEquivalence(vPrime, f);
bdd = transition * bdd;
i++;
}
return bdd;
}
BDD otherVarsDoNotChange(const Cudd& manager, int i, int numVars) {
BDD bdd = manager.bddOne();
for (int j = 0; j < numVars; j++) {
if (j != i) {
BDD v = manager.bddVar(j);
BDD vPrime = manager.bddVar(numVars + j);
bdd = bdd * logicalEquivalence(v, vPrime);
}
}
return bdd;
}
BDD representAsyncTransitionRelation(const Cudd& manager, const std::vector<std::vector<std::vector<int>>>& network) {
BDD fixpoint = manager.bddOne();
for (size_t i = 0; i < network.size(); i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
fixpoint = fixpoint * logicalEquivalence(v, vPrime);
}
BDD bdd = manager.bddZero();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
BDD vChanges = !logicalEquivalence(v, vPrime);
BDD f = representUpdateFunction(manager, *it);
BDD update = logicalEquivalence(vPrime, f) * otherVarsDoNotChange(manager, i, network.size());
BDD transition = update * (fixpoint + vChanges);
bdd = transition + bdd;
i++;
}
return bdd;
}
BDD renameRemovingPrimes(const BDD& bdd, int numUnprimedBDDVars) {
int *permute = new int[numUnprimedBDDVars * 2];
for (int i = 0; i < numUnprimedBDDVars; i++) {
permute[i] = i;
permute[i + numUnprimedBDDVars] = i;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD nonPrimeVariables(const Cudd& manager, int numUnprimedBDDVars) {
return representState(manager, std::vector<bool>(numUnprimedBDDVars, true));
}
BDD primeVariables(const Cudd& manager, int numUnprimedBDDVars) {
BDD bdd = manager.bddOne();
for (int i = numUnprimedBDDVars; i < numUnprimedBDDVars * 2; i++) {
BDD var = manager.bddVar(i);
bdd = var * bdd;
}
return bdd;
}
BDD immediateSuccessorStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD bdd = transitionBdd * valuesBdd;
bdd = bdd.ExistAbstract(nonPrimeVariables(manager, numUnprimedBDDVars));
bdd = renameRemovingPrimes(bdd, numUnprimedBDDVars);
return bdd;
}
BDD forwardReachableStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediateSuccessorStates(manager, transitionBdd, frontier, numUnprimedBDDVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD renameAddingPrimes(const BDD& bdd, int numUnprimedBDDVars) {
int *permute = new int[numUnprimedBDDVars * 2];
for (int i = 0; i < numUnprimedBDDVars; i++) {
permute[i] = i + numUnprimedBDDVars;
permute[i + numUnprimedBDDVars] = i + numUnprimedBDDVars;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD immediatePredecessorStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD bdd = renameAddingPrimes(valuesBdd, numUnprimedBDDVars);
bdd = transitionBdd * bdd;
bdd = bdd.ExistAbstract(primeVariables(manager, numUnprimedBDDVars));
return bdd;
}
BDD backwardReachableStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediatePredecessorStates(manager, transitionBdd, frontier, numUnprimedBDDVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD randomState(const Cudd& manager, BDD S, int numVars) {
char *out = new char[numVars * 2];
S.PickOneCube(out);
std::vector<bool> values;
for (int i = 0; i < numVars; i++) {
if (out[i] == 0) {
values.push_back(false);
}
else {
values.push_back(true);
}
}
delete[] out;
return representState(manager, values);
}
std::list<BDD> attractorsBN(const Cudd& manager, const BDD& transitionBdd, int numVars) {
std::list<BDD> attractors;
BDD S = manager.bddOne();
while (S != manager.bddZero()) {
BDD s = randomState(manager, S, numVars);
BDD fr = forwardReachableStates(manager, transitionBdd, s, numVars);
BDD br = backwardReachableStates(manager, transitionBdd, s, numVars);
if ((fr * !br) == manager.bddZero()) {
attractors.push_back(fr);
}
S = S * !(s + br);
}
return attractors;
}
int log2(unsigned int i) {
unsigned int r = 0;
while (i >>= 1) r++;
return r;
}
int bits(unsigned int i) {
return i == 0 ? 0 : log2(i) + 1;
}
bool nthBitSet(int i, int n) {
return (1 << n) & i;
}
BDD representUnprimedVarQN(const Cudd& manager, int var, int val, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
auto lambda = [](int a, int b) { return a + bits(b); };
int i = std::accumulate(ranges.begin(), ranges.begin() + var, 0, lambda);
int b = bits(ranges[var]);
for (int n = 0; n < b; n++) {
BDD var = manager.bddVar(i);
if (!nthBitSet(val, n)) {
var = !var;
}
bdd = bdd * var;
i++;
}
return bdd;
}
BDD representPrimedVarQN(const Cudd& manager, int var, int val, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
auto lambda = [](int a, int b) { return a + bits(b); };
int i = std::accumulate(ranges.begin(), ranges.end(), 0, lambda) + std::accumulate(ranges.begin(), ranges.begin() + var, 0, lambda);
int b = bits(ranges[var]);
for (int n = 0; n < b; n++) {
BDD var = manager.bddVar(i);
if (!nthBitSet(val, n)) {
var = !var;
}
bdd = bdd * var;
i++;
}
return bdd;
}
BDD representStateQN(const Cudd& manager, const std::vector<int>& vars, const std::vector<int>& values, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
for (/*std::vector<int>::size_type*/ size_t i = 0; i < vars.size(); i++) {
int var = vars[i];
int val = values[i];
bdd = bdd * representUnprimedVarQN(manager, var, val, ranges);
}
return bdd;
}
BDD removeInvalidBitCombinations(const Cudd& manager, const BDD& S, const std::vector<int>& ranges) {
BDD bdd = S;
for (int var = 0; var < ranges.size(); var++) {
if (ranges[var] > 0) {
int b = bits(ranges[var]);
int theoreticalMax = (1 << b) - 1;
for (int val = ranges[var] + 1; val <= theoreticalMax; val++) {
bdd = bdd * !representUnprimedVarQN(manager, var, val, ranges);
}
}
}
return bdd;
}
BDD representSyncQNTransitionRelation(const Cudd& manager, const std::vector<int>& ranges, const std::vector<std::vector<int>>& inputVars,
const std::vector<std::vector<std::vector<int>>>& inputValues, const std::vector<std::vector<int>>& outputValues) {
BDD bdd = manager.bddOne();
int v = 0;
for (int v = 0; v < ranges.size(); v++) {
if (ranges[v] > 0) {
auto iVars = inputVars[v];
auto iValues = inputValues[v];
auto oValues = outputValues[v];
std::vector<BDD> states(ranges[v] + 1, manager.bddZero());
for (int i = 0; i < oValues.size(); i++) {
states[oValues[i]] = states[oValues[i]] + representStateQN(manager, iVars, iValues[i], ranges);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
for (int val = 0; val <= ranges[v]; val++) {
BDD vPrime = representPrimedVarQN(manager, v, val, ranges);
bdd = bdd * logicalEquivalence(states[val], vPrime);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
}
}
return bdd;
}
std::list<BDD> attractorsQN(Cudd manager, const BDD& transitionBdd, const std::vector<int>& ranges) {
auto lambda = [](int a, int b) { return a + bits(b); };
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
std::list<BDD> attractors;
BDD S = manager.bddOne();
S = removeInvalidBitCombinations(manager, S, ranges);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
while (S != manager.bddZero()) {
BDD s = randomState(manager, S, numUnprimedBDDVars);
for (int i = 0; i < 20; i++) {
BDD sP = forwardReachableStates(manager, transitionBdd, s, numUnprimedBDDVars);
s = randomState(manager, sP, numUnprimedBDDVars);
}
BDD fr = forwardReachableStates(manager, transitionBdd, s, numUnprimedBDDVars);
BDD br = backwardReachableStates(manager, transitionBdd, s, numUnprimedBDDVars);
if ((fr * !br) == manager.bddZero()) {
attractors.push_back(fr);
}
S = S * !(s + br);
}
return attractors;
}
BDD varDoesChangeQN(const Cudd& manager, int var, const std::vector<int>& ranges) {
auto lambda = [](int a, int b) { return a + bits(b); };
int start = std::accumulate(ranges.begin(), ranges.begin() + var, 0, lambda);
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
int numBits = bits(ranges[var]);
BDD bdd = manager.bddZero();
for (int i = start; i < start + numBits; i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(i + numUnprimedBDDVars);
bdd = bdd + !logicalEquivalence(v, vPrime);
}
return bdd;
}
BDD otherVarsDoNotChangeQN(const Cudd& manager, int var, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
for (int i = 0; i < ranges.size(); i++) {
if (i != var) {
bdd = bdd * !varDoesChangeQN(manager, i, ranges);
}
}
return bdd;
}
BDD representAsyncQNTransitionRelation(/*const*/ Cudd& manager, const std::vector<int>& ranges, const std::vector<std::vector<int>>& inputVars,
const std::vector<std::vector<std::vector<int>>>& inputValues, const std::vector<std::vector<int>>& outputValues) {
auto lambda = [](int a, int b) { return a + bits(b); };
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
BDD fixpoint = manager.bddOne();
for (int i = 0; i < numUnprimedBDDVars; i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(numUnprimedBDDVars + i);
fixpoint = fixpoint * logicalEquivalence(v, vPrime);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
BDD bdd = manager.bddZero();
int v = 0;
for (int v = 0; v < ranges.size(); v++) {
if (ranges[v] > 0) {
auto iVars = inputVars[v];
auto iValues = inputValues[v];
auto oValues = outputValues[v];
std::vector<BDD> states(ranges[v] + 1, manager.bddZero());
for (int i = 0; i < oValues.size(); i++) {
states[oValues[i]] = states[oValues[i]] + representStateQN(manager, iVars, iValues[i], ranges);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
BDD updates = manager.bddOne();
for (int val = 0; val <= ranges[v]; val++) {
BDD vPrime = representPrimedVarQN(manager, v, val, ranges);
BDD u = logicalEquivalence(states[val], vPrime);
updates = updates * u;
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
BDD otherVarsDoNotChange = otherVarsDoNotChangeQN(manager, v, ranges);
BDD vChanges = varDoesChangeQN(manager, v, ranges);
BDD transition = updates * otherVarsDoNotChange * (fixpoint + vChanges);
bdd = bdd + transition;
}
}
return bdd;
}
Functionally complete, but in need of refactoring
#include "stdafx.h"
BDD representState(const Cudd& manager, const std::vector<bool>& values) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(values); it != std::end(values); ++it) {
BDD var = manager.bddVar(i);
if (!*it) {
var = !var;
}
bdd = var * bdd;
i++;
}
return bdd;
}
BDD representClause(const Cudd& manager, const std::vector<int>& clause) {
BDD bdd = manager.bddZero();
for (auto it = std::begin(clause); it != std::end(clause); ++it) {
BDD var = manager.bddVar(abs(*it));
if (*it < 0) {
var = !var;
}
bdd = var + bdd;
}
return bdd;
}
BDD representUpdateFunction(const Cudd& manager, const std::vector<std::vector<int>>& cnf) {
BDD bdd = manager.bddOne();
for (auto it = std::begin(cnf); it != std::end(cnf); ++it) {
bdd = bdd * representClause(manager, *it);
}
return bdd;
}
BDD implication(const BDD& a, const BDD& b) {
return !a + b;
}
BDD logicalEquivalence(const BDD& a, const BDD& b) {
return implication(a, b) * implication(b, a);
}
BDD representSyncTransitionRelation(const Cudd& manager, const std::vector<std::vector<std::vector<int>>>& network) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD f = representUpdateFunction(manager, *it);
BDD vPrime = manager.bddVar(network.size() + i);
BDD transition = logicalEquivalence(vPrime, f);
bdd = transition * bdd;
i++;
}
return bdd;
}
BDD otherVarsDoNotChange(const Cudd& manager, int i, int numVars) {
BDD bdd = manager.bddOne();
for (int j = 0; j < numVars; j++) {
if (j != i) {
BDD v = manager.bddVar(j);
BDD vPrime = manager.bddVar(numVars + j);
bdd = bdd * logicalEquivalence(v, vPrime);
}
}
return bdd;
}
BDD representAsyncTransitionRelation(const Cudd& manager, const std::vector<std::vector<std::vector<int>>>& network) {
BDD fixpoint = manager.bddOne();
for (size_t i = 0; i < network.size(); i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
fixpoint = fixpoint * logicalEquivalence(v, vPrime);
}
BDD bdd = manager.bddZero();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
BDD vChanges = !logicalEquivalence(v, vPrime);
BDD f = representUpdateFunction(manager, *it);
BDD update = logicalEquivalence(vPrime, f) * otherVarsDoNotChange(manager, i, network.size());
BDD transition = update * (fixpoint + vChanges);
bdd = transition + bdd;
i++;
}
return bdd;
}
BDD renameRemovingPrimes(const BDD& bdd, int numUnprimedBDDVars) {
int *permute = new int[numUnprimedBDDVars * 2];
for (int i = 0; i < numUnprimedBDDVars; i++) {
permute[i] = i;
permute[i + numUnprimedBDDVars] = i;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD nonPrimeVariables(const Cudd& manager, int numUnprimedBDDVars) {
return representState(manager, std::vector<bool>(numUnprimedBDDVars, true));
}
BDD primeVariables(const Cudd& manager, int numUnprimedBDDVars) {
BDD bdd = manager.bddOne();
for (int i = numUnprimedBDDVars; i < numUnprimedBDDVars * 2; i++) {
BDD var = manager.bddVar(i);
bdd = var * bdd;
}
return bdd;
}
BDD immediateSuccessorStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD bdd = transitionBdd * valuesBdd;
bdd = bdd.ExistAbstract(nonPrimeVariables(manager, numUnprimedBDDVars));
return renameRemovingPrimes(bdd, numUnprimedBDDVars);
}
BDD forwardReachableStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediateSuccessorStates(manager, transitionBdd, frontier, numUnprimedBDDVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD renameAddingPrimes(const BDD& bdd, int numUnprimedBDDVars) {
int *permute = new int[numUnprimedBDDVars * 2];
for (int i = 0; i < numUnprimedBDDVars; i++) {
permute[i] = i + numUnprimedBDDVars;
permute[i + numUnprimedBDDVars] = i + numUnprimedBDDVars;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD immediatePredecessorStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD bdd = renameAddingPrimes(valuesBdd, numUnprimedBDDVars);
bdd = transitionBdd * bdd;
return bdd.ExistAbstract(primeVariables(manager, numUnprimedBDDVars));
}
BDD backwardReachableStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numUnprimedBDDVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediatePredecessorStates(manager, transitionBdd, frontier, numUnprimedBDDVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD randomState(const Cudd& manager, const BDD& S, int numVars) {
char *out = new char[numVars * 2];
S.PickOneCube(out);
std::vector<bool> values;
for (int i = 0; i < numVars; i++) {
if (out[i] == 0) {
values.push_back(false);
}
else {
values.push_back(true);
}
}
delete[] out;
return representState(manager, values);
}
std::list<BDD> attractorsBN(const Cudd& manager, const BDD& transitionBdd, int numVars) {
std::list<BDD> attractors;
BDD S = manager.bddOne();
while (S != manager.bddZero()) {
BDD s = randomState(manager, S, numVars);
for (int i = 0; i < 20; i++) {
BDD sP = immediateSuccessorStates(manager, transitionBdd, s, numVars);
s = randomState(manager, sP, numVars);
}
BDD fr = forwardReachableStates(manager, transitionBdd, s, numVars);
BDD br = backwardReachableStates(manager, transitionBdd, s, numVars);
if ((fr * !br) == manager.bddZero()) {
attractors.push_back(fr);
}
S = S * !(s + br);
}
return attractors;
}
int log2(unsigned int i) {
unsigned int r = 0;
while (i >>= 1) r++;
return r;
}
int bits(unsigned int i) {
return i == 0 ? 0 : log2(i) + 1;
}
bool nthBitSet(int i, int n) {
return (1 << n) & i;
}
BDD representUnprimedVarQN(const Cudd& manager, int var, int val, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
auto lambda = [](int a, int b) { return a + bits(b); };
int i = std::accumulate(ranges.begin(), ranges.begin() + var, 0, lambda);
int b = bits(ranges[var]);
for (int n = 0; n < b; n++) {
BDD var = manager.bddVar(i);
if (!nthBitSet(val, n)) {
var = !var;
}
bdd = bdd * var;
i++;
}
return bdd;
}
BDD representPrimedVarQN(const Cudd& manager, int var, int val, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
auto lambda = [](int a, int b) { return a + bits(b); };
int i = std::accumulate(ranges.begin(), ranges.end(), 0, lambda) + std::accumulate(ranges.begin(), ranges.begin() + var, 0, lambda);
int b = bits(ranges[var]);
for (int n = 0; n < b; n++) {
BDD var = manager.bddVar(i);
if (!nthBitSet(val, n)) {
var = !var;
}
bdd = bdd * var;
i++;
}
return bdd;
}
BDD representStateQN(const Cudd& manager, const std::vector<int>& vars, const std::vector<int>& values, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
for (size_t i = 0; i < vars.size(); i++) {
int var = vars[i];
int val = values[i];
bdd = bdd * representUnprimedVarQN(manager, var, val, ranges);
}
return bdd;
}
BDD removeInvalidBitCombinations(const Cudd& manager, BDD S, const std::vector<int>& ranges) {
for (int var = 0; var < ranges.size(); var++) {
if (ranges[var] > 0) {
int b = bits(ranges[var]);
int theoreticalMax = (1 << b) - 1;
for (int val = ranges[var] + 1; val <= theoreticalMax; val++) {
S = S * !representUnprimedVarQN(manager, var, val, ranges);
}
}
}
return S;
}
BDD representSyncQNTransitionRelation(/*const*/ Cudd& manager, const std::vector<int>& ranges, const std::vector<std::vector<int>>& inputVars,
const std::vector<std::vector<std::vector<int>>>& inputValues, const std::vector<std::vector<int>>& outputValues) {
BDD bdd = manager.bddOne();
int v = 0;
for (int v = 0; v < ranges.size(); v++) {
if (ranges[v] > 0) {
auto iVars = inputVars[v];
auto iValues = inputValues[v];
auto oValues = outputValues[v];
std::vector<BDD> states(ranges[v] + 1, manager.bddZero());
for (int i = 0; i < oValues.size(); i++) {
states[oValues[i]] = states[oValues[i]] + representStateQN(manager, iVars, iValues[i], ranges);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
for (int val = 0; val <= ranges[v]; val++) {
BDD vPrime = representPrimedVarQN(manager, v, val, ranges);
bdd = bdd * logicalEquivalence(states[val], vPrime);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
}
}
return bdd;
}
std::list<BDD> attractorsQN(Cudd manager, const BDD& transitionBdd, const std::vector<int>& ranges, const BDD& statesToRemove) {
auto lambda = [](int a, int b) { return a + bits(b); };
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
std::list<BDD> attractors;
BDD S = manager.bddOne();
S = removeInvalidBitCombinations(manager, S, ranges);
S = S * !(statesToRemove);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
while (S != manager.bddZero()) {
BDD s = randomState(manager, S, numUnprimedBDDVars);
for (int i = 0; i < 20; i++) {
BDD sP = immediateSuccessorStates(manager, transitionBdd, s, numUnprimedBDDVars);
s = randomState(manager, sP, numUnprimedBDDVars);
}
BDD fr = forwardReachableStates(manager, transitionBdd, s, numUnprimedBDDVars);
BDD br = backwardReachableStates(manager, transitionBdd, s, numUnprimedBDDVars);
if ((fr * !br) == manager.bddZero()) {
attractors.push_back(fr);
}
S = S * !(s + br);
}
return attractors;
}
BDD varDoesChangeQN(const Cudd& manager, int var, const std::vector<int>& ranges) {
auto lambda = [](int a, int b) { return a + bits(b); };
int start = std::accumulate(ranges.begin(), ranges.begin() + var, 0, lambda);
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
int numBits = bits(ranges[var]);
BDD bdd = manager.bddZero();
for (int i = start; i < start + numBits; i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(i + numUnprimedBDDVars);
bdd = bdd + !logicalEquivalence(v, vPrime);
}
return bdd;
}
BDD otherVarsDoNotChangeQN(const Cudd& manager, int var, const std::vector<int>& ranges) {
BDD bdd = manager.bddOne();
for (int i = 0; i < ranges.size(); i++) {
if (i != var) {
bdd = bdd * !varDoesChangeQN(manager, i, ranges);
}
}
return bdd;
}
BDD representAsyncQNTransitionRelation(/*const*/ Cudd& manager, const std::vector<int>& ranges, const std::vector<std::vector<int>>& inputVars,
const std::vector<std::vector<std::vector<int>>>& inputValues, const std::vector<std::vector<int>>& outputValues) {
auto lambda = [](int a, int b) { return a + bits(b); };
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
BDD fixpoint = manager.bddOne();
for (int i = 0; i < numUnprimedBDDVars; i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(numUnprimedBDDVars + i);
fixpoint = fixpoint * logicalEquivalence(v, vPrime);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
BDD bdd = manager.bddZero();
int v = 0;
for (int v = 0; v < ranges.size(); v++) {
if (ranges[v] > 0) {
auto iVars = inputVars[v];
auto iValues = inputValues[v];
auto oValues = outputValues[v];
std::vector<BDD> states(ranges[v] + 1, manager.bddZero());
for (int i = 0; i < oValues.size(); i++) {
states[oValues[i]] = states[oValues[i]] + representStateQN(manager, iVars, iValues[i], ranges);
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
BDD updates = manager.bddOne();
for (int val = 0; val <= ranges[v]; val++) {
BDD vPrime = representPrimedVarQN(manager, v, val, ranges);
BDD u = logicalEquivalence(states[val], vPrime);
updates = updates * u;
manager.ReduceHeap(CUDD_REORDER_SIFT, 0);
}
BDD otherVarsDoNotChange = otherVarsDoNotChangeQN(manager, v, ranges);
BDD vChanges = varDoesChangeQN(manager, v, ranges);
BDD transition = updates * otherVarsDoNotChange * (fixpoint + vChanges);
bdd = bdd + transition;
}
}
return bdd;
}
bool isAsyncLoop(const Cudd& manager, const BDD& S, const BDD& syncTransitionBdd, const std::vector<int>& ranges) {
auto lambda = [](int a, int b) { return a + bits(b); };
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
BDD reached = manager.bddZero();
BDD s = randomState(manager, S, numUnprimedBDDVars);
while (s != manager.bddZero()) {
BDD sP = immediateSuccessorStates(manager, syncTransitionBdd, s, numUnprimedBDDVars);
char *sCube = new char[numUnprimedBDDVars * 2];
s.PickOneCube(sCube);
char *sPCube = new char[numUnprimedBDDVars * 2];
sP.PickOneCube(sPCube);
int nVarDiff = 0;
int i = 0;
for (int range : ranges) {
int b = bits(range);
for (int j = i; j < i + b; j++) {
if (sCube[j] != sPCube[j]) {
nVarDiff++;
break;
}
}
if (nVarDiff >= 2) return false;
i += b;
}
s = sP * !reached;
reached = reached + s;
}
return true;
}
std::list<BDD> combinedAlgorithm(Cudd manager, const BDD& syncTransitionBdd, const BDD& asyncTransitionBdd, const std::vector<int>& ranges) {
auto lambda = [](int a, int b) { return a + bits(b); };
int numUnprimedBDDVars = std::accumulate(ranges.begin(), ranges.end(), 0, lambda);
std::list<BDD> asyncAttractors;
std::list<BDD> syncAttractors = attractorsQN(manager, syncTransitionBdd, ranges, manager.bddZero());
BDD syncAsyncAttractors = manager.bddZero();
for (BDD a : syncAttractors) {
if (isAsyncLoop(manager, a, syncTransitionBdd, ranges)) {
syncAsyncAttractors = syncAsyncAttractors + a;
asyncAttractors.push_back(a);
}
}
BDD br = backwardReachableStates(manager, asyncTransitionBdd, syncAsyncAttractors, numUnprimedBDDVars);
asyncAttractors.splice(asyncAttractors.end(), attractorsQN(manager, asyncTransitionBdd, ranges, syncAsyncAttractors + br));
return asyncAttractors;
}
std::string printRange(const std::list<int>& values) {
auto lambda = [](std::string a, int b) { return a + "; " + std::to_string(b); };
return "[" + std::accumulate(std::next(values.begin()), values.end(), std::to_string(values.front()), lambda) + "]";
}
std::string fromBinary(const std::string& bits, int offset) {
int i = 0;
auto lambda = [&i](int a) { return a + std::pow(2.0f, i); };
std::list<int> values{ offset };
for (auto it = std::rbegin(bits); it < std::rend(bits); ++it) {
if (*it == '-') {
std::list<int> copy(values);
std::transform(copy.begin(), copy.end(), copy.begin(), lambda);
values.splice(values.end(), copy);
}
else if (*it == '1') {
std::transform(values.begin(), values.end(), values.begin(), lambda);
}
i++;
}
return values.size() > 1 ? printRange(values) : std::to_string(values.front());
}
std::string prettyPrint(const Cudd& manager, const BDD& attractor, const std::vector<int>& ranges, const std::vector<int>& offsets) {
FILE *old = manager.ReadStdout();
FILE *fp = fopen("temp.txt", "w");
manager.SetStdout(fp);
attractor.PrintMinterm();
manager.SetStdout(old);
fclose(fp);
std::string out;
std::ifstream infile("temp.txt");
std::string line;
auto lambda = [](std::string a, std::string b) { return a + ", " + b; };
while (std::getline(infile, line)) {
std::list<std::string> output;
int i = 0;
for (int v = 1; v < ranges.size(); v++) {
if (ranges[v] == 0) {
output.push_back(std::to_string(offsets[v]));
}
else {
int b = bits(ranges[v]);
output.push_back(fromBinary(line.substr(i, b), offsets[v]));
i += b;
}
}
out += std::accumulate(std::next(output.begin()), output.end(), output.front(), lambda) + "\n";
}
return out;
}
extern "C" __declspec(dllexport) int attractors(int numVars, int ranges[], int offsets[], int numInputs[], int inputVars[], int numUpdates[], int inputValues[], int outputValues[], int mode) {
std::vector<int> rangesV(ranges, ranges + numVars);
std::vector<int> offsetsV(offsets, offsets + numVars);
std::vector<std::vector<int>> inputVarsV;
std::vector<std::vector<int>> outputValuesV;
std::vector<std::vector<std::vector<int>>> inputValuesV;
int k = 0;
for (int i = 0; i < numVars; i++) {
std::vector<int> in;
for (int j = 0; j < numInputs[i]; j++) {
in.push_back(inputVars[k]);
k++;
}
inputVarsV.push_back(in);
}
k = 0;
for (int i = 0; i < numVars; i++) {
std::vector<int> out;
for (int j = 0; j < numUpdates[i]; j++) {
out.push_back(outputValues[k]);
k++;
}
outputValuesV.push_back(out);
}
k = 0;
for (int i = 0; i < numVars; i++) {
std::vector<std::vector<int>> in;
for (int j = 0; j < numUpdates[i]; j++) {
std::vector<int> v;
for (int l = 0; l < numInputs[i]; l++) {
v.push_back(inputValues[k]);
k++;
}
in.push_back(v);
}
inputValuesV.push_back(in);
}
Cudd manager(0, 0);
if (mode == 0) {
std::cout << "Building synchronous transition relation..." << std::endl;
BDD transitionBdd = representSyncQNTransitionRelation(manager, rangesV, inputVarsV, inputValuesV, outputValuesV);
std::cout << "Finding attractors..." << std::endl;
std::list<BDD> atts = attractorsQN(manager, transitionBdd, rangesV, manager.bddZero());
int i = 0;
for (const auto& attractor : atts) {
std::cout << "Attractor " << i << ":" << std::endl;
attractor.PrintMinterm();
std::cout << prettyPrint(manager, attractor, rangesV, offsetsV) << std::endl;
i++;
}
return i;
}
else {
std::cout << "Building synchronous transition relation..." << std::endl;
BDD syncTransitionBdd = representSyncQNTransitionRelation(manager, rangesV, inputVarsV, inputValuesV, outputValuesV);
std::cout << "Building asynchronous transition relation..." << std::endl;
BDD asyncTransitionBdd = representAsyncQNTransitionRelation(manager, rangesV, inputVarsV, inputValuesV, outputValuesV);
std::cout << "Finding attractors with combined algorithm..." << std::endl;
std::list<BDD> atts = combinedAlgorithm(manager, syncTransitionBdd, asyncTransitionBdd, rangesV);
int i = 0;
std::cout << "Pretty printing..." << std::endl;
for (const auto& attractor : atts) {
std::cout << "Attractor " << i << ":" << std::endl;
attractor.PrintMinterm();
std::cout << prettyPrint(manager, attractor, rangesV, offsetsV) << std::endl;
i++;
}
return i;
}
}
|
#include <dynet/dynet.h>
#include <dynet/expr.h>
#include <dynet/grad-check.h>
#include <boost/test/unit_test.hpp>
#include <stdexcept>
using namespace dynet;
using namespace dynet::expr;
using namespace std;
struct NodeTest {
NodeTest() {
// initialize if necessary
if(default_device == nullptr) {
for (auto x : {"NodeTest", "--dynet-mem", "10"}) {
av.push_back(strdup(x));
}
char **argv = &av[0];
int argc = av.size();
dynet::initialize(argc, argv);
}
ones3_vals = {1.f,1.f,1.f};
first_one_vals = {1.f,0.f,0.f};
ones2_vals = {1.f,1.f};
batch_vals = {1.f,2.f,3.f,4.f,5.f,6.f};
// Create parameters
std::vector<float> param1_vals = {1.1f,-2.2f,3.3f};
std::vector<float> param2_vals = {2.2f,3.4f,-1.2f};
std::vector<float> param3_vals = {1.1f,2.2f,3.3f};
std::vector<float> param4_vals = {1.1f,2.2f,3.3f,-1.2f,2.1f,3.4f};
std::vector<float> param_scalar1_vals = {2.2f};
std::vector<float> param_scalar2_vals = {1.1f};
std::vector<float> param_kernel1_vals = {1.1f,2.2f,-1.0f,1.2f,-3.4f,-0.2f};
std::vector<float> param_filter1_vals = {1.1f,2.2f,-1.0f,1.2f,-3.4f,-0.2f,
11.1f,12.2f,13.3f,11.2f,12.2f,13.2f};
std::vector<float> param_square1_vals = {1.1f,2.2f,3.4f,1.2f,2.5f,3.2f,5.3f,2.3f,3.3f};
std::vector<float> param_cube1_vals = {.011f,.022f,.033f,.012f,.022f,.032f,.013f,.023f,.033f,
.111f,-.122f,-.033f,-.112f,-.022f,-.132f,-.113f,-.123f,-.133f,
.211f,.222f,.233f,.212f,.222f,.232f,.213f,.223f,.233f};
param1 = mod.add_parameters({3});
TensorTools::SetElements(param1.get()->values,param1_vals);
param2 = mod.add_parameters({3});
TensorTools::SetElements(param2.get()->values,param2_vals);
param3 = mod.add_parameters({3});
TensorTools::SetElements(param3.get()->values,param3_vals);
param4 = mod.add_parameters({6});
TensorTools::SetElements(param4.get()->values,param4_vals);
param_scalar1 = mod.add_parameters({1});
TensorTools::SetElements(param_scalar1.get()->values,param_scalar1_vals);
param_scalar2 = mod.add_parameters({1});
TensorTools::SetElements(param_scalar2.get()->values,param_scalar2_vals);
param_kernel1 = mod.add_parameters({3,2});
TensorTools::SetElements(param_kernel1.get()->values,param_kernel1_vals);
param_filter1 = mod.add_parameters({3,2,2});
TensorTools::SetElements(param_filter1.get()->values,param_filter1_vals);
param_square1 = mod.add_parameters({3,3});
TensorTools::SetElements(param_square1.get()->values,param_square1_vals);
param_cube1 = mod.add_parameters({3,3,3});
TensorTools::SetElements(param_cube1.get()->values,param_cube1_vals);
}
~NodeTest() {
for (auto x : av) free(x);
}
template <class T>
std::string print_vec(const std::vector<T> vec) {
ostringstream oss;
if(vec.size()) oss << vec[0];
for(size_t i = 1; i < vec.size(); i++)
oss << ' ' << vec[i];
return oss.str();
}
std::vector<float> ones3_vals, ones2_vals, first_one_vals, batch_vals;
std::vector<char*> av;
dynet::Model mod;
dynet::Parameter param1, param2, param3, param4, param_scalar1, param_scalar2, param_kernel1, param_filter1, param_square1, param_cube1;
};
// define the test suite
BOOST_FIXTURE_TEST_SUITE(node_test, NodeTest);
// Expression operator-(const Expression& x);
BOOST_AUTO_TEST_CASE( negate_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = -x1;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator+(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( add_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = x1+x2;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression logsumexp(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( logsumexp_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param_scalar1);
Expression x2 = parameter(cg, param_scalar2);
Expression z = logsumexp({x1, x2});
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator+(const Expression& x, real y);
BOOST_AUTO_TEST_CASE( addscalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1+2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator+(real x, const Expression& y);
BOOST_AUTO_TEST_CASE( scalaradd_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = 2.0+x1;
Expression z =input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator-(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( subtract_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = x1+x2;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator-(real x, const Expression& y);
BOOST_AUTO_TEST_CASE( scalarsubtract_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = 2.0-x1;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator-(const Expression& x, real y);
BOOST_AUTO_TEST_CASE( subtractscalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1-2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( multiply_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = x1*transpose(x2);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( multiply_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = x1*transpose(x2);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * y * transpose(ones3));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = parameter(cg, param2);
Expression y = affine_transform({x1, x2, scalar});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * sqrt(y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = affine_transform({x1, x2, scalar});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * sqrt(y));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch_col_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = input(cg, Dim({1,3},2), batch_vals);
Expression y = affine_transform({transpose(x1), scalar, x2});
Expression ones3 = input(cg, {3,1}, ones3_vals);
Expression z = sum_batches(sqrt(y) * ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch2_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = input(cg, Dim({1,3},2), batch_vals);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = parameter(cg, param2);
Expression y = affine_transform({x1, scalar, transpose(x2) });
Expression ones3 = input(cg, {3,1}, ones3_vals);
Expression z = sum_batches(sqrt(y) * ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch3_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param_square1);
Expression inp = input(cg, Dim({3},2), batch_vals);
Expression y = affine_transform({x1, x2, inp });
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * sqrt(y));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, float y);
BOOST_AUTO_TEST_CASE( multiplyscalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1*2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// inline Expression operator*(float y, const Expression& x) { return x * y; }
BOOST_AUTO_TEST_CASE( scalarmultiply_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = 2.0*x1;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// inline Expression operator/(const Expression& x, float y) { return x * (1.f / y); }
BOOST_AUTO_TEST_CASE( dividescalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1/2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cdiv(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cdiv_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = cdiv(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cdiv(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cdiv_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = cdiv(x1, x2) + cdiv(x2, x1);
Expression z = sum_batches(input(cg, {1,3}, ones3_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression colwise_add(const Expression& x, const Expression& bias);
BOOST_AUTO_TEST_CASE( colwise_add_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = colwise_add(x1 * transpose(x2), x2);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression concatenate_cols(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( concatenate_cols_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = concatenate_cols({x1, x2, x1});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression concatenate(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( concatenate_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = transpose(parameter(cg, param1));
Expression x2 = transpose(parameter(cg, param2));
Expression y = concatenate({x1, x2, x1});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b);
BOOST_AUTO_TEST_CASE( contract3d_1d_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression square1 = parameter(cg, param_square1);
Expression cube1 = parameter(cg, param_cube1);
Expression y = contract3d_1d(cube1, x1, square1);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression contract3d_1d_1d(const Expression& x, const Expression& y, const Expression& z, const Expression& b);
BOOST_AUTO_TEST_CASE( contract3d_1d_1d_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression x3 = parameter(cg, param3);
Expression cube1 = parameter(cg, param_cube1);
Expression y = contract3d_1d_1d(cube1, x1, x2, x3);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sqrt(const Expression& x);
BOOST_AUTO_TEST_CASE( sqrt_gradient ) {
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression y = sqrt(x3);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression erf(const Expression& x);
BOOST_AUTO_TEST_CASE( erf_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = erf(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression tanh(const Expression& x);
BOOST_AUTO_TEST_CASE( tanh_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = tanh(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression exp(const Expression& x);
BOOST_AUTO_TEST_CASE( exp_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = exp(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression square(const Expression& x);
BOOST_AUTO_TEST_CASE( square_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = square(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cube(const Expression& x);
BOOST_AUTO_TEST_CASE( cube_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = cube(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression lgamma(const Expression& x);
BOOST_AUTO_TEST_CASE( lgamma_gradient ) {
dynet::ComputationGraph cg;
Expression x2 = parameter(cg, param2);
Expression y = lgamma(x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log(const Expression& x);
BOOST_AUTO_TEST_CASE( log_gradient ) {
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression y = log(x3);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression logistic(const Expression& x);
BOOST_AUTO_TEST_CASE( logistic_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = logistic(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression rectify(const Expression& x);
BOOST_AUTO_TEST_CASE( rectify_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = rectify(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression hinge(const Expression& x, unsigned index, float m = 1.0);
BOOST_AUTO_TEST_CASE( hinge_gradient ) {
unsigned index = 0;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = hinge(x1, index, 0.5);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression hinge(const Expression& x, unsigned index, float m = 1.0);
BOOST_AUTO_TEST_CASE( hinge_batch_gradient ) {
std::vector<unsigned> idx = {1,2};
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(hinge(x1+x2, idx, 2.f));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression hinge(const Expression& x, const unsigned* pindex, float m = 1.0);
BOOST_AUTO_TEST_CASE( hingeptr_gradient ) {
unsigned index = 0;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = hinge(x1, &index, 0.5);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log_softmax(const Expression& x);
BOOST_AUTO_TEST_CASE( log_softmax_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = log_softmax(x1);
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log_softmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( log_softmax_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = log_softmax(x1+x2);
Expression z = sum_batches(input(cg, {1,3}, first_one_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log_softmax(const Expression& x, const std::vector<unsigned>& restriction);
BOOST_AUTO_TEST_CASE( restricted_log_softmax_gradient ) {
vector<unsigned> restriction = {0,1};
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression y = exp( log_softmax(x3, restriction) );
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression softmax(const Expression& x);
BOOST_AUTO_TEST_CASE( softmax_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = log(softmax(x1));
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression softmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( softmax_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = log(softmax(x1+x2));
Expression z = sum_batches(input(cg, {1,3}, first_one_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sparsemax(const Expression& x);
BOOST_AUTO_TEST_CASE( sparsemax_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = sparsemax(x1);
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sparsemax_loss(const Expression& x);
BOOST_AUTO_TEST_CASE( sparsemax_loss_gradient ) {
std::vector<unsigned> idxs(2); idxs[0] = 1; idxs[1] = 2;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = sparsemax_loss(x1, idxs);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression softsign(const Expression& x);
BOOST_AUTO_TEST_CASE( softsign_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = softsign(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pow(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( pow_gradient ) {
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression x_scalar1 = parameter(cg, param_scalar1);
Expression y = pow(x3, x_scalar1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression min(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( min_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = min(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression max(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( max_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = max(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// TODO: Noise is random, so it cannot be tested simply?
// // Expression noise(const Expression& x, real stddev);
// BOOST_AUTO_TEST_CASE( noise_gradient ) {
// dynet::ComputationGraph cg;
// Expression x1 = parameter(cg, param1);
// Expression y = noise(x1, 0.5);
// input(cg, {1,3}, ones3_vals) * y;
// BOOST_CHECK(check_grad(mod, cg, 0));
// }
// TODO: Dropout scales the gradients at training time, so they don't match.
// // Expression dropout(const Expression& x, real p);
// BOOST_AUTO_TEST_CASE( dropout_gradient ) {
// dynet::ComputationGraph cg;
// Expression x1 = parameter(cg, param1);
// Expression y = dropout(x1, 0.5);
// input(cg, {1,3}, ones3_vals) * y;
// BOOST_CHECK(check_grad(mod, cg, 0));
// }
// TODO: Dropout scales the gradients at training time, so they don't match.
// Expression block_dropout(const Expression& x, real p);
// Expression reshape(const Expression& x, const Dim& d);
BOOST_AUTO_TEST_CASE( reshape_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = reshape(x1, {1,3});
Expression z = y * input(cg, {3}, ones3_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression reshape(const Expression& x, const Dim& d);
BOOST_AUTO_TEST_CASE( reshape_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y1 = x1*transpose(x2);
Expression y2 = reshape(y1, Dim({3,3}, 2));
Expression z = sum_batches(input(cg, {1,3}, ones3_vals) * y2 * input(cg, {3,1}, ones3_vals));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression transpose(const Expression& x);
BOOST_AUTO_TEST_CASE( transpose_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = softsign(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// inverse is too numerically unstable to test appropriately
// // Expression inverse(const Expression& x);
// BOOST_AUTO_TEST_CASE( inverse_gradient ) {
// dynet::ComputationGraph cg;
// Expression x = parameter(cg, param_square1);
// Expression y = inverse(x);
// Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {3,1}, ones3_vals);
// BOOST_CHECK(check_grad(mod, z, 0));
// }
// Expression trace_of_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( trace_of_product_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = trace_of_product(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cmult(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cmult_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = cmult(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cmult(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cmult_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = cmult(x1, x2) + cmult(x2, x1);
Expression z = sum_batches(input(cg, {1,3}, ones3_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression dot_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( dot_product_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = dot_product(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression dot_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( dot_product_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(dot_product(x1, x2) + dot_product(x2, x1) * 2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression squared_distance(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( squared_distance_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = squared_distance(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression huber_distance(const Expression& x, const Expression& y, float c = 1.345f);
BOOST_AUTO_TEST_CASE( huber_distance_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = huber_distance(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression l1_distance(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( l1_distance_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = l1_distance(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression binary_log_loss(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( binary_log_loss_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = logistic( parameter(cg, param1) );
Expression x2 = input(cg, {3}, ones3_vals);
Expression z = binary_log_loss(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m=1.0);
BOOST_AUTO_TEST_CASE( pairwise_rank_loss_gradient ) {
dynet::ComputationGraph cg;
Expression x_scalar1 = parameter(cg, param_scalar1);
Expression x_scalar2 = parameter(cg, param_scalar2);
Expression z = pairwise_rank_loss(x_scalar1, x_scalar2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression poisson_loss(const Expression& x, unsigned y);
BOOST_AUTO_TEST_CASE( possion_loss_gradient ) {
dynet::ComputationGraph cg;
Expression scalar = parameter(cg, param_scalar1);
Expression z = poisson_loss(scalar, 3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression conv1d_narrow(const Expression& x, const Expression& f);
BOOST_AUTO_TEST_CASE( conv1d_narrow_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression xkernel = parameter(cg, param_kernel1);
Expression y = conv1d_narrow(xsquare, xkernel);
Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {2,1}, ones2_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression conv1d_wide(const Expression& x, const Expression& f);
BOOST_AUTO_TEST_CASE( conv1d_wide_gradient ) {
dynet::ComputationGraph cg;
Expression xkernel = parameter(cg, param_kernel1);
Expression y = conv1d_wide(xkernel, xkernel);
Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {3,1}, ones3_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression filter1d_narrow(const Expression& x, const Expression& f);
BOOST_AUTO_TEST_CASE( filter1d_narrow_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression xfilter = parameter(cg, param_filter1);
Expression y = filter1d_narrow(xsquare, xfilter);
Expression z = input(cg, {1,2}, ones3_vals) * y * input(cg, {2,1}, ones2_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression kmax_pooling(const Expression& x, unsigned k);
BOOST_AUTO_TEST_CASE( kmax_pooling_keq1_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(kmax_pooling(xsquare, 1));
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression kmax_pooling(const Expression& x, unsigned k);
BOOST_AUTO_TEST_CASE( kmax_pooling_keq2_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(kmax_pooling(xsquare, 2));
Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {2,1}, ones2_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression fold_rows(const Expression& x, unsigned nrows=2);
BOOST_AUTO_TEST_CASE( fold_rows_gradient ) {
dynet::ComputationGraph cg;
Expression x4 = parameter(cg, param4);
Expression y = fold_rows(x4, 2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression average_cols(const Expression& x);
BOOST_AUTO_TEST_CASE( average_cols_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(average_cols(xsquare));
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sum_cols(const Expression& x);
BOOST_AUTO_TEST_CASE( sum_cols_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(sum_cols(xsquare));
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// TODO: These are all unimplemented
// Expression kmh_ngram(const Expression& x, unsigned n);
// Expression pick(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pick_gradient ) {
unsigned idx = 1;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = pick(x1, idx);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pick(const Expression& x, unsigned* pv);
BOOST_AUTO_TEST_CASE( pickptr_gradient ) {
unsigned idx = 1;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = pick(x1, &idx);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pick(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pick_batch_gradient ) {
std::vector<unsigned> idx = {1,2};
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(pick(x1+x2, idx));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pickrange(const Expression& x, unsigned v, unsigned u);
BOOST_AUTO_TEST_CASE( pickrange_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = pickrange(x1, 0, 2);
Expression z = input(cg, {1,2}, ones2_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pickneglogsoftmax_gradient ) {
unsigned idx = 1;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = pickneglogsoftmax(x1, idx);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pickneglogsoftmax_batch_gradient ) {
std::vector<unsigned> idx = {1,2};
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(pickneglogsoftmax(x1+x2, idx));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sparse_input(vector<unsigned int>& ids, vector<float>& src, float def);
BOOST_AUTO_TEST_CASE( sparse_input_test ) {
dynet::ComputationGraph cg;
std::vector<unsigned int> ids = {0, 4};
Expression z = input(cg, Dim({3},2), ids, ones2_vals, 0.5);
std::vector<float> exp = {1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.5f};
std::vector<float> act = as_vector(cg.forward(z));
assert(exp.size() == act.size());
for(size_t i = 0; i < exp.size(); ++i)
BOOST_CHECK_CLOSE(exp[i], act[i], 0.001);
}
BOOST_AUTO_TEST_SUITE_END()
Added some tests for sum with minibatches
#include <dynet/dynet.h>
#include <dynet/expr.h>
#include <dynet/grad-check.h>
#include <boost/test/unit_test.hpp>
#include <stdexcept>
using namespace dynet;
using namespace dynet::expr;
using namespace std;
struct NodeTest {
NodeTest() {
// initialize if necessary
if(default_device == nullptr) {
for (auto x : {"NodeTest", "--dynet-mem", "10"}) {
av.push_back(strdup(x));
}
char **argv = &av[0];
int argc = av.size();
dynet::initialize(argc, argv);
}
ones3_vals = {1.f,1.f,1.f};
first_one_vals = {1.f,0.f,0.f};
ones2_vals = {1.f,1.f};
batch_vals = {1.f,2.f,3.f,4.f,5.f,6.f};
// Create parameters
std::vector<float> param1_vals = {1.1f,-2.2f,3.3f};
std::vector<float> param2_vals = {2.2f,3.4f,-1.2f};
std::vector<float> param3_vals = {1.1f,2.2f,3.3f};
std::vector<float> param4_vals = {1.1f,2.2f,3.3f,-1.2f,2.1f,3.4f};
std::vector<float> param_scalar1_vals = {2.2f};
std::vector<float> param_scalar2_vals = {1.1f};
std::vector<float> param_kernel1_vals = {1.1f,2.2f,-1.0f,1.2f,-3.4f,-0.2f};
std::vector<float> param_filter1_vals = {1.1f,2.2f,-1.0f,1.2f,-3.4f,-0.2f,
11.1f,12.2f,13.3f,11.2f,12.2f,13.2f};
std::vector<float> param_square1_vals = {1.1f,2.2f,3.4f,1.2f,2.5f,3.2f,5.3f,2.3f,3.3f};
std::vector<float> param_cube1_vals = {.011f,.022f,.033f,.012f,.022f,.032f,.013f,.023f,.033f,
.111f,-.122f,-.033f,-.112f,-.022f,-.132f,-.113f,-.123f,-.133f,
.211f,.222f,.233f,.212f,.222f,.232f,.213f,.223f,.233f};
param1 = mod.add_parameters({3});
TensorTools::SetElements(param1.get()->values,param1_vals);
param2 = mod.add_parameters({3});
TensorTools::SetElements(param2.get()->values,param2_vals);
param3 = mod.add_parameters({3});
TensorTools::SetElements(param3.get()->values,param3_vals);
param4 = mod.add_parameters({6});
TensorTools::SetElements(param4.get()->values,param4_vals);
param_scalar1 = mod.add_parameters({1});
TensorTools::SetElements(param_scalar1.get()->values,param_scalar1_vals);
param_scalar2 = mod.add_parameters({1});
TensorTools::SetElements(param_scalar2.get()->values,param_scalar2_vals);
param_kernel1 = mod.add_parameters({3,2});
TensorTools::SetElements(param_kernel1.get()->values,param_kernel1_vals);
param_filter1 = mod.add_parameters({3,2,2});
TensorTools::SetElements(param_filter1.get()->values,param_filter1_vals);
param_square1 = mod.add_parameters({3,3});
TensorTools::SetElements(param_square1.get()->values,param_square1_vals);
param_cube1 = mod.add_parameters({3,3,3});
TensorTools::SetElements(param_cube1.get()->values,param_cube1_vals);
}
~NodeTest() {
for (auto x : av) free(x);
}
template <class T>
std::string print_vec(const std::vector<T> vec) {
ostringstream oss;
if(vec.size()) oss << vec[0];
for(size_t i = 1; i < vec.size(); i++)
oss << ' ' << vec[i];
return oss.str();
}
std::vector<float> ones3_vals, ones2_vals, first_one_vals, batch_vals;
std::vector<char*> av;
dynet::Model mod;
dynet::Parameter param1, param2, param3, param4, param_scalar1, param_scalar2, param_kernel1, param_filter1, param_square1, param_cube1;
};
// define the test suite
BOOST_FIXTURE_TEST_SUITE(node_test, NodeTest);
// Expression operator-(const Expression& x);
BOOST_AUTO_TEST_CASE( negate_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = -x1;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator+(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( add_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = x1+x2;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sum(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( sum_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = sum({x2,x1,x2});
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sum(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( sum_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression x3 = input(cg, Dim({3},2), batch_vals);
Expression y = sum({x3,x1,cmult(x2,x3)});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression logsumexp(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( logsumexp_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param_scalar1);
Expression x2 = parameter(cg, param_scalar2);
Expression z = logsumexp({x1, x2});
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator+(const Expression& x, real y);
BOOST_AUTO_TEST_CASE( addscalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1+2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator+(real x, const Expression& y);
BOOST_AUTO_TEST_CASE( scalaradd_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = 2.0+x1;
Expression z =input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator-(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( subtract_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = x1+x2;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator-(real x, const Expression& y);
BOOST_AUTO_TEST_CASE( scalarsubtract_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = 2.0-x1;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator-(const Expression& x, real y);
BOOST_AUTO_TEST_CASE( subtractscalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1-2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( multiply_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = x1*transpose(x2);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( multiply_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = x1*transpose(x2);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * y * transpose(ones3));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = parameter(cg, param2);
Expression y = affine_transform({x1, x2, scalar});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * sqrt(y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = affine_transform({x1, x2, scalar});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * sqrt(y));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch_col_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = input(cg, Dim({1,3},2), batch_vals);
Expression y = affine_transform({transpose(x1), scalar, x2});
Expression ones3 = input(cg, {3,1}, ones3_vals);
Expression z = sum_batches(sqrt(y) * ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch2_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = input(cg, Dim({1,3},2), batch_vals);
Expression scalar = parameter(cg, param_scalar1);
Expression x2 = parameter(cg, param2);
Expression y = affine_transform({x1, scalar, transpose(x2) });
Expression ones3 = input(cg, {3,1}, ones3_vals);
Expression z = sum_batches(sqrt(y) * ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch3_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param_square1);
Expression inp = input(cg, Dim({3},2), batch_vals);
Expression y = affine_transform({x1, x2, inp });
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = sum_batches(ones3 * sqrt(y));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression operator*(const Expression& x, float y);
BOOST_AUTO_TEST_CASE( multiplyscalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1*2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// inline Expression operator*(float y, const Expression& x) { return x * y; }
BOOST_AUTO_TEST_CASE( scalarmultiply_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = 2.0*x1;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// inline Expression operator/(const Expression& x, float y) { return x * (1.f / y); }
BOOST_AUTO_TEST_CASE( dividescalar_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = x1/2.0;
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cdiv(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cdiv_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = cdiv(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cdiv(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cdiv_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = cdiv(x1, x2) + cdiv(x2, x1);
Expression z = sum_batches(input(cg, {1,3}, ones3_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression colwise_add(const Expression& x, const Expression& bias);
BOOST_AUTO_TEST_CASE( colwise_add_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = colwise_add(x1 * transpose(x2), x2);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression concatenate_cols(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( concatenate_cols_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = concatenate_cols({x1, x2, x1});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression concatenate(const std::initializer_list<Expression>& xs);
BOOST_AUTO_TEST_CASE( concatenate_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = transpose(parameter(cg, param1));
Expression x2 = transpose(parameter(cg, param2));
Expression y = concatenate({x1, x2, x1});
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b);
BOOST_AUTO_TEST_CASE( contract3d_1d_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression square1 = parameter(cg, param_square1);
Expression cube1 = parameter(cg, param_cube1);
Expression y = contract3d_1d(cube1, x1, square1);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y * transpose(ones3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression contract3d_1d_1d(const Expression& x, const Expression& y, const Expression& z, const Expression& b);
BOOST_AUTO_TEST_CASE( contract3d_1d_1d_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression x3 = parameter(cg, param3);
Expression cube1 = parameter(cg, param_cube1);
Expression y = contract3d_1d_1d(cube1, x1, x2, x3);
Expression ones3 = input(cg, {1,3}, ones3_vals);
Expression z = ones3 * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sqrt(const Expression& x);
BOOST_AUTO_TEST_CASE( sqrt_gradient ) {
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression y = sqrt(x3);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression erf(const Expression& x);
BOOST_AUTO_TEST_CASE( erf_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = erf(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression tanh(const Expression& x);
BOOST_AUTO_TEST_CASE( tanh_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = tanh(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression exp(const Expression& x);
BOOST_AUTO_TEST_CASE( exp_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = exp(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression square(const Expression& x);
BOOST_AUTO_TEST_CASE( square_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = square(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cube(const Expression& x);
BOOST_AUTO_TEST_CASE( cube_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = cube(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression lgamma(const Expression& x);
BOOST_AUTO_TEST_CASE( lgamma_gradient ) {
dynet::ComputationGraph cg;
Expression x2 = parameter(cg, param2);
Expression y = lgamma(x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log(const Expression& x);
BOOST_AUTO_TEST_CASE( log_gradient ) {
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression y = log(x3);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression logistic(const Expression& x);
BOOST_AUTO_TEST_CASE( logistic_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = logistic(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression rectify(const Expression& x);
BOOST_AUTO_TEST_CASE( rectify_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = rectify(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression hinge(const Expression& x, unsigned index, float m = 1.0);
BOOST_AUTO_TEST_CASE( hinge_gradient ) {
unsigned index = 0;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = hinge(x1, index, 0.5);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression hinge(const Expression& x, unsigned index, float m = 1.0);
BOOST_AUTO_TEST_CASE( hinge_batch_gradient ) {
std::vector<unsigned> idx = {1,2};
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(hinge(x1+x2, idx, 2.f));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression hinge(const Expression& x, const unsigned* pindex, float m = 1.0);
BOOST_AUTO_TEST_CASE( hingeptr_gradient ) {
unsigned index = 0;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = hinge(x1, &index, 0.5);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log_softmax(const Expression& x);
BOOST_AUTO_TEST_CASE( log_softmax_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = log_softmax(x1);
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log_softmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( log_softmax_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = log_softmax(x1+x2);
Expression z = sum_batches(input(cg, {1,3}, first_one_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression log_softmax(const Expression& x, const std::vector<unsigned>& restriction);
BOOST_AUTO_TEST_CASE( restricted_log_softmax_gradient ) {
vector<unsigned> restriction = {0,1};
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression y = exp( log_softmax(x3, restriction) );
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression softmax(const Expression& x);
BOOST_AUTO_TEST_CASE( softmax_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = log(softmax(x1));
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression softmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( softmax_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = log(softmax(x1+x2));
Expression z = sum_batches(input(cg, {1,3}, first_one_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sparsemax(const Expression& x);
BOOST_AUTO_TEST_CASE( sparsemax_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = sparsemax(x1);
Expression z = input(cg, {1,3}, first_one_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sparsemax_loss(const Expression& x);
BOOST_AUTO_TEST_CASE( sparsemax_loss_gradient ) {
std::vector<unsigned> idxs(2); idxs[0] = 1; idxs[1] = 2;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = sparsemax_loss(x1, idxs);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression softsign(const Expression& x);
BOOST_AUTO_TEST_CASE( softsign_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = softsign(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pow(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( pow_gradient ) {
dynet::ComputationGraph cg;
Expression x3 = parameter(cg, param3);
Expression x_scalar1 = parameter(cg, param_scalar1);
Expression y = pow(x3, x_scalar1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression min(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( min_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = min(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression max(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( max_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = max(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// TODO: Noise is random, so it cannot be tested simply?
// // Expression noise(const Expression& x, real stddev);
// BOOST_AUTO_TEST_CASE( noise_gradient ) {
// dynet::ComputationGraph cg;
// Expression x1 = parameter(cg, param1);
// Expression y = noise(x1, 0.5);
// input(cg, {1,3}, ones3_vals) * y;
// BOOST_CHECK(check_grad(mod, cg, 0));
// }
// TODO: Dropout scales the gradients at training time, so they don't match.
// // Expression dropout(const Expression& x, real p);
// BOOST_AUTO_TEST_CASE( dropout_gradient ) {
// dynet::ComputationGraph cg;
// Expression x1 = parameter(cg, param1);
// Expression y = dropout(x1, 0.5);
// input(cg, {1,3}, ones3_vals) * y;
// BOOST_CHECK(check_grad(mod, cg, 0));
// }
// TODO: Dropout scales the gradients at training time, so they don't match.
// Expression block_dropout(const Expression& x, real p);
// Expression reshape(const Expression& x, const Dim& d);
BOOST_AUTO_TEST_CASE( reshape_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = reshape(x1, {1,3});
Expression z = y * input(cg, {3}, ones3_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression reshape(const Expression& x, const Dim& d);
BOOST_AUTO_TEST_CASE( reshape_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y1 = x1*transpose(x2);
Expression y2 = reshape(y1, Dim({3,3}, 2));
Expression z = sum_batches(input(cg, {1,3}, ones3_vals) * y2 * input(cg, {3,1}, ones3_vals));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression transpose(const Expression& x);
BOOST_AUTO_TEST_CASE( transpose_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = softsign(x1);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// inverse is too numerically unstable to test appropriately
// // Expression inverse(const Expression& x);
// BOOST_AUTO_TEST_CASE( inverse_gradient ) {
// dynet::ComputationGraph cg;
// Expression x = parameter(cg, param_square1);
// Expression y = inverse(x);
// Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {3,1}, ones3_vals);
// BOOST_CHECK(check_grad(mod, z, 0));
// }
// Expression trace_of_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( trace_of_product_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = trace_of_product(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cmult(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cmult_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression y = cmult(x1, x2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression cmult(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cmult_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression y = cmult(x1, x2) + cmult(x2, x1);
Expression z = sum_batches(input(cg, {1,3}, ones3_vals) * y);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression dot_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( dot_product_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = dot_product(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression dot_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( dot_product_batch_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(dot_product(x1, x2) + dot_product(x2, x1) * 2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression squared_distance(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( squared_distance_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = squared_distance(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression huber_distance(const Expression& x, const Expression& y, float c = 1.345f);
BOOST_AUTO_TEST_CASE( huber_distance_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = huber_distance(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression l1_distance(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( l1_distance_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = parameter(cg, param2);
Expression z = l1_distance(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression binary_log_loss(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( binary_log_loss_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = logistic( parameter(cg, param1) );
Expression x2 = input(cg, {3}, ones3_vals);
Expression z = binary_log_loss(x1, x2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m=1.0);
BOOST_AUTO_TEST_CASE( pairwise_rank_loss_gradient ) {
dynet::ComputationGraph cg;
Expression x_scalar1 = parameter(cg, param_scalar1);
Expression x_scalar2 = parameter(cg, param_scalar2);
Expression z = pairwise_rank_loss(x_scalar1, x_scalar2);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression poisson_loss(const Expression& x, unsigned y);
BOOST_AUTO_TEST_CASE( possion_loss_gradient ) {
dynet::ComputationGraph cg;
Expression scalar = parameter(cg, param_scalar1);
Expression z = poisson_loss(scalar, 3);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression conv1d_narrow(const Expression& x, const Expression& f);
BOOST_AUTO_TEST_CASE( conv1d_narrow_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression xkernel = parameter(cg, param_kernel1);
Expression y = conv1d_narrow(xsquare, xkernel);
Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {2,1}, ones2_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression conv1d_wide(const Expression& x, const Expression& f);
BOOST_AUTO_TEST_CASE( conv1d_wide_gradient ) {
dynet::ComputationGraph cg;
Expression xkernel = parameter(cg, param_kernel1);
Expression y = conv1d_wide(xkernel, xkernel);
Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {3,1}, ones3_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression filter1d_narrow(const Expression& x, const Expression& f);
BOOST_AUTO_TEST_CASE( filter1d_narrow_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression xfilter = parameter(cg, param_filter1);
Expression y = filter1d_narrow(xsquare, xfilter);
Expression z = input(cg, {1,2}, ones3_vals) * y * input(cg, {2,1}, ones2_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression kmax_pooling(const Expression& x, unsigned k);
BOOST_AUTO_TEST_CASE( kmax_pooling_keq1_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(kmax_pooling(xsquare, 1));
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression kmax_pooling(const Expression& x, unsigned k);
BOOST_AUTO_TEST_CASE( kmax_pooling_keq2_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(kmax_pooling(xsquare, 2));
Expression z = input(cg, {1,3}, ones3_vals) * y * input(cg, {2,1}, ones2_vals);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression fold_rows(const Expression& x, unsigned nrows=2);
BOOST_AUTO_TEST_CASE( fold_rows_gradient ) {
dynet::ComputationGraph cg;
Expression x4 = parameter(cg, param4);
Expression y = fold_rows(x4, 2);
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression average_cols(const Expression& x);
BOOST_AUTO_TEST_CASE( average_cols_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(average_cols(xsquare));
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sum_cols(const Expression& x);
BOOST_AUTO_TEST_CASE( sum_cols_gradient ) {
dynet::ComputationGraph cg;
Expression xsquare = parameter(cg, param_square1);
Expression y = tanh(sum_cols(xsquare));
Expression z = input(cg, {1,3}, ones3_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// TODO: These are all unimplemented
// Expression kmh_ngram(const Expression& x, unsigned n);
// Expression pick(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pick_gradient ) {
unsigned idx = 1;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = pick(x1, idx);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pick(const Expression& x, unsigned* pv);
BOOST_AUTO_TEST_CASE( pickptr_gradient ) {
unsigned idx = 1;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = pick(x1, &idx);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pick(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pick_batch_gradient ) {
std::vector<unsigned> idx = {1,2};
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(pick(x1+x2, idx));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pickrange(const Expression& x, unsigned v, unsigned u);
BOOST_AUTO_TEST_CASE( pickrange_gradient ) {
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression y = pickrange(x1, 0, 2);
Expression z = input(cg, {1,2}, ones2_vals) * y;
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pickneglogsoftmax_gradient ) {
unsigned idx = 1;
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression z = pickneglogsoftmax(x1, idx);
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pickneglogsoftmax_batch_gradient ) {
std::vector<unsigned> idx = {1,2};
dynet::ComputationGraph cg;
Expression x1 = parameter(cg, param1);
Expression x2 = input(cg, Dim({3},2), batch_vals);
Expression z = sum_batches(pickneglogsoftmax(x1+x2, idx));
BOOST_CHECK(check_grad(mod, z, 0));
}
// Expression sparse_input(vector<unsigned int>& ids, vector<float>& src, float def);
BOOST_AUTO_TEST_CASE( sparse_input_test ) {
dynet::ComputationGraph cg;
std::vector<unsigned int> ids = {0, 4};
Expression z = input(cg, Dim({3},2), ids, ones2_vals, 0.5);
std::vector<float> exp = {1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.5f};
std::vector<float> act = as_vector(cg.forward(z));
assert(exp.size() == act.size());
for(size_t i = 0; i < exp.size(); ++i)
BOOST_CHECK_CLOSE(exp[i], act[i], 0.001);
}
BOOST_AUTO_TEST_SUITE_END()
|
/** \file
*
* Unit tests for the Features API, which lets us attach metadata to Alignments and MultipathAlignments.
*/
#include <iostream>
#include <sstream>
#include "../features.hpp"
#include "catch.hpp"
namespace vg {
namespace unittest {
using namespace std;
TEST_CASE("Tag features work", "[features][alignment]") {
Alignment aln;
SECTION("Feature starts not present") {
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
SECTION("Feature is present after addition") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
SECTION("Feature can be removed again") {
remove_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
}
SECTION("Feature can be added with a bool value") {
SECTION("False does not set it") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, false);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
SECTION("True sets it") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, true);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
}
SECTION("Feature can be set") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
set_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, true);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
set_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, false);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
set_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, true);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
}
TEST_CASE("Single-value features work", "[features][alignment]") {
Alignment aln;
SECTION("Features start not present") {
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
}
SECTION("Feature is present after addition") {
add_feature(aln, FeatureType::HAPLOTYPE_LOGPROB, 1.0);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
REQUIRE(get_feature(aln, FeatureType::HAPLOTYPE_LOGPROB) == 1.0);
}
}
}
}
Test the multi-valued features too
/** \file
*
* Unit tests for the Features API, which lets us attach metadata to Alignments and MultipathAlignments.
*/
#include <iostream>
#include <sstream>
#include "../features.hpp"
#include "catch.hpp"
namespace vg {
namespace unittest {
using namespace std;
TEST_CASE("Tag features work", "[features][alignment]") {
Alignment aln;
SECTION("Feature starts not present") {
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
SECTION("Feature is present after addition") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
SECTION("Feature can be removed again") {
remove_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
}
SECTION("Feature can be added with a bool value") {
SECTION("False does not set it") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, false);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
SECTION("True sets it") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, true);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
}
SECTION("Feature can be set") {
add_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
set_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, true);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
set_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, false);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
set_feature(&aln, FeatureType::HAPLOTYPE_SCORED_TAG, true);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_SCORED_TAG));
}
}
TEST_CASE("Single-value features work", "[features][alignment]") {
Alignment aln;
SECTION("Features start not present") {
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
}
SECTION("Feature is present after addition") {
add_feature(&aln, FeatureType::HAPLOTYPE_LOGPROB, 1.0);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
REQUIRE(get_feature(aln, FeatureType::HAPLOTYPE_LOGPROB) == 1.0);
SECTION("Feature can be removed") {
remove_feature(&aln, FeatureType::HAPLOTYPE_LOGPROB);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
}
}
SECTION("Feature can be set") {
set_feature(&aln, FeatureType::HAPLOTYPE_LOGPROB, 1.0);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
REQUIRE(get_feature(aln, FeatureType::HAPLOTYPE_LOGPROB) == 1.0);
set_feature(&aln, FeatureType::HAPLOTYPE_LOGPROB, 15);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
REQUIRE(get_feature(aln, FeatureType::HAPLOTYPE_LOGPROB) == (double)15);
set_feature(&aln, FeatureType::HAPLOTYPE_LOGPROB, 2.0);
REQUIRE(has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
REQUIRE(get_feature(aln, FeatureType::HAPLOTYPE_LOGPROB) == 2.0);
remove_feature(&aln, FeatureType::HAPLOTYPE_LOGPROB);
REQUIRE(!has_feature(aln, FeatureType::HAPLOTYPE_LOGPROB));
}
}
TEST_CASE("Multi-value features work", "[features][alignment]") {
Alignment aln;
SECTION("Features start not present") {
REQUIRE(!has_feature(aln, FeatureType::SECONDARY_SCORES));
}
SECTION("Feature is present after addition") {
add_feature(&aln, FeatureType::SECONDARY_SCORES, 1.0);
REQUIRE(has_feature(aln, FeatureType::SECONDARY_SCORES));
REQUIRE(get_feature(aln, FeatureType::SECONDARY_SCORES) == 1.0);
auto vals = get_features(aln, FeatureType::SECONDARY_SCORES);
REQUIRE(vals.size() == 1);
REQUIRE(vals[0] == 1.0);
SECTION("Feature can be removed") {
remove_feature(&aln, FeatureType::SECONDARY_SCORES);
REQUIRE(!has_feature(aln, FeatureType::SECONDARY_SCORES));
auto vals = get_features(aln, FeatureType::SECONDARY_SCORES);
REQUIRE(vals.size() == 0);
}
SECTION("More values can be added") {
add_feature(&aln, FeatureType::SECONDARY_SCORES, 2.0);
add_feature(&aln, FeatureType::SECONDARY_SCORES, 3.0);
REQUIRE(get_feature(aln, FeatureType::SECONDARY_SCORES) == 1.0);
auto vals = get_features(aln, FeatureType::SECONDARY_SCORES);
REQUIRE(vals.size() == 3);
REQUIRE(vals[0] == 1.0);
REQUIRE(vals[1] == 2.0);
REQUIRE(vals[2] == 3.0);
SECTION("All values can be removed") {
remove_feature(&aln, FeatureType::SECONDARY_SCORES);
REQUIRE(!has_feature(aln, FeatureType::SECONDARY_SCORES));
auto vals = get_features(aln, FeatureType::SECONDARY_SCORES);
REQUIRE(vals.size() == 0);
}
}
}
}
}
}
|
/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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
* COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
****************************************************************************/
/*
* @file attitude_estimator_q_main.cpp
*
* Attitude estimator (quaternion based)
*
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <px4_config.h>
#include <px4_posix.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
#include <fcntl.h>
#include <float.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <uORB/uORB.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_attitude.h>
#include <uORB/topics/vehicle_control_mode.h>
#include <uORB/topics/vehicle_global_position.h>
#include <uORB/topics/parameter_update.h>
#include <drivers/drv_hrt.h>
#include <mathlib/mathlib.h>
#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <lib/geo/geo.h>
#include <lib/ecl/validation/data_validator_group.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/systemlib.h>
#include <systemlib/param/param.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
extern "C" __EXPORT int attitude_estimator_q_main(int argc, char *argv[]);
using math::Vector;
using math::Matrix;
using math::Quaternion;
class AttitudeEstimatorQ;
namespace attitude_estimator_q {
AttitudeEstimatorQ *instance;
}
class AttitudeEstimatorQ {
public:
/**
* Constructor
*/
AttitudeEstimatorQ();
/**
* Destructor, also kills task.
*/
~AttitudeEstimatorQ();
/**
* Start task.
*
* @return OK on success.
*/
int start();
static void task_main_trampoline(int argc, char *argv[]);
void task_main();
void print();
private:
static constexpr float _dt_max = 0.02;
bool _task_should_exit = false; /**< if true, task should exit */
int _control_task = -1; /**< task handle for task */
int _sensors_sub = -1;
int _params_sub = -1;
int _global_pos_sub = -1;
orb_advert_t _att_pub = nullptr;
struct {
param_t w_acc;
param_t w_mag;
param_t w_gyro_bias;
param_t mag_decl;
param_t mag_decl_auto;
param_t acc_comp;
param_t bias_max;
param_t vibe_thresh;
} _params_handles; /**< handles for interesting parameters */
float _w_accel = 0.0f;
float _w_mag = 0.0f;
float _w_gyro_bias = 0.0f;
float _mag_decl = 0.0f;
bool _mag_decl_auto = false;
bool _acc_comp = false;
float _bias_max = 0.0f;
float _vibration_warning_threshold = 1.0f;
hrt_abstime _vibration_warning_timestamp = 0;
Vector<3> _gyro;
Vector<3> _accel;
Vector<3> _mag;
Quaternion _q;
Vector<3> _rates;
Vector<3> _gyro_bias;
vehicle_global_position_s _gpos = {};
Vector<3> _vel_prev;
Vector<3> _pos_acc;
DataValidatorGroup _voter_gyro;
DataValidatorGroup _voter_accel;
DataValidatorGroup _voter_mag;
/* Low pass filter for attitude rates */
math::LowPassFilter2p _lp_roll_rate;
math::LowPassFilter2p _lp_pitch_rate;
hrt_abstime _vel_prev_t = 0;
bool _inited = false;
bool _data_good = false;
bool _failsafe = false;
bool _vibration_warning = false;
int _mavlink_fd = -1;
perf_counter_t _update_perf;
perf_counter_t _loop_perf;
void update_parameters(bool force);
int update_subscriptions();
bool init();
bool update(float dt);
};
AttitudeEstimatorQ::AttitudeEstimatorQ() :
_voter_gyro(3),
_voter_accel(3),
_voter_mag(3),
_lp_roll_rate(250.0f, 20.0f),
_lp_pitch_rate(250.0f, 20.0f)
{
_voter_mag.set_timeout(200000);
_params_handles.w_acc = param_find("ATT_W_ACC");
_params_handles.w_mag = param_find("ATT_W_MAG");
_params_handles.w_gyro_bias = param_find("ATT_W_GYRO_BIAS");
_params_handles.mag_decl = param_find("ATT_MAG_DECL");
_params_handles.mag_decl_auto = param_find("ATT_MAG_DECL_A");
_params_handles.acc_comp = param_find("ATT_ACC_COMP");
_params_handles.bias_max = param_find("ATT_BIAS_MAX");
_params_handles.vibe_thresh = param_find("ATT_VIBE_THRESH");
}
/**
* Destructor, also kills task.
*/
AttitudeEstimatorQ::~AttitudeEstimatorQ()
{
if (_control_task != -1) {
/* task wakes up every 100ms or so at the longest */
_task_should_exit = true;
/* wait for a second for the task to quit at our request */
unsigned i = 0;
do {
/* wait 20ms */
usleep(20000);
/* if we have given up, kill it */
if (++i > 50) {
px4_task_delete(_control_task);
break;
}
} while (_control_task != -1);
}
attitude_estimator_q::instance = nullptr;
}
int AttitudeEstimatorQ::start()
{
ASSERT(_control_task == -1);
/* start the task */
_control_task = px4_task_spawn_cmd("attitude_estimator_q",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
2100,
(px4_main_t)&AttitudeEstimatorQ::task_main_trampoline,
nullptr);
if (_control_task < 0) {
warn("task start failed");
return -errno;
}
return OK;
}
void AttitudeEstimatorQ::print()
{
warnx("gyro status:");
_voter_gyro.print();
warnx("accel status:");
_voter_accel.print();
warnx("mag status:");
_voter_mag.print();
}
void AttitudeEstimatorQ::task_main_trampoline(int argc, char *argv[])
{
attitude_estimator_q::instance->task_main();
}
void AttitudeEstimatorQ::task_main()
{
_sensors_sub = orb_subscribe(ORB_ID(sensor_combined));
_params_sub = orb_subscribe(ORB_ID(parameter_update));
_global_pos_sub = orb_subscribe(ORB_ID(vehicle_global_position));
update_parameters(true);
hrt_abstime last_time = 0;
px4_pollfd_struct_t fds[1];
fds[0].fd = _sensors_sub;
fds[0].events = POLLIN;
while (!_task_should_exit) {
int ret = px4_poll(fds, 1, 1000);
if (_mavlink_fd < 0) {
_mavlink_fd = open(MAVLINK_LOG_DEVICE, 0);
}
if (ret < 0) {
// Poll error, sleep and try again
usleep(10000);
continue;
} else if (ret == 0) {
// Poll timeout, do nothing
continue;
}
update_parameters(false);
// Update sensors
sensor_combined_s sensors;
if (!orb_copy(ORB_ID(sensor_combined), _sensors_sub, &sensors)) {
// Feed validator with recent sensor data
for (unsigned i = 0; i < (sizeof(sensors.gyro_timestamp) / sizeof(sensors.gyro_timestamp[0])); i++) {
/* ignore empty fields */
if (sensors.gyro_timestamp[i] > 0) {
float gyro[3];
for (unsigned j = 0; j < 3; j++) {
if (sensors.gyro_integral_dt[i] > 0) {
gyro[j] = (double)sensors.gyro_integral_rad[i * 3 + j] / (sensors.gyro_integral_dt[i] / 1e6);
} else {
/* fall back to angular rate */
gyro[j] = sensors.gyro_rad_s[i * 3 + j];
}
}
_voter_gyro.put(i, sensors.gyro_timestamp[i], &gyro[0], sensors.gyro_errcount[i], sensors.gyro_priority[i]);
}
_voter_accel.put(i, sensors.accelerometer_timestamp[i], &sensors.accelerometer_m_s2[i * 3],
sensors.accelerometer_errcount[i], sensors.accelerometer_priority[i]);
_voter_mag.put(i, sensors.magnetometer_timestamp[i], &sensors.magnetometer_ga[i * 3],
sensors.magnetometer_errcount[i], sensors.magnetometer_priority[i]);
}
int best_gyro, best_accel, best_mag;
// Get best measurement values
hrt_abstime curr_time = hrt_absolute_time();
_gyro.set(_voter_gyro.get_best(curr_time, &best_gyro));
_accel.set(_voter_accel.get_best(curr_time, &best_accel));
_mag.set(_voter_mag.get_best(curr_time, &best_mag));
if (_accel.length() < 0.01f || _mag.length() < 0.01f) {
warnx("WARNING: degenerate accel / mag!");
continue;
}
_data_good = true;
if (!_failsafe && (_voter_gyro.failover_count() > 0 ||
_voter_accel.failover_count() > 0 ||
_voter_mag.failover_count() > 0)) {
_failsafe = true;
mavlink_and_console_log_emergency(_mavlink_fd, "SENSOR FAILSAFE! RETURN TO LAND IMMEDIATELY");
}
if (!_vibration_warning && (_voter_gyro.get_vibration_factor(curr_time) > _vibration_warning_threshold ||
_voter_accel.get_vibration_factor(curr_time) > _vibration_warning_threshold ||
_voter_mag.get_vibration_factor(curr_time) > _vibration_warning_threshold)) {
if (_vibration_warning_timestamp == 0) {
_vibration_warning_timestamp = curr_time;
} else if (hrt_elapsed_time(&_vibration_warning_timestamp) > 10000000) {
_vibration_warning = true;
mavlink_and_console_log_critical(_mavlink_fd, "HIGH VIBRATION! g: %d a: %d m: %d",
(int)(100 * _voter_gyro.get_vibration_factor(curr_time)),
(int)(100 * _voter_accel.get_vibration_factor(curr_time)),
(int)(100 * _voter_mag.get_vibration_factor(curr_time)));
}
} else {
_vibration_warning_timestamp = 0;
}
}
bool gpos_updated;
orb_check(_global_pos_sub, &gpos_updated);
if (gpos_updated) {
orb_copy(ORB_ID(vehicle_global_position), _global_pos_sub, &_gpos);
if (_mag_decl_auto && _gpos.eph < 20.0f && hrt_elapsed_time(&_gpos.timestamp) < 1000000) {
/* set magnetic declination automatically */
_mag_decl = math::radians(get_mag_declination(_gpos.lat, _gpos.lon));
}
}
if (_acc_comp && _gpos.timestamp != 0 && hrt_absolute_time() < _gpos.timestamp + 20000 && _gpos.eph < 5.0f && _inited) {
/* position data is actual */
if (gpos_updated) {
Vector<3> vel(_gpos.vel_n, _gpos.vel_e, _gpos.vel_d);
/* velocity updated */
if (_vel_prev_t != 0 && _gpos.timestamp != _vel_prev_t) {
float vel_dt = (_gpos.timestamp - _vel_prev_t) / 1000000.0f;
/* calculate acceleration in body frame */
_pos_acc = _q.conjugate_inversed((vel - _vel_prev) / vel_dt);
}
_vel_prev_t = _gpos.timestamp;
_vel_prev = vel;
}
} else {
/* position data is outdated, reset acceleration */
_pos_acc.zero();
_vel_prev.zero();
_vel_prev_t = 0;
}
// Time from previous iteration
hrt_abstime now = hrt_absolute_time();
float dt = (last_time > 0) ? ((now - last_time) / 1000000.0f) : 0.00001f;
last_time = now;
if (dt > _dt_max) {
dt = _dt_max;
}
if (!update(dt)) {
continue;
}
Vector<3> euler = _q.to_euler();
struct vehicle_attitude_s att = {};
att.timestamp = sensors.timestamp;
att.roll = euler(0);
att.pitch = euler(1);
att.yaw = euler(2);
/* the complimentary filter should reflect the true system
* state, but we need smoother outputs for the control system
*/
att.rollspeed = _lp_roll_rate.apply(_rates(0));
att.pitchspeed = _lp_pitch_rate.apply(_rates(1));
att.yawspeed = _rates(2);
for (int i = 0; i < 3; i++) {
att.g_comp[i] = _accel(i) - _pos_acc(i);
}
/* copy offsets */
memcpy(&att.rate_offsets, _gyro_bias.data, sizeof(att.rate_offsets));
Matrix<3, 3> R = _q.to_dcm();
/* copy rotation matrix */
memcpy(&att.R[0], R.data, sizeof(att.R));
att.R_valid = true;
att.rate_vibration = _voter_gyro.get_vibration_factor(hrt_absolute_time());
att.accel_vibration = _voter_accel.get_vibration_factor(hrt_absolute_time());
att.mag_vibration = _voter_mag.get_vibration_factor(hrt_absolute_time());
if (_att_pub == nullptr) {
_att_pub = orb_advertise(ORB_ID(vehicle_attitude), &att);
} else {
orb_publish(ORB_ID(vehicle_attitude), _att_pub, &att);
}
}
}
void AttitudeEstimatorQ::update_parameters(bool force) {
bool updated = force;
if (!updated) {
orb_check(_params_sub, &updated);
}
if (updated) {
parameter_update_s param_update;
orb_copy(ORB_ID(parameter_update), _params_sub, ¶m_update);
param_get(_params_handles.w_acc, &_w_accel);
param_get(_params_handles.w_mag, &_w_mag);
param_get(_params_handles.w_gyro_bias, &_w_gyro_bias);
float mag_decl_deg = 0.0f;
param_get(_params_handles.mag_decl, &mag_decl_deg);
_mag_decl = math::radians(mag_decl_deg);
int32_t mag_decl_auto_int;
param_get(_params_handles.mag_decl_auto, &mag_decl_auto_int);
_mag_decl_auto = mag_decl_auto_int != 0;
int32_t acc_comp_int;
param_get(_params_handles.acc_comp, &acc_comp_int);
_acc_comp = acc_comp_int != 0;
param_get(_params_handles.bias_max, &_bias_max);
param_get(_params_handles.vibe_thresh, &_vibration_warning_threshold);
}
}
bool AttitudeEstimatorQ::init() {
// Rotation matrix can be easily constructed from acceleration and mag field vectors
// 'k' is Earth Z axis (Down) unit vector in body frame
Vector<3> k = -_accel;
k.normalize();
// 'i' is Earth X axis (North) unit vector in body frame, orthogonal with 'k'
Vector<3> i = (_mag - k * (_mag * k));
i.normalize();
// 'j' is Earth Y axis (East) unit vector in body frame, orthogonal with 'k' and 'i'
Vector<3> j = k % i;
// Fill rotation matrix
Matrix<3, 3> R;
R.set_row(0, i);
R.set_row(1, j);
R.set_row(2, k);
// Convert to quaternion
_q.from_dcm(R);
_q.normalize();
if (PX4_ISFINITE(_q(0)) && PX4_ISFINITE(_q(1)) &&
PX4_ISFINITE(_q(2)) && PX4_ISFINITE(_q(3)) &&
_q.length() > 0.95f && _q.length() < 1.05f) {
_inited = true;
} else {
_inited = false;
}
return _inited;
}
bool AttitudeEstimatorQ::update(float dt) {
if (!_inited) {
if (!_data_good) {
return false;
}
return init();
}
Quaternion q_last = _q;
// Angular rate of correction
Vector<3> corr;
// Magnetometer correction
// Project mag field vector to global frame and extract XY component
Vector<3> mag_earth = _q.conjugate(_mag);
float mag_err = _wrap_pi(atan2f(mag_earth(1), mag_earth(0)) - _mag_decl);
// Project magnetometer correction to body frame
corr += _q.conjugate_inversed(Vector<3>(0.0f, 0.0f, -mag_err)) * _w_mag;
// Accelerometer correction
// Project 'k' unit vector of earth frame to body frame
// Vector<3> k = _q.conjugate_inversed(Vector<3>(0.0f, 0.0f, 1.0f));
// Optimized version with dropped zeros
Vector<3> k(
2.0f * (_q(1) * _q(3) - _q(0) * _q(2)),
2.0f * (_q(2) * _q(3) + _q(0) * _q(1)),
(_q(0) * _q(0) - _q(1) * _q(1) - _q(2) * _q(2) + _q(3) * _q(3))
);
corr += (k % (_accel - _pos_acc).normalized()) * _w_accel;
// Gyro bias estimation
_gyro_bias += corr * (_w_gyro_bias * dt);
for (int i = 0; i < 3; i++) {
_gyro_bias(i) = math::constrain(_gyro_bias(i), -_bias_max, _bias_max);
}
_rates = _gyro + _gyro_bias;
// Feed forward gyro
corr += _rates;
// Apply correction to state
_q += _q.derivative(corr) * dt;
// Normalize quaternion
_q.normalize();
if (!(PX4_ISFINITE(_q(0)) && PX4_ISFINITE(_q(1)) &&
PX4_ISFINITE(_q(2)) && PX4_ISFINITE(_q(3)))) {
// Reset quaternion to last good state
_q = q_last;
_rates.zero();
_gyro_bias.zero();
return false;
}
return true;
}
int attitude_estimator_q_main(int argc, char *argv[]) {
if (argc < 1) {
warnx("usage: attitude_estimator_q {start|stop|status}");
return 1;
}
if (!strcmp(argv[1], "start")) {
if (attitude_estimator_q::instance != nullptr) {
warnx("already running");
return 1;
}
attitude_estimator_q::instance = new AttitudeEstimatorQ;
if (attitude_estimator_q::instance == nullptr) {
warnx("alloc failed");
return 1;
}
if (OK != attitude_estimator_q::instance->start()) {
delete attitude_estimator_q::instance;
attitude_estimator_q::instance = nullptr;
warnx("start failed");
return 1;
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
if (attitude_estimator_q::instance == nullptr) {
warnx("not running");
return 1;
}
delete attitude_estimator_q::instance;
attitude_estimator_q::instance = nullptr;
return 0;
}
if (!strcmp(argv[1], "status")) {
if (attitude_estimator_q::instance) {
attitude_estimator_q::instance->print();
warnx("running");
return 0;
} else {
warnx("not running");
return 1;
}
}
warnx("unrecognized command");
return 1;
}
Q Estimator: Fix code style
/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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
* COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
****************************************************************************/
/*
* @file attitude_estimator_q_main.cpp
*
* Attitude estimator (quaternion based)
*
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <px4_config.h>
#include <px4_posix.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
#include <fcntl.h>
#include <float.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <uORB/uORB.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_attitude.h>
#include <uORB/topics/vehicle_control_mode.h>
#include <uORB/topics/vehicle_global_position.h>
#include <uORB/topics/parameter_update.h>
#include <drivers/drv_hrt.h>
#include <mathlib/mathlib.h>
#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <lib/geo/geo.h>
#include <lib/ecl/validation/data_validator_group.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/systemlib.h>
#include <systemlib/param/param.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
extern "C" __EXPORT int attitude_estimator_q_main(int argc, char *argv[]);
using math::Vector;
using math::Matrix;
using math::Quaternion;
class AttitudeEstimatorQ;
namespace attitude_estimator_q
{
AttitudeEstimatorQ *instance;
}
class AttitudeEstimatorQ
{
public:
/**
* Constructor
*/
AttitudeEstimatorQ();
/**
* Destructor, also kills task.
*/
~AttitudeEstimatorQ();
/**
* Start task.
*
* @return OK on success.
*/
int start();
static void task_main_trampoline(int argc, char *argv[]);
void task_main();
void print();
private:
static constexpr float _dt_max = 0.02;
bool _task_should_exit = false; /**< if true, task should exit */
int _control_task = -1; /**< task handle for task */
int _sensors_sub = -1;
int _params_sub = -1;
int _global_pos_sub = -1;
orb_advert_t _att_pub = nullptr;
struct {
param_t w_acc;
param_t w_mag;
param_t w_gyro_bias;
param_t mag_decl;
param_t mag_decl_auto;
param_t acc_comp;
param_t bias_max;
param_t vibe_thresh;
} _params_handles; /**< handles for interesting parameters */
float _w_accel = 0.0f;
float _w_mag = 0.0f;
float _w_gyro_bias = 0.0f;
float _mag_decl = 0.0f;
bool _mag_decl_auto = false;
bool _acc_comp = false;
float _bias_max = 0.0f;
float _vibration_warning_threshold = 1.0f;
hrt_abstime _vibration_warning_timestamp = 0;
Vector<3> _gyro;
Vector<3> _accel;
Vector<3> _mag;
Quaternion _q;
Vector<3> _rates;
Vector<3> _gyro_bias;
vehicle_global_position_s _gpos = {};
Vector<3> _vel_prev;
Vector<3> _pos_acc;
DataValidatorGroup _voter_gyro;
DataValidatorGroup _voter_accel;
DataValidatorGroup _voter_mag;
/* Low pass filter for attitude rates */
math::LowPassFilter2p _lp_roll_rate;
math::LowPassFilter2p _lp_pitch_rate;
hrt_abstime _vel_prev_t = 0;
bool _inited = false;
bool _data_good = false;
bool _failsafe = false;
bool _vibration_warning = false;
int _mavlink_fd = -1;
perf_counter_t _update_perf;
perf_counter_t _loop_perf;
void update_parameters(bool force);
int update_subscriptions();
bool init();
bool update(float dt);
};
AttitudeEstimatorQ::AttitudeEstimatorQ() :
_voter_gyro(3),
_voter_accel(3),
_voter_mag(3),
_lp_roll_rate(250.0f, 20.0f),
_lp_pitch_rate(250.0f, 20.0f)
{
_voter_mag.set_timeout(200000);
_params_handles.w_acc = param_find("ATT_W_ACC");
_params_handles.w_mag = param_find("ATT_W_MAG");
_params_handles.w_gyro_bias = param_find("ATT_W_GYRO_BIAS");
_params_handles.mag_decl = param_find("ATT_MAG_DECL");
_params_handles.mag_decl_auto = param_find("ATT_MAG_DECL_A");
_params_handles.acc_comp = param_find("ATT_ACC_COMP");
_params_handles.bias_max = param_find("ATT_BIAS_MAX");
_params_handles.vibe_thresh = param_find("ATT_VIBE_THRESH");
}
/**
* Destructor, also kills task.
*/
AttitudeEstimatorQ::~AttitudeEstimatorQ()
{
if (_control_task != -1) {
/* task wakes up every 100ms or so at the longest */
_task_should_exit = true;
/* wait for a second for the task to quit at our request */
unsigned i = 0;
do {
/* wait 20ms */
usleep(20000);
/* if we have given up, kill it */
if (++i > 50) {
px4_task_delete(_control_task);
break;
}
} while (_control_task != -1);
}
attitude_estimator_q::instance = nullptr;
}
int AttitudeEstimatorQ::start()
{
ASSERT(_control_task == -1);
/* start the task */
_control_task = px4_task_spawn_cmd("attitude_estimator_q",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
2100,
(px4_main_t)&AttitudeEstimatorQ::task_main_trampoline,
nullptr);
if (_control_task < 0) {
warn("task start failed");
return -errno;
}
return OK;
}
void AttitudeEstimatorQ::print()
{
warnx("gyro status:");
_voter_gyro.print();
warnx("accel status:");
_voter_accel.print();
warnx("mag status:");
_voter_mag.print();
}
void AttitudeEstimatorQ::task_main_trampoline(int argc, char *argv[])
{
attitude_estimator_q::instance->task_main();
}
void AttitudeEstimatorQ::task_main()
{
_sensors_sub = orb_subscribe(ORB_ID(sensor_combined));
_params_sub = orb_subscribe(ORB_ID(parameter_update));
_global_pos_sub = orb_subscribe(ORB_ID(vehicle_global_position));
update_parameters(true);
hrt_abstime last_time = 0;
px4_pollfd_struct_t fds[1];
fds[0].fd = _sensors_sub;
fds[0].events = POLLIN;
while (!_task_should_exit) {
int ret = px4_poll(fds, 1, 1000);
if (_mavlink_fd < 0) {
_mavlink_fd = open(MAVLINK_LOG_DEVICE, 0);
}
if (ret < 0) {
// Poll error, sleep and try again
usleep(10000);
continue;
} else if (ret == 0) {
// Poll timeout, do nothing
continue;
}
update_parameters(false);
// Update sensors
sensor_combined_s sensors;
if (!orb_copy(ORB_ID(sensor_combined), _sensors_sub, &sensors)) {
// Feed validator with recent sensor data
for (unsigned i = 0; i < (sizeof(sensors.gyro_timestamp) / sizeof(sensors.gyro_timestamp[0])); i++) {
/* ignore empty fields */
if (sensors.gyro_timestamp[i] > 0) {
float gyro[3];
for (unsigned j = 0; j < 3; j++) {
if (sensors.gyro_integral_dt[i] > 0) {
gyro[j] = (double)sensors.gyro_integral_rad[i * 3 + j] / (sensors.gyro_integral_dt[i] / 1e6);
} else {
/* fall back to angular rate */
gyro[j] = sensors.gyro_rad_s[i * 3 + j];
}
}
_voter_gyro.put(i, sensors.gyro_timestamp[i], &gyro[0], sensors.gyro_errcount[i], sensors.gyro_priority[i]);
}
_voter_accel.put(i, sensors.accelerometer_timestamp[i], &sensors.accelerometer_m_s2[i * 3],
sensors.accelerometer_errcount[i], sensors.accelerometer_priority[i]);
_voter_mag.put(i, sensors.magnetometer_timestamp[i], &sensors.magnetometer_ga[i * 3],
sensors.magnetometer_errcount[i], sensors.magnetometer_priority[i]);
}
int best_gyro, best_accel, best_mag;
// Get best measurement values
hrt_abstime curr_time = hrt_absolute_time();
_gyro.set(_voter_gyro.get_best(curr_time, &best_gyro));
_accel.set(_voter_accel.get_best(curr_time, &best_accel));
_mag.set(_voter_mag.get_best(curr_time, &best_mag));
if (_accel.length() < 0.01f || _mag.length() < 0.01f) {
warnx("WARNING: degenerate accel / mag!");
continue;
}
_data_good = true;
if (!_failsafe && (_voter_gyro.failover_count() > 0 ||
_voter_accel.failover_count() > 0 ||
_voter_mag.failover_count() > 0)) {
_failsafe = true;
mavlink_and_console_log_emergency(_mavlink_fd, "SENSOR FAILSAFE! RETURN TO LAND IMMEDIATELY");
}
if (!_vibration_warning && (_voter_gyro.get_vibration_factor(curr_time) > _vibration_warning_threshold ||
_voter_accel.get_vibration_factor(curr_time) > _vibration_warning_threshold ||
_voter_mag.get_vibration_factor(curr_time) > _vibration_warning_threshold)) {
if (_vibration_warning_timestamp == 0) {
_vibration_warning_timestamp = curr_time;
} else if (hrt_elapsed_time(&_vibration_warning_timestamp) > 10000000) {
_vibration_warning = true;
mavlink_and_console_log_critical(_mavlink_fd, "HIGH VIBRATION! g: %d a: %d m: %d",
(int)(100 * _voter_gyro.get_vibration_factor(curr_time)),
(int)(100 * _voter_accel.get_vibration_factor(curr_time)),
(int)(100 * _voter_mag.get_vibration_factor(curr_time)));
}
} else {
_vibration_warning_timestamp = 0;
}
}
bool gpos_updated;
orb_check(_global_pos_sub, &gpos_updated);
if (gpos_updated) {
orb_copy(ORB_ID(vehicle_global_position), _global_pos_sub, &_gpos);
if (_mag_decl_auto && _gpos.eph < 20.0f && hrt_elapsed_time(&_gpos.timestamp) < 1000000) {
/* set magnetic declination automatically */
_mag_decl = math::radians(get_mag_declination(_gpos.lat, _gpos.lon));
}
}
if (_acc_comp && _gpos.timestamp != 0 && hrt_absolute_time() < _gpos.timestamp + 20000 && _gpos.eph < 5.0f && _inited) {
/* position data is actual */
if (gpos_updated) {
Vector<3> vel(_gpos.vel_n, _gpos.vel_e, _gpos.vel_d);
/* velocity updated */
if (_vel_prev_t != 0 && _gpos.timestamp != _vel_prev_t) {
float vel_dt = (_gpos.timestamp - _vel_prev_t) / 1000000.0f;
/* calculate acceleration in body frame */
_pos_acc = _q.conjugate_inversed((vel - _vel_prev) / vel_dt);
}
_vel_prev_t = _gpos.timestamp;
_vel_prev = vel;
}
} else {
/* position data is outdated, reset acceleration */
_pos_acc.zero();
_vel_prev.zero();
_vel_prev_t = 0;
}
// Time from previous iteration
hrt_abstime now = hrt_absolute_time();
float dt = (last_time > 0) ? ((now - last_time) / 1000000.0f) : 0.00001f;
last_time = now;
if (dt > _dt_max) {
dt = _dt_max;
}
if (!update(dt)) {
continue;
}
Vector<3> euler = _q.to_euler();
struct vehicle_attitude_s att = {};
att.timestamp = sensors.timestamp;
att.roll = euler(0);
att.pitch = euler(1);
att.yaw = euler(2);
/* the complimentary filter should reflect the true system
* state, but we need smoother outputs for the control system
*/
att.rollspeed = _lp_roll_rate.apply(_rates(0));
att.pitchspeed = _lp_pitch_rate.apply(_rates(1));
att.yawspeed = _rates(2);
for (int i = 0; i < 3; i++) {
att.g_comp[i] = _accel(i) - _pos_acc(i);
}
/* copy offsets */
memcpy(&att.rate_offsets, _gyro_bias.data, sizeof(att.rate_offsets));
Matrix<3, 3> R = _q.to_dcm();
/* copy rotation matrix */
memcpy(&att.R[0], R.data, sizeof(att.R));
att.R_valid = true;
att.rate_vibration = _voter_gyro.get_vibration_factor(hrt_absolute_time());
att.accel_vibration = _voter_accel.get_vibration_factor(hrt_absolute_time());
att.mag_vibration = _voter_mag.get_vibration_factor(hrt_absolute_time());
if (_att_pub == nullptr) {
_att_pub = orb_advertise(ORB_ID(vehicle_attitude), &att);
} else {
orb_publish(ORB_ID(vehicle_attitude), _att_pub, &att);
}
}
}
void AttitudeEstimatorQ::update_parameters(bool force)
{
bool updated = force;
if (!updated) {
orb_check(_params_sub, &updated);
}
if (updated) {
parameter_update_s param_update;
orb_copy(ORB_ID(parameter_update), _params_sub, ¶m_update);
param_get(_params_handles.w_acc, &_w_accel);
param_get(_params_handles.w_mag, &_w_mag);
param_get(_params_handles.w_gyro_bias, &_w_gyro_bias);
float mag_decl_deg = 0.0f;
param_get(_params_handles.mag_decl, &mag_decl_deg);
_mag_decl = math::radians(mag_decl_deg);
int32_t mag_decl_auto_int;
param_get(_params_handles.mag_decl_auto, &mag_decl_auto_int);
_mag_decl_auto = mag_decl_auto_int != 0;
int32_t acc_comp_int;
param_get(_params_handles.acc_comp, &acc_comp_int);
_acc_comp = acc_comp_int != 0;
param_get(_params_handles.bias_max, &_bias_max);
param_get(_params_handles.vibe_thresh, &_vibration_warning_threshold);
}
}
bool AttitudeEstimatorQ::init()
{
// Rotation matrix can be easily constructed from acceleration and mag field vectors
// 'k' is Earth Z axis (Down) unit vector in body frame
Vector<3> k = -_accel;
k.normalize();
// 'i' is Earth X axis (North) unit vector in body frame, orthogonal with 'k'
Vector<3> i = (_mag - k * (_mag * k));
i.normalize();
// 'j' is Earth Y axis (East) unit vector in body frame, orthogonal with 'k' and 'i'
Vector<3> j = k % i;
// Fill rotation matrix
Matrix<3, 3> R;
R.set_row(0, i);
R.set_row(1, j);
R.set_row(2, k);
// Convert to quaternion
_q.from_dcm(R);
_q.normalize();
if (PX4_ISFINITE(_q(0)) && PX4_ISFINITE(_q(1)) &&
PX4_ISFINITE(_q(2)) && PX4_ISFINITE(_q(3)) &&
_q.length() > 0.95f && _q.length() < 1.05f) {
_inited = true;
} else {
_inited = false;
}
return _inited;
}
bool AttitudeEstimatorQ::update(float dt)
{
if (!_inited) {
if (!_data_good) {
return false;
}
return init();
}
Quaternion q_last = _q;
// Angular rate of correction
Vector<3> corr;
// Magnetometer correction
// Project mag field vector to global frame and extract XY component
Vector<3> mag_earth = _q.conjugate(_mag);
float mag_err = _wrap_pi(atan2f(mag_earth(1), mag_earth(0)) - _mag_decl);
// Project magnetometer correction to body frame
corr += _q.conjugate_inversed(Vector<3>(0.0f, 0.0f, -mag_err)) * _w_mag;
// Accelerometer correction
// Project 'k' unit vector of earth frame to body frame
// Vector<3> k = _q.conjugate_inversed(Vector<3>(0.0f, 0.0f, 1.0f));
// Optimized version with dropped zeros
Vector<3> k(
2.0f * (_q(1) * _q(3) - _q(0) * _q(2)),
2.0f * (_q(2) * _q(3) + _q(0) * _q(1)),
(_q(0) * _q(0) - _q(1) * _q(1) - _q(2) * _q(2) + _q(3) * _q(3))
);
corr += (k % (_accel - _pos_acc).normalized()) * _w_accel;
// Gyro bias estimation
_gyro_bias += corr * (_w_gyro_bias * dt);
for (int i = 0; i < 3; i++) {
_gyro_bias(i) = math::constrain(_gyro_bias(i), -_bias_max, _bias_max);
}
_rates = _gyro + _gyro_bias;
// Feed forward gyro
corr += _rates;
// Apply correction to state
_q += _q.derivative(corr) * dt;
// Normalize quaternion
_q.normalize();
if (!(PX4_ISFINITE(_q(0)) && PX4_ISFINITE(_q(1)) &&
PX4_ISFINITE(_q(2)) && PX4_ISFINITE(_q(3)))) {
// Reset quaternion to last good state
_q = q_last;
_rates.zero();
_gyro_bias.zero();
return false;
}
return true;
}
int attitude_estimator_q_main(int argc, char *argv[])
{
if (argc < 1) {
warnx("usage: attitude_estimator_q {start|stop|status}");
return 1;
}
if (!strcmp(argv[1], "start")) {
if (attitude_estimator_q::instance != nullptr) {
warnx("already running");
return 1;
}
attitude_estimator_q::instance = new AttitudeEstimatorQ;
if (attitude_estimator_q::instance == nullptr) {
warnx("alloc failed");
return 1;
}
if (OK != attitude_estimator_q::instance->start()) {
delete attitude_estimator_q::instance;
attitude_estimator_q::instance = nullptr;
warnx("start failed");
return 1;
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
if (attitude_estimator_q::instance == nullptr) {
warnx("not running");
return 1;
}
delete attitude_estimator_q::instance;
attitude_estimator_q::instance = nullptr;
return 0;
}
if (!strcmp(argv[1], "status")) {
if (attitude_estimator_q::instance) {
attitude_estimator_q::instance->print();
warnx("running");
return 0;
} else {
warnx("not running");
return 1;
}
}
warnx("unrecognized command");
return 1;
}
|
// Copyright 2014 BitPay Inc.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <ctype.h>
#include <sstream>
#include "univalue.h"
using namespace std;
static const UniValue nullValue;
void UniValue::clear()
{
typ = VNULL;
val.clear();
keys.clear();
values.clear();
}
bool UniValue::setNull()
{
clear();
return true;
}
bool UniValue::setBool(bool val_)
{
clear();
typ = VBOOL;
if (val_)
val = "1";
return true;
}
static bool validNumStr(const string& s)
{
string tokenVal;
unsigned int consumed;
enum jtokentype tt = getJsonToken(tokenVal, consumed, s.c_str());
return (tt == JTOK_NUMBER);
}
bool UniValue::setNumStr(const string& val_)
{
if (!validNumStr(val))
return false;
clear();
typ = VNUM;
val = val_;
return true;
}
bool UniValue::setInt(uint64_t val)
{
string s;
ostringstream oss;
oss << val;
return setNumStr(oss.str());
}
bool UniValue::setInt(int64_t val)
{
string s;
ostringstream oss;
oss << val;
return setNumStr(oss.str());
}
bool UniValue::setFloat(double val)
{
string s;
ostringstream oss;
oss << val;
return setNumStr(oss.str());
}
bool UniValue::setStr(const string& val_)
{
clear();
typ = VSTR;
val = val_;
return true;
}
bool UniValue::setArray()
{
clear();
typ = VARR;
return true;
}
bool UniValue::setObject()
{
clear();
typ = VOBJ;
return true;
}
bool UniValue::push_back(const UniValue& val)
{
if (typ != VARR)
return false;
values.push_back(val);
return true;
}
bool UniValue::push_backV(const std::vector<UniValue>& vec)
{
if (typ != VARR)
return false;
values.insert(values.end(), vec.begin(), vec.end());
return true;
}
bool UniValue::pushKV(const std::string& key, const UniValue& val)
{
if (typ != VOBJ)
return false;
keys.push_back(key);
values.push_back(val);
return true;
}
bool UniValue::pushKVs(const UniValue& obj)
{
if (typ != VOBJ || obj.typ != VOBJ)
return false;
for (unsigned int i = 0; i < obj.keys.size(); i++) {
keys.push_back(obj.keys[i]);
values.push_back(obj.values[i]);
}
return true;
}
int UniValue::findKey(const std::string& key) const
{
for (unsigned int i = 0; i < keys.size(); i++) {
if (keys[i] == key)
return (int) i;
}
return -1;
}
bool UniValue::checkObject(const std::map<std::string,UniValue::VType>& t)
{
for (std::map<std::string,UniValue::VType>::const_iterator it = t.begin();
it != t.end(); it++) {
int idx = findKey(it->first);
if (idx < 0)
return false;
if (values[idx].getType() != it->second)
return false;
}
return true;
}
const UniValue& UniValue::operator[](const std::string& key) const
{
if (typ != VOBJ)
return nullValue;
int index = findKey(key);
if (index < 0)
return nullValue;
return values[index];
}
const UniValue& UniValue::operator[](unsigned int index) const
{
if (typ != VOBJ && typ != VARR)
return nullValue;
if (index >= values.size())
return nullValue;
return values[index];
}
const char *uvTypeName(UniValue::VType t)
{
switch (t) {
case UniValue::VNULL: return "null";
case UniValue::VBOOL: return "bool";
case UniValue::VOBJ: return "object";
case UniValue::VARR: return "array";
case UniValue::VSTR: return "string";
case UniValue::VNUM: return "number";
}
// not reached
return NULL;
}
UniValue: use correct setNumStr() input val, when setting number values
// Copyright 2014 BitPay Inc.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <ctype.h>
#include <sstream>
#include "univalue.h"
using namespace std;
static const UniValue nullValue;
void UniValue::clear()
{
typ = VNULL;
val.clear();
keys.clear();
values.clear();
}
bool UniValue::setNull()
{
clear();
return true;
}
bool UniValue::setBool(bool val_)
{
clear();
typ = VBOOL;
if (val_)
val = "1";
return true;
}
static bool validNumStr(const string& s)
{
string tokenVal;
unsigned int consumed;
enum jtokentype tt = getJsonToken(tokenVal, consumed, s.c_str());
return (tt == JTOK_NUMBER);
}
bool UniValue::setNumStr(const string& val_)
{
if (!validNumStr(val_))
return false;
clear();
typ = VNUM;
val = val_;
return true;
}
bool UniValue::setInt(uint64_t val)
{
string s;
ostringstream oss;
oss << val;
return setNumStr(oss.str());
}
bool UniValue::setInt(int64_t val)
{
string s;
ostringstream oss;
oss << val;
return setNumStr(oss.str());
}
bool UniValue::setFloat(double val)
{
string s;
ostringstream oss;
oss << val;
return setNumStr(oss.str());
}
bool UniValue::setStr(const string& val_)
{
clear();
typ = VSTR;
val = val_;
return true;
}
bool UniValue::setArray()
{
clear();
typ = VARR;
return true;
}
bool UniValue::setObject()
{
clear();
typ = VOBJ;
return true;
}
bool UniValue::push_back(const UniValue& val)
{
if (typ != VARR)
return false;
values.push_back(val);
return true;
}
bool UniValue::push_backV(const std::vector<UniValue>& vec)
{
if (typ != VARR)
return false;
values.insert(values.end(), vec.begin(), vec.end());
return true;
}
bool UniValue::pushKV(const std::string& key, const UniValue& val)
{
if (typ != VOBJ)
return false;
keys.push_back(key);
values.push_back(val);
return true;
}
bool UniValue::pushKVs(const UniValue& obj)
{
if (typ != VOBJ || obj.typ != VOBJ)
return false;
for (unsigned int i = 0; i < obj.keys.size(); i++) {
keys.push_back(obj.keys[i]);
values.push_back(obj.values[i]);
}
return true;
}
int UniValue::findKey(const std::string& key) const
{
for (unsigned int i = 0; i < keys.size(); i++) {
if (keys[i] == key)
return (int) i;
}
return -1;
}
bool UniValue::checkObject(const std::map<std::string,UniValue::VType>& t)
{
for (std::map<std::string,UniValue::VType>::const_iterator it = t.begin();
it != t.end(); it++) {
int idx = findKey(it->first);
if (idx < 0)
return false;
if (values[idx].getType() != it->second)
return false;
}
return true;
}
const UniValue& UniValue::operator[](const std::string& key) const
{
if (typ != VOBJ)
return nullValue;
int index = findKey(key);
if (index < 0)
return nullValue;
return values[index];
}
const UniValue& UniValue::operator[](unsigned int index) const
{
if (typ != VOBJ && typ != VARR)
return nullValue;
if (index >= values.size())
return nullValue;
return values[index];
}
const char *uvTypeName(UniValue::VType t)
{
switch (t) {
case UniValue::VNULL: return "null";
case UniValue::VBOOL: return "bool";
case UniValue::VOBJ: return "object";
case UniValue::VARR: return "array";
case UniValue::VSTR: return "string";
case UniValue::VNUM: return "number";
}
// not reached
return NULL;
}
|
#include "Resources.hpp"
#include <array>
#include <cassert>
#include <condition_variable>
#include <fstream>
#include <iostream>
#include <thread>
// libarchive
#include "archive.h"
#include "archive_entry.h"
// spdlog
#include "spdlog/details/os.h"
#include "spdlog/fmt/chrono.h"
#include "spdlog/spdlog.h"
// shared
#include "depthai-shared/device/PrebootConfig.hpp"
#include "depthai-shared/utility/Checksum.hpp"
extern "C" {
#include "bspatch/bspatch.h"
}
// Resource compiled assets (cmds)
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
#include "cmrc/cmrc.hpp"
CMRC_DECLARE(depthai);
#endif
namespace dai {
static std::vector<std::uint8_t> createPrebootHeader(const std::vector<uint8_t>& payload, uint32_t magic1, uint32_t magic2);
constexpr static auto CMRC_DEPTHAI_DEVICE_TAR_XZ = "depthai-device-fwp-" DEPTHAI_DEVICE_VERSION ".tar.xz";
// Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_4_PATH = "depthai-device-openvino-2021.4-" DEPTHAI_DEVICE_VERSION ".cmd";
constexpr static auto MAIN_FW_PATH = DEPTHAI_CMD_OPENVINO_2021_4_PATH;
constexpr static auto MAIN_FW_VERSION = OpenVINO::VERSION_2021_4;
// Patches from Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH = "depthai-device-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH = "depthai-device-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH = "depthai-device-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH = "depthai-device-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH = "depthai-device-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".patch";
// Creates std::array without explicitly needing to state the size
template <typename V, typename... T>
static constexpr auto array_of(T&&... t) -> std::array<V, sizeof...(T)> {
return {{std::forward<T>(t)...}};
}
constexpr static auto RESOURCE_LIST_DEVICE = array_of<const char*>(DEPTHAI_CMD_OPENVINO_2021_4_PATH,
DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH);
std::vector<std::uint8_t> Resources::getDeviceFirmware(Device::Config config, std::string pathToMvcmd) {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtxDevice);
std::vector<std::uint8_t> finalFwBinary;
// Get OpenVINO version
auto& version = config.version;
// Check if pathToMvcmd variable is set
std::string finalFwBinaryPath = "";
if(!pathToMvcmd.empty()) {
finalFwBinaryPath = pathToMvcmd;
}
// Override if env variable DEPTHAI_DEVICE_BINARY is set
auto fwBinaryPath = spdlog::details::os::getenv("DEPTHAI_DEVICE_BINARY");
if(!fwBinaryPath.empty()) {
finalFwBinaryPath = fwBinaryPath;
}
// Return binary from file if any of above paths are present
if(!finalFwBinaryPath.empty()) {
// Load binary file at path
std::ifstream stream(finalFwBinaryPath, std::ios::binary);
if(!stream.is_open()) {
// Throw an error
// TODO(themarpe) - Unify exceptions into meaningful groups
throw std::runtime_error(fmt::format("File at path {} pointed to by DEPTHAI_DEVICE_BINARY doesn't exist.", fwBinaryPath));
}
// Read the file and return its contents
finalFwBinary = std::vector<std::uint8_t>(std::istreambuf_iterator<char>(stream), {});
} else {
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
// Main FW
std::vector<std::uint8_t> depthaiBinary;
// Patch from main to specified
std::vector<std::uint8_t> depthaiPatch;
switch(version) {
case OpenVINO::VERSION_2020_3:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_4:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_1:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_2:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_3:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH];
break;
case MAIN_FW_VERSION:
spdlog::debug("resourceMapDevice[{}] size: {}", MAIN_FW_PATH, resourceMapDevice[MAIN_FW_PATH].size());
depthaiBinary = resourceMapDevice[MAIN_FW_PATH];
break;
}
// is patching required?
if(version != MAIN_FW_VERSION) {
spdlog::debug("Patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(MAIN_FW_VERSION), OpenVINO::getVersionName(version));
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(depthaiPatch.data(), depthaiPatch.size());
// Reserve space for patched binary
std::vector<std::uint8_t> tmpDepthaiBinary{};
tmpDepthaiBinary.resize(patchedSize);
// Patch
int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiPatch.data(), depthaiPatch.size(), tmpDepthaiBinary.data());
// if patch not successful
if(error > 0) {
throw std::runtime_error(fmt::format(
"Error while patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(MAIN_FW_VERSION), OpenVINO::getVersionName(version)));
}
// Change depthaiBinary to tmpDepthaiBinary
depthaiBinary = std::move(tmpDepthaiBinary);
}
finalFwBinary = std::move(depthaiBinary);
#else
// Binaries from default path (TODO)
#endif
}
// Prepend preboot config
auto prebootHeader = createPrebootHeader(nlohmann::json::to_msgpack(config.preboot), PREBOOT_CONFIG_MAGIC1, PREBOOT_CONFIG_MAGIC2);
finalFwBinary.insert(finalFwBinary.begin(), prebootHeader.begin(), prebootHeader.end());
// Return created firmware
return finalFwBinary;
}
constexpr static auto CMRC_DEPTHAI_BOOTLOADER_TAR_XZ = "depthai-bootloader-fwp-" DEPTHAI_BOOTLOADER_VERSION ".tar.xz";
constexpr static auto DEVICE_BOOTLOADER_USB_PATH = "depthai-bootloader-usb.cmd";
constexpr static auto DEVICE_BOOTLOADER_ETH_PATH = "depthai-bootloader-eth.cmd";
constexpr static std::array<const char*, 2> RESOURCE_LIST_BOOTLOADER = {
DEVICE_BOOTLOADER_USB_PATH,
DEVICE_BOOTLOADER_ETH_PATH,
};
std::vector<std::uint8_t> Resources::getBootloaderFirmware(dai::bootloader::Type type) {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtxBootloader);
switch(type) {
case dai::bootloader::Type::USB:
return resourceMapBootloader[DEVICE_BOOTLOADER_USB_PATH];
break;
case dai::bootloader::Type::NETWORK:
return resourceMapBootloader[DEVICE_BOOTLOADER_ETH_PATH];
break;
default:
throw std::invalid_argument("Invalid Bootloader Type specified.");
break;
}
}
Resources& Resources::getInstance() {
static Resources instance; // Guaranteed to be destroyed, instantiated on first use.
return instance;
}
template <typename CV, typename BOOL, typename MTX, typename PATH, typename LIST, typename MAP>
std::function<void()> getLazyTarXzFunction(MTX& lazyMtx, CV& cv, BOOL& mutexAcquired, MTX& mtxCv, PATH cmrcPath, LIST& resourceList, MAP& resourceMap) {
return [&lazyMtx, &cv, &mutexAcquired, &mtxCv, cmrcPath, &resourceList, &resourceMap] {
using namespace std::chrono;
// Hold 'lazyMtx' until initial preload is finished
std::unique_lock<std::mutex> lock(lazyMtx);
// Let the calling thread know that it may continue
{
std::unique_lock<std::mutex> cvLock(mtxCv);
mutexAcquired = true;
cv.notify_all();
}
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
auto tarXz = fs.open(cmrcPath);
auto t1 = steady_clock::now();
// Load tar.xz archive from memory
struct archive* a = archive_read_new();
archive_read_support_filter_xz(a);
archive_read_support_format_tar(a);
int r = archive_read_open_memory(a, tarXz.begin(), tarXz.size());
assert(r == ARCHIVE_OK);
auto t2 = steady_clock::now();
struct archive_entry* entry;
while(archive_read_next_header(a, &entry) == ARCHIVE_OK) {
// Check whether filename matches to one of required resources
for(const auto& cpath : resourceList) {
std::string resPath(cpath);
if(resPath == std::string(archive_entry_pathname(entry))) {
// Create an emtpy entry
resourceMap[resPath] = std::vector<std::uint8_t>();
// Read size, 16KiB
std::size_t readSize = 16 * 1024;
if(archive_entry_size_is_set(entry)) {
// if size is specified, use that for read size
readSize = archive_entry_size(entry);
}
// Record number of bytes actually read
long long finalSize = 0;
while(true) {
// Current size, as a offset to write next data to
auto currentSize = resourceMap[resPath].size();
// Resize to accomodate for extra data
resourceMap[resPath].resize(currentSize + readSize);
long long size = archive_read_data(a, &resourceMap[resPath][currentSize], readSize);
// Assert that no errors occured
assert(size >= 0);
// Append number of bytes actually read to finalSize
finalSize += size;
// All bytes were read
if(size == 0) {
break;
}
}
// Resize vector to actual read size
resourceMap[resPath].resize(finalSize);
// Entry found - go to next required resource
break;
}
}
}
r = archive_read_free(a); // Note 3
assert(r == ARCHIVE_OK);
// Ignore 'r' variable when in Release build
(void)r;
// Check that all resources were read
for(const auto& cpath : resourceList) {
std::string resPath(cpath);
assert(resourceMap.count(resPath) > 0);
}
auto t3 = steady_clock::now();
// Debug - logs loading times
spdlog::debug(
"Resources - Archive '{}' open: {}, archive read: {}", cmrcPath, duration_cast<milliseconds>(t2 - t1), duration_cast<milliseconds>(t3 - t2));
};
}
Resources::Resources() {
// Device resources
{
// condition variable to let this thread know when the mutex was acquired
std::mutex mtxCv;
std::condition_variable cv;
bool mutexAcquired = false;
// Create a thread which lazy-loads firmware resources package
lazyThreadDevice =
std::thread(getLazyTarXzFunction(mtxDevice, cv, mutexAcquired, mtxCv, CMRC_DEPTHAI_DEVICE_TAR_XZ, RESOURCE_LIST_DEVICE, resourceMapDevice));
// Wait for 'cv' to signal
std::unique_lock<std::mutex> l(mtxCv);
cv.wait(l, [&mutexAcquired]() { return mutexAcquired; });
}
// Bootloader resources
{
// condition variable to let this thread know when the mutex was acquired
std::mutex mtxCv;
std::condition_variable cv;
bool mutexAcquired = false;
// Create a thread which lazy-loads firmware resources package
lazyThreadBootloader = std::thread(
getLazyTarXzFunction(mtxBootloader, cv, mutexAcquired, mtxCv, CMRC_DEPTHAI_BOOTLOADER_TAR_XZ, RESOURCE_LIST_BOOTLOADER, resourceMapBootloader));
// Wait for 'cv' to signal
std::unique_lock<std::mutex> l(mtxCv);
cv.wait(l, [&mutexAcquired]() { return mutexAcquired; });
}
}
Resources::~Resources() {
// join the lazy threads
if(lazyThreadDevice.joinable()) lazyThreadDevice.join();
if(lazyThreadBootloader.joinable()) lazyThreadBootloader.join();
}
// Get device firmware
std::vector<std::uint8_t> Resources::getDeviceFirmware(bool usb2Mode, OpenVINO::Version version) {
Device::Config cfg;
if(usb2Mode) {
cfg.preboot.usb.maxSpeed = UsbSpeed::HIGH;
} else {
cfg.preboot.usb.maxSpeed = Device::DEFAULT_USB_SPEED;
}
cfg.version = version;
return getDeviceFirmware(cfg);
}
std::vector<std::uint8_t> createPrebootHeader(const std::vector<uint8_t>& payload, uint32_t magic1, uint32_t magic2) {
const std::uint8_t HEADER[] = {77,
65,
50,
120,
0x8A,
static_cast<uint8_t>((magic1 >> 0) & 0xFF),
static_cast<uint8_t>((magic1 >> 8) & 0xFF),
static_cast<uint8_t>((magic1 >> 16) & 0xFF),
static_cast<uint8_t>((magic1 >> 24) & 0xFF)};
// Store the constructed preboot information
std::vector<std::uint8_t> prebootHeader;
// Store initial header
prebootHeader.insert(prebootHeader.begin(), std::begin(HEADER), std::end(HEADER));
// Calculate size
std::size_t totalPayloadSize = payload.size() + sizeof(magic2) + sizeof(uint32_t) + sizeof(uint32_t);
std::size_t toAddBytes = 0;
if(totalPayloadSize % 4 != 0) {
toAddBytes = 4 - (totalPayloadSize % 4);
}
std::size_t totalSize = totalPayloadSize + toAddBytes;
std::size_t totalSizeWord = totalSize / 4;
// Write size in words in little endian
prebootHeader.push_back((totalSizeWord >> 0) & 0xFF);
prebootHeader.push_back((totalSizeWord >> 8) & 0xFF);
// Compute payload checksum
auto checksum = utility::checksum(payload.data(), payload.size());
// Write checksum & payload size as uint32_t LE
for(const auto& field : {magic2, checksum, static_cast<uint32_t>(payload.size())}) {
for(int i = 0; i < 4; i++) {
prebootHeader.push_back((field >> (i * 8)) & 0xFF);
}
}
// Copy payload
prebootHeader.insert(prebootHeader.end(), payload.begin(), payload.end());
// Add missing bytes
for(std::size_t i = 0; i < toAddBytes; i++) {
prebootHeader.push_back(0x00);
}
return prebootHeader;
}
} // namespace dai
Fixed patching
#include "Resources.hpp"
#include <array>
#include <cassert>
#include <condition_variable>
#include <fstream>
#include <iostream>
#include <thread>
// libarchive
#include "archive.h"
#include "archive_entry.h"
// spdlog
#include "spdlog/details/os.h"
#include "spdlog/fmt/chrono.h"
#include "spdlog/spdlog.h"
// shared
#include "depthai-shared/device/PrebootConfig.hpp"
#include "depthai-shared/utility/Checksum.hpp"
extern "C" {
#include "bspatch/bspatch.h"
}
// Resource compiled assets (cmds)
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
#include "cmrc/cmrc.hpp"
CMRC_DECLARE(depthai);
#endif
namespace dai {
static std::vector<std::uint8_t> createPrebootHeader(const std::vector<uint8_t>& payload, uint32_t magic1, uint32_t magic2);
constexpr static auto CMRC_DEPTHAI_DEVICE_TAR_XZ = "depthai-device-fwp-" DEPTHAI_DEVICE_VERSION ".tar.xz";
// Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_4_PATH = "depthai-device-openvino-2021.4-" DEPTHAI_DEVICE_VERSION ".cmd";
constexpr static auto MAIN_FW_PATH = DEPTHAI_CMD_OPENVINO_2021_4_PATH;
constexpr static auto MAIN_FW_VERSION = OpenVINO::VERSION_2021_4;
// Patches from Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH = "depthai-device-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH = "depthai-device-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH = "depthai-device-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH = "depthai-device-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH = "depthai-device-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".patch";
// Creates std::array without explicitly needing to state the size
template <typename V, typename... T>
static constexpr auto array_of(T&&... t) -> std::array<V, sizeof...(T)> {
return {{std::forward<T>(t)...}};
}
constexpr static auto RESOURCE_LIST_DEVICE = array_of<const char*>(DEPTHAI_CMD_OPENVINO_2021_4_PATH,
DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH);
std::vector<std::uint8_t> Resources::getDeviceFirmware(Device::Config config, std::string pathToMvcmd) {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtxDevice);
std::vector<std::uint8_t> finalFwBinary;
// Get OpenVINO version
auto& version = config.version;
// Check if pathToMvcmd variable is set
std::string finalFwBinaryPath = "";
if(!pathToMvcmd.empty()) {
finalFwBinaryPath = pathToMvcmd;
}
// Override if env variable DEPTHAI_DEVICE_BINARY is set
auto fwBinaryPath = spdlog::details::os::getenv("DEPTHAI_DEVICE_BINARY");
if(!fwBinaryPath.empty()) {
finalFwBinaryPath = fwBinaryPath;
}
// Return binary from file if any of above paths are present
if(!finalFwBinaryPath.empty()) {
// Load binary file at path
std::ifstream stream(finalFwBinaryPath, std::ios::binary);
if(!stream.is_open()) {
// Throw an error
// TODO(themarpe) - Unify exceptions into meaningful groups
throw std::runtime_error(fmt::format("File at path {} pointed to by DEPTHAI_DEVICE_BINARY doesn't exist.", fwBinaryPath));
}
// Read the file and return its contents
finalFwBinary = std::vector<std::uint8_t>(std::istreambuf_iterator<char>(stream), {});
} else {
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
// Main FW
std::vector<std::uint8_t> depthaiBinary;
// Patch from main to specified
std::vector<std::uint8_t> depthaiPatch;
switch(version) {
case OpenVINO::VERSION_2020_3:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_4:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_1:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_2:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_3:
depthaiPatch = resourceMapDevice[DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH];
break;
case MAIN_FW_VERSION:
depthaiBinary = resourceMapDevice[MAIN_FW_PATH];
break;
}
// is patching required?
if(!depthaiPatch.empty()) {
spdlog::debug("Patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(MAIN_FW_VERSION), OpenVINO::getVersionName(version));
// Load full binary for patch
depthaiBinary = resourceMapDevice[MAIN_FW_PATH];
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(depthaiPatch.data(), depthaiPatch.size());
// Reserve space for patched binary
std::vector<std::uint8_t> tmpDepthaiBinary{};
tmpDepthaiBinary.resize(patchedSize);
// Patch
int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiPatch.data(), depthaiPatch.size(), tmpDepthaiBinary.data());
// if patch not successful
if(error > 0) {
throw std::runtime_error(fmt::format(
"Error while patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(MAIN_FW_VERSION), OpenVINO::getVersionName(version)));
}
// Change depthaiBinary to tmpDepthaiBinary
depthaiBinary = std::move(tmpDepthaiBinary);
}
finalFwBinary = std::move(depthaiBinary);
#else
// Binaries from default path (TODO)
#endif
}
// Prepend preboot config
auto prebootHeader = createPrebootHeader(nlohmann::json::to_msgpack(config.preboot), PREBOOT_CONFIG_MAGIC1, PREBOOT_CONFIG_MAGIC2);
finalFwBinary.insert(finalFwBinary.begin(), prebootHeader.begin(), prebootHeader.end());
// Return created firmware
return finalFwBinary;
}
constexpr static auto CMRC_DEPTHAI_BOOTLOADER_TAR_XZ = "depthai-bootloader-fwp-" DEPTHAI_BOOTLOADER_VERSION ".tar.xz";
constexpr static auto DEVICE_BOOTLOADER_USB_PATH = "depthai-bootloader-usb.cmd";
constexpr static auto DEVICE_BOOTLOADER_ETH_PATH = "depthai-bootloader-eth.cmd";
constexpr static std::array<const char*, 2> RESOURCE_LIST_BOOTLOADER = {
DEVICE_BOOTLOADER_USB_PATH,
DEVICE_BOOTLOADER_ETH_PATH,
};
std::vector<std::uint8_t> Resources::getBootloaderFirmware(dai::bootloader::Type type) {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtxBootloader);
switch(type) {
case dai::bootloader::Type::USB:
return resourceMapBootloader[DEVICE_BOOTLOADER_USB_PATH];
break;
case dai::bootloader::Type::NETWORK:
return resourceMapBootloader[DEVICE_BOOTLOADER_ETH_PATH];
break;
default:
throw std::invalid_argument("Invalid Bootloader Type specified.");
break;
}
}
Resources& Resources::getInstance() {
static Resources instance; // Guaranteed to be destroyed, instantiated on first use.
return instance;
}
template <typename CV, typename BOOL, typename MTX, typename PATH, typename LIST, typename MAP>
std::function<void()> getLazyTarXzFunction(MTX& lazyMtx, CV& cv, BOOL& mutexAcquired, MTX& mtxCv, PATH cmrcPath, LIST& resourceList, MAP& resourceMap) {
return [&lazyMtx, &cv, &mutexAcquired, &mtxCv, cmrcPath, &resourceList, &resourceMap] {
using namespace std::chrono;
// Hold 'lazyMtx' until initial preload is finished
std::unique_lock<std::mutex> lock(lazyMtx);
// Let the calling thread know that it may continue
{
std::unique_lock<std::mutex> cvLock(mtxCv);
mutexAcquired = true;
cv.notify_all();
}
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
auto tarXz = fs.open(cmrcPath);
auto t1 = steady_clock::now();
// Load tar.xz archive from memory
struct archive* a = archive_read_new();
archive_read_support_filter_xz(a);
archive_read_support_format_tar(a);
int r = archive_read_open_memory(a, tarXz.begin(), tarXz.size());
assert(r == ARCHIVE_OK);
auto t2 = steady_clock::now();
struct archive_entry* entry;
while(archive_read_next_header(a, &entry) == ARCHIVE_OK) {
// Check whether filename matches to one of required resources
for(const auto& cpath : resourceList) {
std::string resPath(cpath);
if(resPath == std::string(archive_entry_pathname(entry))) {
// Create an emtpy entry
resourceMap[resPath] = std::vector<std::uint8_t>();
// Read size, 16KiB
std::size_t readSize = 16 * 1024;
if(archive_entry_size_is_set(entry)) {
// if size is specified, use that for read size
readSize = archive_entry_size(entry);
}
// Record number of bytes actually read
long long finalSize = 0;
while(true) {
// Current size, as a offset to write next data to
auto currentSize = resourceMap[resPath].size();
// Resize to accomodate for extra data
resourceMap[resPath].resize(currentSize + readSize);
long long size = archive_read_data(a, &resourceMap[resPath][currentSize], readSize);
// Assert that no errors occured
assert(size >= 0);
// Append number of bytes actually read to finalSize
finalSize += size;
// All bytes were read
if(size == 0) {
break;
}
}
// Resize vector to actual read size
resourceMap[resPath].resize(finalSize);
// Entry found - go to next required resource
break;
}
}
}
r = archive_read_free(a); // Note 3
assert(r == ARCHIVE_OK);
// Ignore 'r' variable when in Release build
(void)r;
// Check that all resources were read
for(const auto& cpath : resourceList) {
std::string resPath(cpath);
assert(resourceMap.count(resPath) > 0);
}
auto t3 = steady_clock::now();
// Debug - logs loading times
spdlog::debug(
"Resources - Archive '{}' open: {}, archive read: {}", cmrcPath, duration_cast<milliseconds>(t2 - t1), duration_cast<milliseconds>(t3 - t2));
};
}
Resources::Resources() {
// Device resources
{
// condition variable to let this thread know when the mutex was acquired
std::mutex mtxCv;
std::condition_variable cv;
bool mutexAcquired = false;
// Create a thread which lazy-loads firmware resources package
lazyThreadDevice =
std::thread(getLazyTarXzFunction(mtxDevice, cv, mutexAcquired, mtxCv, CMRC_DEPTHAI_DEVICE_TAR_XZ, RESOURCE_LIST_DEVICE, resourceMapDevice));
// Wait for 'cv' to signal
std::unique_lock<std::mutex> l(mtxCv);
cv.wait(l, [&mutexAcquired]() { return mutexAcquired; });
}
// Bootloader resources
{
// condition variable to let this thread know when the mutex was acquired
std::mutex mtxCv;
std::condition_variable cv;
bool mutexAcquired = false;
// Create a thread which lazy-loads firmware resources package
lazyThreadBootloader = std::thread(
getLazyTarXzFunction(mtxBootloader, cv, mutexAcquired, mtxCv, CMRC_DEPTHAI_BOOTLOADER_TAR_XZ, RESOURCE_LIST_BOOTLOADER, resourceMapBootloader));
// Wait for 'cv' to signal
std::unique_lock<std::mutex> l(mtxCv);
cv.wait(l, [&mutexAcquired]() { return mutexAcquired; });
}
}
Resources::~Resources() {
// join the lazy threads
if(lazyThreadDevice.joinable()) lazyThreadDevice.join();
if(lazyThreadBootloader.joinable()) lazyThreadBootloader.join();
}
// Get device firmware
std::vector<std::uint8_t> Resources::getDeviceFirmware(bool usb2Mode, OpenVINO::Version version) {
Device::Config cfg;
if(usb2Mode) {
cfg.preboot.usb.maxSpeed = UsbSpeed::HIGH;
} else {
cfg.preboot.usb.maxSpeed = Device::DEFAULT_USB_SPEED;
}
cfg.version = version;
return getDeviceFirmware(cfg);
}
std::vector<std::uint8_t> createPrebootHeader(const std::vector<uint8_t>& payload, uint32_t magic1, uint32_t magic2) {
const std::uint8_t HEADER[] = {77,
65,
50,
120,
0x8A,
static_cast<uint8_t>((magic1 >> 0) & 0xFF),
static_cast<uint8_t>((magic1 >> 8) & 0xFF),
static_cast<uint8_t>((magic1 >> 16) & 0xFF),
static_cast<uint8_t>((magic1 >> 24) & 0xFF)};
// Store the constructed preboot information
std::vector<std::uint8_t> prebootHeader;
// Store initial header
prebootHeader.insert(prebootHeader.begin(), std::begin(HEADER), std::end(HEADER));
// Calculate size
std::size_t totalPayloadSize = payload.size() + sizeof(magic2) + sizeof(uint32_t) + sizeof(uint32_t);
std::size_t toAddBytes = 0;
if(totalPayloadSize % 4 != 0) {
toAddBytes = 4 - (totalPayloadSize % 4);
}
std::size_t totalSize = totalPayloadSize + toAddBytes;
std::size_t totalSizeWord = totalSize / 4;
// Write size in words in little endian
prebootHeader.push_back((totalSizeWord >> 0) & 0xFF);
prebootHeader.push_back((totalSizeWord >> 8) & 0xFF);
// Compute payload checksum
auto checksum = utility::checksum(payload.data(), payload.size());
// Write checksum & payload size as uint32_t LE
for(const auto& field : {magic2, checksum, static_cast<uint32_t>(payload.size())}) {
for(int i = 0; i < 4; i++) {
prebootHeader.push_back((field >> (i * 8)) & 0xFF);
}
}
// Copy payload
prebootHeader.insert(prebootHeader.end(), payload.begin(), payload.end());
// Add missing bytes
for(std::size_t i = 0; i < toAddBytes; i++) {
prebootHeader.push_back(0x00);
}
return prebootHeader;
}
} // namespace dai
|
#include "Resources.hpp"
#include <array>
#include <cassert>
#include <condition_variable>
#include <iostream>
#include <thread>
// libarchive
#include "archive.h"
#include "archive_entry.h"
// spdlog
#include "spdlog/fmt/chrono.h"
#include "spdlog/spdlog.h"
extern "C" {
#include "bspatch/bspatch.h"
}
// Resource compiled assets (cmds)
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
#include "cmrc/cmrc.hpp"
CMRC_DECLARE(depthai);
#endif
namespace dai {
static std::vector<std::uint8_t> getEmbeddedBootloaderBinary();
#ifdef DEPTHAI_RESOURCES_TAR_XZ
constexpr static auto CMRC_DEPTHAI_DEVICE_TAR_XZ = "depthai-device-fwp-" DEPTHAI_DEVICE_VERSION ".tar.xz";
// Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_PATH = "depthai-device-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".cmd";
// Patches from Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_1_PATCH_PATH = "depthai-device-openvino-2020.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH = "depthai-device-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_2_PATCH_PATH = DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH;
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH = "depthai-device-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH = "depthai-device-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH = "depthai-device-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
// Usb2 patches
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_1_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2020.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_2_USB2_PATCH_PATH = DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH;
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static std::array<const char*, 14> resourcesListTarXz = {
DEPTHAI_CMD_OPENVINO_2021_3_PATH,
DEPTHAI_CMD_OPENVINO_2020_1_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_1_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_2_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_4_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_1_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_2_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH,
};
std::vector<std::uint8_t> Resources::getDeviceBinary(OpenVINO::Version version, bool usb2Mode) {
std::vector<std::uint8_t> finalCmd;
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
// Temporary binary
std::vector<std::uint8_t> tmpDepthaiBinary;
// Main FW
std::vector<std::uint8_t>& depthaiBinary = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_PATH];
// Patch from main to specified
std::vector<std::uint8_t>& depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH];
// Patch from specified to usb2 specified
std::vector<std::uint8_t>& depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH];
switch(version) {
case OpenVINO::VERSION_2020_1:
spdlog::warn("OpenVino version 2020.1 is deprecated and will be removed in the next release!");
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_1_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_1_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_2:
spdlog::warn("OpenVino version 2020.2 is deprecated and will be removed in the next release!");
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_2_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_2_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_3:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_4:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_4_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_1:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_1_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_2:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_2_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_3:
depthaiBinary = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH];
break;
}
// is patching required?
if(version != OpenVINO::VERSION_2021_3){
spdlog::debug("Patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(OpenVINO::VERSION_2021_3), OpenVINO::getVersionName(version));
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(depthaiPatch.data(), depthaiPatch.size());
// Reserve space for patched binary
tmpDepthaiBinary.resize(patchedSize);
// Patch
int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiPatch.data(), depthaiPatch.size(), tmpDepthaiBinary.data());
// if patch not successful
if(error > 0) throw std::runtime_error("Error while patching cmd for usb2 mode");
// Change depthaiBinary to tmpDepthaiBinary
depthaiBinary = tmpDepthaiBinary;
}
if(usb2Mode) {
#ifdef DEPTHAI_PATCH_ONLY_MODE
spdlog::debug("Patching FW version {} to USB2 mode", OpenVINO::getVersionName(version));
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(depthaiUsb2Patch.data(), depthaiUsb2Patch.size());
// Reserve space for patched binary
finalCmd.resize(patchedSize);
// Patch
int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiUsb2Patch.data(), depthaiUsb2Patch.size(), finalCmd.data());
// if patch not successful
if(error > 0) throw std::runtime_error("Error while patching cmd for usb2 mode");
#else
static_assert("Unsupported currently");
#endif
} else {
return depthaiBinary;
}
#else
// Binaries from default path (TODO)
#endif
return finalCmd;
}
#else
// TODO - DEPRECATE
constexpr static auto CMRC_DEPTHAI_CMD_PATH = "depthai-" DEPTHAI_DEVICE_VERSION ".cmd";
#ifdef DEPTHAI_PATCH_ONLY_MODE
constexpr static auto CMRC_DEPTHAI_USB2_PATCH_PATH = "depthai-usb2-patch-" DEPTHAI_DEVICE_VERSION ".patch";
#else
constexpr static auto CMRC_DEPTHAI_USB2_CMD_PATH = "depthai-usb2-" DEPTHAI_DEVICE_VERSION ".cmd";
#endif
static std::vector<std::uint8_t> getEmbeddedDeviceBinary(bool usb2Mode) {
std::vector<std::uint8_t> finalCmd;
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
if(usb2Mode) {
#ifdef DEPTHAI_PATCH_ONLY_MODE
// Get size of original
auto depthaiBinary = fs.open(CMRC_DEPTHAI_CMD_PATH);
// Open patch
auto depthaiUsb2Patch = fs.open(CMRC_DEPTHAI_USB2_PATCH_PATH);
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(reinterpret_cast<const uint8_t*>(depthaiUsb2Patch.begin()), depthaiUsb2Patch.size());
// Reserve space for patched binary
finalCmd.resize(patchedSize);
// Patch
int error = bspatch_mem(reinterpret_cast<const uint8_t*>(depthaiBinary.begin()),
depthaiBinary.size(),
reinterpret_cast<const uint8_t*>(depthaiUsb2Patch.begin()),
depthaiUsb2Patch.size(),
finalCmd.data());
// if patch not successful
if(error > 0) throw std::runtime_error("Error while patching cmd for usb2 mode");
#else
auto depthaiUsb2Binary = fs.open(CMRC_DEPTHAI_USB2_CMD_PATH);
finalCmd = std::vector<std::uint8_t>(depthaiUsb2Binary.begin(), depthaiUsb2Binary.end());
#endif
} else {
auto depthaiBinary = fs.open(CMRC_DEPTHAI_CMD_PATH);
finalCmd = std::vector<std::uint8_t>(depthaiBinary.begin(), depthaiBinary.end());
}
#else
// Binaries from default path (TODO)
#endif
return finalCmd;
}
#endif
Resources& Resources::getInstance() {
static Resources instance; // Guaranteed to be destroyed, instantiated on first use.
return instance;
}
Resources::Resources() {
#ifdef DEPTHAI_RESOURCES_TAR_XZ
// condition variable to let this thread know when the mutex was acquired
std::mutex mtxCv;
std::condition_variable cv;
bool mutexAcquired = false;
// Create a thread which lazy-loads firmware resources package
lazyThread = std::thread([this, &cv, &mutexAcquired, &mtxCv]() {
using namespace std::chrono;
// Hold 'mtx' until initial preload is finished
std::unique_lock<std::mutex> lock(mtx);
// Let the calling thread know that it may continue
{
std::unique_lock<std::mutex> cvLock(mtxCv);
mutexAcquired = true;
cv.notify_all();
}
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
auto deviceTarXz = fs.open(CMRC_DEPTHAI_DEVICE_TAR_XZ);
auto t1 = steady_clock::now();
// Load tar.xz archive from memory
struct archive* a = archive_read_new();
archive_read_support_filter_xz(a);
archive_read_support_format_tar(a);
int r = archive_read_open_memory(a, deviceTarXz.begin(), deviceTarXz.size());
assert(r == ARCHIVE_OK);
auto t2 = steady_clock::now();
struct archive_entry* entry;
while(archive_read_next_header(a, &entry) == ARCHIVE_OK) {
// Check whether filename matches to one of required resources
for(const auto& cpath : resourcesListTarXz) {
std::string resPath(cpath);
if(resPath == std::string(archive_entry_pathname(entry))) {
// Create an emtpy entry
resourceMap[resPath] = std::vector<std::uint8_t>();
// Read size, 16KiB
std::size_t readSize = 16 * 1024;
if(archive_entry_size_is_set(entry)) {
// if size is specified, use that for read size
readSize = archive_entry_size(entry);
}
// Record number of bytes actually read
long long finalSize = 0;
while(true) {
// Current size, as a offset to write next data to
auto currentSize = resourceMap[resPath].size();
// Resize to accomodate for extra data
resourceMap[resPath].resize(currentSize + readSize);
long long size = archive_read_data(a, &resourceMap[resPath][currentSize], readSize);
// Assert that no errors occured
assert(size >= 0);
// Append number of bytes actually read to finalSize
finalSize += size;
// All bytes were read
if(size == 0) {
break;
}
}
// Resize vector to actual read size
resourceMap[resPath].resize(finalSize);
// Entry found - go to next required resource
break;
}
}
}
r = archive_read_free(a); // Note 3
// Check that all resources were read
for(const auto& cpath : resourcesListTarXz) {
std::string resPath(cpath);
assert(resourceMap.count(resPath) > 0);
}
auto t3 = steady_clock::now();
// Debug - logs loading times
spdlog::debug("Resources - archive open: {}, archive read: {}", t2 - t1, t3 - t2);
});
// Wait for 'cv' to signal
std::unique_lock<std::mutex> l(mtxCv);
cv.wait(l, [&mutexAcquired]() { return mutexAcquired; });
#endif
}
Resources::~Resources() {
// join the lazy thread
if(lazyThread.joinable()) lazyThread.join();
}
// Get device firmware
std::vector<std::uint8_t> Resources::getDeviceFirmware(bool usb2Mode, OpenVINO::Version version) {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtx);
#ifdef DEPTHAI_RESOURCES_TAR_XZ
// Return device firmware
return getDeviceBinary(version, usb2Mode);
#else
// Return device firmware
return getEmbeddedDeviceBinary(usb2Mode);
#endif
}
std::vector<std::uint8_t> Resources::getBootloaderFirmware() {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtx);
return getEmbeddedBootloaderBinary();
}
std::vector<std::uint8_t> getEmbeddedBootloaderBinary() {
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
constexpr static auto CMRC_DEPTHAI_BOOTLOADER_PATH = "depthai-bootloader-" DEPTHAI_BOOTLOADER_VERSION ".cmd";
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
auto bootloaderBinary = fs.open(CMRC_DEPTHAI_BOOTLOADER_PATH);
return std::vector<std::uint8_t>(bootloaderBinary.begin(), bootloaderBinary.end());
#else
static_assert(0 && "Unsupported");
return {};
#endif
}
} // namespace dai
Updated style
#include "Resources.hpp"
#include <array>
#include <cassert>
#include <condition_variable>
#include <iostream>
#include <thread>
// libarchive
#include "archive.h"
#include "archive_entry.h"
// spdlog
#include "spdlog/fmt/chrono.h"
#include "spdlog/spdlog.h"
extern "C" {
#include "bspatch/bspatch.h"
}
// Resource compiled assets (cmds)
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
#include "cmrc/cmrc.hpp"
CMRC_DECLARE(depthai);
#endif
namespace dai {
static std::vector<std::uint8_t> getEmbeddedBootloaderBinary();
#ifdef DEPTHAI_RESOURCES_TAR_XZ
constexpr static auto CMRC_DEPTHAI_DEVICE_TAR_XZ = "depthai-device-fwp-" DEPTHAI_DEVICE_VERSION ".tar.xz";
// Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_PATH = "depthai-device-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".cmd";
// Patches from Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_1_PATCH_PATH = "depthai-device-openvino-2020.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH = "depthai-device-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_2_PATCH_PATH = DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH;
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH = "depthai-device-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH = "depthai-device-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH = "depthai-device-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
// Usb2 patches
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_1_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2020.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_2_USB2_PATCH_PATH = DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH;
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH = "depthai-device-usb2-patch-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static std::array<const char*, 14> resourcesListTarXz = {
DEPTHAI_CMD_OPENVINO_2021_3_PATH,
DEPTHAI_CMD_OPENVINO_2020_1_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_1_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_2_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2020_4_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_1_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_2_USB2_PATCH_PATH,
DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH,
};
std::vector<std::uint8_t> Resources::getDeviceBinary(OpenVINO::Version version, bool usb2Mode) {
std::vector<std::uint8_t> finalCmd;
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
// Temporary binary
std::vector<std::uint8_t> tmpDepthaiBinary;
// Main FW
std::vector<std::uint8_t>& depthaiBinary = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_PATH];
// Patch from main to specified
std::vector<std::uint8_t>& depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH];
// Patch from specified to usb2 specified
std::vector<std::uint8_t>& depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH];
switch(version) {
case OpenVINO::VERSION_2020_1:
spdlog::warn("OpenVino version 2020.1 is deprecated and will be removed in the next release!");
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_1_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_1_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_2:
spdlog::warn("OpenVino version 2020.2 is deprecated and will be removed in the next release!");
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_2_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_2_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_3:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_3_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2020_4:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2020_4_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_1:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_1_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_2:
depthaiPatch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_2_USB2_PATCH_PATH];
break;
case OpenVINO::VERSION_2021_3:
depthaiBinary = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_PATH];
depthaiUsb2Patch = resourceMap[DEPTHAI_CMD_OPENVINO_2021_3_USB2_PATCH_PATH];
break;
}
// is patching required?
if(version != OpenVINO::VERSION_2021_3) {
spdlog::debug("Patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(OpenVINO::VERSION_2021_3), OpenVINO::getVersionName(version));
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(depthaiPatch.data(), depthaiPatch.size());
// Reserve space for patched binary
tmpDepthaiBinary.resize(patchedSize);
// Patch
int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiPatch.data(), depthaiPatch.size(), tmpDepthaiBinary.data());
// if patch not successful
if(error > 0) throw std::runtime_error("Error while patching cmd for usb2 mode");
// Change depthaiBinary to tmpDepthaiBinary
depthaiBinary = tmpDepthaiBinary;
}
if(usb2Mode) {
#ifdef DEPTHAI_PATCH_ONLY_MODE
spdlog::debug("Patching FW version {} to USB2 mode", OpenVINO::getVersionName(version));
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(depthaiUsb2Patch.data(), depthaiUsb2Patch.size());
// Reserve space for patched binary
finalCmd.resize(patchedSize);
// Patch
int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiUsb2Patch.data(), depthaiUsb2Patch.size(), finalCmd.data());
// if patch not successful
if(error > 0) throw std::runtime_error("Error while patching cmd for usb2 mode");
#else
static_assert("Unsupported currently");
#endif
} else {
return depthaiBinary;
}
#else
// Binaries from default path (TODO)
#endif
return finalCmd;
}
#else
// TODO - DEPRECATE
constexpr static auto CMRC_DEPTHAI_CMD_PATH = "depthai-" DEPTHAI_DEVICE_VERSION ".cmd";
#ifdef DEPTHAI_PATCH_ONLY_MODE
constexpr static auto CMRC_DEPTHAI_USB2_PATCH_PATH = "depthai-usb2-patch-" DEPTHAI_DEVICE_VERSION ".patch";
#else
constexpr static auto CMRC_DEPTHAI_USB2_CMD_PATH = "depthai-usb2-" DEPTHAI_DEVICE_VERSION ".cmd";
#endif
static std::vector<std::uint8_t> getEmbeddedDeviceBinary(bool usb2Mode) {
std::vector<std::uint8_t> finalCmd;
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
if(usb2Mode) {
#ifdef DEPTHAI_PATCH_ONLY_MODE
// Get size of original
auto depthaiBinary = fs.open(CMRC_DEPTHAI_CMD_PATH);
// Open patch
auto depthaiUsb2Patch = fs.open(CMRC_DEPTHAI_USB2_PATCH_PATH);
// Get new size
int64_t patchedSize = bspatch_mem_get_newsize(reinterpret_cast<const uint8_t*>(depthaiUsb2Patch.begin()), depthaiUsb2Patch.size());
// Reserve space for patched binary
finalCmd.resize(patchedSize);
// Patch
int error = bspatch_mem(reinterpret_cast<const uint8_t*>(depthaiBinary.begin()),
depthaiBinary.size(),
reinterpret_cast<const uint8_t*>(depthaiUsb2Patch.begin()),
depthaiUsb2Patch.size(),
finalCmd.data());
// if patch not successful
if(error > 0) throw std::runtime_error("Error while patching cmd for usb2 mode");
#else
auto depthaiUsb2Binary = fs.open(CMRC_DEPTHAI_USB2_CMD_PATH);
finalCmd = std::vector<std::uint8_t>(depthaiUsb2Binary.begin(), depthaiUsb2Binary.end());
#endif
} else {
auto depthaiBinary = fs.open(CMRC_DEPTHAI_CMD_PATH);
finalCmd = std::vector<std::uint8_t>(depthaiBinary.begin(), depthaiBinary.end());
}
#else
// Binaries from default path (TODO)
#endif
return finalCmd;
}
#endif
Resources& Resources::getInstance() {
static Resources instance; // Guaranteed to be destroyed, instantiated on first use.
return instance;
}
Resources::Resources() {
#ifdef DEPTHAI_RESOURCES_TAR_XZ
// condition variable to let this thread know when the mutex was acquired
std::mutex mtxCv;
std::condition_variable cv;
bool mutexAcquired = false;
// Create a thread which lazy-loads firmware resources package
lazyThread = std::thread([this, &cv, &mutexAcquired, &mtxCv]() {
using namespace std::chrono;
// Hold 'mtx' until initial preload is finished
std::unique_lock<std::mutex> lock(mtx);
// Let the calling thread know that it may continue
{
std::unique_lock<std::mutex> cvLock(mtxCv);
mutexAcquired = true;
cv.notify_all();
}
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
auto deviceTarXz = fs.open(CMRC_DEPTHAI_DEVICE_TAR_XZ);
auto t1 = steady_clock::now();
// Load tar.xz archive from memory
struct archive* a = archive_read_new();
archive_read_support_filter_xz(a);
archive_read_support_format_tar(a);
int r = archive_read_open_memory(a, deviceTarXz.begin(), deviceTarXz.size());
assert(r == ARCHIVE_OK);
auto t2 = steady_clock::now();
struct archive_entry* entry;
while(archive_read_next_header(a, &entry) == ARCHIVE_OK) {
// Check whether filename matches to one of required resources
for(const auto& cpath : resourcesListTarXz) {
std::string resPath(cpath);
if(resPath == std::string(archive_entry_pathname(entry))) {
// Create an emtpy entry
resourceMap[resPath] = std::vector<std::uint8_t>();
// Read size, 16KiB
std::size_t readSize = 16 * 1024;
if(archive_entry_size_is_set(entry)) {
// if size is specified, use that for read size
readSize = archive_entry_size(entry);
}
// Record number of bytes actually read
long long finalSize = 0;
while(true) {
// Current size, as a offset to write next data to
auto currentSize = resourceMap[resPath].size();
// Resize to accomodate for extra data
resourceMap[resPath].resize(currentSize + readSize);
long long size = archive_read_data(a, &resourceMap[resPath][currentSize], readSize);
// Assert that no errors occured
assert(size >= 0);
// Append number of bytes actually read to finalSize
finalSize += size;
// All bytes were read
if(size == 0) {
break;
}
}
// Resize vector to actual read size
resourceMap[resPath].resize(finalSize);
// Entry found - go to next required resource
break;
}
}
}
r = archive_read_free(a); // Note 3
// Check that all resources were read
for(const auto& cpath : resourcesListTarXz) {
std::string resPath(cpath);
assert(resourceMap.count(resPath) > 0);
}
auto t3 = steady_clock::now();
// Debug - logs loading times
spdlog::debug("Resources - archive open: {}, archive read: {}", t2 - t1, t3 - t2);
});
// Wait for 'cv' to signal
std::unique_lock<std::mutex> l(mtxCv);
cv.wait(l, [&mutexAcquired]() { return mutexAcquired; });
#endif
}
Resources::~Resources() {
// join the lazy thread
if(lazyThread.joinable()) lazyThread.join();
}
// Get device firmware
std::vector<std::uint8_t> Resources::getDeviceFirmware(bool usb2Mode, OpenVINO::Version version) {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtx);
#ifdef DEPTHAI_RESOURCES_TAR_XZ
// Return device firmware
return getDeviceBinary(version, usb2Mode);
#else
// Return device firmware
return getEmbeddedDeviceBinary(usb2Mode);
#endif
}
std::vector<std::uint8_t> Resources::getBootloaderFirmware() {
// Acquire mutex (this mutex signifies that lazy load is complete)
// It is necessary when accessing resourceMap variable
std::unique_lock<std::mutex> lock(mtx);
return getEmbeddedBootloaderBinary();
}
std::vector<std::uint8_t> getEmbeddedBootloaderBinary() {
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
constexpr static auto CMRC_DEPTHAI_BOOTLOADER_PATH = "depthai-bootloader-" DEPTHAI_BOOTLOADER_VERSION ".cmd";
// Get binaries from internal sources
auto fs = cmrc::depthai::get_filesystem();
auto bootloaderBinary = fs.open(CMRC_DEPTHAI_BOOTLOADER_PATH);
return std::vector<std::uint8_t>(bootloaderBinary.begin(), bootloaderBinary.end());
#else
static_assert(0 && "Unsupported");
return {};
#endif
}
} // namespace dai
|
/** \copyright
* Copyright (c) 2013, Stuart W Baker
* 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.
*
* 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*
* \file BufferQueue.hxx
* This file provides an implementation buffered queues.
*
* @author Stuart W. Baker
* @date 3 August 2013
*/
#ifndef _BufferQueue_hxx_
#define _BufferQueue_hxx_
#include <cstdint>
#include <cstdlib>
#include <os/OS.hxx>
class BufferPool;
/** main buffer pool instance */
extern BufferPool *mainBufferPool;
/** Buffer structure that contains both metadata and user data */
class Buffer
{
public:
/** Free this buffer to the BufferPool from whence it came.
*/
inline void free();
/** Advance the position of the buffer.
* @param bytes number of bytes to advance.
* @return pointer to the new position (next available byte)
*/
void *advance(size_t bytes);
/** reset the buffer position back to beginning.
* @return pointer to the new position (next available byte)
*/
void *zero()
{
left = _size;
return data;
}
/** Get a pointer to the first position (byte) of the buffer.
* @return pointer to the first position (byte)
*/
const void *start() const
{
return data;
}
/** Get a pointer to the first position (byte) of the buffer.
* @return pointer to the first position (byte)
*/
void *start()
{
return data;
}
/** Get a pointer to the current position of the buffer.
* @return pointer to the current position (next available byte)
*/
void *position()
{
return &data[_size - left];
}
/** Get the size of the buffer in bytes.
* @return size of the buffer in bytes
*/
size_t size() const
{
return _size;
}
/** Get the number of unused bytes in the buffer.
* @return number of unused bytes
*/
size_t available() const
{
return left;
}
/** Get the number of used bytes in the buffer.
* @return number of used bytes
*/
size_t used() const
{
return _size - left;
}
/** Expand the buffer size.
* @param size size buffer after expansion.
* @return newly expanded buffer with old buffer data moved
*/
Buffer *expand(size_t size);
/** Set the unique identifier for the buffer.
* @param identifier 32-bit unique identifier
*/
void id(uint32_t identifier)
{
_id = identifier;
}
/** Get the unique identifier for the buffer.
* @return 32-bit unique identifier
*/
uint32_t id()
{
return _id;
}
/** Add another reference to the buffer.
* @return total number of references to this point
*/
unsigned int reference();
private:
/** Like a constructor, but in this case, we allocate extra space for the
* user data.
* @param pool BufferPool instance from which this buffer will come
* @param size size of user data in bytes
* @param items number of items to allocate
* @return newly allocated buffer or addres of first item in an array of
* allocated buffers, HASSERT() on failure
*/
static Buffer *alloc(BufferPool *pool, size_t size, size_t items = 1)
{
HASSERT(pool != NULL && items != 0);
size_t align_size = sizeof_buffer(size);
Buffer *buffer = (Buffer*)malloc(align_size * items);
HASSERT(buffer != NULL);
Buffer *result = buffer;
for (size_t i = 0; i < items; ++i)
{
buffer->next = NULL;
buffer->bufferPool = pool;
buffer->_size = size;
buffer->left = size;
buffer->count = 1;
buffer = (Buffer*)((char*)buffer + align_size);
}
return result;
}
/** Like a constructor, but in this case, we re-purpose an existing buffer
* with no new memory allocation.
* @param buffer instance of buffer to reinitialize
* @param size size of user data in bytes
* @return newly reinitialized buffer, HASSERT() on failure
*/
static Buffer *init(Buffer *buffer, size_t size)
{
HASSERT(buffer->bufferPool != NULL);
HASSERT(buffer->_size == size);
buffer->next = NULL;
buffer->left = size;
buffer->count = 1;
return buffer;
}
/** Macro to position to beginning of structure from data member position*/
#define BUFFER(_buffer) (Buffer*)((char *)(_buffer) - sizeof(Buffer));
/* pointer to BufferPool instance that this buffer belongs to */
BufferPool *bufferPool;
/** next buffer in list */
Buffer *next;
/** size of data in bytes */
size_t _size;
/** amount for free space left in the buffer */
size_t left;
/** message ID for uniquely identifying this buffer in a queue */
uint32_t _id;
/** number of references in use */
unsigned int count;
/** user data */
char data[];
/** This class is a helper of BufferPool, so we know where to free to */
friend class BufferPool;
/** This class is a helper of BufferQueue */
friend class BufferQueue;
/** The total size of an array element of a Buffer for given payload.
* @param size payload size
*/
static size_t sizeof_buffer(size_t size)
{
return sizeof(Buffer) + (((size/sizeof(long)) + (size % sizeof(long) ? 1 : 0)) * sizeof(long));
}
/** Default constructor */
Buffer();
/** Default destructor */
~Buffer();
DISALLOW_COPY_AND_ASSIGN(Buffer);
};
/** Pool of previously allocated, but currently unused, buffers. */
class BufferPool
{
public:
/* Default Constructor */
BufferPool()
: totalSize(0),
mutex(),
pool {NULL, NULL, NULL, NULL},
itemSize(0),
items(0)
{
}
/* Constructor for a fixed size pool.
* @param item_size size of each item in the pool
* @param items number of items in the pool
*/
BufferPool(size_t item_size, size_t items)
: totalSize(0),
mutex(),
pool {Buffer::alloc(this, item_size, items), NULL, NULL, NULL},
itemSize(item_size),
items(items)
{
Buffer *current = first;
for (size_t i = 0; i < items; ++i)
{
current->next = pool[1];
pool[1] = current;
current = (Buffer*)((char*)current + Buffer::sizeof_buffer(item_size));
}
/* save the index just after last buffer in the bool */
pool[2] = current;
}
/* default destructor */
~BufferPool()
{
HASSERT(0);
}
/** Used in static pools to tell if this buffer is a member of the pool.
* @param buffer buffer to test validity on
* @return true if the buffer is in the pool, or this is not a fixed pool,
* else return false;
*/
bool valid(Buffer *buffer)
{
if (itemSize != 0)
{
if (buffer >= first && buffer <= pool[2])
{
return true;
}
return false;
}
return true;
}
/** Get a free buffer out of the pool. A buffer may be
* obtained without context (object reference) from the mainBufferPool
* with the ::buffer_free method.
*
* @param size minimum size in bytes the buffer must hold
* @return pointer to the newly allocated buffer
*/
Buffer *buffer_alloc(size_t size);
/** Release a buffer back to the free buffer pool. A buffer may be
* released without context (object reference) to the mainBufferPool
* with the ::buffer_free method.
*
* @param buffer pointer to buffer to release
*/
void buffer_free(Buffer *buffer);
private:
/** keep track of total allocated size of memory */
size_t totalSize;
/** Mutual exclusion for buffer pool */
OSMutex mutex;
/** this union save overlapping memory */
union
{
/** Free buffer pool */
Buffer *pool[4];
/** First buffer in a pre-allocated array pool */
Buffer *first;
};
/** item Size for fixed pools */
size_t itemSize;
/** number of items for fixed pools */
size_t items;
/** This class is a helper of BufferQueue */
friend class BufferQueue;
/** This class is a helper of Buffer */
friend class Buffer;
DISALLOW_COPY_AND_ASSIGN(BufferPool);
};
/** This class implements a linked list "queue" of buffers. It may be
* instantiated to use the mainBufferPool for its memory pool, or optionally
* another BufferPool instance may be specified for its memory pool.
*/
class BufferQueue
{
public:
/** Default Constructor, use mainBufferPool for buffer allocation. */
BufferQueue()
: head(NULL),
tail(NULL),
count(0),
mutex()
{
}
/** Default destructor.
*/
~BufferQueue()
{
}
/** Release a buffer back to the free buffer pool.
* @param buffer pointer to buffer to release
*/
void buffer_free(Buffer *buffer)
{
buffer->free();
}
/** Add a buffer to the back of the queue.
* @param buffer buffer to add to queue
*/
void insert(Buffer *buffer);
/** Get a buffer from the front of the queue.
* @return buffer buffer retrieved from queue
*/
Buffer *next();
/** Get the number of pending items in the queue.
* @return number of pending items in the queue
*/
size_t pending()
{
return count;
}
/** Test if the queue is empty.
* @return true if empty, else false
*/
bool empty()
{
return (head == NULL);
}
protected:
private:
/** head buffer in queue */
Buffer *head;
/** tail buffer in queue */
Buffer *tail;
/** number of buffers in queue */
size_t count;
/** @todo (Stuart Baker) For free RTOS, we may want to consider a different
* (smaller) locking mechanism
*/
/** Mutual exclusion for Queue */
OSMutex mutex;
DISALLOW_COPY_AND_ASSIGN(BufferQueue);
};
/** A BufferQueue that adds the ability to wait on the next buffer.
* Yes this uses multiple inheritance. Yes multiple inheritance is bad. It
* is okay in this case, so get over it.
*/
class BufferQueueWait : public BufferQueue, public OSSem
{
public:
/** Default Constructor, use mainBufferPool for buffer allocation. */
BufferQueueWait()
: BufferQueue(),
sem(0)
{
}
/** Default destructor.
*/
~BufferQueueWait()
{
}
/** Add a buffer to the back of the queue.
* @param buffer buffer to add to queue
*/
void insert(Buffer *buffer)
{
BufferQueue::insert(buffer);
post();
}
/** Get a buffer from the front of the queue.
* @return buffer buffer retrieved from queue
*/
Buffer *next()
{
Buffer *result = BufferQueue::next();
if (result != NULL)
{
/* decrement semaphore */
OSSem::wait();
}
return result;
}
/** Wait for a buffer from the front of the queue.
* @return buffer buffer retrieved from queue
*/
Buffer *wait()
{
OSSem::wait();
Buffer *result = BufferQueue::next();
HASSERT(result != NULL);
return result;
}
/** Wait for a buffer from the front of the queue.
* @param timeout time to wait in nanoseconds
* @return buffer buffer retrieved from queue, NULL on timeout or error
*/
Buffer *timedwait(long long timeout)
{
if (OSSem::timedwait(timeout) != 0)
{
return NULL;
}
Buffer *result = BufferQueue::next();
HASSERT(result != NULL);
return result;
}
private:
/** Semaphore that we will wait on */
OSSem sem;
DISALLOW_COPY_AND_ASSIGN(BufferQueueWait);
};
/** Get a free buffer out of the mainBufferPool pool.
* @param size minimum size in bytes the buffer must hold
* @return pointer to the newly allocated buffer
*/
inline Buffer *buffer_alloc(size_t size)
{
return mainBufferPool->buffer_alloc(size);
}
/** Release a buffer back to the mainBufferPool free buffer pool.
* @param buffer pointer to buffer to release
*/
inline void buffer_free(Buffer *buffer)
{
mainBufferPool->buffer_free(buffer);
}
/** Free this buffer to the BufferPool from whence it came.
*/
inline void Buffer::free()
{
HASSERT(bufferPool != NULL);
bufferPool->buffer_free(this);
}
/** Advance the position of the buffer.
* @param bytes number of bytes to advance.
* @return pointer to the new position (next available byte)
*/
inline void *Buffer::advance(size_t bytes)
{
/** @todo (Stuart Baker) do we really need a mutex lock here? */
bufferPool->mutex.lock();
left -= bytes;
bufferPool->mutex.unlock();
return &data[_size - left];
}
/** Add another reference to the buffer.
* @return total number of references to this point
*/
inline unsigned int Buffer::reference()
{
bufferPool->mutex.lock();
++count;
bufferPool->mutex.unlock();
return count;
}
#endif /* _BufferQueue_hxx_ */
comments out destructor crash.
/** \copyright
* Copyright (c) 2013, Stuart W Baker
* 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.
*
* 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*
* \file BufferQueue.hxx
* This file provides an implementation buffered queues.
*
* @author Stuart W. Baker
* @date 3 August 2013
*/
#ifndef _BufferQueue_hxx_
#define _BufferQueue_hxx_
#include <cstdint>
#include <cstdlib>
#include <os/OS.hxx>
class BufferPool;
/** main buffer pool instance */
extern BufferPool *mainBufferPool;
/** Buffer structure that contains both metadata and user data */
class Buffer
{
public:
/** Free this buffer to the BufferPool from whence it came.
*/
inline void free();
/** Advance the position of the buffer.
* @param bytes number of bytes to advance.
* @return pointer to the new position (next available byte)
*/
void *advance(size_t bytes);
/** reset the buffer position back to beginning.
* @return pointer to the new position (next available byte)
*/
void *zero()
{
left = _size;
return data;
}
/** Get a pointer to the first position (byte) of the buffer.
* @return pointer to the first position (byte)
*/
const void *start() const
{
return data;
}
/** Get a pointer to the first position (byte) of the buffer.
* @return pointer to the first position (byte)
*/
void *start()
{
return data;
}
/** Get a pointer to the current position of the buffer.
* @return pointer to the current position (next available byte)
*/
void *position()
{
return &data[_size - left];
}
/** Get the size of the buffer in bytes.
* @return size of the buffer in bytes
*/
size_t size() const
{
return _size;
}
/** Get the number of unused bytes in the buffer.
* @return number of unused bytes
*/
size_t available() const
{
return left;
}
/** Get the number of used bytes in the buffer.
* @return number of used bytes
*/
size_t used() const
{
return _size - left;
}
/** Expand the buffer size.
* @param size size buffer after expansion.
* @return newly expanded buffer with old buffer data moved
*/
Buffer *expand(size_t size);
/** Set the unique identifier for the buffer.
* @param identifier 32-bit unique identifier
*/
void id(uint32_t identifier)
{
_id = identifier;
}
/** Get the unique identifier for the buffer.
* @return 32-bit unique identifier
*/
uint32_t id()
{
return _id;
}
/** Add another reference to the buffer.
* @return total number of references to this point
*/
unsigned int reference();
private:
/** Like a constructor, but in this case, we allocate extra space for the
* user data.
* @param pool BufferPool instance from which this buffer will come
* @param size size of user data in bytes
* @param items number of items to allocate
* @return newly allocated buffer or addres of first item in an array of
* allocated buffers, HASSERT() on failure
*/
static Buffer *alloc(BufferPool *pool, size_t size, size_t items = 1)
{
HASSERT(pool != NULL && items != 0);
size_t align_size = sizeof_buffer(size);
Buffer *buffer = (Buffer*)malloc(align_size * items);
HASSERT(buffer != NULL);
Buffer *result = buffer;
for (size_t i = 0; i < items; ++i)
{
buffer->next = NULL;
buffer->bufferPool = pool;
buffer->_size = size;
buffer->left = size;
buffer->count = 1;
buffer = (Buffer*)((char*)buffer + align_size);
}
return result;
}
/** Like a constructor, but in this case, we re-purpose an existing buffer
* with no new memory allocation.
* @param buffer instance of buffer to reinitialize
* @param size size of user data in bytes
* @return newly reinitialized buffer, HASSERT() on failure
*/
static Buffer *init(Buffer *buffer, size_t size)
{
HASSERT(buffer->bufferPool != NULL);
HASSERT(buffer->_size == size);
buffer->next = NULL;
buffer->left = size;
buffer->count = 1;
return buffer;
}
/** Macro to position to beginning of structure from data member position*/
#define BUFFER(_buffer) (Buffer*)((char *)(_buffer) - sizeof(Buffer));
/* pointer to BufferPool instance that this buffer belongs to */
BufferPool *bufferPool;
/** next buffer in list */
Buffer *next;
/** size of data in bytes */
size_t _size;
/** amount for free space left in the buffer */
size_t left;
/** message ID for uniquely identifying this buffer in a queue */
uint32_t _id;
/** number of references in use */
unsigned int count;
/** user data */
char data[];
/** This class is a helper of BufferPool, so we know where to free to */
friend class BufferPool;
/** This class is a helper of BufferQueue */
friend class BufferQueue;
/** The total size of an array element of a Buffer for given payload.
* @param size payload size
*/
static size_t sizeof_buffer(size_t size)
{
return sizeof(Buffer) + (((size/sizeof(long)) + (size % sizeof(long) ? 1 : 0)) * sizeof(long));
}
/** Default constructor */
Buffer();
/** Default destructor */
~Buffer();
DISALLOW_COPY_AND_ASSIGN(Buffer);
};
/** Pool of previously allocated, but currently unused, buffers. */
class BufferPool
{
public:
/* Default Constructor */
BufferPool()
: totalSize(0),
mutex(),
pool {NULL, NULL, NULL, NULL},
itemSize(0),
items(0)
{
}
/* Constructor for a fixed size pool.
* @param item_size size of each item in the pool
* @param items number of items in the pool
*/
BufferPool(size_t item_size, size_t items)
: totalSize(0),
mutex(),
pool {Buffer::alloc(this, item_size, items), NULL, NULL, NULL},
itemSize(item_size),
items(items)
{
Buffer *current = first;
for (size_t i = 0; i < items; ++i)
{
current->next = pool[1];
pool[1] = current;
current = (Buffer*)((char*)current + Buffer::sizeof_buffer(item_size));
}
/* save the index just after last buffer in the bool */
pool[2] = current;
}
/* default destructor */
~BufferPool()
{
/** @todo(stbaker): what is the required condition for a buffer pool to
be deallocated?
HASSERT(0);
*/
}
/** Used in static pools to tell if this buffer is a member of the pool.
* @param buffer buffer to test validity on
* @return true if the buffer is in the pool, or this is not a fixed pool,
* else return false;
*/
bool valid(Buffer *buffer)
{
if (itemSize != 0)
{
if (buffer >= first && buffer <= pool[2])
{
return true;
}
return false;
}
return true;
}
/** Get a free buffer out of the pool. A buffer may be
* obtained without context (object reference) from the mainBufferPool
* with the ::buffer_free method.
*
* @param size minimum size in bytes the buffer must hold
* @return pointer to the newly allocated buffer
*/
Buffer *buffer_alloc(size_t size);
/** Release a buffer back to the free buffer pool. A buffer may be
* released without context (object reference) to the mainBufferPool
* with the ::buffer_free method.
*
* @param buffer pointer to buffer to release
*/
void buffer_free(Buffer *buffer);
private:
/** keep track of total allocated size of memory */
size_t totalSize;
/** Mutual exclusion for buffer pool */
OSMutex mutex;
/** this union save overlapping memory */
union
{
/** Free buffer pool */
Buffer *pool[4];
/** First buffer in a pre-allocated array pool */
Buffer *first;
};
/** item Size for fixed pools */
size_t itemSize;
/** number of items for fixed pools */
size_t items;
/** This class is a helper of BufferQueue */
friend class BufferQueue;
/** This class is a helper of Buffer */
friend class Buffer;
DISALLOW_COPY_AND_ASSIGN(BufferPool);
};
/** This class implements a linked list "queue" of buffers. It may be
* instantiated to use the mainBufferPool for its memory pool, or optionally
* another BufferPool instance may be specified for its memory pool.
*/
class BufferQueue
{
public:
/** Default Constructor, use mainBufferPool for buffer allocation. */
BufferQueue()
: head(NULL),
tail(NULL),
count(0),
mutex()
{
}
/** Default destructor.
*/
~BufferQueue()
{
}
/** Release a buffer back to the free buffer pool.
* @param buffer pointer to buffer to release
*/
void buffer_free(Buffer *buffer)
{
buffer->free();
}
/** Add a buffer to the back of the queue.
* @param buffer buffer to add to queue
*/
void insert(Buffer *buffer);
/** Get a buffer from the front of the queue.
* @return buffer buffer retrieved from queue
*/
Buffer *next();
/** Get the number of pending items in the queue.
* @return number of pending items in the queue
*/
size_t pending()
{
return count;
}
/** Test if the queue is empty.
* @return true if empty, else false
*/
bool empty()
{
return (head == NULL);
}
protected:
private:
/** head buffer in queue */
Buffer *head;
/** tail buffer in queue */
Buffer *tail;
/** number of buffers in queue */
size_t count;
/** @todo (Stuart Baker) For free RTOS, we may want to consider a different
* (smaller) locking mechanism
*/
/** Mutual exclusion for Queue */
OSMutex mutex;
DISALLOW_COPY_AND_ASSIGN(BufferQueue);
};
/** A BufferQueue that adds the ability to wait on the next buffer.
* Yes this uses multiple inheritance. Yes multiple inheritance is bad. It
* is okay in this case, so get over it.
*/
class BufferQueueWait : public BufferQueue, public OSSem
{
public:
/** Default Constructor, use mainBufferPool for buffer allocation. */
BufferQueueWait()
: BufferQueue(),
sem(0)
{
}
/** Default destructor.
*/
~BufferQueueWait()
{
}
/** Add a buffer to the back of the queue.
* @param buffer buffer to add to queue
*/
void insert(Buffer *buffer)
{
BufferQueue::insert(buffer);
post();
}
/** Get a buffer from the front of the queue.
* @return buffer buffer retrieved from queue
*/
Buffer *next()
{
Buffer *result = BufferQueue::next();
if (result != NULL)
{
/* decrement semaphore */
OSSem::wait();
}
return result;
}
/** Wait for a buffer from the front of the queue.
* @return buffer buffer retrieved from queue
*/
Buffer *wait()
{
OSSem::wait();
Buffer *result = BufferQueue::next();
HASSERT(result != NULL);
return result;
}
/** Wait for a buffer from the front of the queue.
* @param timeout time to wait in nanoseconds
* @return buffer buffer retrieved from queue, NULL on timeout or error
*/
Buffer *timedwait(long long timeout)
{
if (OSSem::timedwait(timeout) != 0)
{
return NULL;
}
Buffer *result = BufferQueue::next();
HASSERT(result != NULL);
return result;
}
private:
/** Semaphore that we will wait on */
OSSem sem;
DISALLOW_COPY_AND_ASSIGN(BufferQueueWait);
};
/** Get a free buffer out of the mainBufferPool pool.
* @param size minimum size in bytes the buffer must hold
* @return pointer to the newly allocated buffer
*/
inline Buffer *buffer_alloc(size_t size)
{
return mainBufferPool->buffer_alloc(size);
}
/** Release a buffer back to the mainBufferPool free buffer pool.
* @param buffer pointer to buffer to release
*/
inline void buffer_free(Buffer *buffer)
{
mainBufferPool->buffer_free(buffer);
}
/** Free this buffer to the BufferPool from whence it came.
*/
inline void Buffer::free()
{
HASSERT(bufferPool != NULL);
bufferPool->buffer_free(this);
}
/** Advance the position of the buffer.
* @param bytes number of bytes to advance.
* @return pointer to the new position (next available byte)
*/
inline void *Buffer::advance(size_t bytes)
{
/** @todo (Stuart Baker) do we really need a mutex lock here? */
bufferPool->mutex.lock();
left -= bytes;
bufferPool->mutex.unlock();
return &data[_size - left];
}
/** Add another reference to the buffer.
* @return total number of references to this point
*/
inline unsigned int Buffer::reference()
{
bufferPool->mutex.lock();
++count;
bufferPool->mutex.unlock();
return count;
}
#endif /* _BufferQueue_hxx_ */
|
/// \file AddTaskPi0IMGammaCorrQA.C
/// \ingroup CaloTrackCorrMacrosQA
/// \brief Configuration of the analysis QA wagon for PWG-GA EMCal analysis
///
/// Configuration macro of EMCal related PWG-GA analysis, although it can be
/// also used for PHOS. It does:
/// * a simple photon cluster selection
/// * invariant mass analysis
/// * cluster-charged track correlation analysis (optional)
/// * detector general QA analysis (optional)
/// * track general QA analysis (optional)
///
/// Wagon responsible: Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>
///
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
// Uncomment for compilation
//// Set includes for compilation
//
//#if !defined(__CINT__) || defined(__MAKECINT__)
//
//#include <TString.h>
//#include <TROOT.h>
//
//#include "AliLog.h"
//#include "AliAnalysisTaskCaloTrackCorrelation.h"
//#include "AliCaloTrackESDReader.h"
//#include "AliCaloTrackAODReader.h"
//#include "AliCalorimeterUtils.h"
//#include "AliAnaPhoton.h"
//#include "AliAnaPi0.h"
//#include "AliHistogramRanges.h"
//#include "AliAnaParticleIsolation.h"
//#include "AliAnaParticleHadronCorrelation.h"
//#include "AliAnaChargedParticles.h"
//#include "AliAnaCalorimeterQA.h"
//#include "AliAnaGeneratorKine.h"
//#include "AliAnalysisTaskCaloTrackCorrelation.h"
//#include "AliAnaCaloTrackCorrMaker.h"
//#include "AliAnalysisManager.h"
//#include "AliInputEventHandler.h"
//#include "AliVTrack.h"
//#include "ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C"
//#include "AliESDtrackCuts.h"
//#include "CreateTrackCutsPWGJE.C"
//#include "ConfigureEMCALRecoUtils.C"
//#endif
//
//// Declare methods for compilation
//
//AliCaloTrackReader * ConfigureReader (TString inputDataType, TString collision, Bool_t calibrate,
// Int_t minTime, Int_t maxTime,
// Int_t minCen, Int_t maxCen,
// Bool_t simulation, Int_t year, Int_t debugLevel);
//
//AliCalorimeterUtils * ConfigureCaloUtils (TString calorimeter, TString trigger,
// Bool_t simulation , Bool_t calibrate,
// Int_t year , Int_t debugLevel );
//
//AliAnaPhoton * ConfigurePhotonAnalysis(TString calorimeter, Bool_t caloType, TString collision,
// TString containerName, Bool_t simulation,
// Int_t year, Int_t debugLevel);
//
//AliAnaPi0 * ConfigurePi0Analysis (TString calorimeter, Bool_t caloType, TString collision,
// TString containerName, Bool_t simulation, Int_t year,
// Int_t debugLevel, Int_t minCen);
//
//AliAnaChargedParticles * ConfigureChargedAnalysis
// (TString collision , TString containerName,
// Bool_t simulation, Int_t year, Int_t debugLevel);
//
//AliAnaParticleIsolation* ConfigureIsolationAnalysis
// (TString particle , TString calorimeter , Bool_t caloType,
// TString collision , TString containerName,
// Bool_t simulation, Int_t year , Int_t debugLevel);
//
//AliAnaParticleHadronCorrelation * ConfigureHadronCorrelationAnalysis
// (TString particle , TString calorimeter , Bool_t caloType,
// TString collision , TString containerName,
// Bool_t simulation , Int_t year , Int_t debugLevel,
// Int_t minCen);
//
//AliAnaCalorimeterQA * ConfigureQAAnalysis (TString calorimeter, TString collision,
// Bool_t simulation , Int_t year, Int_t debugLevel);
//
//void SetHistoRangeAndNBins (AliHistogramRanges* histoRanges,
// TString calorimeter, Bool_t caloType,
// TString collision, Int_t year );
//
//Bool_t CheckAnalysisTrigger (Bool_t simulation, TString trigger,
// TString period , Int_t year );
//
//// Global variables, set externally, uncomment next lines for local tests and compilation.
//const char* kPeriod = "LHC16t"; // gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTAG");
//const char* kColType = "PbPb"; // gSystem->Getenv("ALIEN_JDL_LPMINTERACTIONTYPE"); //either "pp", "pPb" or "PbPb"
//const char* kProdType = "MC"; // gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTYPE");
//Bool_t kMC = kFALSE;
///
/// Main method calling all the configuration
/// Creates a CaloTrackCorr task, configures it and adds it to the analysis manager.
///
/// The options that can be passed to the macro are:
/// \param calorimeter : A string with he calorimeter used to measure the trigger particle.
/// \param simulation : A bool identifying the data as simulation.
/// \param collision: A string with the colliding system.
/// \param period : A string with the data period: LHC11h, LHC15n ... from it we extract the year.
/// \param qaan: execute the detector QA analysis.
/// \param hadronan: execute the track QA and cluster-track correlation analysis.
/// \param calibrate: if OADB was updated with calibration parameters not used in reconstruction, apply them here.
/// \param minTime: minimum time cut, leave it open by default even if calibration available, ns
/// \param maxTime: maximum time cut, leave it open by default even if calibration available, ns
/// \param minCen : An int to select the minimum centrality, -1 means no selection.
/// \param maxCen : An int to select the maximum centrality, -1 means no selection.
/// \param debugLevel : An int to define the debug level of all the tasks.
/// \param suffix : A string with the type of trigger (default: MB, EMC).
///
AliAnalysisTaskCaloTrackCorrelation *AddTaskPi0IMGammaCorrQA(const TString calorimeter = "EMCAL",
Bool_t simulation = kFALSE,
TString collision = "pp",
TString period = "",
const Bool_t qaan = kTRUE,
const Bool_t hadronan = kTRUE,
const Bool_t calibrate = kFALSE,
const Int_t minTime = -1000,
const Int_t maxTime = 1000,
const Int_t minCen = -1,
const Int_t maxCen = -1,
const Int_t debugLevel = -1,
const char * suffix = "default"
)
{
// Check the global variables, and reset the provided ones if empty.
//
TString trigger = suffix;
if(collision=="")
{
if (!strcmp(kColType, "PbPb")) collision = "PbPb";
else if (!strcmp(kColType, "AA" )) collision = "PbPb";
else if (!strcmp(kColType, "pA" )) collision = "pPb";
else if (!strcmp(kColType, "Ap" )) collision = "pPb";
else if (!strcmp(kColType, "pPb" )) collision = "pPb";
else if (!strcmp(kColType, "Pbp" )) collision = "pPb";
else if (!strcmp(kColType, "pp" )) collision = "pp" ;
simulation = kMC;
period = kPeriod;
// print check on global settings once
if(trigger.Contains("default") ||trigger.Contains("INT") || trigger.Contains("MB") )
printf("AddTaskPi0IMGammaCorrQA - Get the data features from global parameters: col <%s>, period <%s>, mc <%d> \n",
kColType,kPeriod,kMC);
}
Int_t year = 2017;
if ( period!="" )
{
if (period.Contains("16")) year = 2016;
else if(period.Contains("15")) year = 2015;
else if(period.Contains("13")) year = 2013;
else if(period.Contains("12")) year = 2012;
else if(period.Contains("11")) year = 2011;
else if(period.Contains("10")) year = 2010;
}
// Get the pointer to the existing analysis manager via the static access method.
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskPi0IMGammaCorrQA", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskPi0IMGammaCorrQA", "This task requires an input event handler");
return NULL;
}
//
// Create task
//
// Name for containers
TString containerName = Form("%s_Trig_%s",calorimeter.Data(), trigger.Data());
if(collision!="pp" && maxCen>=0) containerName+=Form("Cen%d_%d",minCen,maxCen);
TString taskName =Form("Pi0IM_GammaTrackCorr_%s",containerName.Data());
AliAnalysisTaskCaloTrackCorrelation * task = new AliAnalysisTaskCaloTrackCorrelation (taskName);
//task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
task->SetDebugLevel(debugLevel);
//task->SetBranches("ESD:AliESDRun.,AliESDHeader");
//task->SetBranches("AOD:header,tracks,vertices,emcalCells,caloClusters");
//
// Init main analysis maker and pass it to the task
AliAnaCaloTrackCorrMaker * maker = new AliAnaCaloTrackCorrMaker();
task->SetAnalysisMaker(maker);
//
// Pass the task to the analysis manager
mgr->AddTask(task);
//
// Create containers
TString outputfile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *cout_pc = mgr->CreateContainer(trigger, TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:%s",outputfile.Data(),Form("Pi0IM_GammaTrackCorr_%s",calorimeter.Data())));
AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("Param_%s",trigger.Data()), TList::Class(),
AliAnalysisManager::kParamContainer,
Form("%s_Parameters.root",Form("Pi0IM_GammaTrackCorr_%s",calorimeter.Data())));
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (task, 1, cout_pc);
mgr->ConnectOutput (task, 2, cout_cuts);
//==============================================================================
// Do not configure the wagon for certain analysis combinations
// But create the task so that the sub-wagon train can run
//
Bool_t doAnalysis = CheckAnalysisTrigger(simulation,trigger,period,year);
if(!doAnalysis)
{
maker->SwitchOffProcessEvent();
return task;
}
// #### Start analysis configuration ####
//
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Make sure the B field is enabled for track selection, some cuts need it
//
((AliInputEventHandler*)mgr->GetInputEventHandler())->SetNeedField(kTRUE);
// Print settings to check all is as expected
//
printf("AddTaskPi0IMGammaCorrQA - Task NAME: %s \n",taskName.Data());
printf("AddTaskPi0IMGammaCorrQA - Settings: data <%s>, calo <%s>, MC <%d>, collision <%s>, trigger <%s>, period <%s>, year <%d>,\n"
"\t \t \t CaloQA on <%d>, Track QA on <%d>, Make corrections <%d>, %d < time < %d, %d < cen < %d, debug level <%d> \n",
inputDataType.Data(), calorimeter.Data(),simulation, collision.Data(),trigger.Data(), period.Data(), year,
qaan , hadronan, calibrate, minTime, maxTime, minCen, maxCen, debugLevel);
//
// General frame setting and configuration
maker->SetReader ( ConfigureReader (inputDataType,collision,calibrate,minTime,maxTime,minCen,maxCen,simulation,year,debugLevel) );
if(hadronan)maker->GetReader()->SwitchOnCTS();
maker->SetCaloUtils( ConfigureCaloUtils(calorimeter,trigger,simulation,calibrate,year,debugLevel) );
// Analysis tasks setting and configuration
Int_t n = 0;//Analysis number, order is important
// Cell QA
if(qaan) maker->AddAnalysis(ConfigureQAAnalysis(calorimeter,collision,simulation,year,debugLevel),n++);
// Analysis with EMCal trigger or MB
if ( !trigger.Contains("DCAL") )
{
// Cluster selection
maker->AddAnalysis(ConfigurePhotonAnalysis(calorimeter,0,collision,containerName,simulation,year,debugLevel) ,n++);
// Previous cluster invariant mass
maker->AddAnalysis(ConfigurePi0Analysis (calorimeter,0,collision,containerName,simulation,year,debugLevel,minCen),n++);
if(hadronan)
{
// Isolation of selected clusters by AliAnaPhoton
maker->AddAnalysis(ConfigureIsolationAnalysis("Photon",calorimeter,0,collision,containerName,simulation,year,debugLevel), n++);
// Selected clusters-track correlation
maker->AddAnalysis(ConfigureHadronCorrelationAnalysis("Photon",calorimeter,0,collision,containerName,simulation,year,debugLevel,minCen), n++);
}
}
// Analysis with DCal trigger or MB
if(year > 2014 && calorimeter=="EMCAL" && !trigger.Contains("EMCAL"))
{
// Cluster selection
maker->AddAnalysis(ConfigurePhotonAnalysis(calorimeter,1,collision,containerName,simulation,year,debugLevel) , n++);
// Previous cluster invariant mass
maker->AddAnalysis(ConfigurePi0Analysis (calorimeter,1,collision,containerName,simulation,year,debugLevel,minCen),n++);
if(hadronan)
{
// Isolation of selected clusters by AliAnaPhoton
maker->AddAnalysis(ConfigureIsolationAnalysis("Photon",calorimeter,1,collision,containerName,simulation,year,debugLevel), n++);
// Selected clusters-track correlation
maker->AddAnalysis(ConfigureHadronCorrelationAnalysis("Photon",calorimeter,1,collision,containerName,simulation,year,debugLevel,minCen), n++);
}
}
// Charged tracks plots, any trigger
if(hadronan)
maker->AddAnalysis(ConfigureChargedAnalysis(collision,containerName,simulation,year,debugLevel), n++);
if(simulation)
{
// Calculate the cross section weights, apply them to all histograms
// and fill xsec and trial histo. Sumw2 must be activated.
//maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionCalculation();
//maker->SwitchOnSumw2Histograms();
// For recent productions where the cross sections and trials are not stored in separate file
//maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionFromEventHeader() ;
// Just fill cross section and trials histograms.
maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionHistoFill();
// Add control histogram with pT hard to control aplication of weights
maker->SwitchOnPtHardHistogram();
}
//
// Select events trigger depending on trigger
//
if(!simulation)
{
gROOT->LoadMacro("$ALICE_PHYSICS/PWGGA/CaloTrackCorrelations/macros/ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C");
TString caloTriggerString = "";
UInt_t mask = ConfigureAndGetEventTriggerMaskAndCaloTriggerString(trigger, year, caloTriggerString);
task ->SelectCollisionCandidates( mask );
maker->GetReader()->SetFiredTriggerClassName(caloTriggerString);
printf("AddTaskPi0IMGammaCorrQA - Trigger Mask %d, caloTriggerString <%s>\n", mask, caloTriggerString.Data());
}
//
// Final maker settings
//
maker->SetAnaDebug(debugLevel) ;
maker->SwitchOnHistogramsMaker() ;
maker->SwitchOnAODsMaker() ;
maker->SwitchOnDataControlHistograms();
if(debugLevel > 0) maker->Print("");
return task;
}
///
/// Configure the class handling the events and cluster/tracks filtering.
///
AliCaloTrackReader * ConfigureReader(TString inputDataType, TString collision, Bool_t calibrate,
Int_t minTime, Int_t maxTime,
Int_t minCen, Int_t maxCen,
Bool_t simulation, Int_t year, Int_t debugLevel)
{
AliCaloTrackReader * reader = 0;
if (inputDataType=="AOD")
reader = new AliCaloTrackAODReader();
else if(inputDataType=="ESD")
reader = new AliCaloTrackESDReader();
else
printf("AliCaloTrackReader::ConfigureReader() - Data combination not known input Data=%s\n",
inputDataType.Data());
reader->SetDebug(debugLevel);//10 for lots of messages
//------------------------
// Detector input filling
//------------------------
//Min cluster/track E
reader->SetEMCALEMin(0.3);
reader->SetEMCALEMax(1000);
reader->SetPHOSEMin(0.3);
reader->SetPHOSEMax(1000);
reader->SetCTSPtMin(0.2);
reader->SetCTSPtMax(1000);
// Time cut
reader->SwitchOffUseParametrizedTimeCut();
if(calibrate)
{
reader->SwitchOnUseEMCALTimeCut() ;
reader->SetEMCALTimeCut(minTime,maxTime);
}
reader->SwitchOffUseTrackTimeCut();
reader->SetTrackTimeCut(-1e10,1e10);
reader->SwitchOffFiducialCut();
// Tracks
reader->SwitchOffCTS();
reader->SwitchOffRejectNoTrackEvents();
reader->SwitchOffRecalculateVertexBC();
reader->SwitchOffVertexBCEventSelection();
reader->SwitchOffUseTrackDCACut();
//reader->SetTrackDCACut(0,0.0105);
//reader->SetTrackDCACut(1,0.035);
//reader->SetTrackDCACut(2,1.1);
if(inputDataType=="ESD")
{
gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/macros/CreateTrackCutsPWGJE.C");
if(year > 2010)
{
//Hybrids 2011
AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10001008);
reader->SetTrackCuts(esdTrackCuts);
AliESDtrackCuts * esdTrackCuts2 = CreateTrackCutsPWGJE(10011008);
reader->SetTrackComplementaryCuts(esdTrackCuts2);
}
else
{
//Hybrids 2010
AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10001006);
reader->SetTrackCuts(esdTrackCuts);
AliESDtrackCuts * esdTrackCuts2 = CreateTrackCutsPWGJE(10041006);
reader->SetTrackComplementaryCuts(esdTrackCuts2);
}
}
else if(inputDataType=="AOD")
{
reader->SwitchOnAODHybridTrackSelection(); // Check that the AODs have Hybrids!!!!
reader->SetTrackStatus(AliVTrack::kITSrefit);
}
// Calorimeter
//reader->SetEMCALClusterListName("");
if(calibrate && !simulation) reader->SwitchOnClusterRecalculation();
else reader->SwitchOffClusterRecalculation();
reader->SwitchOnEMCALCells();
reader->SwitchOnEMCAL();
reader->SwitchOffPHOSCells();
reader->SwitchOffPHOS();
//-----------------
// Event selection
//-----------------
reader->SwitchOnEventTriggerAtSE();
reader->SetZvertexCut(10.);
reader->SwitchOnPrimaryVertexSelection(); // and besides primary vertex
reader->SwitchOffPileUpEventRejection(); // remove pileup
reader->SwitchOffV0ANDSelection() ; // and besides v0 AND
if(collision=="PbPb")
{
if(year < 2014) reader->SwitchOnAliCentrality();
reader->SetCentralityBin(minCen,maxCen); // Accept all events, if not select range
reader->SetCentralityOpt(100); // 10 (c= 0-10, 10-20 ...), 20 (c= 0-5, 5-10 ...) or 100 (c= 1, 2, 3 ..)
}
if(debugLevel > 0) reader->Print("");
return reader;
}
///
/// Configure the class handling the calorimeter clusters specific methods
///
AliCalorimeterUtils* ConfigureCaloUtils(TString calorimeter, TString trigger,
Bool_t simulation , Bool_t calibrate,
Int_t year , Int_t debugLevel)
{
AliCalorimeterUtils *cu = new AliCalorimeterUtils;
cu->SetDebug(debugLevel);
// Remove clusters close to borders, at least max energy cell is 1 cell away
cu->SetNumberOfCellsFromEMCALBorder(1);
cu->SetNumberOfCellsFromPHOSBorder(2);
// Search of local maxima in cluster
cu->SetLocalMaximaCutE(0.1);
cu->SetLocalMaximaCutEDiff(0.03);
//cu->SwitchOffClusterPlot();
cu->SwitchOffRecalculateClusterTrackMatching();
cu->SwitchOnBadChannelsRemoval() ;
//EMCAL settings
if(!simulation)
cu->SwitchOnLoadOwnEMCALGeometryMatrices();
AliEMCALRecoUtils * recou = cu->GetEMCALRecoUtils();
cu->SwitchOffRecalibration(); // Check the reader if it is taken into account during filtering
cu->SwitchOffRunDepCorrection();
cu->SwitchOffCorrectClusterLinearity();
Bool_t bExotic = kTRUE;
Bool_t bNonLin = kFALSE;
Bool_t bBadMap = kTRUE;
Bool_t bEnCalib = kFALSE;
Bool_t bTiCalib = kFALSE;
if(calibrate && !simulation)
{
cu->SwitchOnRecalibration(); // Check the reader if it is taken into account during filtering
cu->SwitchOffRunDepCorrection();
cu->SwitchOnRecalculateClusterPosition() ;
bEnCalib = kTRUE;
bTiCalib = kTRUE;
}
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C");
ConfigureEMCALRecoUtils(recou,
simulation,
bExotic,
bNonLin,
bEnCalib,
bBadMap,
bTiCalib,
debugLevel
);
//recou->SetExoticCellDiffTimeCut(50.);
if(calorimeter=="PHOS")
{
if(year < 2014) cu->SetNumberOfSuperModulesUsed(3);
else cu->SetNumberOfSuperModulesUsed(4);
}
else
{
Int_t nSM = 20;
Int_t lastEMC = 11;
if (year == 2010) { nSM = 4; lastEMC = 3; }// EMCAL first year
else if (year < 2014) { nSM = 10; lastEMC = 9; }// EMCAL active 2011-2013
cu->SetNumberOfSuperModulesUsed(nSM);
if (trigger.Contains("EMCAL"))
{
cu->SetFirstSuperModuleUsed( 0);
cu->SetLastSuperModuleUsed (lastEMC);
}
else if (trigger.Contains("DCAL"))
{
cu->SetFirstSuperModuleUsed(12);
cu->SetLastSuperModuleUsed (19);
}
else
{
cu->SetFirstSuperModuleUsed(0);
cu->SetLastSuperModuleUsed (cu->GetNumberOfSuperModulesUsed()-1);
}
printf("AddTaskPi0IMGammaCorrQA - CalorimeterUtils: nSM %d, first %d, last %d\n",
cu->GetNumberOfSuperModulesUsed(),cu->GetFirstSuperModuleUsed(), cu->GetLastSuperModuleUsed());
}
// PHOS
cu->SwitchOffLoadOwnPHOSGeometryMatrices();
if(debugLevel > 0) cu->Print("");
return cu;
}
///
/// Configure the task doing the first photon cluster selections
/// Basically the track matching, minor shower shape cut, NLM selection ...
///
AliAnaPhoton* ConfigurePhotonAnalysis(TString calorimeter, Bool_t caloType, TString collision,
TString containerName, Bool_t simulation,
Int_t year, Int_t debugLevel)
{
AliAnaPhoton *ana = new AliAnaPhoton();
ana->SetDebug(debugLevel); //10 for lots of messages
// cluster selection cuts
ana->SwitchOnFiducialCut();
if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC
else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC
ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE);
ana->SetCalorimeter(calorimeter);
if(calorimeter == "PHOS")
{
ana->SetNCellCut(2);// At least 3 cells
ana->SetMinPt(0.5);
ana->SetMinDistanceToBadChannel(2, 4, 5);
ana->SetTimeCut(-1e10,1e10); // open cut
}
else
{
// EMCAL
ana->SetConstantTimeShift(615); // for MC and uncalibrated data, whenever there is time > 400 ns
ana->SetNCellCut(1);// At least 2 cells
ana->SetMinEnergy(0.5); // avoid mip peak at E = 260 MeV
ana->SetMaxEnergy(1000);
ana->SetTimeCut(-1e10,1e10); // open cut, usual time window of [425-825] ns if time recalibration is off
// restrict to less than 100 ns when time calibration is on
ana->SetMinDistanceToBadChannel(2, 4, 6);
// Not useful if M02 cut is already strong
ana->SetNLMCut(1, 2) ;
}
ana->SwitchOnTrackMatchRejection() ;
ana->SwitchOnTMHistoFill() ;
ana->SwitchOnAcceptanceHistoPerEBin();
ana->SetNEBinCuts(2);
// Set the acceptance E bins depending on the trigger and their likely values
if(containerName.Contains("efault") || containerName.Contains("INT") || containerName.Contains("MB"))
{
ana->SetEBinCutsAt(0, 0.5);
ana->SetEBinCutsAt(1, 3.0);
ana->SetEBinCutsAt(2, 100.0);
}
else if(containerName.Contains("L0"))
{
ana->SetEBinCutsAt(0, 2.0);
ana->SetEBinCutsAt(1, 5.0);
ana->SetEBinCutsAt(2, 100.0);
}
else
{
ana->SetEBinCutsAt(0, 5.0);
ana->SetEBinCutsAt(1, 12.0);
ana->SetEBinCutsAt(2, 100.0);
}
//PID cuts (shower shape)
ana->SwitchOnCaloPID(); // do PID selection, unless specified in GetCaloPID, selection not based on bayesian
AliCaloPID* caloPID = ana->GetCaloPID();
//Not used in bayesian
//EMCAL
caloPID->SetEMCALLambda0CutMax(0.4); // Rather open
caloPID->SetEMCALLambda0CutMin(0.10);
caloPID->SetEMCALDEtaCut(0.025);
caloPID->SetEMCALDPhiCut(0.030);
//PHOS
caloPID->SetPHOSDispersionCut(2.5);
caloPID->SetPHOSRCut(2.);
ana->SwitchOnFillShowerShapeHistograms(); // Filled before photon shower shape selection
//if(!simulation)ana->SwitchOnFillPileUpHistograms();
if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms();
// Input / output delta AOD settings
ana->SetOutputAODName(Form("Photon%s_Calo%d",containerName.Data(),caloType));
ana->SetOutputAODClassName("AliAODPWG4ParticleCorrelation");
ana->SetInputAODName (Form("Photon%s_Calo%d",containerName.Data(),caloType));
// Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("AnaPhoton_Calo%d_",caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
// Number of particle type MC histograms
ana->FillNOriginHistograms(7);
ana->FillNPrimaryHistograms(4);
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0 ) ana->Print("");
return ana;
}
///
/// Configure the task doing the 2 cluster invariant mass analysis
///
AliAnaPi0* ConfigurePi0Analysis(TString calorimeter , Bool_t caloType , TString collision,
TString containerName, Bool_t simulation, Int_t year,
Int_t debugLevel , Int_t minCen)
{
AliAnaPi0 *ana = new AliAnaPi0();
ana->SetDebug(debugLevel);//10 for lots of messages
// Input delta AOD settings
ana->SetInputAODName(Form("Photon%s_Calo%d",containerName.Data(),caloType));
// Calorimeter settings
ana->SetCalorimeter(calorimeter);
ana->SwitchOnFiducialCut();
if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC
else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC
ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE);
ana->SwitchOnRealCaloAcceptance();
// Settings for pp collision mixing
ana->SwitchOnOwnMix(); //Off when mixing done with general mixing frame
// Cuts
if(calorimeter=="EMCAL")
{
ana->SetPairTimeCut(100);
// Angle cut, avoid pairs with too large angle
ana->SwitchOnAngleSelection();
ana->SetAngleMaxCut(TMath::DegToRad()*80.); // EMCal: 4 SM in phi, 2 full SMs in eta
ana->SetAngleCut(0.016); // Minimum angle open, ~cell size
}
ana->SetNPIDBits(1);
ana->SetNAsymCuts(1); // no asymmetry cut, previous studies showed small effect.
// In EMCAL assymetry cut prevents combination of assymetric decays which is the main source of pi0 at high E.
if (collision == "pp" )
{
ana->SetNCentrBin(1);
ana->SetNZvertBin(10);
ana->SetNRPBin(1);
ana->SetNMaxEvMix(100);
ana->SetMinPt(0.5);
}
else if(collision =="PbPb")
{
ana->SetNCentrBin(10);
ana->SetNZvertBin(10);
ana->SetNRPBin(4);
ana->SetNMaxEvMix(10);
if(minCen >= 10) ana->SetNMaxEvMix(50);
if(minCen >= 50) ana->SetNMaxEvMix(100);
ana->SetMinPt(1.5);
ana->SwitchOnFillHighMultiplicityHistograms();
}
else if(collision =="pPb")
{
ana->SetNCentrBin(1);
ana->SetNZvertBin(10);
ana->SetNRPBin(4);
ana->SetNMaxEvMix(100);
ana->SetMinPt(0.5);
ana->SwitchOnFillHighMultiplicityHistograms();
}
ana->SwitchOffMultipleCutAnalysis();
ana->SwitchOnSMCombinations();
ana->SwitchOffFillAngleHisto();
ana->SwitchOffFillOriginHisto();
// Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("AnaPi0_Calo%d_",caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing charged track selection
///
AliAnaChargedParticles* ConfigureChargedAnalysis(TString collision,TString containerName,
Bool_t simulation, Int_t year, Int_t debugLevel)
{
AliAnaChargedParticles *ana = new AliAnaChargedParticles();
ana->SetDebug(debugLevel); //10 for lots of messages
// selection cuts
ana->SetMinPt(0.5);
ana->SwitchOnFiducialCut();
Float_t etacut = 0.8;
ana->GetFiducialCut()->SetSimpleCTSFiducialCut(etacut, 0, 360) ; //more restrictive cut in reader and after in isolation
// histogram switchs
ana->SwitchOffFillVertexBC0Histograms() ;
//if(!simulation) ana->SwitchOnFillPileUpHistograms();
ana->SwitchOffFillTrackMultiplicityHistograms();
// Input / output delta AOD settings
ana->SetOutputAODName(Form("Hadron%s",containerName.Data()));
ana->SetOutputAODClassName("AliAODPWG4ParticleCorrelation");
ana->SetInputAODName(Form("Hadron%s",containerName.Data()));
//Set Histograms name tag, bins and ranges
ana->AddToHistogramsName("AnaHadrons_");
SetHistoRangeAndNBins(ana->GetHistogramRanges(),"",kFALSE,collision,year); // see method below
ana->GetHistogramRanges()->SetHistoPhiRangeAndNBins(0, TMath::TwoPi(), 120) ;
ana->GetHistogramRanges()->SetHistoEtaRangeAndNBins(-1.*etacut, 1.*etacut, etacut*100) ;
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing the trigger particle hadron correlation
///
AliAnaParticleIsolation* ConfigureIsolationAnalysis(TString particle , TString calorimeter , Bool_t caloType,
TString collision , TString containerName,
Bool_t simulation, Int_t year , Int_t debugLevel)
{
AliAnaParticleIsolation *ana = new AliAnaParticleIsolation();
ana->SetDebug(debugLevel);
//if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms();
ana->SetMinPt(5);
ana->SwitchOffStudyTracksInCone() ;
ana->SwitchOnUEBandSubtractionHistoFill();
ana->SwitchOffDecayTaggedHistoFill() ;
ana->SwitchOnSSHistoFill();
ana->SwitchOffLeadingOnly();
ana->SwitchOffCheckNeutralClustersForLeading();
ana->SwitchOffPtTrigBinHistoFill();
ana->SwitchOffBackgroundBinHistoFill();
ana->SwitchOffTMHistoFill();
// MC
ana->SwitchOffPrimariesInConeSelection();
ana->SwitchOffPrimariesPi0DecayStudy() ;
ana->SwitchOnRealCaloAcceptance();
ana->SwitchOnFiducialCut();
if(calorimeter == "EMCAL" && caloType == 0)
{
// Avoid borders of EMCal
ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.60, 86, 174) ;
}
if(calorimeter == "EMCAL" && caloType == 1)
{
// Avoid borders of DCal
ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.60, 264, 316) ;
}
AliCaloPID* caloPID = ana->GetCaloPID();
caloPID->SetEMCALDEtaCut(0.025);
caloPID->SetEMCALDPhiCut(0.030);
ana->SwitchOffSeveralIsolation() ;
ana->SwitchOffReIsolation();
//
// Do settings for main isolation cut class
//
AliIsolationCut * ic = ana->GetIsolationCut();
ic->SetDebug(debugLevel);
ic->SetParticleTypeInCone(AliIsolationCut::kNeutralAndCharged);
ic->SetICMethod(AliIsolationCut::kSumPtIC);
if ( collision == "pp" || collision == "pPb" )
{
ic->SetPtThreshold(0.5);
ic->SetSumPtThreshold(2.0) ;
ic->SetConeSize(0.4);
}
if ( collision == "PbPb" )
{
ic->SetPtThreshold(3.);
ic->SetSumPtThreshold(3.0) ;
ic->SetConeSize(0.3);
}
// Input / output delta AOD settings
ana->SetInputAODName(Form("%s%s_Calo%d",particle.Data(),containerName.Data(),caloType));
ana->SetAODObjArrayName(Form("%sIso_%s_Calo%d",particle.Data(),containerName.Data(),caloType));
// Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("AnaIsol%s_Calo%d_",particle.Data(),caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing the trigger particle hadron correlation
///
AliAnaParticleHadronCorrelation* ConfigureHadronCorrelationAnalysis(TString particle, TString calorimeter, Bool_t caloType,
TString collision, TString containerName,
Bool_t simulation, Int_t year, Int_t debugLevel, Int_t minCen)
{
AliAnaParticleHadronCorrelation *ana = new AliAnaParticleHadronCorrelation();
ana->SetDebug(debugLevel);
ana->SetTriggerPtRange(5,100);
ana->SetAssociatedPtRange(0.2,100);
//ana->SetDeltaPhiCutRange( TMath::Pi()/2,3*TMath::Pi()/2 ); //[90 deg, 270 deg]
ana->SetDeltaPhiCutRange (TMath::DegToRad()*120.,TMath::DegToRad()*240.);
ana->SetUeDeltaPhiCutRange(TMath::DegToRad()*60. ,TMath::DegToRad()*120.);
ana->SwitchOffFillEtaGapHistograms();
ana->SetNAssocPtBins(4);
ana->SetAssocPtBinLimit(0, 0.5) ;
ana->SetAssocPtBinLimit(1, 2) ;
ana->SetAssocPtBinLimit(2, 5) ;
ana->SetAssocPtBinLimit(3, 10) ;
ana->SetAssocPtBinLimit(4, 20) ;
ana->SelectIsolated(kFALSE); // do correlation with isolated photons
//if(!simulation) ana->SwitchOnFillPileUpHistograms();
ana->SwitchOffAbsoluteLeading(); // Select trigger leading particle of all the selected tracks
ana->SwitchOffNearSideLeading(); // Select trigger leading particle of all the particles at +-90 degrees, default
//ana->SwitchOnLeadHadronSelection();
//ana->SetLeadHadronPhiCut(TMath::DegToRad()*100., TMath::DegToRad()*260.);
//ana->SetLeadHadronPtCut(0.5, 100);
// Mixing with own pool
ana->SwitchOffOwnMix();
ana->SetNZvertBin(20);
ana->SwitchOffCorrelationVzBin() ;
//if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms();
if(collision=="pp")
{
ana->SetNMaxEvMix(100);
ana->SwitchOnTrackMultBins();
ana->SetNTrackMultBin(10); // same as SetNCentrBin(10);
ana->SetNRPBin(1);
}
else
{
ana->SetNMaxEvMix(10);
if(minCen >= 10) ana->SetNMaxEvMix(50);
if(minCen >= 50) ana->SetNMaxEvMix(100);
ana->SwitchOffTrackMultBins(); // centrality bins
ana->SetNCentrBin(10);
ana->SetNRPBin(3);
}
// Input / output delta AOD settings
ana->SetInputAODName(Form("%s%s_Calo%d",particle.Data(),containerName.Data(),caloType));
ana->SetAODObjArrayName(Form("%sHadronCorr_%s_Calo%d",particle.Data(),containerName.Data(),caloType));
ana->SwitchOffPi0TriggerDecayCorr();
ana->SwitchOffDecayTriggerDecayCorr();
ana->SwitchOffNeutralCorr(); // Do only correlation with TPC
ana->SwitchOffHMPIDCorrelation();
ana->SwitchOffFillBradHistograms();
// Underlying event
ana->SwitchOffSeveralUECalculation();
ana->SetUeDeltaPhiCutRange(TMath::Pi()/3, 2*TMath::Pi()/3);
//Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("Ana%sHadronCorr_Calo%d_",particle.Data(),caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing standard calorimeter QA
///
AliAnaCalorimeterQA* ConfigureQAAnalysis(TString calorimeter, TString collision,
Bool_t simulation ,
Int_t year, Int_t debugLevel)
{
AliAnaCalorimeterQA *ana = new AliAnaCalorimeterQA();
ana->SetDebug(debugLevel); //10 for lots of messages
ana->SetCalorimeter(calorimeter);
//printf("QA: calorimeter %s, caloType %d, collision %s, simulation %d, fillCellTime %d, year %d, debugLevel %d\n",
// calorimeter.Data(),caloType,collision.Data(),simulation,fillCellTime,year,debugLevel);
ana->SetTimeCut(-1e10,1e10); // Open time cut
ana->SetConstantTimeShift(615); // for MC and uncalibrated data, whenever there is time > 400 ns
ana->SetEMCALCellAmpMin(0.5);
ana->SwitchOffStudyBadClusters() ;
ana->SwitchOffFillAllTH3Histogram();
ana->SwitchOffFillAllPositionHistogram();
ana->SwitchOffFillAllPositionHistogram2();
ana->SwitchOffStudyBadClusters();
ana->SwitchOffStudyClustersAsymmetry();
ana->SwitchOffStudyWeight();
ana->SwitchOffFillAllPi0Histogram() ;
ana->SwitchOffCorrelation();
ana->SwitchOffFillAllCellAbsIdHistogram();
ana->SwitchOffFillAllTrackMatchingHistogram();
ana->SwitchOnFillAllCellTimeHisto() ;
ana->SwitchOnFillAllCellHistogram();
ana->SwitchOffFillAllClusterHistogram() ;
ana->AddToHistogramsName("QA_Cell_"); //Begining of histograms name
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter, -1, collision,year); // see method below
// ana->SwitchOnFiducialCut();
// if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC
// else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC
//
// ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE);
//if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure histograms ranges and bins
///
void SetHistoRangeAndNBins (AliHistogramRanges* histoRanges, TString calorimeter, Bool_t caloType,
TString collision, Int_t year)
{
histoRanges->SetHistoPtRangeAndNBins(0, 100, 200) ; // Energy and pt histograms
if(calorimeter=="EMCAL")
{
if ( year == 2010 )
{
histoRanges->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 121*TMath::DegToRad(), 42) ;
histoRanges->SetHistoXRangeAndNBins(-230,90,120); // QA
histoRanges->SetHistoYRangeAndNBins(370,450,40); // QA
}
else if ( year < 2014 )
{
histoRanges->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 182*TMath::DegToRad(), 108) ;
histoRanges->SetHistoXRangeAndNBins(-460,90,200); // QA
histoRanges->SetHistoYRangeAndNBins(100,450,100); // QA
}
else // Run2
{
if (caloType == 0)
histoRanges->SetHistoPhiRangeAndNBins(78 *TMath::DegToRad(), 189*TMath::DegToRad(), 111) ;
else if (caloType == 1)
histoRanges->SetHistoPhiRangeAndNBins(258*TMath::DegToRad(), 329*TMath::DegToRad(), 71) ;
else
histoRanges->SetHistoPhiRangeAndNBins(80 *TMath::DegToRad(), 327*TMath::DegToRad(), 247) ;
histoRanges->SetHistoXRangeAndNBins(-460,460,230); // QA
histoRanges->SetHistoYRangeAndNBins(-450,450,225); // QA
}
histoRanges->SetHistoEtaRangeAndNBins(-0.72, 0.72, 144) ;
}
else
{
histoRanges->SetHistoPhiRangeAndNBins(250*TMath::DegToRad(), 320*TMath::DegToRad(), 70) ;
histoRanges->SetHistoEtaRangeAndNBins(-0.13, 0.13, 130) ;
}
histoRanges->SetHistoShowerShapeRangeAndNBins(-0.1, 2.9, 300);
// Invariant mass histoRangeslysis
histoRanges->SetHistoMassRangeAndNBins(0., 0.8, 160) ;
histoRanges->SetHistoAsymmetryRangeAndNBins(0., 1. , 100) ;
histoRanges->SetHistoOpeningAngleRangeAndNBins(0,0.7,50);
// check if time calibration is on
histoRanges->SetHistoTimeRangeAndNBins(-250.,250,250);
histoRanges->SetHistoDiffTimeRangeAndNBins(-150, 150, 150);
// track-cluster residuals
histoRanges->SetHistoTrackResidualEtaRangeAndNBins(-0.05,0.05,100);
histoRanges->SetHistoTrackResidualPhiRangeAndNBins(-0.05,0.05,100);
histoRanges->SetHistodRRangeAndNBins(0.,0.05,50);//QA
// QA, electron, charged
histoRanges->SetHistoPOverERangeAndNBins(0, 2. ,100);
histoRanges->SetHistodEdxRangeAndNBins (0.,200.,100);
// QA
histoRanges->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
histoRanges->SetHistoVertexDistRangeAndNBins(0.,500.,250);
histoRanges->SetHistoZRangeAndNBins(-350,350,175);
histoRanges->SetHistoRRangeAndNBins(430,460,30);
histoRanges->SetHistoV0SignalRangeAndNBins(0,5000,250);
histoRanges->SetHistoV0MultiplicityRangeAndNBins(0,5000,250);
// QA, correlation
if(collision=="PbPb")
{
histoRanges->SetHistoNClusterCellRangeAndNBins(0,100,100);
histoRanges->SetHistoNClustersRangeAndNBins(0,500,50);
histoRanges->SetHistoTrackMultiplicityRangeAndNBins(0,2000,200);
}
else
{
histoRanges->SetHistoNClusterCellRangeAndNBins(0,50,50);
histoRanges->SetHistoNClustersRangeAndNBins(0,50,50);
histoRanges->SetHistoTrackMultiplicityRangeAndNBins(0,200,200);
}
// xE, zT
histoRanges->SetHistoRatioRangeAndNBins(0.,1.2,120);
histoRanges->SetHistoHBPRangeAndNBins (0.,10.,100);
// Isolation
histoRanges->SetHistoPtInConeRangeAndNBins(0, 50 , 100);
histoRanges->SetHistoPtSumRangeAndNBins (0, 100, 100);
if(collision.Contains("pPb"))
histoRanges->SetHistoPtSumRangeAndNBins (0, 200, 100);
else if(collision.Contains("PbPb"))
histoRanges->SetHistoPtSumRangeAndNBins (0, 500, 100);
}
///
/// Check if the selected trigger is appropriate
/// to run the analysis, depending on the period
/// certain triggers were not available.
///
/// Run MC analysis for no trigger.
///
/// \param simulation: bool with data (0) or MC (1) condition
/// \param trigger: trigger string name (EMCAL_L0, EMCAL_L1, EMCAL_L2, DCAL_L0, DCAL_L1, DCAL_L2)
/// \param period: LHCXX
/// \param year: 2011, ...
///
/// \return True if analysis can be done.
///
Bool_t CheckAnalysisTrigger(Bool_t simulation, TString trigger, TString period, Int_t year)
{
// Accept directly all MB kind of events
//
if ( trigger.Contains("default") || trigger.Contains("INT") || trigger.Contains("MB") ) return kTRUE;
// MC analysis has no trigger dependence, execute only for the default case
//
if ( simulation )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : Triggered events not checked in simulation, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// Triggers introduced in 2011
//
if ( year < 2011 && ( trigger.Contains("EMCAL") || trigger.Contains("DCAL") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events for year < 2011, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// DCal Triggers introduced in 2015
//
if ( year < 2014 && trigger.Contains("DCAL") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events by DCal for year < 2014, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// EG2 trigger only activated from 2013
//
if ( year < 2013 && trigger.Contains("L2") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : EG2 trigger not available for year < 2012, SKIP trigger %s in %s \n", trigger.Data(),period.Data());
return kFALSE;
}
// Triggers only activated in 2013 from LHC13d for physics (it might be there are in b and c but not taking data)
//
if ( year == 2013 && trigger.Contains("L") && ( period.Contains("b") || period.Contains("c") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : Triggers not available for year 2013 in period %s, SKIP trigger %s! \n",period.Data(), trigger.Data());
return kFALSE;
}
// DCal Triggers introduced in 2015
//
if ( year < 2014 && ( trigger.Contains("DCAL") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events by DCal for year < 2014, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// L0 trigger used for periods below LHC11e?
//
if ( period == "LHC11h" && trigger.Contains("EMCAL_L0") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No EMCAL_L0 triggered events by EMCal for period LHC11h, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// L1 trigger not used until LHC11e? period, what about LHC11f?
//
if ( period.Contains("LHC11") && period != "LHC11h" && trigger.Contains("EMCAL_L1") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// L1 trigger not used again until LHC12c period
//
if ( ( period == "LHC12a" || period == "LHC12b" ) && trigger.Contains("EMCAL_L1") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// Run2: No trigger used again until LHC15i period
//
if ( year == 2015 && ( period == "LHC15h" || period == "LHC15g" || period == "LHC15f" || period == "LHC15e" ||
period == "LHC15d" || period == "LHC15c" || period == "LHC15b" || period == "LHC15a" ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// Run2: L1 trigger not used again until LHC15o period
//
if ( year == 2015 && period != "LHC15o" && !trigger.Contains("L0") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// Run2: L1 trigger not used again until LHC15o period
//
if ( year == 2015 && period == "LHC15o" && ( trigger.Contains("L0") || trigger.Contains("L2") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
return kTRUE;
}
remove switchs of unused settings that are moved to a different task
/// \file AddTaskPi0IMGammaCorrQA.C
/// \ingroup CaloTrackCorrMacrosQA
/// \brief Configuration of the analysis QA wagon for PWG-GA EMCal analysis
///
/// Configuration macro of EMCal related PWG-GA analysis, although it can be
/// also used for PHOS. It does:
/// * a simple photon cluster selection
/// * invariant mass analysis
/// * cluster-charged track correlation analysis (optional)
/// * detector general QA analysis (optional)
/// * track general QA analysis (optional)
///
/// Wagon responsible: Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>
///
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
// Uncomment for compilation
//// Set includes for compilation
//
//#if !defined(__CINT__) || defined(__MAKECINT__)
//
//#include <TString.h>
//#include <TROOT.h>
//
//#include "AliLog.h"
//#include "AliAnalysisTaskCaloTrackCorrelation.h"
//#include "AliCaloTrackESDReader.h"
//#include "AliCaloTrackAODReader.h"
//#include "AliCalorimeterUtils.h"
//#include "AliAnaPhoton.h"
//#include "AliAnaPi0.h"
//#include "AliHistogramRanges.h"
//#include "AliAnaParticleIsolation.h"
//#include "AliAnaParticleHadronCorrelation.h"
//#include "AliAnaChargedParticles.h"
//#include "AliAnaCalorimeterQA.h"
//#include "AliAnaGeneratorKine.h"
//#include "AliAnalysisTaskCaloTrackCorrelation.h"
//#include "AliAnaCaloTrackCorrMaker.h"
//#include "AliAnalysisManager.h"
//#include "AliInputEventHandler.h"
//#include "AliVTrack.h"
//#include "ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C"
//#include "AliESDtrackCuts.h"
//#include "CreateTrackCutsPWGJE.C"
//#include "ConfigureEMCALRecoUtils.C"
//#endif
//
//// Declare methods for compilation
//
//AliCaloTrackReader * ConfigureReader (TString inputDataType, TString collision, Bool_t calibrate,
// Int_t minTime, Int_t maxTime,
// Int_t minCen, Int_t maxCen,
// Bool_t simulation, Int_t year, Int_t debugLevel);
//
//AliCalorimeterUtils * ConfigureCaloUtils (TString calorimeter, TString trigger,
// Bool_t simulation , Bool_t calibrate,
// Int_t year , Int_t debugLevel );
//
//AliAnaPhoton * ConfigurePhotonAnalysis(TString calorimeter, Bool_t caloType, TString collision,
// TString containerName, Bool_t simulation,
// Int_t year, Int_t debugLevel);
//
//AliAnaPi0 * ConfigurePi0Analysis (TString calorimeter, Bool_t caloType, TString collision,
// TString containerName, Bool_t simulation, Int_t year,
// Int_t debugLevel, Int_t minCen);
//
//AliAnaChargedParticles * ConfigureChargedAnalysis
// (TString collision , TString containerName,
// Bool_t simulation, Int_t year, Int_t debugLevel);
//
//AliAnaParticleIsolation* ConfigureIsolationAnalysis
// (TString particle , TString calorimeter , Bool_t caloType,
// TString collision , TString containerName,
// Bool_t simulation, Int_t year , Int_t debugLevel);
//
//AliAnaParticleHadronCorrelation * ConfigureHadronCorrelationAnalysis
// (TString particle , TString calorimeter , Bool_t caloType,
// TString collision , TString containerName,
// Bool_t simulation , Int_t year , Int_t debugLevel,
// Int_t minCen);
//
//AliAnaCalorimeterQA * ConfigureQAAnalysis (TString calorimeter, TString collision,
// Bool_t simulation , Int_t year, Int_t debugLevel);
//
//void SetHistoRangeAndNBins (AliHistogramRanges* histoRanges,
// TString calorimeter, Bool_t caloType,
// TString collision, Int_t year );
//
//Bool_t CheckAnalysisTrigger (Bool_t simulation, TString trigger,
// TString period , Int_t year );
//
//// Global variables, set externally, uncomment next lines for local tests and compilation.
//const char* kPeriod = "LHC16t"; // gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTAG");
//const char* kColType = "PbPb"; // gSystem->Getenv("ALIEN_JDL_LPMINTERACTIONTYPE"); //either "pp", "pPb" or "PbPb"
//const char* kProdType = "MC"; // gSystem->Getenv("ALIEN_JDL_LPMPRODUCTIONTYPE");
//Bool_t kMC = kFALSE;
///
/// Main method calling all the configuration
/// Creates a CaloTrackCorr task, configures it and adds it to the analysis manager.
///
/// The options that can be passed to the macro are:
/// \param calorimeter : A string with he calorimeter used to measure the trigger particle.
/// \param simulation : A bool identifying the data as simulation.
/// \param collision: A string with the colliding system.
/// \param period : A string with the data period: LHC11h, LHC15n ... from it we extract the year.
/// \param qaan: execute the detector QA analysis.
/// \param hadronan: execute the track QA and cluster-track correlation analysis.
/// \param calibrate: if OADB was updated with calibration parameters not used in reconstruction, apply them here.
/// \param minTime: minimum time cut, leave it open by default even if calibration available, ns
/// \param maxTime: maximum time cut, leave it open by default even if calibration available, ns
/// \param minCen : An int to select the minimum centrality, -1 means no selection.
/// \param maxCen : An int to select the maximum centrality, -1 means no selection.
/// \param debugLevel : An int to define the debug level of all the tasks.
/// \param suffix : A string with the type of trigger (default: MB, EMC).
///
AliAnalysisTaskCaloTrackCorrelation *AddTaskPi0IMGammaCorrQA(const TString calorimeter = "EMCAL",
Bool_t simulation = kFALSE,
TString collision = "pp",
TString period = "",
const Bool_t qaan = kTRUE,
const Bool_t hadronan = kTRUE,
const Bool_t calibrate = kFALSE,
const Int_t minTime = -1000,
const Int_t maxTime = 1000,
const Int_t minCen = -1,
const Int_t maxCen = -1,
const Int_t debugLevel = -1,
const char * suffix = "default"
)
{
// Check the global variables, and reset the provided ones if empty.
//
TString trigger = suffix;
if(collision=="")
{
if (!strcmp(kColType, "PbPb")) collision = "PbPb";
else if (!strcmp(kColType, "AA" )) collision = "PbPb";
else if (!strcmp(kColType, "pA" )) collision = "pPb";
else if (!strcmp(kColType, "Ap" )) collision = "pPb";
else if (!strcmp(kColType, "pPb" )) collision = "pPb";
else if (!strcmp(kColType, "Pbp" )) collision = "pPb";
else if (!strcmp(kColType, "pp" )) collision = "pp" ;
simulation = kMC;
period = kPeriod;
// print check on global settings once
if(trigger.Contains("default") ||trigger.Contains("INT") || trigger.Contains("MB") )
printf("AddTaskPi0IMGammaCorrQA - Get the data features from global parameters: col <%s>, period <%s>, mc <%d> \n",
kColType,kPeriod,kMC);
}
Int_t year = 2017;
if ( period!="" )
{
if (period.Contains("16")) year = 2016;
else if(period.Contains("15")) year = 2015;
else if(period.Contains("13")) year = 2013;
else if(period.Contains("12")) year = 2012;
else if(period.Contains("11")) year = 2011;
else if(period.Contains("10")) year = 2010;
}
// Get the pointer to the existing analysis manager via the static access method.
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskPi0IMGammaCorrQA", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskPi0IMGammaCorrQA", "This task requires an input event handler");
return NULL;
}
//
// Create task
//
// Name for containers
TString containerName = Form("%s_Trig_%s",calorimeter.Data(), trigger.Data());
if(collision!="pp" && maxCen>=0) containerName+=Form("Cen%d_%d",minCen,maxCen);
TString taskName =Form("Pi0IM_GammaTrackCorr_%s",containerName.Data());
AliAnalysisTaskCaloTrackCorrelation * task = new AliAnalysisTaskCaloTrackCorrelation (taskName);
//task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
task->SetDebugLevel(debugLevel);
//task->SetBranches("ESD:AliESDRun.,AliESDHeader");
//task->SetBranches("AOD:header,tracks,vertices,emcalCells,caloClusters");
//
// Init main analysis maker and pass it to the task
AliAnaCaloTrackCorrMaker * maker = new AliAnaCaloTrackCorrMaker();
task->SetAnalysisMaker(maker);
//
// Pass the task to the analysis manager
mgr->AddTask(task);
//
// Create containers
TString outputfile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *cout_pc = mgr->CreateContainer(trigger, TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:%s",outputfile.Data(),Form("Pi0IM_GammaTrackCorr_%s",calorimeter.Data())));
AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("Param_%s",trigger.Data()), TList::Class(),
AliAnalysisManager::kParamContainer,
Form("%s_Parameters.root",Form("Pi0IM_GammaTrackCorr_%s",calorimeter.Data())));
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (task, 1, cout_pc);
mgr->ConnectOutput (task, 2, cout_cuts);
//==============================================================================
// Do not configure the wagon for certain analysis combinations
// But create the task so that the sub-wagon train can run
//
Bool_t doAnalysis = CheckAnalysisTrigger(simulation,trigger,period,year);
if(!doAnalysis)
{
maker->SwitchOffProcessEvent();
return task;
}
// #### Start analysis configuration ####
//
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Make sure the B field is enabled for track selection, some cuts need it
//
((AliInputEventHandler*)mgr->GetInputEventHandler())->SetNeedField(kTRUE);
// Print settings to check all is as expected
//
printf("AddTaskPi0IMGammaCorrQA - Task NAME: %s \n",taskName.Data());
printf("AddTaskPi0IMGammaCorrQA - Settings: data <%s>, calo <%s>, MC <%d>, collision <%s>, trigger <%s>, period <%s>, year <%d>,\n"
"\t \t \t CaloQA on <%d>, Track QA on <%d>, Make corrections <%d>, %d < time < %d, %d < cen < %d, debug level <%d> \n",
inputDataType.Data(), calorimeter.Data(),simulation, collision.Data(),trigger.Data(), period.Data(), year,
qaan , hadronan, calibrate, minTime, maxTime, minCen, maxCen, debugLevel);
//
// General frame setting and configuration
maker->SetReader ( ConfigureReader (inputDataType,collision,calibrate,minTime,maxTime,minCen,maxCen,simulation,year,debugLevel) );
if(hadronan)maker->GetReader()->SwitchOnCTS();
maker->SetCaloUtils( ConfigureCaloUtils(calorimeter,trigger,simulation,calibrate,year,debugLevel) );
// Analysis tasks setting and configuration
Int_t n = 0;//Analysis number, order is important
// Cell QA
if(qaan) maker->AddAnalysis(ConfigureQAAnalysis(calorimeter,collision,simulation,year,debugLevel),n++);
// Analysis with EMCal trigger or MB
if ( !trigger.Contains("DCAL") )
{
// Cluster selection
maker->AddAnalysis(ConfigurePhotonAnalysis(calorimeter,0,collision,containerName,simulation,year,debugLevel) ,n++);
// Previous cluster invariant mass
maker->AddAnalysis(ConfigurePi0Analysis (calorimeter,0,collision,containerName,simulation,year,debugLevel,minCen),n++);
if(hadronan)
{
// Isolation of selected clusters by AliAnaPhoton
maker->AddAnalysis(ConfigureIsolationAnalysis("Photon",calorimeter,0,collision,containerName,simulation,year,debugLevel), n++);
// Selected clusters-track correlation
maker->AddAnalysis(ConfigureHadronCorrelationAnalysis("Photon",calorimeter,0,collision,containerName,simulation,year,debugLevel,minCen), n++);
}
}
// Analysis with DCal trigger or MB
if(year > 2014 && calorimeter=="EMCAL" && !trigger.Contains("EMCAL"))
{
// Cluster selection
maker->AddAnalysis(ConfigurePhotonAnalysis(calorimeter,1,collision,containerName,simulation,year,debugLevel) , n++);
// Previous cluster invariant mass
maker->AddAnalysis(ConfigurePi0Analysis (calorimeter,1,collision,containerName,simulation,year,debugLevel,minCen),n++);
if(hadronan)
{
// Isolation of selected clusters by AliAnaPhoton
maker->AddAnalysis(ConfigureIsolationAnalysis("Photon",calorimeter,1,collision,containerName,simulation,year,debugLevel), n++);
// Selected clusters-track correlation
maker->AddAnalysis(ConfigureHadronCorrelationAnalysis("Photon",calorimeter,1,collision,containerName,simulation,year,debugLevel,minCen), n++);
}
}
// Charged tracks plots, any trigger
if(hadronan)
maker->AddAnalysis(ConfigureChargedAnalysis(collision,containerName,simulation,year,debugLevel), n++);
if(simulation)
{
// Calculate the cross section weights, apply them to all histograms
// and fill xsec and trial histo. Sumw2 must be activated.
//maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionCalculation();
//maker->SwitchOnSumw2Histograms();
// For recent productions where the cross sections and trials are not stored in separate file
//maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionFromEventHeader() ;
// Just fill cross section and trials histograms.
maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionHistoFill();
// Add control histogram with pT hard to control aplication of weights
maker->SwitchOnPtHardHistogram();
}
//
// Select events trigger depending on trigger
//
if(!simulation)
{
gROOT->LoadMacro("$ALICE_PHYSICS/PWGGA/CaloTrackCorrelations/macros/ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C");
TString caloTriggerString = "";
UInt_t mask = ConfigureAndGetEventTriggerMaskAndCaloTriggerString(trigger, year, caloTriggerString);
task ->SelectCollisionCandidates( mask );
maker->GetReader()->SetFiredTriggerClassName(caloTriggerString);
printf("AddTaskPi0IMGammaCorrQA - Trigger Mask %d, caloTriggerString <%s>\n", mask, caloTriggerString.Data());
}
//
// Final maker settings
//
maker->SetAnaDebug(debugLevel) ;
maker->SwitchOnHistogramsMaker() ;
maker->SwitchOnAODsMaker() ;
maker->SwitchOnDataControlHistograms();
if(debugLevel > 0) maker->Print("");
return task;
}
///
/// Configure the class handling the events and cluster/tracks filtering.
///
AliCaloTrackReader * ConfigureReader(TString inputDataType, TString collision, Bool_t calibrate,
Int_t minTime, Int_t maxTime,
Int_t minCen, Int_t maxCen,
Bool_t simulation, Int_t year, Int_t debugLevel)
{
AliCaloTrackReader * reader = 0;
if (inputDataType=="AOD")
reader = new AliCaloTrackAODReader();
else if(inputDataType=="ESD")
reader = new AliCaloTrackESDReader();
else
printf("AliCaloTrackReader::ConfigureReader() - Data combination not known input Data=%s\n",
inputDataType.Data());
reader->SetDebug(debugLevel);//10 for lots of messages
//------------------------
// Detector input filling
//------------------------
//Min cluster/track E
reader->SetEMCALEMin(0.3);
reader->SetEMCALEMax(1000);
reader->SetPHOSEMin(0.3);
reader->SetPHOSEMax(1000);
reader->SetCTSPtMin(0.2);
reader->SetCTSPtMax(1000);
// Time cut
reader->SwitchOffUseParametrizedTimeCut();
if(calibrate)
{
reader->SwitchOnUseEMCALTimeCut() ;
reader->SetEMCALTimeCut(minTime,maxTime);
}
reader->SwitchOffUseTrackTimeCut();
reader->SetTrackTimeCut(-1e10,1e10);
reader->SwitchOffFiducialCut();
// Tracks
reader->SwitchOffCTS();
reader->SwitchOffRejectNoTrackEvents();
reader->SwitchOffRecalculateVertexBC();
reader->SwitchOffVertexBCEventSelection();
reader->SwitchOffUseTrackDCACut();
//reader->SetTrackDCACut(0,0.0105);
//reader->SetTrackDCACut(1,0.035);
//reader->SetTrackDCACut(2,1.1);
if(inputDataType=="ESD")
{
gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/macros/CreateTrackCutsPWGJE.C");
if(year > 2010)
{
//Hybrids 2011
AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10001008);
reader->SetTrackCuts(esdTrackCuts);
AliESDtrackCuts * esdTrackCuts2 = CreateTrackCutsPWGJE(10011008);
reader->SetTrackComplementaryCuts(esdTrackCuts2);
}
else
{
//Hybrids 2010
AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10001006);
reader->SetTrackCuts(esdTrackCuts);
AliESDtrackCuts * esdTrackCuts2 = CreateTrackCutsPWGJE(10041006);
reader->SetTrackComplementaryCuts(esdTrackCuts2);
}
}
else if(inputDataType=="AOD")
{
reader->SwitchOnAODHybridTrackSelection(); // Check that the AODs have Hybrids!!!!
reader->SetTrackStatus(AliVTrack::kITSrefit);
}
// Calorimeter
//reader->SetEMCALClusterListName("");
if(calibrate && !simulation) reader->SwitchOnClusterRecalculation();
else reader->SwitchOffClusterRecalculation();
reader->SwitchOnEMCALCells();
reader->SwitchOnEMCAL();
reader->SwitchOffPHOSCells();
reader->SwitchOffPHOS();
//-----------------
// Event selection
//-----------------
reader->SwitchOnEventTriggerAtSE();
reader->SetZvertexCut(10.);
reader->SwitchOnPrimaryVertexSelection(); // and besides primary vertex
reader->SwitchOffPileUpEventRejection(); // remove pileup
reader->SwitchOffV0ANDSelection() ; // and besides v0 AND
if(collision=="PbPb")
{
if(year < 2014) reader->SwitchOnAliCentrality();
reader->SetCentralityBin(minCen,maxCen); // Accept all events, if not select range
reader->SetCentralityOpt(100); // 10 (c= 0-10, 10-20 ...), 20 (c= 0-5, 5-10 ...) or 100 (c= 1, 2, 3 ..)
}
if(debugLevel > 0) reader->Print("");
return reader;
}
///
/// Configure the class handling the calorimeter clusters specific methods
///
AliCalorimeterUtils* ConfigureCaloUtils(TString calorimeter, TString trigger,
Bool_t simulation , Bool_t calibrate,
Int_t year , Int_t debugLevel)
{
AliCalorimeterUtils *cu = new AliCalorimeterUtils;
cu->SetDebug(debugLevel);
// Remove clusters close to borders, at least max energy cell is 1 cell away
cu->SetNumberOfCellsFromEMCALBorder(1);
cu->SetNumberOfCellsFromPHOSBorder(2);
// Search of local maxima in cluster
cu->SetLocalMaximaCutE(0.1);
cu->SetLocalMaximaCutEDiff(0.03);
//cu->SwitchOffClusterPlot();
cu->SwitchOffRecalculateClusterTrackMatching();
cu->SwitchOnBadChannelsRemoval() ;
//EMCAL settings
if(!simulation)
cu->SwitchOnLoadOwnEMCALGeometryMatrices();
AliEMCALRecoUtils * recou = cu->GetEMCALRecoUtils();
cu->SwitchOffRecalibration(); // Check the reader if it is taken into account during filtering
cu->SwitchOffRunDepCorrection();
cu->SwitchOffCorrectClusterLinearity();
Bool_t bExotic = kTRUE;
Bool_t bNonLin = kFALSE;
Bool_t bBadMap = kTRUE;
Bool_t bEnCalib = kFALSE;
Bool_t bTiCalib = kFALSE;
if(calibrate && !simulation)
{
cu->SwitchOnRecalibration(); // Check the reader if it is taken into account during filtering
cu->SwitchOffRunDepCorrection();
cu->SwitchOnRecalculateClusterPosition() ;
bEnCalib = kTRUE;
bTiCalib = kTRUE;
}
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C");
ConfigureEMCALRecoUtils(recou,
simulation,
bExotic,
bNonLin,
bEnCalib,
bBadMap,
bTiCalib,
debugLevel
);
//recou->SetExoticCellDiffTimeCut(50.);
if(calorimeter=="PHOS")
{
if(year < 2014) cu->SetNumberOfSuperModulesUsed(3);
else cu->SetNumberOfSuperModulesUsed(4);
}
else
{
Int_t nSM = 20;
Int_t lastEMC = 11;
if (year == 2010) { nSM = 4; lastEMC = 3; }// EMCAL first year
else if (year < 2014) { nSM = 10; lastEMC = 9; }// EMCAL active 2011-2013
cu->SetNumberOfSuperModulesUsed(nSM);
if (trigger.Contains("EMCAL"))
{
cu->SetFirstSuperModuleUsed( 0);
cu->SetLastSuperModuleUsed (lastEMC);
}
else if (trigger.Contains("DCAL"))
{
cu->SetFirstSuperModuleUsed(12);
cu->SetLastSuperModuleUsed (19);
}
else
{
cu->SetFirstSuperModuleUsed(0);
cu->SetLastSuperModuleUsed (cu->GetNumberOfSuperModulesUsed()-1);
}
printf("AddTaskPi0IMGammaCorrQA - CalorimeterUtils: nSM %d, first %d, last %d\n",
cu->GetNumberOfSuperModulesUsed(),cu->GetFirstSuperModuleUsed(), cu->GetLastSuperModuleUsed());
}
// PHOS
cu->SwitchOffLoadOwnPHOSGeometryMatrices();
if(debugLevel > 0) cu->Print("");
return cu;
}
///
/// Configure the task doing the first photon cluster selections
/// Basically the track matching, minor shower shape cut, NLM selection ...
///
AliAnaPhoton* ConfigurePhotonAnalysis(TString calorimeter, Bool_t caloType, TString collision,
TString containerName, Bool_t simulation,
Int_t year, Int_t debugLevel)
{
AliAnaPhoton *ana = new AliAnaPhoton();
ana->SetDebug(debugLevel); //10 for lots of messages
// cluster selection cuts
ana->SwitchOnFiducialCut();
if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC
else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC
ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE);
ana->SetCalorimeter(calorimeter);
if(calorimeter == "PHOS")
{
ana->SetNCellCut(2);// At least 3 cells
ana->SetMinPt(0.5);
ana->SetMinDistanceToBadChannel(2, 4, 5);
ana->SetTimeCut(-1e10,1e10); // open cut
}
else
{
// EMCAL
ana->SetConstantTimeShift(615); // for MC and uncalibrated data, whenever there is time > 400 ns
ana->SetNCellCut(1);// At least 2 cells
ana->SetMinEnergy(0.5); // avoid mip peak at E = 260 MeV
ana->SetMaxEnergy(1000);
ana->SetTimeCut(-1e10,1e10); // open cut, usual time window of [425-825] ns if time recalibration is off
// restrict to less than 100 ns when time calibration is on
ana->SetMinDistanceToBadChannel(2, 4, 6);
// Not useful if M02 cut is already strong
ana->SetNLMCut(1, 2) ;
}
ana->SwitchOnTrackMatchRejection() ;
ana->SwitchOnTMHistoFill() ;
ana->SwitchOnAcceptanceHistoPerEBin();
ana->SetNEBinCuts(2);
// Set the acceptance E bins depending on the trigger and their likely values
if(containerName.Contains("efault") || containerName.Contains("INT") || containerName.Contains("MB"))
{
ana->SetEBinCutsAt(0, 0.5);
ana->SetEBinCutsAt(1, 3.0);
ana->SetEBinCutsAt(2, 100.0);
}
else if(containerName.Contains("L0"))
{
ana->SetEBinCutsAt(0, 2.0);
ana->SetEBinCutsAt(1, 5.0);
ana->SetEBinCutsAt(2, 100.0);
}
else
{
ana->SetEBinCutsAt(0, 5.0);
ana->SetEBinCutsAt(1, 12.0);
ana->SetEBinCutsAt(2, 100.0);
}
//PID cuts (shower shape)
ana->SwitchOnCaloPID(); // do PID selection, unless specified in GetCaloPID, selection not based on bayesian
AliCaloPID* caloPID = ana->GetCaloPID();
//Not used in bayesian
//EMCAL
caloPID->SetEMCALLambda0CutMax(0.4); // Rather open
caloPID->SetEMCALLambda0CutMin(0.10);
caloPID->SetEMCALDEtaCut(0.025);
caloPID->SetEMCALDPhiCut(0.030);
//PHOS
caloPID->SetPHOSDispersionCut(2.5);
caloPID->SetPHOSRCut(2.);
ana->SwitchOnFillShowerShapeHistograms(); // Filled before photon shower shape selection
//if(!simulation)ana->SwitchOnFillPileUpHistograms();
if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms();
// Input / output delta AOD settings
ana->SetOutputAODName(Form("Photon%s_Calo%d",containerName.Data(),caloType));
ana->SetOutputAODClassName("AliAODPWG4ParticleCorrelation");
ana->SetInputAODName (Form("Photon%s_Calo%d",containerName.Data(),caloType));
// Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("AnaPhoton_Calo%d_",caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
// Number of particle type MC histograms
ana->FillNOriginHistograms(7);
ana->FillNPrimaryHistograms(4);
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0 ) ana->Print("");
return ana;
}
///
/// Configure the task doing the 2 cluster invariant mass analysis
///
AliAnaPi0* ConfigurePi0Analysis(TString calorimeter , Bool_t caloType , TString collision,
TString containerName, Bool_t simulation, Int_t year,
Int_t debugLevel , Int_t minCen)
{
AliAnaPi0 *ana = new AliAnaPi0();
ana->SetDebug(debugLevel);//10 for lots of messages
// Input delta AOD settings
ana->SetInputAODName(Form("Photon%s_Calo%d",containerName.Data(),caloType));
// Calorimeter settings
ana->SetCalorimeter(calorimeter);
ana->SwitchOnFiducialCut();
if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC
else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC
ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE);
ana->SwitchOnRealCaloAcceptance();
// Settings for pp collision mixing
ana->SwitchOnOwnMix(); //Off when mixing done with general mixing frame
// Cuts
if(calorimeter=="EMCAL")
{
ana->SetPairTimeCut(100);
// Angle cut, avoid pairs with too large angle
ana->SwitchOnAngleSelection();
ana->SetAngleMaxCut(TMath::DegToRad()*80.); // EMCal: 4 SM in phi, 2 full SMs in eta
ana->SetAngleCut(0.016); // Minimum angle open, ~cell size
}
ana->SetNPIDBits(1);
ana->SetNAsymCuts(1); // no asymmetry cut, previous studies showed small effect.
// In EMCAL assymetry cut prevents combination of assymetric decays which is the main source of pi0 at high E.
if (collision == "pp" )
{
ana->SetNCentrBin(1);
ana->SetNZvertBin(10);
ana->SetNRPBin(1);
ana->SetNMaxEvMix(100);
ana->SetMinPt(0.5);
}
else if(collision =="PbPb")
{
ana->SetNCentrBin(10);
ana->SetNZvertBin(10);
ana->SetNRPBin(4);
ana->SetNMaxEvMix(10);
if(minCen >= 10) ana->SetNMaxEvMix(50);
if(minCen >= 50) ana->SetNMaxEvMix(100);
ana->SetMinPt(1.5);
ana->SwitchOnFillHighMultiplicityHistograms();
}
else if(collision =="pPb")
{
ana->SetNCentrBin(1);
ana->SetNZvertBin(10);
ana->SetNRPBin(4);
ana->SetNMaxEvMix(100);
ana->SetMinPt(0.5);
ana->SwitchOnFillHighMultiplicityHistograms();
}
ana->SwitchOffMultipleCutAnalysis();
ana->SwitchOnSMCombinations();
ana->SwitchOffFillAngleHisto();
ana->SwitchOffFillOriginHisto();
// Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("AnaPi0_Calo%d_",caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing charged track selection
///
AliAnaChargedParticles* ConfigureChargedAnalysis(TString collision,TString containerName,
Bool_t simulation, Int_t year, Int_t debugLevel)
{
AliAnaChargedParticles *ana = new AliAnaChargedParticles();
ana->SetDebug(debugLevel); //10 for lots of messages
// selection cuts
ana->SetMinPt(0.5);
ana->SwitchOnFiducialCut();
Float_t etacut = 0.8;
ana->GetFiducialCut()->SetSimpleCTSFiducialCut(etacut, 0, 360) ; //more restrictive cut in reader and after in isolation
// histogram switchs
ana->SwitchOffFillVertexBC0Histograms() ;
//if(!simulation) ana->SwitchOnFillPileUpHistograms();
ana->SwitchOffFillTrackMultiplicityHistograms();
// Input / output delta AOD settings
ana->SetOutputAODName(Form("Hadron%s",containerName.Data()));
ana->SetOutputAODClassName("AliAODPWG4ParticleCorrelation");
ana->SetInputAODName(Form("Hadron%s",containerName.Data()));
//Set Histograms name tag, bins and ranges
ana->AddToHistogramsName("AnaHadrons_");
SetHistoRangeAndNBins(ana->GetHistogramRanges(),"",kFALSE,collision,year); // see method below
ana->GetHistogramRanges()->SetHistoPhiRangeAndNBins(0, TMath::TwoPi(), 120) ;
ana->GetHistogramRanges()->SetHistoEtaRangeAndNBins(-1.*etacut, 1.*etacut, etacut*100) ;
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing the trigger particle hadron correlation
///
AliAnaParticleIsolation* ConfigureIsolationAnalysis(TString particle , TString calorimeter , Bool_t caloType,
TString collision , TString containerName,
Bool_t simulation, Int_t year , Int_t debugLevel)
{
AliAnaParticleIsolation *ana = new AliAnaParticleIsolation();
ana->SetDebug(debugLevel);
//if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms();
ana->SetMinPt(5);
ana->SwitchOffStudyTracksInCone() ;
ana->SwitchOnUEBandSubtractionHistoFill();
ana->SwitchOffDecayTaggedHistoFill() ;
ana->SwitchOnSSHistoFill();
ana->SwitchOffLeadingOnly();
ana->SwitchOffCheckNeutralClustersForLeading();
ana->SwitchOffPtTrigBinHistoFill();
ana->SwitchOffBackgroundBinHistoFill();
ana->SwitchOffTMHistoFill();
// MC
ana->SwitchOffPrimariesInConeSelection();
ana->SwitchOffPrimariesPi0DecayStudy() ;
ana->SwitchOnRealCaloAcceptance();
ana->SwitchOnFiducialCut();
if(calorimeter == "EMCAL" && caloType == 0)
{
// Avoid borders of EMCal
ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.60, 86, 174) ;
}
if(calorimeter == "EMCAL" && caloType == 1)
{
// Avoid borders of DCal
ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.60, 264, 316) ;
}
AliCaloPID* caloPID = ana->GetCaloPID();
caloPID->SetEMCALDEtaCut(0.025);
caloPID->SetEMCALDPhiCut(0.030);
ana->SwitchOffSeveralIsolation() ;
ana->SwitchOffReIsolation();
//
// Do settings for main isolation cut class
//
AliIsolationCut * ic = ana->GetIsolationCut();
ic->SetDebug(debugLevel);
ic->SetParticleTypeInCone(AliIsolationCut::kNeutralAndCharged);
ic->SetICMethod(AliIsolationCut::kSumPtIC);
if ( collision == "pp" || collision == "pPb" )
{
ic->SetPtThreshold(0.5);
ic->SetSumPtThreshold(2.0) ;
ic->SetConeSize(0.4);
}
if ( collision == "PbPb" )
{
ic->SetPtThreshold(3.);
ic->SetSumPtThreshold(3.0) ;
ic->SetConeSize(0.3);
}
// Input / output delta AOD settings
ana->SetInputAODName(Form("%s%s_Calo%d",particle.Data(),containerName.Data(),caloType));
ana->SetAODObjArrayName(Form("%sIso_%s_Calo%d",particle.Data(),containerName.Data(),caloType));
// Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("AnaIsol%s_Calo%d_",particle.Data(),caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing the trigger particle hadron correlation
///
AliAnaParticleHadronCorrelation* ConfigureHadronCorrelationAnalysis(TString particle, TString calorimeter, Bool_t caloType,
TString collision, TString containerName,
Bool_t simulation, Int_t year, Int_t debugLevel, Int_t minCen)
{
AliAnaParticleHadronCorrelation *ana = new AliAnaParticleHadronCorrelation();
ana->SetDebug(debugLevel);
ana->SetTriggerPtRange(5,100);
ana->SetAssociatedPtRange(0.2,100);
//ana->SetDeltaPhiCutRange( TMath::Pi()/2,3*TMath::Pi()/2 ); //[90 deg, 270 deg]
ana->SetDeltaPhiCutRange (TMath::DegToRad()*120.,TMath::DegToRad()*240.);
ana->SetUeDeltaPhiCutRange(TMath::DegToRad()*60. ,TMath::DegToRad()*120.);
ana->SwitchOffFillEtaGapHistograms();
ana->SetNAssocPtBins(4);
ana->SetAssocPtBinLimit(0, 0.5) ;
ana->SetAssocPtBinLimit(1, 2) ;
ana->SetAssocPtBinLimit(2, 5) ;
ana->SetAssocPtBinLimit(3, 10) ;
ana->SetAssocPtBinLimit(4, 20) ;
ana->SelectIsolated(kFALSE); // do correlation with isolated photons
//if(!simulation) ana->SwitchOnFillPileUpHistograms();
ana->SwitchOffAbsoluteLeading(); // Select trigger leading particle of all the selected tracks
ana->SwitchOffNearSideLeading(); // Select trigger leading particle of all the particles at +-90 degrees, default
//ana->SwitchOnLeadHadronSelection();
//ana->SetLeadHadronPhiCut(TMath::DegToRad()*100., TMath::DegToRad()*260.);
//ana->SetLeadHadronPtCut(0.5, 100);
// Mixing with own pool
ana->SwitchOffOwnMix();
ana->SetNZvertBin(20);
ana->SwitchOffCorrelationVzBin() ;
//if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms();
if(collision=="pp")
{
ana->SetNMaxEvMix(100);
ana->SwitchOnTrackMultBins();
ana->SetNTrackMultBin(10); // same as SetNCentrBin(10);
ana->SetNRPBin(1);
}
else
{
ana->SetNMaxEvMix(10);
if(minCen >= 10) ana->SetNMaxEvMix(50);
if(minCen >= 50) ana->SetNMaxEvMix(100);
ana->SwitchOffTrackMultBins(); // centrality bins
ana->SetNCentrBin(10);
ana->SetNRPBin(3);
}
// Input / output delta AOD settings
ana->SetInputAODName(Form("%s%s_Calo%d",particle.Data(),containerName.Data(),caloType));
ana->SetAODObjArrayName(Form("%sHadronCorr_%s_Calo%d",particle.Data(),containerName.Data(),caloType));
ana->SwitchOffPi0TriggerDecayCorr();
ana->SwitchOffDecayTriggerDecayCorr();
ana->SwitchOffNeutralCorr(); // Do only correlation with TPC
ana->SwitchOffHMPIDCorrelation();
ana->SwitchOffFillBradHistograms();
// Underlying event
ana->SwitchOffSeveralUECalculation();
ana->SetUeDeltaPhiCutRange(TMath::Pi()/3, 2*TMath::Pi()/3);
//Set Histograms name tag, bins and ranges
ana->AddToHistogramsName(Form("Ana%sHadronCorr_Calo%d_",particle.Data(),caloType));
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below
if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure the task doing standard calorimeter QA
///
AliAnaCalorimeterQA* ConfigureQAAnalysis(TString calorimeter, TString collision,
Bool_t simulation ,
Int_t year, Int_t debugLevel)
{
AliAnaCalorimeterQA *ana = new AliAnaCalorimeterQA();
ana->SetDebug(debugLevel); //10 for lots of messages
ana->SetCalorimeter(calorimeter);
//printf("QA: calorimeter %s, caloType %d, collision %s, simulation %d, fillCellTime %d, year %d, debugLevel %d\n",
// calorimeter.Data(),caloType,collision.Data(),simulation,fillCellTime,year,debugLevel);
ana->SetTimeCut(-1e10,1e10); // Open time cut
ana->SetConstantTimeShift(615); // for MC and uncalibrated data, whenever there is time > 400 ns
ana->SetEMCALCellAmpMin(0.5);
ana->SwitchOffStudyBadClusters() ;
ana->SwitchOffFillAllTH3Histogram();
ana->SwitchOffFillAllPositionHistogram();
ana->SwitchOffFillAllPositionHistogram2();
ana->SwitchOffStudyBadClusters();
ana->SwitchOffFillAllPi0Histogram() ;
ana->SwitchOffCorrelation();
ana->SwitchOffFillAllCellAbsIdHistogram();
ana->SwitchOffFillAllTrackMatchingHistogram();
ana->SwitchOnFillAllCellTimeHisto() ;
ana->SwitchOnFillAllCellHistogram();
ana->SwitchOffFillAllClusterHistogram() ;
ana->AddToHistogramsName("QA_Cell_"); //Begining of histograms name
SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter, -1, collision,year); // see method below
// ana->SwitchOnFiducialCut();
// if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC
// else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC
//
// ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE);
//if(simulation) ana->SwitchOnDataMC();
if(debugLevel > 0) ana->Print("");
return ana;
}
///
/// Configure histograms ranges and bins
///
void SetHistoRangeAndNBins (AliHistogramRanges* histoRanges, TString calorimeter, Bool_t caloType,
TString collision, Int_t year)
{
histoRanges->SetHistoPtRangeAndNBins(0, 100, 200) ; // Energy and pt histograms
if(calorimeter=="EMCAL")
{
if ( year == 2010 )
{
histoRanges->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 121*TMath::DegToRad(), 42) ;
histoRanges->SetHistoXRangeAndNBins(-230,90,120); // QA
histoRanges->SetHistoYRangeAndNBins(370,450,40); // QA
}
else if ( year < 2014 )
{
histoRanges->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 182*TMath::DegToRad(), 108) ;
histoRanges->SetHistoXRangeAndNBins(-460,90,200); // QA
histoRanges->SetHistoYRangeAndNBins(100,450,100); // QA
}
else // Run2
{
if (caloType == 0)
histoRanges->SetHistoPhiRangeAndNBins(78 *TMath::DegToRad(), 189*TMath::DegToRad(), 111) ;
else if (caloType == 1)
histoRanges->SetHistoPhiRangeAndNBins(258*TMath::DegToRad(), 329*TMath::DegToRad(), 71) ;
else
histoRanges->SetHistoPhiRangeAndNBins(80 *TMath::DegToRad(), 327*TMath::DegToRad(), 247) ;
histoRanges->SetHistoXRangeAndNBins(-460,460,230); // QA
histoRanges->SetHistoYRangeAndNBins(-450,450,225); // QA
}
histoRanges->SetHistoEtaRangeAndNBins(-0.72, 0.72, 144) ;
}
else
{
histoRanges->SetHistoPhiRangeAndNBins(250*TMath::DegToRad(), 320*TMath::DegToRad(), 70) ;
histoRanges->SetHistoEtaRangeAndNBins(-0.13, 0.13, 130) ;
}
histoRanges->SetHistoShowerShapeRangeAndNBins(-0.1, 2.9, 300);
// Invariant mass histoRangeslysis
histoRanges->SetHistoMassRangeAndNBins(0., 0.8, 160) ;
histoRanges->SetHistoAsymmetryRangeAndNBins(0., 1. , 100) ;
histoRanges->SetHistoOpeningAngleRangeAndNBins(0,0.7,50);
// check if time calibration is on
histoRanges->SetHistoTimeRangeAndNBins(-250.,250,250);
histoRanges->SetHistoDiffTimeRangeAndNBins(-150, 150, 150);
// track-cluster residuals
histoRanges->SetHistoTrackResidualEtaRangeAndNBins(-0.05,0.05,100);
histoRanges->SetHistoTrackResidualPhiRangeAndNBins(-0.05,0.05,100);
histoRanges->SetHistodRRangeAndNBins(0.,0.05,50);//QA
// QA, electron, charged
histoRanges->SetHistoPOverERangeAndNBins(0, 2. ,100);
histoRanges->SetHistodEdxRangeAndNBins (0.,200.,100);
// QA
histoRanges->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
histoRanges->SetHistoVertexDistRangeAndNBins(0.,500.,250);
histoRanges->SetHistoZRangeAndNBins(-350,350,175);
histoRanges->SetHistoRRangeAndNBins(430,460,30);
histoRanges->SetHistoV0SignalRangeAndNBins(0,5000,250);
histoRanges->SetHistoV0MultiplicityRangeAndNBins(0,5000,250);
// QA, correlation
if(collision=="PbPb")
{
histoRanges->SetHistoNClusterCellRangeAndNBins(0,100,100);
histoRanges->SetHistoNClustersRangeAndNBins(0,500,50);
histoRanges->SetHistoTrackMultiplicityRangeAndNBins(0,2000,200);
}
else
{
histoRanges->SetHistoNClusterCellRangeAndNBins(0,50,50);
histoRanges->SetHistoNClustersRangeAndNBins(0,50,50);
histoRanges->SetHistoTrackMultiplicityRangeAndNBins(0,200,200);
}
// xE, zT
histoRanges->SetHistoRatioRangeAndNBins(0.,1.2,120);
histoRanges->SetHistoHBPRangeAndNBins (0.,10.,100);
// Isolation
histoRanges->SetHistoPtInConeRangeAndNBins(0, 50 , 100);
histoRanges->SetHistoPtSumRangeAndNBins (0, 100, 100);
if(collision.Contains("pPb"))
histoRanges->SetHistoPtSumRangeAndNBins (0, 200, 100);
else if(collision.Contains("PbPb"))
histoRanges->SetHistoPtSumRangeAndNBins (0, 500, 100);
}
///
/// Check if the selected trigger is appropriate
/// to run the analysis, depending on the period
/// certain triggers were not available.
///
/// Run MC analysis for no trigger.
///
/// \param simulation: bool with data (0) or MC (1) condition
/// \param trigger: trigger string name (EMCAL_L0, EMCAL_L1, EMCAL_L2, DCAL_L0, DCAL_L1, DCAL_L2)
/// \param period: LHCXX
/// \param year: 2011, ...
///
/// \return True if analysis can be done.
///
Bool_t CheckAnalysisTrigger(Bool_t simulation, TString trigger, TString period, Int_t year)
{
// Accept directly all MB kind of events
//
if ( trigger.Contains("default") || trigger.Contains("INT") || trigger.Contains("MB") ) return kTRUE;
// MC analysis has no trigger dependence, execute only for the default case
//
if ( simulation )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : Triggered events not checked in simulation, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// Triggers introduced in 2011
//
if ( year < 2011 && ( trigger.Contains("EMCAL") || trigger.Contains("DCAL") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events for year < 2011, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// DCal Triggers introduced in 2015
//
if ( year < 2014 && trigger.Contains("DCAL") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events by DCal for year < 2014, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// EG2 trigger only activated from 2013
//
if ( year < 2013 && trigger.Contains("L2") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : EG2 trigger not available for year < 2012, SKIP trigger %s in %s \n", trigger.Data(),period.Data());
return kFALSE;
}
// Triggers only activated in 2013 from LHC13d for physics (it might be there are in b and c but not taking data)
//
if ( year == 2013 && trigger.Contains("L") && ( period.Contains("b") || period.Contains("c") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : Triggers not available for year 2013 in period %s, SKIP trigger %s! \n",period.Data(), trigger.Data());
return kFALSE;
}
// DCal Triggers introduced in 2015
//
if ( year < 2014 && ( trigger.Contains("DCAL") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events by DCal for year < 2014, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// L0 trigger used for periods below LHC11e?
//
if ( period == "LHC11h" && trigger.Contains("EMCAL_L0") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No EMCAL_L0 triggered events by EMCal for period LHC11h, SKIP trigger %s! \n", trigger.Data());
return kFALSE;
}
// L1 trigger not used until LHC11e? period, what about LHC11f?
//
if ( period.Contains("LHC11") && period != "LHC11h" && trigger.Contains("EMCAL_L1") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// L1 trigger not used again until LHC12c period
//
if ( ( period == "LHC12a" || period == "LHC12b" ) && trigger.Contains("EMCAL_L1") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// Run2: No trigger used again until LHC15i period
//
if ( year == 2015 && ( period == "LHC15h" || period == "LHC15g" || period == "LHC15f" || period == "LHC15e" ||
period == "LHC15d" || period == "LHC15c" || period == "LHC15b" || period == "LHC15a" ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// Run2: L1 trigger not used again until LHC15o period
//
if ( year == 2015 && period != "LHC15o" && !trigger.Contains("L0") )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
// Run2: L1 trigger not used again until LHC15o period
//
if ( year == 2015 && period == "LHC15o" && ( trigger.Contains("L0") || trigger.Contains("L2") ) )
{
printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data());
return kFALSE;
}
return kTRUE;
}
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video/rtp_stream_receiver.h"
#include <vector>
#include <utility>
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/common_types.h"
#include "webrtc/config.h"
#include "webrtc/media/base/mediaconstants.h"
#include "webrtc/modules/pacing/packet_router.h"
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_cvo.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_header_parser.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h"
#include "webrtc/modules/rtp_rtcp/include/ulpfec_receiver.h"
#include "webrtc/modules/video_coding/frame_object.h"
#include "webrtc/modules/video_coding/h264_sprop_parameter_sets.h"
#include "webrtc/modules/video_coding/h264_sps_pps_tracker.h"
#include "webrtc/modules/video_coding/packet_buffer.h"
#include "webrtc/modules/video_coding/video_coding_impl.h"
#include "webrtc/system_wrappers/include/field_trial.h"
#include "webrtc/system_wrappers/include/metrics.h"
#include "webrtc/system_wrappers/include/timestamp_extrapolator.h"
#include "webrtc/system_wrappers/include/trace.h"
#include "webrtc/video/receive_statistics_proxy.h"
#include "webrtc/video/vie_remb.h"
namespace webrtc {
namespace {
constexpr int kPacketBufferStartSize = 32;
constexpr int kPacketBufferMaxSixe = 2048;
}
std::unique_ptr<RtpRtcp> CreateRtpRtcpModule(
ReceiveStatistics* receive_statistics,
Transport* outgoing_transport,
RtcpRttStats* rtt_stats,
RtcpPacketTypeCounterObserver* rtcp_packet_type_counter_observer,
RemoteBitrateEstimator* remote_bitrate_estimator,
TransportSequenceNumberAllocator* transport_sequence_number_allocator) {
RtpRtcp::Configuration configuration;
configuration.audio = false;
configuration.receiver_only = true;
configuration.receive_statistics = receive_statistics;
configuration.outgoing_transport = outgoing_transport;
configuration.intra_frame_callback = nullptr;
configuration.rtt_stats = rtt_stats;
configuration.rtcp_packet_type_counter_observer =
rtcp_packet_type_counter_observer;
configuration.transport_sequence_number_allocator =
transport_sequence_number_allocator;
configuration.send_bitrate_observer = nullptr;
configuration.send_frame_count_observer = nullptr;
configuration.send_side_delay_observer = nullptr;
configuration.send_packet_observer = nullptr;
configuration.bandwidth_callback = nullptr;
configuration.transport_feedback_callback = nullptr;
std::unique_ptr<RtpRtcp> rtp_rtcp(RtpRtcp::CreateRtpRtcp(configuration));
rtp_rtcp->SetSendingStatus(false);
rtp_rtcp->SetSendingMediaStatus(false);
rtp_rtcp->SetRTCPStatus(RtcpMode::kCompound);
return rtp_rtcp;
}
static const int kPacketLogIntervalMs = 10000;
RtpStreamReceiver::RtpStreamReceiver(
vcm::VideoReceiver* video_receiver,
RemoteBitrateEstimator* remote_bitrate_estimator,
Transport* transport,
RtcpRttStats* rtt_stats,
PacketRouter* packet_router,
VieRemb* remb,
const VideoReceiveStream::Config* config,
ReceiveStatisticsProxy* receive_stats_proxy,
ProcessThread* process_thread,
NackSender* nack_sender,
KeyFrameRequestSender* keyframe_request_sender,
video_coding::OnCompleteFrameCallback* complete_frame_callback,
VCMTiming* timing)
: clock_(Clock::GetRealTimeClock()),
config_(*config),
video_receiver_(video_receiver),
remote_bitrate_estimator_(remote_bitrate_estimator),
packet_router_(packet_router),
remb_(remb),
process_thread_(process_thread),
ntp_estimator_(clock_),
rtp_header_parser_(RtpHeaderParser::Create()),
rtp_receiver_(RtpReceiver::CreateVideoReceiver(clock_,
this,
this,
&rtp_payload_registry_)),
rtp_receive_statistics_(ReceiveStatistics::Create(clock_)),
ulpfec_receiver_(UlpfecReceiver::Create(this)),
receiving_(false),
restored_packet_in_use_(false),
last_packet_log_ms_(-1),
rtp_rtcp_(CreateRtpRtcpModule(rtp_receive_statistics_.get(),
transport,
rtt_stats,
receive_stats_proxy,
remote_bitrate_estimator_,
packet_router)),
complete_frame_callback_(complete_frame_callback),
keyframe_request_sender_(keyframe_request_sender),
timing_(timing) {
packet_router_->AddRtpModule(rtp_rtcp_.get());
rtp_receive_statistics_->RegisterRtpStatisticsCallback(receive_stats_proxy);
rtp_receive_statistics_->RegisterRtcpStatisticsCallback(receive_stats_proxy);
RTC_DCHECK(config_.rtp.rtcp_mode != RtcpMode::kOff)
<< "A stream should not be configured with RTCP disabled. This value is "
"reserved for internal usage.";
RTC_DCHECK(config_.rtp.remote_ssrc != 0);
// TODO(pbos): What's an appropriate local_ssrc for receive-only streams?
RTC_DCHECK(config_.rtp.local_ssrc != 0);
RTC_DCHECK(config_.rtp.remote_ssrc != config_.rtp.local_ssrc);
rtp_rtcp_->SetRTCPStatus(config_.rtp.rtcp_mode);
rtp_rtcp_->SetSSRC(config_.rtp.local_ssrc);
rtp_rtcp_->SetKeyFrameRequestMethod(kKeyFrameReqPliRtcp);
if (config_.rtp.remb) {
rtp_rtcp_->SetREMBStatus(true);
remb_->AddReceiveChannel(rtp_rtcp_.get());
}
for (size_t i = 0; i < config_.rtp.extensions.size(); ++i) {
EnableReceiveRtpHeaderExtension(config_.rtp.extensions[i].uri,
config_.rtp.extensions[i].id);
}
static const int kMaxPacketAgeToNack = 450;
const int max_reordering_threshold = (config_.rtp.nack.rtp_history_ms > 0)
? kMaxPacketAgeToNack
: kDefaultMaxReorderingThreshold;
rtp_receive_statistics_->SetMaxReorderingThreshold(max_reordering_threshold);
if (config_.rtp.rtx_ssrc) {
rtp_payload_registry_.SetRtxSsrc(config_.rtp.rtx_ssrc);
for (const auto& kv : config_.rtp.rtx_payload_types) {
RTC_DCHECK(kv.second != 0);
rtp_payload_registry_.SetRtxPayloadType(kv.second, kv.first);
}
}
if (IsUlpfecEnabled()) {
VideoCodec ulpfec_codec = {};
ulpfec_codec.codecType = kVideoCodecULPFEC;
strncpy(ulpfec_codec.plName, "ulpfec", sizeof(ulpfec_codec.plName));
ulpfec_codec.plType = config_.rtp.ulpfec.ulpfec_payload_type;
RTC_CHECK(AddReceiveCodec(ulpfec_codec));
}
if (IsRedEnabled()) {
VideoCodec red_codec = {};
red_codec.codecType = kVideoCodecRED;
strncpy(red_codec.plName, "red", sizeof(red_codec.plName));
red_codec.plType = config_.rtp.ulpfec.red_payload_type;
RTC_CHECK(AddReceiveCodec(red_codec));
if (config_.rtp.ulpfec.red_rtx_payload_type != -1) {
rtp_payload_registry_.SetRtxPayloadType(
config_.rtp.ulpfec.red_rtx_payload_type,
config_.rtp.ulpfec.red_payload_type);
}
}
if (config_.rtp.rtcp_xr.receiver_reference_time_report)
rtp_rtcp_->SetRtcpXrRrtrStatus(true);
// Stats callback for CNAME changes.
rtp_rtcp_->RegisterRtcpStatisticsCallback(receive_stats_proxy);
process_thread_->RegisterModule(rtp_rtcp_.get());
jitter_buffer_experiment_ =
field_trial::FindFullName("WebRTC-NewVideoJitterBuffer") == "Enabled";
if (jitter_buffer_experiment_) {
nack_module_.reset(
new NackModule(clock_, nack_sender, keyframe_request_sender));
process_thread_->RegisterModule(nack_module_.get());
packet_buffer_ = video_coding::PacketBuffer::Create(
clock_, kPacketBufferStartSize, kPacketBufferMaxSixe, this);
reference_finder_.reset(new video_coding::RtpFrameReferenceFinder(this));
}
}
RtpStreamReceiver::~RtpStreamReceiver() {
process_thread_->DeRegisterModule(rtp_rtcp_.get());
if (jitter_buffer_experiment_)
process_thread_->DeRegisterModule(nack_module_.get());
packet_router_->RemoveRtpModule(rtp_rtcp_.get());
rtp_rtcp_->SetREMBStatus(false);
if (config_.rtp.remb) {
remb_->RemoveReceiveChannel(rtp_rtcp_.get());
}
UpdateHistograms();
}
bool RtpStreamReceiver::AddReceiveCodec(
const VideoCodec& video_codec,
const std::map<std::string, std::string>& codec_params) {
pt_codec_params_.insert(make_pair(video_codec.plType, codec_params));
return AddReceiveCodec(video_codec);
}
bool RtpStreamReceiver::AddReceiveCodec(const VideoCodec& video_codec) {
int8_t old_pltype = -1;
if (rtp_payload_registry_.ReceivePayloadType(video_codec, &old_pltype) !=
-1) {
rtp_payload_registry_.DeRegisterReceivePayload(old_pltype);
}
return rtp_payload_registry_.RegisterReceivePayload(video_codec) == 0;
}
uint32_t RtpStreamReceiver::GetRemoteSsrc() const {
return rtp_receiver_->SSRC();
}
int RtpStreamReceiver::GetCsrcs(uint32_t* csrcs) const {
return rtp_receiver_->CSRCs(csrcs);
}
RtpReceiver* RtpStreamReceiver::GetRtpReceiver() const {
return rtp_receiver_.get();
}
int32_t RtpStreamReceiver::OnReceivedPayloadData(
const uint8_t* payload_data,
size_t payload_size,
const WebRtcRTPHeader* rtp_header) {
WebRtcRTPHeader rtp_header_with_ntp = *rtp_header;
rtp_header_with_ntp.ntp_time_ms =
ntp_estimator_.Estimate(rtp_header->header.timestamp);
if (jitter_buffer_experiment_) {
VCMPacket packet(payload_data, payload_size, rtp_header_with_ntp);
timing_->IncomingTimestamp(packet.timestamp, clock_->TimeInMilliseconds());
packet.timesNacked = nack_module_->OnReceivedPacket(packet);
if (packet.codec == kVideoCodecH264) {
// Only when we start to receive packets will we know what payload type
// that will be used. When we know the payload type insert the correct
// sps/pps into the tracker.
if (packet.payloadType != last_payload_type_) {
last_payload_type_ = packet.payloadType;
InsertSpsPpsIntoTracker(packet.payloadType);
}
switch (tracker_.CopyAndFixBitstream(&packet)) {
case video_coding::H264SpsPpsTracker::kRequestKeyframe:
keyframe_request_sender_->RequestKeyFrame();
FALLTHROUGH();
case video_coding::H264SpsPpsTracker::kDrop:
return 0;
case video_coding::H264SpsPpsTracker::kInsert:
break;
}
} else {
uint8_t* data = new uint8_t[packet.sizeBytes];
memcpy(data, packet.dataPtr, packet.sizeBytes);
packet.dataPtr = data;
}
packet_buffer_->InsertPacket(&packet);
} else {
RTC_DCHECK(video_receiver_);
if (video_receiver_->IncomingPacket(payload_data, payload_size,
rtp_header_with_ntp) != 0) {
// Check this...
return -1;
}
}
return 0;
}
bool RtpStreamReceiver::OnRecoveredPacket(const uint8_t* rtp_packet,
size_t rtp_packet_length) {
RTPHeader header;
if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
return false;
}
header.payload_type_frequency = kVideoPayloadTypeFrequency;
bool in_order = IsPacketInOrder(header);
return ReceivePacket(rtp_packet, rtp_packet_length, header, in_order);
}
// TODO(pbos): Remove as soon as audio can handle a changing payload type
// without this callback.
int32_t RtpStreamReceiver::OnInitializeDecoder(
const int8_t payload_type,
const char payload_name[RTP_PAYLOAD_NAME_SIZE],
const int frequency,
const size_t channels,
const uint32_t rate) {
RTC_NOTREACHED();
return 0;
}
void RtpStreamReceiver::OnIncomingSSRCChanged(const uint32_t ssrc) {
rtp_rtcp_->SetRemoteSSRC(ssrc);
}
bool RtpStreamReceiver::DeliverRtp(const uint8_t* rtp_packet,
size_t rtp_packet_length,
const PacketTime& packet_time) {
RTC_DCHECK(remote_bitrate_estimator_);
{
rtc::CritScope lock(&receive_cs_);
if (!receiving_) {
return false;
}
}
RTPHeader header;
if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length,
&header)) {
return false;
}
size_t payload_length = rtp_packet_length - header.headerLength;
int64_t arrival_time_ms;
int64_t now_ms = clock_->TimeInMilliseconds();
if (packet_time.timestamp != -1)
arrival_time_ms = (packet_time.timestamp + 500) / 1000;
else
arrival_time_ms = now_ms;
{
// Periodically log the RTP header of incoming packets.
rtc::CritScope lock(&receive_cs_);
if (now_ms - last_packet_log_ms_ > kPacketLogIntervalMs) {
std::stringstream ss;
ss << "Packet received on SSRC: " << header.ssrc << " with payload type: "
<< static_cast<int>(header.payloadType) << ", timestamp: "
<< header.timestamp << ", sequence number: " << header.sequenceNumber
<< ", arrival time: " << arrival_time_ms;
if (header.extension.hasTransmissionTimeOffset)
ss << ", toffset: " << header.extension.transmissionTimeOffset;
if (header.extension.hasAbsoluteSendTime)
ss << ", abs send time: " << header.extension.absoluteSendTime;
LOG(LS_INFO) << ss.str();
last_packet_log_ms_ = now_ms;
}
}
remote_bitrate_estimator_->IncomingPacket(arrival_time_ms, payload_length,
header);
header.payload_type_frequency = kVideoPayloadTypeFrequency;
bool in_order = IsPacketInOrder(header);
rtp_payload_registry_.SetIncomingPayloadType(header);
bool ret = ReceivePacket(rtp_packet, rtp_packet_length, header, in_order);
// Update receive statistics after ReceivePacket.
// Receive statistics will be reset if the payload type changes (make sure
// that the first packet is included in the stats).
rtp_receive_statistics_->IncomingPacket(
header, rtp_packet_length, IsPacketRetransmitted(header, in_order));
return ret;
}
int32_t RtpStreamReceiver::RequestKeyFrame() {
return rtp_rtcp_->RequestKeyFrame();
}
int32_t RtpStreamReceiver::SliceLossIndicationRequest(
const uint64_t picture_id) {
return rtp_rtcp_->SendRTCPSliceLossIndication(
static_cast<uint8_t>(picture_id));
}
bool RtpStreamReceiver::IsUlpfecEnabled() const {
return config_.rtp.ulpfec.ulpfec_payload_type != -1;
}
bool RtpStreamReceiver::IsRedEnabled() const {
return config_.rtp.ulpfec.red_payload_type != -1;
}
bool RtpStreamReceiver::IsRetransmissionsEnabled() const {
return config_.rtp.nack.rtp_history_ms > 0;
}
void RtpStreamReceiver::RequestPacketRetransmit(
const std::vector<uint16_t>& sequence_numbers) {
rtp_rtcp_->SendNack(sequence_numbers);
}
int32_t RtpStreamReceiver::ResendPackets(const uint16_t* sequence_numbers,
uint16_t length) {
return rtp_rtcp_->SendNACK(sequence_numbers, length);
}
void RtpStreamReceiver::OnReceivedFrame(
std::unique_ptr<video_coding::RtpFrameObject> frame) {
reference_finder_->ManageFrame(std::move(frame));
}
void RtpStreamReceiver::OnCompleteFrame(
std::unique_ptr<video_coding::FrameObject> frame) {
{
rtc::CritScope lock(&last_seq_num_cs_);
video_coding::RtpFrameObject* rtp_frame =
static_cast<video_coding::RtpFrameObject*>(frame.get());
last_seq_num_for_pic_id_[rtp_frame->picture_id] = rtp_frame->last_seq_num();
}
complete_frame_callback_->OnCompleteFrame(std::move(frame));
}
void RtpStreamReceiver::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) {
if (jitter_buffer_experiment_)
nack_module_->UpdateRtt(max_rtt_ms);
}
bool RtpStreamReceiver::ReceivePacket(const uint8_t* packet,
size_t packet_length,
const RTPHeader& header,
bool in_order) {
if (rtp_payload_registry_.IsEncapsulated(header)) {
return ParseAndHandleEncapsulatingHeader(packet, packet_length, header);
}
const uint8_t* payload = packet + header.headerLength;
assert(packet_length >= header.headerLength);
size_t payload_length = packet_length - header.headerLength;
PayloadUnion payload_specific;
if (!rtp_payload_registry_.GetPayloadSpecifics(header.payloadType,
&payload_specific)) {
return false;
}
return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
payload_specific, in_order);
}
bool RtpStreamReceiver::ParseAndHandleEncapsulatingHeader(
const uint8_t* packet, size_t packet_length, const RTPHeader& header) {
if (rtp_payload_registry_.IsRed(header)) {
int8_t ulpfec_pt = rtp_payload_registry_.ulpfec_payload_type();
if (packet[header.headerLength] == ulpfec_pt) {
rtp_receive_statistics_->FecPacketReceived(header, packet_length);
// Notify video_receiver about received FEC packets to avoid NACKing these
// packets.
NotifyReceiverOfFecPacket(header);
}
if (ulpfec_receiver_->AddReceivedRedPacket(header, packet, packet_length,
ulpfec_pt) != 0) {
return false;
}
return ulpfec_receiver_->ProcessReceivedFec() == 0;
} else if (rtp_payload_registry_.IsRtx(header)) {
if (header.headerLength + header.paddingLength == packet_length) {
// This is an empty packet and should be silently dropped before trying to
// parse the RTX header.
return true;
}
// Remove the RTX header and parse the original RTP header.
if (packet_length < header.headerLength)
return false;
if (packet_length > sizeof(restored_packet_))
return false;
rtc::CritScope lock(&receive_cs_);
if (restored_packet_in_use_) {
LOG(LS_WARNING) << "Multiple RTX headers detected, dropping packet.";
return false;
}
if (!rtp_payload_registry_.RestoreOriginalPacket(
restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
header)) {
LOG(LS_WARNING) << "Incoming RTX packet: Invalid RTP header ssrc: "
<< header.ssrc << " payload type: "
<< static_cast<int>(header.payloadType);
return false;
}
restored_packet_in_use_ = true;
bool ret = OnRecoveredPacket(restored_packet_, packet_length);
restored_packet_in_use_ = false;
return ret;
}
return false;
}
void RtpStreamReceiver::NotifyReceiverOfFecPacket(const RTPHeader& header) {
int8_t last_media_payload_type =
rtp_payload_registry_.last_received_media_payload_type();
if (last_media_payload_type < 0) {
LOG(LS_WARNING) << "Failed to get last media payload type.";
return;
}
// Fake an empty media packet.
WebRtcRTPHeader rtp_header = {};
rtp_header.header = header;
rtp_header.header.payloadType = last_media_payload_type;
rtp_header.header.paddingLength = 0;
PayloadUnion payload_specific;
if (!rtp_payload_registry_.GetPayloadSpecifics(last_media_payload_type,
&payload_specific)) {
LOG(LS_WARNING) << "Failed to get payload specifics.";
return;
}
rtp_header.type.Video.codec = payload_specific.Video.videoCodecType;
rtp_header.type.Video.rotation = kVideoRotation_0;
if (header.extension.hasVideoRotation) {
rtp_header.type.Video.rotation = header.extension.videoRotation;
}
rtp_header.type.Video.playout_delay = header.extension.playout_delay;
OnReceivedPayloadData(nullptr, 0, &rtp_header);
}
bool RtpStreamReceiver::DeliverRtcp(const uint8_t* rtcp_packet,
size_t rtcp_packet_length) {
{
rtc::CritScope lock(&receive_cs_);
if (!receiving_) {
return false;
}
}
rtp_rtcp_->IncomingRtcpPacket(rtcp_packet, rtcp_packet_length);
int64_t rtt = 0;
rtp_rtcp_->RTT(rtp_receiver_->SSRC(), &rtt, nullptr, nullptr, nullptr);
if (rtt == 0) {
// Waiting for valid rtt.
return true;
}
uint32_t ntp_secs = 0;
uint32_t ntp_frac = 0;
uint32_t rtp_timestamp = 0;
if (rtp_rtcp_->RemoteNTP(&ntp_secs, &ntp_frac, nullptr, nullptr,
&rtp_timestamp) != 0) {
// Waiting for RTCP.
return true;
}
ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
return true;
}
void RtpStreamReceiver::FrameContinuous(uint16_t picture_id) {
if (jitter_buffer_experiment_) {
int seq_num = -1;
{
rtc::CritScope lock(&last_seq_num_cs_);
auto seq_num_it = last_seq_num_for_pic_id_.find(picture_id);
if (seq_num_it != last_seq_num_for_pic_id_.end())
seq_num = seq_num_it->second;
}
if (seq_num != -1)
nack_module_->ClearUpTo(seq_num);
}
}
void RtpStreamReceiver::FrameDecoded(uint16_t picture_id) {
if (jitter_buffer_experiment_) {
int seq_num = -1;
{
rtc::CritScope lock(&last_seq_num_cs_);
auto seq_num_it = last_seq_num_for_pic_id_.find(picture_id);
if (seq_num_it != last_seq_num_for_pic_id_.end()) {
seq_num = seq_num_it->second;
last_seq_num_for_pic_id_.erase(last_seq_num_for_pic_id_.begin(),
++seq_num_it);
}
}
if (seq_num != -1) {
packet_buffer_->ClearTo(seq_num);
reference_finder_->ClearTo(seq_num);
}
}
}
void RtpStreamReceiver::SignalNetworkState(NetworkState state) {
rtp_rtcp_->SetRTCPStatus(state == kNetworkUp ? config_.rtp.rtcp_mode
: RtcpMode::kOff);
}
void RtpStreamReceiver::StartReceive() {
rtc::CritScope lock(&receive_cs_);
receiving_ = true;
}
void RtpStreamReceiver::StopReceive() {
rtc::CritScope lock(&receive_cs_);
receiving_ = false;
}
bool RtpStreamReceiver::IsPacketInOrder(const RTPHeader& header) const {
StreamStatistician* statistician =
rtp_receive_statistics_->GetStatistician(header.ssrc);
if (!statistician)
return false;
return statistician->IsPacketInOrder(header.sequenceNumber);
}
bool RtpStreamReceiver::IsPacketRetransmitted(const RTPHeader& header,
bool in_order) const {
// Retransmissions are handled separately if RTX is enabled.
if (rtp_payload_registry_.RtxEnabled())
return false;
StreamStatistician* statistician =
rtp_receive_statistics_->GetStatistician(header.ssrc);
if (!statistician)
return false;
// Check if this is a retransmission.
int64_t min_rtt = 0;
rtp_rtcp_->RTT(rtp_receiver_->SSRC(), nullptr, nullptr, &min_rtt, nullptr);
return !in_order &&
statistician->IsRetransmitOfOldPacket(header, min_rtt);
}
void RtpStreamReceiver::UpdateHistograms() {
FecPacketCounter counter = ulpfec_receiver_->GetPacketCounter();
if (counter.first_packet_time_ms == -1)
return;
int64_t elapsed_sec =
(clock_->TimeInMilliseconds() - counter.first_packet_time_ms) / 1000;
if (elapsed_sec < metrics::kMinRunTimeInSeconds)
return;
if (counter.num_packets > 0) {
RTC_HISTOGRAM_PERCENTAGE(
"WebRTC.Video.ReceivedFecPacketsInPercent",
static_cast<int>(counter.num_fec_packets * 100 / counter.num_packets));
}
if (counter.num_fec_packets > 0) {
RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.RecoveredMediaPacketsInPercentOfFec",
static_cast<int>(counter.num_recovered_packets *
100 / counter.num_fec_packets));
}
}
void RtpStreamReceiver::EnableReceiveRtpHeaderExtension(
const std::string& extension, int id) {
// One-byte-extension local identifiers are in the range 1-14 inclusive.
RTC_DCHECK_GE(id, 1);
RTC_DCHECK_LE(id, 14);
RTC_DCHECK(RtpExtension::IsSupportedForVideo(extension));
RTC_CHECK(rtp_header_parser_->RegisterRtpHeaderExtension(
StringToRtpExtensionType(extension), id));
}
void RtpStreamReceiver::InsertSpsPpsIntoTracker(uint8_t payload_type) {
auto codec_params_it = pt_codec_params_.find(payload_type);
if (codec_params_it == pt_codec_params_.end())
return;
LOG(LS_INFO) << "Found out of band supplied codec parameters for"
<< " payload type: " << static_cast<int>(payload_type);
H264SpropParameterSets sprop_decoder;
auto sprop_base64_it =
codec_params_it->second.find(cricket::kH264FmtpSpropParameterSets);
if (sprop_base64_it == codec_params_it->second.end())
return;
if (!sprop_decoder.DecodeSprop(sprop_base64_it->second.c_str()))
return;
tracker_.InsertSpsPpsNalus(sprop_decoder.sps_nalu(),
sprop_decoder.pps_nalu());
}
} // namespace webrtc
Only update VCMTiming on every received frame instead of every received packet.
BUG=webrtc:5514, chromium:682636
Review-Url: https://codereview.webrtc.org/2663513003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#16345}
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video/rtp_stream_receiver.h"
#include <vector>
#include <utility>
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/common_types.h"
#include "webrtc/config.h"
#include "webrtc/media/base/mediaconstants.h"
#include "webrtc/modules/pacing/packet_router.h"
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_cvo.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_header_parser.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h"
#include "webrtc/modules/rtp_rtcp/include/ulpfec_receiver.h"
#include "webrtc/modules/video_coding/frame_object.h"
#include "webrtc/modules/video_coding/h264_sprop_parameter_sets.h"
#include "webrtc/modules/video_coding/h264_sps_pps_tracker.h"
#include "webrtc/modules/video_coding/packet_buffer.h"
#include "webrtc/modules/video_coding/video_coding_impl.h"
#include "webrtc/system_wrappers/include/field_trial.h"
#include "webrtc/system_wrappers/include/metrics.h"
#include "webrtc/system_wrappers/include/timestamp_extrapolator.h"
#include "webrtc/system_wrappers/include/trace.h"
#include "webrtc/video/receive_statistics_proxy.h"
#include "webrtc/video/vie_remb.h"
namespace webrtc {
namespace {
constexpr int kPacketBufferStartSize = 32;
constexpr int kPacketBufferMaxSixe = 2048;
}
std::unique_ptr<RtpRtcp> CreateRtpRtcpModule(
ReceiveStatistics* receive_statistics,
Transport* outgoing_transport,
RtcpRttStats* rtt_stats,
RtcpPacketTypeCounterObserver* rtcp_packet_type_counter_observer,
RemoteBitrateEstimator* remote_bitrate_estimator,
TransportSequenceNumberAllocator* transport_sequence_number_allocator) {
RtpRtcp::Configuration configuration;
configuration.audio = false;
configuration.receiver_only = true;
configuration.receive_statistics = receive_statistics;
configuration.outgoing_transport = outgoing_transport;
configuration.intra_frame_callback = nullptr;
configuration.rtt_stats = rtt_stats;
configuration.rtcp_packet_type_counter_observer =
rtcp_packet_type_counter_observer;
configuration.transport_sequence_number_allocator =
transport_sequence_number_allocator;
configuration.send_bitrate_observer = nullptr;
configuration.send_frame_count_observer = nullptr;
configuration.send_side_delay_observer = nullptr;
configuration.send_packet_observer = nullptr;
configuration.bandwidth_callback = nullptr;
configuration.transport_feedback_callback = nullptr;
std::unique_ptr<RtpRtcp> rtp_rtcp(RtpRtcp::CreateRtpRtcp(configuration));
rtp_rtcp->SetSendingStatus(false);
rtp_rtcp->SetSendingMediaStatus(false);
rtp_rtcp->SetRTCPStatus(RtcpMode::kCompound);
return rtp_rtcp;
}
static const int kPacketLogIntervalMs = 10000;
RtpStreamReceiver::RtpStreamReceiver(
vcm::VideoReceiver* video_receiver,
RemoteBitrateEstimator* remote_bitrate_estimator,
Transport* transport,
RtcpRttStats* rtt_stats,
PacketRouter* packet_router,
VieRemb* remb,
const VideoReceiveStream::Config* config,
ReceiveStatisticsProxy* receive_stats_proxy,
ProcessThread* process_thread,
NackSender* nack_sender,
KeyFrameRequestSender* keyframe_request_sender,
video_coding::OnCompleteFrameCallback* complete_frame_callback,
VCMTiming* timing)
: clock_(Clock::GetRealTimeClock()),
config_(*config),
video_receiver_(video_receiver),
remote_bitrate_estimator_(remote_bitrate_estimator),
packet_router_(packet_router),
remb_(remb),
process_thread_(process_thread),
ntp_estimator_(clock_),
rtp_header_parser_(RtpHeaderParser::Create()),
rtp_receiver_(RtpReceiver::CreateVideoReceiver(clock_,
this,
this,
&rtp_payload_registry_)),
rtp_receive_statistics_(ReceiveStatistics::Create(clock_)),
ulpfec_receiver_(UlpfecReceiver::Create(this)),
receiving_(false),
restored_packet_in_use_(false),
last_packet_log_ms_(-1),
rtp_rtcp_(CreateRtpRtcpModule(rtp_receive_statistics_.get(),
transport,
rtt_stats,
receive_stats_proxy,
remote_bitrate_estimator_,
packet_router)),
complete_frame_callback_(complete_frame_callback),
keyframe_request_sender_(keyframe_request_sender),
timing_(timing) {
packet_router_->AddRtpModule(rtp_rtcp_.get());
rtp_receive_statistics_->RegisterRtpStatisticsCallback(receive_stats_proxy);
rtp_receive_statistics_->RegisterRtcpStatisticsCallback(receive_stats_proxy);
RTC_DCHECK(config_.rtp.rtcp_mode != RtcpMode::kOff)
<< "A stream should not be configured with RTCP disabled. This value is "
"reserved for internal usage.";
RTC_DCHECK(config_.rtp.remote_ssrc != 0);
// TODO(pbos): What's an appropriate local_ssrc for receive-only streams?
RTC_DCHECK(config_.rtp.local_ssrc != 0);
RTC_DCHECK(config_.rtp.remote_ssrc != config_.rtp.local_ssrc);
rtp_rtcp_->SetRTCPStatus(config_.rtp.rtcp_mode);
rtp_rtcp_->SetSSRC(config_.rtp.local_ssrc);
rtp_rtcp_->SetKeyFrameRequestMethod(kKeyFrameReqPliRtcp);
if (config_.rtp.remb) {
rtp_rtcp_->SetREMBStatus(true);
remb_->AddReceiveChannel(rtp_rtcp_.get());
}
for (size_t i = 0; i < config_.rtp.extensions.size(); ++i) {
EnableReceiveRtpHeaderExtension(config_.rtp.extensions[i].uri,
config_.rtp.extensions[i].id);
}
static const int kMaxPacketAgeToNack = 450;
const int max_reordering_threshold = (config_.rtp.nack.rtp_history_ms > 0)
? kMaxPacketAgeToNack
: kDefaultMaxReorderingThreshold;
rtp_receive_statistics_->SetMaxReorderingThreshold(max_reordering_threshold);
if (config_.rtp.rtx_ssrc) {
rtp_payload_registry_.SetRtxSsrc(config_.rtp.rtx_ssrc);
for (const auto& kv : config_.rtp.rtx_payload_types) {
RTC_DCHECK(kv.second != 0);
rtp_payload_registry_.SetRtxPayloadType(kv.second, kv.first);
}
}
if (IsUlpfecEnabled()) {
VideoCodec ulpfec_codec = {};
ulpfec_codec.codecType = kVideoCodecULPFEC;
strncpy(ulpfec_codec.plName, "ulpfec", sizeof(ulpfec_codec.plName));
ulpfec_codec.plType = config_.rtp.ulpfec.ulpfec_payload_type;
RTC_CHECK(AddReceiveCodec(ulpfec_codec));
}
if (IsRedEnabled()) {
VideoCodec red_codec = {};
red_codec.codecType = kVideoCodecRED;
strncpy(red_codec.plName, "red", sizeof(red_codec.plName));
red_codec.plType = config_.rtp.ulpfec.red_payload_type;
RTC_CHECK(AddReceiveCodec(red_codec));
if (config_.rtp.ulpfec.red_rtx_payload_type != -1) {
rtp_payload_registry_.SetRtxPayloadType(
config_.rtp.ulpfec.red_rtx_payload_type,
config_.rtp.ulpfec.red_payload_type);
}
}
if (config_.rtp.rtcp_xr.receiver_reference_time_report)
rtp_rtcp_->SetRtcpXrRrtrStatus(true);
// Stats callback for CNAME changes.
rtp_rtcp_->RegisterRtcpStatisticsCallback(receive_stats_proxy);
process_thread_->RegisterModule(rtp_rtcp_.get());
jitter_buffer_experiment_ =
field_trial::FindFullName("WebRTC-NewVideoJitterBuffer") == "Enabled";
if (jitter_buffer_experiment_) {
nack_module_.reset(
new NackModule(clock_, nack_sender, keyframe_request_sender));
process_thread_->RegisterModule(nack_module_.get());
packet_buffer_ = video_coding::PacketBuffer::Create(
clock_, kPacketBufferStartSize, kPacketBufferMaxSixe, this);
reference_finder_.reset(new video_coding::RtpFrameReferenceFinder(this));
}
}
RtpStreamReceiver::~RtpStreamReceiver() {
process_thread_->DeRegisterModule(rtp_rtcp_.get());
if (jitter_buffer_experiment_)
process_thread_->DeRegisterModule(nack_module_.get());
packet_router_->RemoveRtpModule(rtp_rtcp_.get());
rtp_rtcp_->SetREMBStatus(false);
if (config_.rtp.remb) {
remb_->RemoveReceiveChannel(rtp_rtcp_.get());
}
UpdateHistograms();
}
bool RtpStreamReceiver::AddReceiveCodec(
const VideoCodec& video_codec,
const std::map<std::string, std::string>& codec_params) {
pt_codec_params_.insert(make_pair(video_codec.plType, codec_params));
return AddReceiveCodec(video_codec);
}
bool RtpStreamReceiver::AddReceiveCodec(const VideoCodec& video_codec) {
int8_t old_pltype = -1;
if (rtp_payload_registry_.ReceivePayloadType(video_codec, &old_pltype) !=
-1) {
rtp_payload_registry_.DeRegisterReceivePayload(old_pltype);
}
return rtp_payload_registry_.RegisterReceivePayload(video_codec) == 0;
}
uint32_t RtpStreamReceiver::GetRemoteSsrc() const {
return rtp_receiver_->SSRC();
}
int RtpStreamReceiver::GetCsrcs(uint32_t* csrcs) const {
return rtp_receiver_->CSRCs(csrcs);
}
RtpReceiver* RtpStreamReceiver::GetRtpReceiver() const {
return rtp_receiver_.get();
}
int32_t RtpStreamReceiver::OnReceivedPayloadData(
const uint8_t* payload_data,
size_t payload_size,
const WebRtcRTPHeader* rtp_header) {
WebRtcRTPHeader rtp_header_with_ntp = *rtp_header;
rtp_header_with_ntp.ntp_time_ms =
ntp_estimator_.Estimate(rtp_header->header.timestamp);
if (jitter_buffer_experiment_) {
VCMPacket packet(payload_data, payload_size, rtp_header_with_ntp);
packet.timesNacked = nack_module_->OnReceivedPacket(packet);
if (packet.codec == kVideoCodecH264) {
// Only when we start to receive packets will we know what payload type
// that will be used. When we know the payload type insert the correct
// sps/pps into the tracker.
if (packet.payloadType != last_payload_type_) {
last_payload_type_ = packet.payloadType;
InsertSpsPpsIntoTracker(packet.payloadType);
}
switch (tracker_.CopyAndFixBitstream(&packet)) {
case video_coding::H264SpsPpsTracker::kRequestKeyframe:
keyframe_request_sender_->RequestKeyFrame();
FALLTHROUGH();
case video_coding::H264SpsPpsTracker::kDrop:
return 0;
case video_coding::H264SpsPpsTracker::kInsert:
break;
}
} else {
uint8_t* data = new uint8_t[packet.sizeBytes];
memcpy(data, packet.dataPtr, packet.sizeBytes);
packet.dataPtr = data;
}
packet_buffer_->InsertPacket(&packet);
} else {
RTC_DCHECK(video_receiver_);
if (video_receiver_->IncomingPacket(payload_data, payload_size,
rtp_header_with_ntp) != 0) {
// Check this...
return -1;
}
}
return 0;
}
bool RtpStreamReceiver::OnRecoveredPacket(const uint8_t* rtp_packet,
size_t rtp_packet_length) {
RTPHeader header;
if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
return false;
}
header.payload_type_frequency = kVideoPayloadTypeFrequency;
bool in_order = IsPacketInOrder(header);
return ReceivePacket(rtp_packet, rtp_packet_length, header, in_order);
}
// TODO(pbos): Remove as soon as audio can handle a changing payload type
// without this callback.
int32_t RtpStreamReceiver::OnInitializeDecoder(
const int8_t payload_type,
const char payload_name[RTP_PAYLOAD_NAME_SIZE],
const int frequency,
const size_t channels,
const uint32_t rate) {
RTC_NOTREACHED();
return 0;
}
void RtpStreamReceiver::OnIncomingSSRCChanged(const uint32_t ssrc) {
rtp_rtcp_->SetRemoteSSRC(ssrc);
}
bool RtpStreamReceiver::DeliverRtp(const uint8_t* rtp_packet,
size_t rtp_packet_length,
const PacketTime& packet_time) {
RTC_DCHECK(remote_bitrate_estimator_);
{
rtc::CritScope lock(&receive_cs_);
if (!receiving_) {
return false;
}
}
RTPHeader header;
if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length,
&header)) {
return false;
}
size_t payload_length = rtp_packet_length - header.headerLength;
int64_t arrival_time_ms;
int64_t now_ms = clock_->TimeInMilliseconds();
if (packet_time.timestamp != -1)
arrival_time_ms = (packet_time.timestamp + 500) / 1000;
else
arrival_time_ms = now_ms;
{
// Periodically log the RTP header of incoming packets.
rtc::CritScope lock(&receive_cs_);
if (now_ms - last_packet_log_ms_ > kPacketLogIntervalMs) {
std::stringstream ss;
ss << "Packet received on SSRC: " << header.ssrc << " with payload type: "
<< static_cast<int>(header.payloadType) << ", timestamp: "
<< header.timestamp << ", sequence number: " << header.sequenceNumber
<< ", arrival time: " << arrival_time_ms;
if (header.extension.hasTransmissionTimeOffset)
ss << ", toffset: " << header.extension.transmissionTimeOffset;
if (header.extension.hasAbsoluteSendTime)
ss << ", abs send time: " << header.extension.absoluteSendTime;
LOG(LS_INFO) << ss.str();
last_packet_log_ms_ = now_ms;
}
}
remote_bitrate_estimator_->IncomingPacket(arrival_time_ms, payload_length,
header);
header.payload_type_frequency = kVideoPayloadTypeFrequency;
bool in_order = IsPacketInOrder(header);
rtp_payload_registry_.SetIncomingPayloadType(header);
bool ret = ReceivePacket(rtp_packet, rtp_packet_length, header, in_order);
// Update receive statistics after ReceivePacket.
// Receive statistics will be reset if the payload type changes (make sure
// that the first packet is included in the stats).
rtp_receive_statistics_->IncomingPacket(
header, rtp_packet_length, IsPacketRetransmitted(header, in_order));
return ret;
}
int32_t RtpStreamReceiver::RequestKeyFrame() {
return rtp_rtcp_->RequestKeyFrame();
}
int32_t RtpStreamReceiver::SliceLossIndicationRequest(
const uint64_t picture_id) {
return rtp_rtcp_->SendRTCPSliceLossIndication(
static_cast<uint8_t>(picture_id));
}
bool RtpStreamReceiver::IsUlpfecEnabled() const {
return config_.rtp.ulpfec.ulpfec_payload_type != -1;
}
bool RtpStreamReceiver::IsRedEnabled() const {
return config_.rtp.ulpfec.red_payload_type != -1;
}
bool RtpStreamReceiver::IsRetransmissionsEnabled() const {
return config_.rtp.nack.rtp_history_ms > 0;
}
void RtpStreamReceiver::RequestPacketRetransmit(
const std::vector<uint16_t>& sequence_numbers) {
rtp_rtcp_->SendNack(sequence_numbers);
}
int32_t RtpStreamReceiver::ResendPackets(const uint16_t* sequence_numbers,
uint16_t length) {
return rtp_rtcp_->SendNACK(sequence_numbers, length);
}
void RtpStreamReceiver::OnReceivedFrame(
std::unique_ptr<video_coding::RtpFrameObject> frame) {
if (!frame->delayed_by_retransmission())
timing_->IncomingTimestamp(frame->timestamp, clock_->TimeInMilliseconds());
reference_finder_->ManageFrame(std::move(frame));
}
void RtpStreamReceiver::OnCompleteFrame(
std::unique_ptr<video_coding::FrameObject> frame) {
{
rtc::CritScope lock(&last_seq_num_cs_);
video_coding::RtpFrameObject* rtp_frame =
static_cast<video_coding::RtpFrameObject*>(frame.get());
last_seq_num_for_pic_id_[rtp_frame->picture_id] = rtp_frame->last_seq_num();
}
complete_frame_callback_->OnCompleteFrame(std::move(frame));
}
void RtpStreamReceiver::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) {
if (jitter_buffer_experiment_)
nack_module_->UpdateRtt(max_rtt_ms);
}
bool RtpStreamReceiver::ReceivePacket(const uint8_t* packet,
size_t packet_length,
const RTPHeader& header,
bool in_order) {
if (rtp_payload_registry_.IsEncapsulated(header)) {
return ParseAndHandleEncapsulatingHeader(packet, packet_length, header);
}
const uint8_t* payload = packet + header.headerLength;
assert(packet_length >= header.headerLength);
size_t payload_length = packet_length - header.headerLength;
PayloadUnion payload_specific;
if (!rtp_payload_registry_.GetPayloadSpecifics(header.payloadType,
&payload_specific)) {
return false;
}
return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
payload_specific, in_order);
}
bool RtpStreamReceiver::ParseAndHandleEncapsulatingHeader(
const uint8_t* packet, size_t packet_length, const RTPHeader& header) {
if (rtp_payload_registry_.IsRed(header)) {
int8_t ulpfec_pt = rtp_payload_registry_.ulpfec_payload_type();
if (packet[header.headerLength] == ulpfec_pt) {
rtp_receive_statistics_->FecPacketReceived(header, packet_length);
// Notify video_receiver about received FEC packets to avoid NACKing these
// packets.
NotifyReceiverOfFecPacket(header);
}
if (ulpfec_receiver_->AddReceivedRedPacket(header, packet, packet_length,
ulpfec_pt) != 0) {
return false;
}
return ulpfec_receiver_->ProcessReceivedFec() == 0;
} else if (rtp_payload_registry_.IsRtx(header)) {
if (header.headerLength + header.paddingLength == packet_length) {
// This is an empty packet and should be silently dropped before trying to
// parse the RTX header.
return true;
}
// Remove the RTX header and parse the original RTP header.
if (packet_length < header.headerLength)
return false;
if (packet_length > sizeof(restored_packet_))
return false;
rtc::CritScope lock(&receive_cs_);
if (restored_packet_in_use_) {
LOG(LS_WARNING) << "Multiple RTX headers detected, dropping packet.";
return false;
}
if (!rtp_payload_registry_.RestoreOriginalPacket(
restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
header)) {
LOG(LS_WARNING) << "Incoming RTX packet: Invalid RTP header ssrc: "
<< header.ssrc << " payload type: "
<< static_cast<int>(header.payloadType);
return false;
}
restored_packet_in_use_ = true;
bool ret = OnRecoveredPacket(restored_packet_, packet_length);
restored_packet_in_use_ = false;
return ret;
}
return false;
}
void RtpStreamReceiver::NotifyReceiverOfFecPacket(const RTPHeader& header) {
int8_t last_media_payload_type =
rtp_payload_registry_.last_received_media_payload_type();
if (last_media_payload_type < 0) {
LOG(LS_WARNING) << "Failed to get last media payload type.";
return;
}
// Fake an empty media packet.
WebRtcRTPHeader rtp_header = {};
rtp_header.header = header;
rtp_header.header.payloadType = last_media_payload_type;
rtp_header.header.paddingLength = 0;
PayloadUnion payload_specific;
if (!rtp_payload_registry_.GetPayloadSpecifics(last_media_payload_type,
&payload_specific)) {
LOG(LS_WARNING) << "Failed to get payload specifics.";
return;
}
rtp_header.type.Video.codec = payload_specific.Video.videoCodecType;
rtp_header.type.Video.rotation = kVideoRotation_0;
if (header.extension.hasVideoRotation) {
rtp_header.type.Video.rotation = header.extension.videoRotation;
}
rtp_header.type.Video.playout_delay = header.extension.playout_delay;
OnReceivedPayloadData(nullptr, 0, &rtp_header);
}
bool RtpStreamReceiver::DeliverRtcp(const uint8_t* rtcp_packet,
size_t rtcp_packet_length) {
{
rtc::CritScope lock(&receive_cs_);
if (!receiving_) {
return false;
}
}
rtp_rtcp_->IncomingRtcpPacket(rtcp_packet, rtcp_packet_length);
int64_t rtt = 0;
rtp_rtcp_->RTT(rtp_receiver_->SSRC(), &rtt, nullptr, nullptr, nullptr);
if (rtt == 0) {
// Waiting for valid rtt.
return true;
}
uint32_t ntp_secs = 0;
uint32_t ntp_frac = 0;
uint32_t rtp_timestamp = 0;
if (rtp_rtcp_->RemoteNTP(&ntp_secs, &ntp_frac, nullptr, nullptr,
&rtp_timestamp) != 0) {
// Waiting for RTCP.
return true;
}
ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
return true;
}
void RtpStreamReceiver::FrameContinuous(uint16_t picture_id) {
if (jitter_buffer_experiment_) {
int seq_num = -1;
{
rtc::CritScope lock(&last_seq_num_cs_);
auto seq_num_it = last_seq_num_for_pic_id_.find(picture_id);
if (seq_num_it != last_seq_num_for_pic_id_.end())
seq_num = seq_num_it->second;
}
if (seq_num != -1)
nack_module_->ClearUpTo(seq_num);
}
}
void RtpStreamReceiver::FrameDecoded(uint16_t picture_id) {
if (jitter_buffer_experiment_) {
int seq_num = -1;
{
rtc::CritScope lock(&last_seq_num_cs_);
auto seq_num_it = last_seq_num_for_pic_id_.find(picture_id);
if (seq_num_it != last_seq_num_for_pic_id_.end()) {
seq_num = seq_num_it->second;
last_seq_num_for_pic_id_.erase(last_seq_num_for_pic_id_.begin(),
++seq_num_it);
}
}
if (seq_num != -1) {
packet_buffer_->ClearTo(seq_num);
reference_finder_->ClearTo(seq_num);
}
}
}
void RtpStreamReceiver::SignalNetworkState(NetworkState state) {
rtp_rtcp_->SetRTCPStatus(state == kNetworkUp ? config_.rtp.rtcp_mode
: RtcpMode::kOff);
}
void RtpStreamReceiver::StartReceive() {
rtc::CritScope lock(&receive_cs_);
receiving_ = true;
}
void RtpStreamReceiver::StopReceive() {
rtc::CritScope lock(&receive_cs_);
receiving_ = false;
}
bool RtpStreamReceiver::IsPacketInOrder(const RTPHeader& header) const {
StreamStatistician* statistician =
rtp_receive_statistics_->GetStatistician(header.ssrc);
if (!statistician)
return false;
return statistician->IsPacketInOrder(header.sequenceNumber);
}
bool RtpStreamReceiver::IsPacketRetransmitted(const RTPHeader& header,
bool in_order) const {
// Retransmissions are handled separately if RTX is enabled.
if (rtp_payload_registry_.RtxEnabled())
return false;
StreamStatistician* statistician =
rtp_receive_statistics_->GetStatistician(header.ssrc);
if (!statistician)
return false;
// Check if this is a retransmission.
int64_t min_rtt = 0;
rtp_rtcp_->RTT(rtp_receiver_->SSRC(), nullptr, nullptr, &min_rtt, nullptr);
return !in_order &&
statistician->IsRetransmitOfOldPacket(header, min_rtt);
}
void RtpStreamReceiver::UpdateHistograms() {
FecPacketCounter counter = ulpfec_receiver_->GetPacketCounter();
if (counter.first_packet_time_ms == -1)
return;
int64_t elapsed_sec =
(clock_->TimeInMilliseconds() - counter.first_packet_time_ms) / 1000;
if (elapsed_sec < metrics::kMinRunTimeInSeconds)
return;
if (counter.num_packets > 0) {
RTC_HISTOGRAM_PERCENTAGE(
"WebRTC.Video.ReceivedFecPacketsInPercent",
static_cast<int>(counter.num_fec_packets * 100 / counter.num_packets));
}
if (counter.num_fec_packets > 0) {
RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.RecoveredMediaPacketsInPercentOfFec",
static_cast<int>(counter.num_recovered_packets *
100 / counter.num_fec_packets));
}
}
void RtpStreamReceiver::EnableReceiveRtpHeaderExtension(
const std::string& extension, int id) {
// One-byte-extension local identifiers are in the range 1-14 inclusive.
RTC_DCHECK_GE(id, 1);
RTC_DCHECK_LE(id, 14);
RTC_DCHECK(RtpExtension::IsSupportedForVideo(extension));
RTC_CHECK(rtp_header_parser_->RegisterRtpHeaderExtension(
StringToRtpExtensionType(extension), id));
}
void RtpStreamReceiver::InsertSpsPpsIntoTracker(uint8_t payload_type) {
auto codec_params_it = pt_codec_params_.find(payload_type);
if (codec_params_it == pt_codec_params_.end())
return;
LOG(LS_INFO) << "Found out of band supplied codec parameters for"
<< " payload type: " << static_cast<int>(payload_type);
H264SpropParameterSets sprop_decoder;
auto sprop_base64_it =
codec_params_it->second.find(cricket::kH264FmtpSpropParameterSets);
if (sprop_base64_it == codec_params_it->second.end())
return;
if (!sprop_decoder.DecodeSprop(sprop_base64_it->second.c_str()))
return;
tracker_.InsertSpsPpsNalus(sprop_decoder.sps_nalu(),
sprop_decoder.pps_nalu());
}
} // namespace webrtc
|
/**
* @file sql_well.cpp
* @brief implementation of frac storage
* @author Oleg Borschuk
* @version
* @date 2011-07-29
*/
// d REAL NOT NULL REFERENCES dates(d) ON UPDATE CASCADE ON DELETE CASCADE,
//
// d REAL NOT NULL,
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/fstream.hpp"
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include "bs_kernel.h"
#include "sql_well.h"
#include "frac_comp_ident.h"
#include "i_cant_link_2_mesh.h"
using namespace boost;
#ifdef BSPY_EXPORTING_PLUGIN
#include <boost/python.hpp>
using namespace boost::python;
#endif //BSPY_EXPORTING_PLUGIN
// shorthand macro to pass values via val2str filter
#define V2S(t) val2str::go(t).c_str()
namespace blue_sky
{
// hidden details
namespace {
// the purpose of this helper is to print '1*' if argument == -1
// otherwise number converted to string is unchanged
struct val2str {
// specialization for floating-point numbers
template< class T >
static std::string do_fix(const T& v, const boost::true_type) {
if(v == -1.0)
return "1*";
else
return boost::lexical_cast< std::string >(v);
}
// specialization for other types
template< class T >
static std::string do_fix(const T& v, const boost::false_type) {
return boost::lexical_cast< std::string >(v);
}
// main operator
template< class T >
static std::string go(const T& v) {
return do_fix(v, boost::is_floating_point< T >());
}
};
}
int clear_table (void *pData, int nColumns,
char **values, char ** /*columns*/)
{
int rc = 0;
char *zErrMsg = 0;
if (nColumns != 1)
return 1; // Error
sqlite3* db = (sqlite3*)pData;
char *stmt = sqlite3_mprintf("DELETE FROM backup.%q",
values[0]);
rc = sqlite3_exec (db, stmt, NULL, NULL, &zErrMsg);
sqlite3_free (stmt);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
int main_to_backup (void *pData, int nColumns,
char **values, char ** /*columns*/)
{
int rc = 0;
char *zErrMsg = 0;
if (nColumns != 1)
return 1; // Error
sqlite3* db = (sqlite3*)pData;
char *stmt = sqlite3_mprintf("insert into backup.%q select * from main.%q",
values[0], values[0]);
rc = sqlite3_exec (db, stmt, NULL, NULL, &zErrMsg);
sqlite3_free (stmt);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
int backup_to_main (void *pData, int nColumns,
char **values, char ** /*columns*/)
{
int rc = 0;
char *zErrMsg = 0;
if (nColumns != 1)
return 1; // Error
sqlite3* db = (sqlite3*)pData;
char *stmt = sqlite3_mprintf("insert into main.%q select * from backup.%q",
values[0], values[0]);
rc = sqlite3_exec (db, stmt, NULL, NULL, &zErrMsg);
sqlite3_free (stmt);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
sql_well::sql_well (bs_type_ctor_param)
{
db = 0;
stmp_sql = 0;
fr_file = 0;
}
sql_well::sql_well (const sql_well& rhs)
: bs_refcounter (), file_name(rhs.file_name), db(rhs.db)
{
//*this = rhs;
// don't copy pending statement
stmp_sql = 0;
fr_file = 0;
}
sql_well::~sql_well ()
{
}
int
sql_well::open_db (const std::wstring &file_)
{
int rc = 0;
char *zErrMsg = 0;
if (db)
close_db ();
std::string file = wstr2str (file_);
printf ("SQL open_db %s\n", file.c_str ());
if (!strcmp(file.c_str(),":memory:") || !boost::filesystem::exists (file))
{
rc = sqlite3_open (file.c_str (), &db);
if (rc)
{
fprintf (stderr, "Can't open database: %s (%s)\n", sqlite3_errmsg (db), file.c_str());
sqlite3_close (db);
db = 0;
return -1;
}
create_db (db);
rc = sqlite3_exec (db, "INSERT INTO groups(name) VALUES ('field');", NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
//sqlite3_close (db);
}
else
{
rc = sqlite3_open (file.c_str (), &db);
if (rc)
{
fprintf (stderr, "Can't open database: %s (%s) - 2\n", sqlite3_errmsg (db), file.c_str());
sqlite3_close (db);
db = 0;
return -1;
}
}
file_name = file;
#if 0
char buf[2048];
rc = sqlite3_open (":memory:", &db);
if (rc)
{
fprintf (stderr, "Can't open database: %s\n", sqlite3_errmsg (db));
sqlite3_close (db);
db = 0;
return -1;
}
file_name = file;
// load from file to memory
rc = create_db (db);
if (rc)
return rc;
sprintf (buf, "ATTACH DATABASE '%s' as backup; BEGIN", file.c_str ());
rc = sqlite3_exec (db, buf, NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
rc = sqlite3_exec(db, "SELECT name FROM backup.sqlite_master WHERE type='table'",
&backup_to_main, db, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
sqlite3_exec(db, "COMMIT; DETACH DATABASE backup", NULL, NULL, NULL);
#else //0
#endif //0
return 0;
}
void
sql_well::backup_to_file (const std::wstring &filename)
{
if (!db)
return;
sqlite3 *ddb = 0;
int rc = sqlite3_open (wstr2str (filename).c_str (), &ddb);
if (rc)
{
fprintf (stderr, "Can't open database: %s\n", sqlite3_errmsg (ddb));
sqlite3_close (ddb);
ddb = 0;
return;
}
sqlite3_backup *b = sqlite3_backup_init(ddb, "main", db, "main");
if (b)
{
while(sqlite3_backup_step(b, -1) == SQLITE_OK) {}
//while (sqlite3_backup_remaining(b) > 0)
sqlite3_backup_finish(b);
}
rc = sqlite3_errcode(ddb);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error with backup_to_file: %d\n", rc);
}
sqlite3_close(ddb);
//db->sqlite_backup_to_file(filename);
}
int
sql_well::merge_with_db(const std::wstring& dbname_)
{
if (!db)
return 0;
if (stmp_sql)
finalize_sql ();
std::string dbname = wstr2str (dbname_);
int rc = 0;
char *zErrMsg = 0;
std::string sql = "attach '" + dbname + "' as tomerge; insert or ignore into groups select * from tomerge.groups; \
insert or ignore into dates select * from tomerge.dates; \
insert or ignore into wells select * from tomerge.wells; \
insert or replace into branches select * from tomerge.branches; \
insert or ignore into completions select * from tomerge.completions; \
insert or ignore into fractures select * from tomerge.fractures; \
insert or ignore into permfrac select * from tomerge.permfrac; \
insert or ignore into well_hist select * from tomerge.well_hist; \
insert or ignore into wells_in_group select * from tomerge.wells_in_group; \
detach database tomerge";
rc = sqlite3_exec (db, sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error with tomerge: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
return 0;
}
int
sql_well::create_db (sqlite3 *db_in)
{
int rc = 0;
char *zErrMsg = 0;
const char *sql = \
"\
PRAGMA foreign_keys=ON;\
BEGIN;\
CREATE TABLE wells(name TEXT UNIQUE PRIMARY KEY, \
x REAL DEFAULT -1, \
y REAL DEFAULT -1, \
horiz INTEGER DEFAULT 0);\
CREATE TABLE groups(name TEXT UNIQUE PRIMARY KEY);\
CREATE TABLE wells_in_group(gr_name TEXT NOT NULL REFERENCES groups(name) ON UPDATE CASCADE ON DELETE CASCADE,\
well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE);\
CREATE INDEX i4 ON wells_in_group (gr_name ASC);\
CREATE INDEX i5 ON wells_in_group (well_name ASC);\
CREATE TABLE dates(d REAL UNIQUE PRIMARY KEY);\
CREATE TABLE well_hist(well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE,\
d REAL NOT NULL, \
p_or REAL DEFAULT -1,\
p_wr REAL DEFAULT -1,\
p_gr REAL DEFAULT -1,\
p_lr REAL DEFAULT -1,\
p_bhp REAL DEFAULT -1,\
p_fgr REAL DEFAULT -1,\
i_or REAL DEFAULT -1,\
i_wr REAL DEFAULT -1,\
i_gr REAL DEFAULT -1,\
i_bhp REAL DEFAULT -1,\
wefac REAL DEFAULT 1.0,\
ctrl INTEGER DEFAULT 0,\
status INTEGER DEFAULT 0,\
lim_p_or REAL DEFAULT -1,\
lim_p_wr REAL DEFAULT -1,\
lim_p_gr REAL DEFAULT -1,\
lim_p_lr REAL DEFAULT -1,\
lim_p_bhp REAL DEFAULT -1,\
lim_i_or REAL DEFAULT -1,\
lim_i_wr REAL DEFAULT -1,\
lim_i_gr REAL DEFAULT -1,\
lim_i_bhp REAL DEFAULT -1);\
CREATE INDEX i1 ON well_hist (well_name ASC);\
CREATE INDEX i2 ON well_hist (d ASC);\
CREATE UNIQUE INDEX i3 ON well_hist (well_name, d ASC);\
CREATE TABLE well_res(well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE,\
d REAL NOT NULL, \
p_or REAL DEFAULT -1,\
p_wr REAL DEFAULT -1,\
p_gr REAL DEFAULT -1,\
p_bhp REAL DEFAULT -1,\
i_or REAL DEFAULT -1,\
i_wr REAL DEFAULT -1,\
i_gr REAL DEFAULT -1,\
i_bhp REAL DEFAULT -1,\
wefac REAL DEFAULT 1,\
p_gor REAL DEFAULT -1,\
p_fgr REAL DEFAULT -1,\
ctrl INTEGER DEFAULT 0,\
status INTEGER DEFAULT 0,\
tot_p_or REAL DEFAULT -1,\
tot_p_wr REAL DEFAULT -1,\
tot_p_gr REAL DEFAULT -1,\
tot_p_fgr REAL DEFAULT -1,\
tot_i_or REAL DEFAULT -1,\
tot_i_wr REAL DEFAULT -1,\
tot_i_gr REAL DEFAULT -1);\
CREATE INDEX i6 ON well_res (well_name ASC);\
CREATE INDEX i7 ON well_res (d ASC);\
CREATE UNIQUE INDEX i8 ON well_res (well_name, d ASC);\
CREATE TABLE branches(well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE,\
branch_name TEXT NOT NULL DEFAULT 'main', \
md REAL DEFAULT -1,\
parent TEXT DEFAULT '',\
traj BLOB, \
well_log BLOB,\
PRIMARY KEY (well_name, branch_name));\
CREATE INDEX i9 ON branches (well_name ASC);\
CREATE UNIQUE INDEX i10 ON branches (well_name, branch_name ASC);\
CREATE TRIGGER tr1 AFTER INSERT ON wells\
BEGIN\
INSERT INTO branches(well_name, branch_name) VALUES(new.name, 'main');\
END;\
CREATE TRIGGER tr2 AFTER INSERT ON wells\
BEGIN\
INSERT INTO wells_in_group(gr_name, well_name) VALUES ('field', new.name);\
END;\
CREATE TABLE fractures(well_name TEXT NOT NULL,\
branch_name TEXT DEFAULT 'main', \
md REAL NOT NULL, \
d REAL NOT NULL, \
status INTEGER DEFAULT 0,\
half_up REAL DEFAULT 5,\
half_down REAL DEFAULT 5,\
angle REAL DEFAULT 0,\
half_length_1 REAL DEFAULT 50,\
half_length_2 REAL DEFAULT 50,\
perm REAL DEFAULT -1,\
half_thin REAL DEFAULT 0.005,\
skin REAL DEFAULT 0,\
FOREIGN KEY (well_name, branch_name) REFERENCES branches(well_name, branch_name) ON UPDATE CASCADE ON DELETE CASCADE\
);\
CREATE INDEX i11 ON fractures (well_name ASC);\
CREATE INDEX i12 ON fractures (well_name, branch_name ASC);\
CREATE TABLE completions(well_name TEXT NOT NULL, \
branch_name TEXT NOT NULL DEFAULT 'main', \
md REAL NOT NULL, \
d REAL NOT NULL, \
status INTEGER DEFAULT 0,\
length REAL DEFAULT 1,\
rw REAL DEFAULT 0.08,\
r0 REAL DEFAULT -1,\
kh REAL DEFAULT -1,\
kh_mult REAL DEFAULT 1,\
skin REAL DEFAULT 0,\
FOREIGN KEY (well_name, branch_name) REFERENCES branches(well_name, branch_name) ON UPDATE CASCADE ON DELETE CASCADE\
); \
CREATE INDEX i13 ON completions (well_name ASC);\
CREATE INDEX i14 ON completions (well_name, branch_name ASC);\
CREATE TRIGGER tr3 BEFORE INSERT ON fractures\
BEGIN\
INSERT OR REPLACE INTO dates(d) VALUES(new.d);\
END;\
CREATE TRIGGER tr4 BEFORE INSERT ON completions\
BEGIN\
INSERT OR REPLACE INTO dates(d) VALUES(new.d);\
END;\
CREATE TRIGGER tr5 BEFORE INSERT ON well_hist\
BEGIN\
INSERT OR REPLACE INTO dates(d) VALUES(new.d);\
END;\
CREATE TABLE permfrac(d REAL NOT NULL, \
status INTEGER DEFAULT 0,\
x1 REAL NOT NULL,\
y1 REAL NOT NULL,\
x2 REAL NOT NULL,\
y2 REAL NOT NULL,\
z_top REAL NOT NULL,\
z_bottom REAL NOT NULL,\
dx REAL DEFAULT 0.01,\
dy REAL DEFAULT 0.01,\
perm REAL NOT NULL,\
i1 INTEGER DEFAULT -1,\
j1 INTEGER DEFAULT -1,\
i2 INTEGER DEFAULT -1,\
j2 INTEGER DEFAULT -1,\
k1 INTEGER DEFAULT -1,\
k2 INTEGER DEFAULT -1);\
COMMIT;\
";
if (!db_in)
return -1;
rc = sqlite3_exec (db_in, sql, NULL, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
void
sql_well::close_db ()
{
if (db)
{
if (stmp_sql)
finalize_sql ();
#if 0
int rc = 0;
char *zErrMsg = 0;
char buf[2048];
sprintf (buf, "ATTACH DATABASE '%s' as backup; BEGIN", file_name.c_str ());
rc = sqlite3_exec (db, buf, NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
rc = sqlite3_exec (db, "SELECT name FROM backup.sqlite_master WHERE type='table'",
&clear_table, db, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
rc = sqlite3_exec (db, "SELECT name FROM main.sqlite_master WHERE type='table'",
&main_to_backup, db, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
sqlite3_exec(db, "COMMIT; DETACH DATABASE backup", NULL, NULL, NULL);
#endif //0
sqlite3_close (db);
}
db = 0;
file_name = "";
}
int
sql_well::create_db_struct ()
{
return create_db (db);
}
void
sql_well::fill_db ()
{
//int rc = 0;
//char *zErrMsg = 0;
char sw_name[4096];
char sw_sel[4096];
char sw_ins[4096];
char sw_up[4096];
if (!db)
return;
if (stmp_sql)
finalize_sql ();
//rc = sqlite3_exec (db, "BEGIN TRANSACTION", NULL, 0, &zErrMsg);
for (int i = 0; i < 500; ++i)
{
sprintf (sw_name, "well_%d", i);
add_well (std::string (sw_name));
for (double j = 0; j < 240; j = j + 1.0)
{
sprintf (sw_ins, "INSERT INTO well_dynamic (well_name, date, h_wrate) VALUES ('well_%d', %lf, %lf)",
i, j, 50.0);
sprintf (sw_up, "UPDATE well_dynamic SET h_orate = %lf WHERE well_name='well_%d' and date=%lf",
j, i, j);
sprintf (sw_sel, "SELECT * FROM well_dynamic WHERE well_name='well_%d' and date=%lf",
i, j);
//printf ("%s\n", sw);
if (insert_or_update (std::string (sw_sel),
std::string (sw_ins),
std::string (sw_up)))
{
return;
}
}
}
//rc = sqlite3_exec (db, "COMMIT TRANSACTION", NULL, 0, &zErrMsg);
return;
}
int
sql_well::insert_or_update (const std::string &select_sql,
const std::string &insert_sql,
const std::string &update_sql)
{
if (!db)
return -2;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
rc = sqlite3_prepare_v2 (db, select_sql.c_str (), select_sql.length () + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -1;
}
if (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
sqlite3_finalize (stmp);
rc = sqlite3_exec (db, update_sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
}
else
{
sqlite3_finalize (stmp);
rc = sqlite3_exec (db, insert_sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
}
return 0;
}
int
sql_well::add_well (const std::string &well_name)
{
if (!db)
return -2;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
char buf[2048];
sprintf (buf, "INSERT INTO wells (name) VALUES('%s');",
well_name.c_str ());
rc = sqlite3_exec (db, buf, NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error (add_well): %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
sql_well::list_t
sql_well::get_well_names () const
{
list_t lst;
if (!db)
return lst;
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
std::string sql = "SELECT name FROM wells ORDER BY name ASC";
rc = sqlite3_prepare_v2 (db, sql.c_str (), sql.length () + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return lst;
}
while (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
lst.push_back (std::string ((const char *)sqlite3_column_text (stmp, 0)));
}
sqlite3_finalize (stmp);
return lst;
}
int
sql_well::add_branch_gis (const std::string &wname, const std::string &branch,
sp_gis_t g)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "UPDATE branches SET well_log = @q WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf), &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -1;
}
std::string s = g->to_str();
std::vector<char> ch (s.begin (), s.end ());
//printf ("GIS\n%s\n", s.c_str ());
//printf ("GIS INT %d %d\n", (int)strlen (s.c_str ()), (int)s.length ());
rc = sqlite3_bind_blob (stmp, 1, &ch[0], ch.size (), SQLITE_STATIC);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -3;
}
sqlite3_step (stmp); // UPDATE
sqlite3_finalize (stmp);
return 0;
}
sql_well::sp_gis_t
sql_well::get_branch_gis (const std::string &wname, const std::string &branch) const
{
sp_gis_t sp_gis = BS_KERNEL.create_object ("gis");
if (!db)
return sp_gis_t ();
if (stmp_sql)
return sp_gis_t ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "SELECT well_log FROM branches WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
sqlite3_finalize (stmp);
return sp_gis_t ();
}
if (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
int n = sqlite3_column_bytes (stmp, 0);
if (n < 1)
{
sqlite3_finalize (stmp);
return sp_gis_t ();
}
const char *b = (const char *)sqlite3_column_blob (stmp, 0);
//std::string s = (const char *)sqlite3_column_text (stmp, 0);
std::string s;
s.assign (b, n);
printf ("READ GIS %d\n", (int)s.length ());
sp_gis->from_str(s);
}
else
{
return sp_gis_t ();
}
sqlite3_finalize (stmp);
return sp_gis;
}
int
sql_well::add_branch_traj (const std::string &wname, const std::string &branch,
sp_traj_t t)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "UPDATE branches SET traj = @w WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -1;
}
std::string s = t->to_str();
std::vector<char> ch (s.begin (), s.end ());
rc = sqlite3_bind_blob (stmp, 1, &ch[0], ch.size (), SQLITE_STATIC);
//printf ("TRAJ\n%s\n", s.c_str ());
//printf ("TRAJ INT %d %d\n", (int)strlen (s.c_str ()), (int)s.length ());
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -3;
}
sqlite3_step (stmp); // UPDATE
sqlite3_finalize (stmp);
return 0;
}
sql_well::sp_traj_t
sql_well::get_branch_traj (const std::string &wname, const std::string &branch) const
{
sp_traj_t sp_traj = BS_KERNEL.create_object ("traj");
if (!db)
return sp_traj_t ();
if (stmp_sql)
return sp_traj_t ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "SELECT traj FROM branches WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
sqlite3_finalize (stmp);
return sp_traj_t ();
}
if (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
int n = sqlite3_column_bytes (stmp, 0);
if (!n)
{
sqlite3_finalize (stmp);
return sp_traj_t ();
}
const char *b = (const char *)sqlite3_column_blob (stmp, 0);
//std::string s = (const char *)sqlite3_column_text (stmp, 0);
std::string s;
s.assign (b, n);
printf ("READ TRAJ %d\n", (int)s.length ());
sp_traj->from_str(s);
}
else
{
return sp_traj_t ();
}
sqlite3_finalize (stmp);
return sp_traj;
}
int
sql_well::update_branch_traj (const std::string &wname, const std::string &branch,
sp_traj_t t)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "SELECT traj FROM branches WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
if(stmp) sqlite3_finalize (stmp);
return -1;
}
std::string s = t->to_str();
std::vector<char> ch (s.begin (), s.end ());
rc = sqlite3_bind_blob (stmp, 1, &ch[0], ch.size (), SQLITE_STATIC);
//printf ("TRAJ\n%s\n", s.c_str ());
//printf ("TRAJ INT %d %d\n", (int)strlen (s.c_str ()), (int)s.length ());
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
if(stmp) sqlite3_finalize (stmp);
return -3;
}
sqlite3_step (stmp); // UPDATE
sqlite3_finalize (stmp);
return 0;
}
int
sql_well::prepare_sql (const std::string &sql)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
const char *ttt;
int rc = 0;
rc = sqlite3_prepare_v2 (db, sql.c_str (), sql.length () + 1, &stmp_sql, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s (%d)\n", sqlite3_errmsg (db), rc);
fprintf (stderr, "Query: %s\n", sql.c_str());
return -1;
}
return 0;
}
//#ifdef BSPY_EXPORTING_PLUGIN
spv_double
sql_well::get_table (const std::string &table_name, boost::python::list &table_columns, const std::string &filter)
{
std::string request_str = "SELECT COUNT(*) FROM " + table_name + " " + filter;
prepare_sql (request_str);
step_sql ();
int n_rows = get_sql_int(0);
finalize_sql ();
if (n_rows < 1)
return BS_KERNEL.create_object (v_double::bs_type());
int n_cols = boost::python::len (table_columns);
spv_double table = BS_KERNEL.create_object (v_double::bs_type());
table->resize (n_rows * n_cols);
double *table_values = &(*table)[0];
request_str = "SELECT ";
for (int j = 0; j < n_cols; j++)
{
std::string col_name = extract<std::string>(table_columns[j]);
//TODO: check col_name
request_str = request_str + col_name;
if (j < n_cols - 1)
request_str = request_str + ", ";
}
request_str = request_str + " FROM " + table_name + " " + filter;
prepare_sql (request_str);
for (int i = 0; (i < n_rows) && (!step_sql ()); ++i)
{
for (int j = 0; j < n_cols; j++)
{
table_values[i * n_cols + j] = get_sql_real(j);
}
}
finalize_sql ();
npy_intp dims[] = {n_rows, n_cols};
table->reshape (2, dims);
return table;
}
//#endif //BSPY_EXPORTING_PLUGIN
int
sql_well::step_sql ()
{
if (!db)
return -1;
if (!stmp_sql)
return -1;
if (sqlite3_step (stmp_sql) == SQLITE_ROW) // UPDATE
return 0;
else
return 2;
}
int
sql_well::finalize_sql ()
{
if (stmp_sql)
{
sqlite3_finalize (stmp_sql);
stmp_sql = 0;
}
return 0;
}
t_int
sql_well::get_sql_int (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return (t_int)sqlite3_column_int (stmp_sql, (int)col);
}
t_double
sql_well::get_sql_real (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return (t_double)sqlite3_column_double (stmp_sql, (int)col);
}
bool
sql_well::get_sql_bool (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return (bool)sqlite3_column_int (stmp_sql, (int)col);
}
std::string
sql_well::get_sql_str (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return std::string ((const char *)sqlite3_column_text (stmp_sql, (int)col));
}
bool
sql_well::get_sql_exist (t_int col)
{
if (!db)
return false;
if (!stmp_sql)
return false;
int n = sqlite3_column_bytes(stmp_sql, (int)col);
return (bool)n;
}
int
sql_well::exec_sql (const std::string &sql)
{
if (!db)
return 0;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
rc = sqlite3_exec (db, sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s, when query \"%s\"\n", zErrMsg, sql.c_str());
sqlite3_free (zErrMsg);
return -4;
}
return 0;
}
int
sql_well::exec_sql_and_return_rowid (const std::string &sql)
{
if (!db)
return 0;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
int rowid = -1;
rc = sqlite3_exec (db, sql.c_str (), NULL, 0, &zErrMsg);
rowid = sqlite3_last_insert_rowid(db);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
return rowid;
}
int
sql_well::read_from_ascii_file (const std::string &fname, double starting_date)
{
//if (fr_file)
// delete fr_file;
//fr_file = new FRead (fname.c_str (), fname.c_str ());
fr_file = BS_KERNEL.create_object ("bos_reader");
fr_file->open (fname.c_str (), fname.c_str ());
int rc = 0;
char buf[4096];
char *id = 0;
char *other = 0;
double d = 0;
for (;;)
{
rc = fr_file->read_line (buf, 4096, FREAD_DONT_CONVERT_CASE);
//printf ("%s\n", buf);
if (rc <= 0)
break;
d = starting_date;
// read date and time
rc = read_date_and_time (buf, &id, &d);
if (rc)
return -4;
// read id
fr_file->trim_left (&id);
other = id;
rc |= fr_file->get_phrase (&other);
if (rc)
return -1;
//trim_right_s (id);
fr_file->locale_ucase (id);
if (!strcmp (id, "W_SPEC"))
{
rc = read_w_spec (other);
if (rc)
return rc;
}
else if (!strcmp (id, "W_BRANCH_F"))
{
rc = read_w_branch_f (other);
if (rc)
return rc;
}
else if (!strcmp (id, "W_COMP"))
{
rc = read_w_comp (other, d);
if (rc)
return rc;
}
else if (!strcmp (id, "W_FRAC"))
{
rc = read_w_frac (other, d);
if (rc)
return rc;
}
else if (!strcmp (id, "W_PROD"))
{
rc = read_w_prod (other, d);
if (rc)
return rc;
}
else if (!strcmp (id, "W_INJ"))
{
rc = read_w_inj (other, d);
if (rc)
return rc;
}
//printf ("date %lf\n", d);
//printf ("next: %s\n", next);
}
return 0;
}
int
sql_well::read_w_branch_f (char *buf)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char branch[1024];
char parent[1024];
char fname[1024];
char fname2[1024];
char sql[1024];
double md = -1;
// read well name
wname[0] = '\0';
nx = buf;
// read well name
rc = fr_file->get_phrase_str (&nx, wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_BRANCH_F can not be set by default\n");
return -1;
}
// read branch
strcpy (branch, "main");
rc = fr_file->get_phrase_str (&nx, branch);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read branch name\n");
return -1;
}
// read parent
parent[0] = '\0';
rc = fr_file->get_phrase_str (&nx, parent);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read parent name\n");
return -1;
}
//read md
rc = fr_file->get_phrase_double (&nx, &md);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F\n");
return -1;
}
// read file name
fname[0] = '\0';
rc = fr_file->get_phrase_filepath (&nx, fname);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read file name\n");
return -1;
}
// read well_log file name
fname2[0] = '\0';
rc = fr_file->get_phrase_filepath (&nx, fname2);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read file name\n");
return -1;
}
// add to data base
sprintf (sql, "INSERT OR REPLACE INTO branches(well_name, branch_name, md, parent) VALUES ('%s', '%s', %lf, '%s')",
wname, branch, md, parent);
printf ("SQL: %s\n", sql);
if (exec_sql (sql))
return -1;
if (fname[0] != '\0')
{
sp_traj_t sp_traj = BS_KERNEL.create_object ("traj");
rc = sp_traj->read_from_dev_file (fr_file->get_incdir() + std::string(fname));
if (rc)
{
return rc;
}
if (add_branch_traj (wname, branch, sp_traj))
return -6;
printf ("TRAJ\n %s\n", sp_traj->py_str ().c_str ());
}
if (fname2[0] != '\0')
{
sp_gis_t sp_gis = BS_KERNEL.create_object ("gis");
rc = sp_gis->read_from_las_file (fr_file->get_incdir() + std::string(fname2));
if (rc)
{
return rc;
}
if (add_branch_gis (wname, branch, sp_gis))
return -6;
}
printf ("W_BRANCH_F %s %s %s %lf\n", wname, branch, parent, md);
return 0;
}
int
sql_well::read_w_spec (char *buf)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char sql[1024];
double x = -1, y = -1;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_SPEC can not be set by default\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &x);
//printf ("rc: %lf\n", x);
rc |= fr_file->get_phrase_double (&nx, &y);
//printf ("rc: %lf\n", y);
if (rc)
{
fprintf (stderr, "Error: W_SPEC\n");
return -1;
}
printf ("W_SPEC %s %lf %lf\n", wname, x, y);
// add to data base
sprintf (sql, "INSERT INTO wells(name, x, y) VALUES ('%s', %lf, %lf)",
wname, x, y);
return exec_sql (sql);
}
int
sql_well::read_w_frac (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char branch[1024];
char status[1024];
int i_status;
char sql[1024];
double md = -1;
double angle = 0;
double half_length_1 = 50.0;
double half_length_2 = 50.0;
double half_up = 5.0;
double half_down = 5.0;
double perm = -1;
double half_thin = 0.005;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_FRAC can not be set by default\n");
return -1;
}
strcpy (branch, "main");
rc = fr_file->get_phrase_str (&nx, branch);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well branch name in keyword W_FRAC\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_FRAC\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &md);
rc |= fr_file->get_phrase_double (&nx, &angle);
rc |= fr_file->get_phrase_double (&nx, &half_length_1);
rc |= fr_file->get_phrase_double (&nx, &half_length_2);
rc |= fr_file->get_phrase_double (&nx, &half_up);
rc |= fr_file->get_phrase_double (&nx, &half_down);
rc |= fr_file->get_phrase_double (&nx, &perm);
rc |= fr_file->get_phrase_double (&nx, &half_thin);
if (rc)
{
fprintf (stderr, "Error: W_SPEC\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
if (status[0] == 'S')
i_status = STATUS_CON_SHUT;
//else if (status[0] == 'C') // close
// i_status = 1;
else if (status[0] == 'O') // OPEN
i_status = STATUS_CON_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_FRAC not aloowed\n", status);
return -9;
}
if (md < 0)
{
fprintf (stderr, "Error: you should specify md for W_FRAC \n");
return -9;
}
if (half_length_1 <= 0)
{
fprintf (stderr, "Error: HALF_LENGTH_1 should be > 0 for W_FRAC \n");
return -9;
}
if (half_length_2 <= 0)
{
fprintf (stderr, "Error: HALF_LENGTH_2 should be > 0 for W_FRAC \n");
return -9;
}
if (half_up <= 0)
{
fprintf (stderr, "Error: HALF_UP should be > 0 for W_FRAC \n");
return -9;
}
if (half_down <= 0)
{
fprintf (stderr, "Error: HALF_DOWN should be > 0 for W_FRAC \n");
return -9;
}
if (half_thin <= 0)
{
fprintf (stderr, "Error: HALF_THIN should be > 0 for W_FRAC \n");
return -9;
}
printf ("W_FRAC %s %s %s %lf %lf %lf %lf %lf %lf %lf %lf\n",
wname, branch, status, md, angle, half_length_1, half_length_2,
half_up, half_down, perm, half_thin);
// add to data base
sprintf (sql, "INSERT INTO fractures(well_name, branch_name, md, d, status, \
half_up, half_down, angle, half_length_1, half_length_2, perm, half_thin) \
VALUES ('%s', '%s', %lf, %lf, %d, %lf, %lf, %lf, %lf, %lf, %lf, %lf)",
wname, branch, md, d, i_status, half_up, half_down, angle,
half_length_1, half_length_2, perm, half_thin);
return exec_sql (sql);
return 0;
}
int
sql_well::read_w_comp (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char branch[1024];
char status[1024];
int i_status;
char sql[1024];
double md = -1, length = 1, rw = 0.08, skin = 0, khmult = 1.0;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_COMP can not be set by default\n");
return -1;
}
strcpy (branch, "main");
rc = fr_file->get_phrase_str (&nx, branch);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well branch name in keyword W_COMP\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_COMP\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &md);
rc |= fr_file->get_phrase_double (&nx, &length);
rc |= fr_file->get_phrase_double (&nx, &rw);
rc |= fr_file->get_phrase_double (&nx, &skin);
rc |= fr_file->get_phrase_double (&nx, &khmult);
if (rc)
{
fprintf (stderr, "Error: W_SPEC\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
if (status[0] == 'S')
i_status = STATUS_CON_SHUT;
//else if (status[0] == 'C') // close
// i_status = 1;
else if (status[0] == 'O') // OPEN
i_status = STATUS_CON_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_COMP not aloowed\n", status);
return -9;
}
if (md < 0)
{
fprintf (stderr, "Error: you should specify md for W_COMP \n");
return -9;
}
if (length <= 0)
{
fprintf (stderr, "Error: length should be > 0 for W_COMP \n");
return -9;
}
if (rw <= 0)
{
fprintf (stderr, "Error: rw should be > 0 for W_COMP \n");
return -9;
}
if (khmult <= 0)
{
fprintf (stderr, "Error: khmult should be > 0 for W_COMP \n");
return -9;
}
printf ("W_COMP %s %s %lf %lf %lf %lf %lf\n",
wname, branch, md, length, rw, skin, khmult);
// add to data base
sprintf (sql, "INSERT INTO completions(well_name, branch_name, md, d, length, status, rw, kh_mult) VALUES ('%s', '%s', %lf, %lf, %lf, %d, %lf, %lf)",
wname, branch, md, d, length, i_status, rw, khmult);
return exec_sql (sql);
return 0;
}
int
sql_well::read_w_inj (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char status[1024];
char ctrl[1024];
char fluid[1024];
int i_status = 0;
int i_ctrl = 0;
char sql[1024];
double bhp = -1;
double rate = -1;
double orate = -1;
double wrate = -1;
double grate = -1;
double lim_bhp = -1;
double lim_rate = -1;
double lim_orate = -1;
double lim_wrate = -1;
double lim_grate = -1;
double wefac = 1.0;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_INJ can not be set by default\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_INJ\n");
return -1;
}
strcpy (ctrl, "BHP");
rc = fr_file->get_phrase_str (&nx, ctrl);
if (rc)
{
fprintf (stderr, "Error: well control in keyword W_INJ\n");
return -1;
}
strcpy (fluid, "WATER");
rc = fr_file->get_phrase_str (&nx, ctrl);
if (rc)
{
fprintf (stderr, "Error: well control in keyword W_INJ\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &bhp);
rc |= fr_file->get_phrase_double (&nx, &rate);
rc = fr_file->get_phrase_double (&nx, &lim_bhp);
rc |= fr_file->get_phrase_double (&nx, &lim_rate);
rc |= fr_file->get_phrase_double (&nx, &wefac);
if (rc)
{
fprintf (stderr, "Error: W_PROD\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
fr_file->locale_ucase (ctrl);
fr_file->locale_ucase (fluid);
if (status[0] == 'S')
i_status = STATUS_SHUT;
else if (status[0] == 'C') // close
i_status = STATUS_CLOSE;
else if (status[0] == 'O') // OPEN
i_status = STATUS_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_COMP not aloowed\n", status);
return -9;
}
if (ctrl[0] == 'B')
{
i_ctrl = CTRL_I_BHP;
if (i_status == 2 && bhp <= 0)
{
fprintf (stderr, "Error: BHP = %lf for CONTROL %s in keyword W_INJ",
bhp, ctrl);
return -1;
}
}
else if (ctrl[0] == 'R') // rate
{
if (i_status == STATUS_OPEN && rate <= 0)
{
fprintf (stderr, "Error: RATE = %lf for CONTROL %s in keyword W_INJ",
wrate, ctrl);
return -1;
}
if (fluid[0] == 'W')
{
i_ctrl = CTRL_I_WRATE;
wrate = rate;
lim_wrate = lim_rate;
}
else if (fluid[0] == 'O')
{
i_ctrl = -CTRL_I_ORATE;
orate = rate;
lim_orate = lim_rate;
}
else if (fluid[0] == 'G')
{
i_ctrl = CTRL_I_GRATE;
grate = rate;
lim_grate = lim_rate;
}
else
{
fprintf (stderr, "Error: FLUID = %s not allowed in keyword W_INJ",
fluid);
return -1;
}
}
else
{
fprintf (stderr, "Error: control %s for W_INJ not aloowed\n", ctrl);
return -9;
}
if (i_status == STATUS_OPEN && wefac <= 0)
{
fprintf (stderr, "Error: WEFAC = %lf in keyword W_INJ",
wefac);
return -1;
}
printf ("W_INJ %s %s %s %s %lf %lf %lf %lf %lf\n",
wname, status, ctrl, fluid, bhp, rate, lim_bhp, lim_rate, wefac);
// add to data base
sprintf (sql, "INSERT INTO well_hist(well_name, d, i_or, i_wr, i_gr, \
i_bhp, wefac, ctrl, status, lim_i_or, lim_i_wr, lim_i_gr, lim_i_bhp) \
VALUES ('%s', %lf, %lf, %lf, %lf, %lf, %lf, %d, %d, %lf, %lf, %lf, %lf)",
wname, d, orate, wrate, grate, bhp, wefac, i_ctrl, i_status,
lim_orate, lim_wrate, lim_grate, lim_bhp);
return exec_sql (sql);
return 0;
}
int
sql_well::read_w_prod (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char status[1024];
char ctrl[1024];
int i_status = 0;
int i_ctrl = 0;
char sql[1024];
double bhp = -1;
double orate = -1;
double wrate = -1;
double grate = -1;
double lrate = -1;
double lim_bhp = -1;
double lim_orate = -1;
double lim_wrate = -1;
double lim_grate = -1;
double lim_lrate = -1;
double wefac = 1.0;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_PROD can not be set by default\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_PROD\n");
return -1;
}
strcpy (ctrl, "BHP");
rc = fr_file->get_phrase_str (&nx, ctrl);
if (rc)
{
fprintf (stderr, "Error: well control in keyword W_PROD\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &bhp);
rc |= fr_file->get_phrase_double (&nx, &wrate);
rc |= fr_file->get_phrase_double (&nx, &orate);
rc |= fr_file->get_phrase_double (&nx, &grate);
rc |= fr_file->get_phrase_double (&nx, &lrate);
rc = fr_file->get_phrase_double (&nx, &lim_bhp);
rc |= fr_file->get_phrase_double (&nx, &lim_wrate);
rc |= fr_file->get_phrase_double (&nx, &lim_orate);
rc |= fr_file->get_phrase_double (&nx, &lim_grate);
rc |= fr_file->get_phrase_double (&nx, &lim_lrate);
rc |= fr_file->get_phrase_double (&nx, &wefac);
if (rc)
{
fprintf (stderr, "Error: W_PROD\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
fr_file->locale_ucase (ctrl);
if (status[0] == 'S')
i_status = STATUS_SHUT;
else if (status[0] == 'C') // close
i_status = STATUS_CLOSE;
else if (status[0] == 'O') // OPEN
i_status = STATUS_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_COMP not aloowed\n", status);
return -9;
}
if (ctrl[0] == 'B')
{
i_ctrl = CTRL_P_BHP;
if (i_status == 2 && bhp <= 0)
{
fprintf (stderr, "Error: BHP = %lf for CONTROL %s in keyword W_PROD",
bhp, ctrl);
return -1;
}
}
else if (ctrl[0] == 'W') // close
{
i_ctrl = CTRL_P_WRATE;
if (i_status == 2 && wrate <= 0)
{
fprintf (stderr, "Error: WRATE = %lf for CONTROL %s in keyword W_PROD",
wrate, ctrl);
return -1;
}
}
else if (ctrl[0] == 'O') // close
{
i_ctrl = CTRL_P_ORATE;
if (i_status == 2 && orate <= 0)
{
fprintf (stderr, "Error: ORATE = %lf for CONTROL %s in keyword W_PROD",
orate, ctrl);
return -1;
}
}
else if (ctrl[0] == 'G') // close
{
i_ctrl = CTRL_P_GRATE;
if (i_status == 2 && grate <= 0)
{
fprintf (stderr, "Error: GRATE = %lf for CONTROL %s in keyword W_PROD",
grate, ctrl);
return -1;
}
}
else if (ctrl[0] == 'L') // close
{
i_ctrl = CTRL_P_LRATE;
if (i_status == 2 && lrate <= 0)
{
fprintf (stderr, "Error: LRATE = %lf for CONTROL %s in keyword W_PROD",
lrate, ctrl);
return -1;
}
}
else
{
fprintf (stderr, "Error: control %s for W_PROD not aloowed\n", status);
return -9;
}
if (i_status == STATUS_OPEN && wefac <= 0)
{
fprintf (stderr, "Error: WEFAC = %lf in keyword W_PROD",
wefac);
return -1;
}
printf ("W_PROD %s %s %s %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\n",
wname, status, ctrl, bhp, wrate, orate, grate, lrate, lim_bhp,
lim_wrate, lim_orate, lim_grate, lim_lrate, wefac);
// add to data base
sprintf (sql, "INSERT INTO well_hist(well_name, d, p_or, p_wr, p_gr, p_lr, \
p_bhp, wefac, ctrl, status, lim_p_or, lim_p_wr, lim_p_gr, lim_p_lr, lim_p_bhp) \
VALUES ('%s', %lf, %lf, %lf, %lf, %lf, %lf, %lf, %d, %d, %lf, %lf, %lf, %lf, %lf)",
wname, d, orate, wrate, grate, lrate, bhp, wefac, i_ctrl, i_status,
lim_orate, lim_wrate, lim_grate, lim_lrate, lim_bhp);
return exec_sql (sql);
return 0;
}
int
sql_well::read_date_and_time (char *buf, char **next_start, double *dd)
{
int rc = 0;
double days;
double t;
char *nx;
*next_start = buf;
fr_file->trim_left (next_start);
nx = *next_start;
rc |= fr_file->get_phrase (&nx);
if (**next_start == '*')
days = 0;
else
{
rc |= fr_file->get_dt ()->cstr2d (*next_start, days);
*dd = (double)days;
}
*next_start = nx;
fr_file->trim_left (next_start);
nx = *next_start;
rc |= fr_file->get_phrase (&nx);
if (**next_start == '*')
t = 0;
else
{
rc |= fr_file->get_dt ()->cstr2t (*next_start, t);
}
*next_start = nx;
*dd += (double)t;
return rc;
}
int
sql_well::save_to_bos_ascii_file (const std::wstring &fname_, sp_pool_t pool, sp_prop_t prop)
{
#ifdef UNIX
std::string fname = wstr2str (fname_);
#else
std::string fname = wstr2str (fname_, "ru_RU.CP1251");
#endif
FILE *fp = fopen (fname.c_str (), "w");
char s_buf[2048];
// interface to mesh
sp_himesh himesh = BS_KERNEL.create_object("handy_mesh_iface");
BS_ASSERT(himesh);
//const double eps = 1e-10;
sp_dt_t dt_t = BS_KERNEL.create_object ("dt_tools");
if (!fp)
{
printf ("Error: Can not open destination file %s\n", fname.c_str ());
return -1;
}
// obtain model dimensions
boost::python::list dims;
dims = pool->py_get_pool_dims();
t_long nx = boost::python::extract<int>(dims[0]);
t_long ny = boost::python::extract<int>(dims[1]);
//nz = boost::python::extract<int>(dims[2]);
//unsigned long nx_ny = nx * ny;
BS_SP (well_pool_iface) sp_wp = this;
// precalc trimesh backend to share among all compl & frac builders
sp_obj trim_backend = fci::wpi_algo::trimesh::create_backend(nx, ny,
pool->get_fp_data("COORD"), pool->get_fp_data("ZCORN"));
// here we wil store builders on every date
typedef std::list< fci::compl_n_frac_builder > cfb_storage_t;
typedef cfb_storage_t::iterator cfb_iterator;
typedef cfb_storage_t::const_iterator cfb_citerator;
cfb_storage_t cfb_storage;
// get dates list
std::string sql = "SELECT d FROM dates ORDER BY d ASC";
if (prepare_sql (sql.c_str ()))
return -1;
// fill dates array & calc COMPDATs on every date
std::list<double> dates;
for (; !step_sql ();)
{
double d = get_sql_real (0);
dates.push_back (d);
// prepare builder
fci::compl_n_frac_builder cfb;
cfb.init(nx, ny, trim_backend);
cfb.init(sp_wp);
if(cfb_storage.size() != 0)
cfb.share_cache_with(cfb_storage.front());
// find completions & save
cfb.compl_build(d);
cfb_storage.push_back(cfb);
}
finalize_sql ();
// wells in mesh come here
std::set< std::string > good_wells;
// check how many wells do we have
prepare_sql("SELECT COUNT(*) FROM wells");
if (!step_sql ())
{
BSOUT << "Wells count " << get_sql_int(0) << bs_end;
//point->resize (3 * get_sql_int(0));
}
else {
finalize_sql();
return -1;
}
finalize_sql();
/*-----------------------------------------------------------------
* Main cycle - iterate over all dates
*----------------------------------------------------------------*/
cfb_iterator p_cfb = cfb_storage.begin();
for (std::list<double>::const_iterator di = dates.begin(), de = dates.end(); di != de; ++di, ++p_cfb)
{
char d_buf[1024];
if (*di - int(*di) == 0) // if *di is integer
{
dt_t->d2ecl (*di, d_buf);
printf ("DATE %s\n", d_buf);
fprintf (fp, "DATES\n%s\n/\n\n", d_buf);
}
else
{
std::list<double>::const_iterator di_prev = di;
di_prev--;
double dt = *di - *di_prev;
printf ("TSTEP %.10lf \t DATETIME %.10lf\n", dt, *di);
fprintf (fp, "TSTEP\n%.10lf\n/\n\n", dt);
}
// WELSPECS only on first date
if(di == dates.begin()) {
fprintf (fp, "WELSPECS\n");
if (prepare_sql ("SELECT name FROM wells ORDER BY name ASC"))
return -1;
for (int i = 0; !step_sql (); i++)
{
// obtain well name
std::string s = get_sql_str (0);
// we can really just skip wells without any COMPDATs
// so we need to check compdats on every date
for(cfb_citerator p_cfb = cfb_storage.begin(), cfb_end = cfb_storage.end(); p_cfb != cfb_end; ++p_cfb) {
const fci::cd_storage& cd = p_cfb->storage_compdat();
fci::cd_storage::const_iterator p_cd = fci::compdat::find_first_cd(cd, s);
if(p_cd != cd.end()) {
// well has at least one COMPDAT, so write it to WELLSPEC
// using first COMPDAT cell_id as well's position
BSOUT << "Exporting well " << s << bs_end;
fprintf (fp,
(boost::format("\'%s\' \'FIELD\' %u %u /\n") % s %
(p_cd->cell_pos[0] + 1) % (p_cd->cell_pos[1] + 1)).str().c_str());
// remember well as good -- not really needed now
good_wells.insert(s);
break;
}
}
// quick and dirty check if well is good enough
if(good_wells.find(s) == good_wells.end()) {
BSOUT << "Warning! Well " << s << " has no active COMPDATs on any date and won't be exported!" << bs_end;
}
}
fprintf (fp, "/\n\n");
finalize_sql ();
}
// COMPDAT
// Building compdat to put first completion I, J to WELLSPECS
const fci::cd_storage& cd = p_cfb->storage_compdat();
const fci::cd_storage::const_iterator cde = cd.end();
const double eps = 1.0e-5;
const std::set< std::string >::const_iterator good_wells_end = good_wells.end();
if (!cd.empty ())
{
fprintf (fp, "COMPDAT\n");
for (fci::cd_storage::const_iterator cdi = cd.begin(); cdi != cde; ++cdi)
{
// skip out of mesh wells
if (fabs(cdi->kh_mult) > eps && good_wells.find(cdi->well_name) != good_wells_end)
{
if (cdi->status)
fprintf (fp,
(boost::format("\'%s\' %u %u %u %u \'OPEN\' 2* %lf 1* %lf 1* \'%c\' /\n") %
cdi->well_name % (cdi->cell_pos[0] + 1) % (cdi->cell_pos[1] + 1) % (cdi->cell_pos[2] + 1) %
(cdi->cell_pos[3] + 1) % cdi->diam % cdi->skin % cdi->dir).str().c_str());
else
fprintf (fp,
(boost::format("\'%s\' %u %u %u %u \'SHUT\' 2* %lf 1* %lf 1* \'%c\' /\n") %
cdi->well_name % (cdi->cell_pos[0] + 1) % (cdi->cell_pos[1] + 1) %
(cdi->cell_pos[2] + 1) % (cdi->cell_pos[3] + 1) % cdi->diam % cdi->skin % cdi->dir).str().c_str());
}
}
fprintf (fp, "/\n\n");
}
// WPIMULT
if (!cd.empty ())
{
int wpimult_exist = 0;
for (fci::cd_storage::const_iterator cdi = cd.begin(); cdi != cde; ++cdi)
{
if (fabs(cdi->kh_mult - 1.0) > 1e-6 && std::abs(cdi->kh_mult) > eps && good_wells.find(cdi->well_name) != good_wells_end)
{
if (!wpimult_exist)
fprintf (fp, "WPIMULT\n");
wpimult_exist = 1;
fprintf (fp,
(boost::format("\'%s\' %lf %u %u %u /\n") % cdi->well_name % cdi->kh_mult % (cdi->cell_pos[0] + 1) %
(cdi->cell_pos[1] + 1) % (cdi->cell_pos[2] + 1)).str().c_str());
}
}
if (wpimult_exist)
fprintf (fp, "/\n\n");
}
// FRACTURES
const fci::frac_storage& ft = p_cfb->frac_build(*di);
const fci::frac_storage::const_iterator fte = ft.end();
if (!ft.empty ())
{
char main_k_str[1024];
char perm_str[1024];
fprintf (fp, "FRACTURE\n");
for (fci::frac_storage::const_iterator fti = ft.begin (); fti != fte; ++fti)
{
// skip out-of-mesh wells
if(good_wells.find(fti->well_name) == good_wells_end)
continue;
if (fti->frac_perm > 0)
sprintf (perm_str, "%lf", fti->frac_perm);
else
sprintf (perm_str, " * * ");
int horiz = 0;
std::string sql = "SELECT name, horiz FROM wells WHERE name = ";
sql += std::string("'") + fti->well_name + std::string("'");
if (prepare_sql (sql.c_str ()))
return -1;
if (!step_sql ())
{
horiz = get_sql_int (1);
}
finalize_sql ();
if (horiz)
sprintf (main_k_str, "%d", fti->frac_main_k + 1);
else
sprintf (main_k_str, " * ");
fprintf (fp,
(boost::format("\'%s\' %u %u %u %u %lf %lf %lf \'%s\' %lf %s %s %s %s /\n") %
fti->well_name % (fti->cell_pos[0] + 1) % (fti->cell_pos[1] + 1) % (fti->cell_pos[2] + 1) %
(fti->cell_pos[3] + 1) % fti->frac_half_length_1 % (fti->frac_angle - 90) % fti->frac_skin %
(fti->frac_status == 0 ? "SHUT" : "OPEN") % fti->frac_half_thin % perm_str % " * " % " * " %
main_k_str).str().c_str()
);
}
fprintf (fp, "/\n\n");
}
// WCONINJH
// Injector wells with rate control having historical bhp value
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND ctrl < -1 AND i_bhp >= 0 ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconinjh_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconinjh_flag == 0)
{
fprintf (fp, "WCONINJH\n");
wconinjh_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double i_or = get_sql_real (8);
double i_wr = get_sql_real (9);
double i_gr = get_sql_real (10);
double i_bhp = get_sql_real (11);
double rate = i_wr;
std::string s_status;
std::string s_phase = "WATER";
std::string s_rate;
std::string s_bhp;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
if (ctrl == CTRL_I_ORATE)
{
s_phase = "OIL";
rate = i_or;
}
else if (ctrl == CTRL_I_GRATE)
{
s_phase = "GAS";
rate = i_gr;
}
if (rate > 0)
{
s_rate = V2S(rate);
}
else
{
s_rate = "*";
}
if (i_bhp > 0)
{
s_bhp = V2S(i_bhp);
}
else
{
s_bhp = "*";
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' %s %s ", s.c_str (), s_phase.c_str(), s_status.c_str(), s_rate.c_str(), s_bhp.c_str());
fprintf (fp, "/\n");
}
if (wconinjh_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WCONINJE
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND (i_bhp < 0 AND ctrl < -1 OR ctrl = -1) ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconinje_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconinje_flag == 0)
{
fprintf (fp, "WCONINJE\n");
wconinje_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double i_or = get_sql_real (8);
double i_wr = get_sql_real (9);
double i_gr = get_sql_real (10);
double i_bhp = get_sql_real (11);
double lim_bhp = get_sql_real (11);
double rate = i_wr;
std::string s_status;
std::string s_ctrl;
std::string s_phase;
std::string s_params;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
s_ctrl = "BHP";
// TODO: add injection phase into DB
s_phase = "WATER";
s_params = (boost::format("2* %lf") % i_bhp).str();
if (ctrl == CTRL_I_BHP)
{
s_ctrl = "BHP";
// TODO: add injection phase into DB
s_phase = "WATER";
s_params = (boost::format("2* %lf") % i_bhp).str();
}
else
{
s_ctrl = "RATE";
if (ctrl == CTRL_I_WRATE)
s_phase = "WATER";
else if (ctrl == CTRL_I_ORATE)
{
s_phase = "OIL";
rate = i_or;
}
else if (ctrl == CTRL_I_GRATE)
{
s_phase = "GAS";
rate = i_gr;
}
else
s_phase = "WATER";
s_params = (boost::format("%s 2*") % V2S(rate)).str();
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' \'%s\' %s ", s.c_str (), s_phase.c_str(), s_status.c_str(),
s_ctrl.c_str(), s_params.c_str());
/*
if (rate < 0)
fprintf (fp, "2* ");
else
fprintf (fp, "%lf 1* ", rate);
if (i_bhp < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", i_bhp);
*/
fprintf (fp, "/\n");
}
if (wconinje_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WCONHIST
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND p_bhp >= 0 AND ctrl > 1 ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconhist_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconhist_flag == 0)
{
fprintf (fp, "WCONHIST\n");
wconhist_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double p_or = get_sql_real (2);
double p_wr = get_sql_real (3);
double p_gr = get_sql_real (4);
double p_bhp = get_sql_real (6);
std::string s_status;
std::string s_ctrl;
std::string s_params;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
if (ctrl == CTRL_P_LRATE)
{
s_ctrl = "LRAT";
if (status == STATUS_OPEN && (p_or + p_wr == 0))
continue;
}
else if (ctrl == CTRL_P_ORATE)
{
s_ctrl = "ORAT";
if (status == STATUS_OPEN && (p_or == 0))
continue;
}
else if (ctrl == CTRL_P_WRATE)
{
s_ctrl = "WRAT";
if (status == STATUS_OPEN && (p_wr == 0))
continue;
}
else if (ctrl == CTRL_P_GRATE)
{
s_ctrl = "GRAT";
if (status == STATUS_OPEN && (p_gr == 0))
continue;
}
if (p_bhp > 0)
{
s_params = (boost::format("%s %s %s 3* %s") % V2S(p_or) % V2S(p_wr)% V2S(p_gr) % V2S(p_bhp)).str();
}
else
{
s_params = (boost::format("%s %s %s 4*") % V2S(p_or) % V2S(p_wr)% V2S(p_gr)).str();
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' %s ", s.c_str (), s_status.c_str(), s_ctrl.c_str(), s_params.c_str());
/*
if (p_or < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_or);
if (p_wr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_wr);
if (p_gr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_gr);
if (p_lr < 0)
fprintf (fp, "2* ");
else
fprintf (fp, "%lf * ", p_lr);
if (p_bhp < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_bhp);
*/
fprintf (fp, "/\n");
}
if (wconhist_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WCONPROD
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND (p_bhp < 0 AND ctrl > 1 OR ctrl = 1) ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconprod_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconprod_flag == 0)
{
fprintf (fp, "WCONPROD\n");
wconprod_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double p_or = get_sql_real (2);
double p_wr = get_sql_real (3);
double p_gr = get_sql_real (4);
double p_lr = get_sql_real (5);
double p_bhp = get_sql_real (6);
std::string s_status;
std::string s_ctrl;
std::string s_params;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
if (ctrl == CTRL_P_LRATE)
{
s_ctrl = "LRAT";
s_params = (boost::format("3* %s 2*") % V2S(p_lr)).str();
}
else if (ctrl == CTRL_P_BHP)
{
s_ctrl = "BHP";
s_params = (boost::format("5* %s") % V2S(p_bhp)).str();
}
else if (ctrl == CTRL_P_ORATE)
{
s_ctrl = "ORAT";
s_params = (boost::format("%s 5*") % V2S(p_or)).str();
}
else if (ctrl == CTRL_P_WRATE)
{
s_ctrl = "WRAT";
s_params = (boost::format("1* %s 4*") % V2S(p_wr)).str();
}
else if (ctrl == CTRL_P_GRATE)
{
s_ctrl = "GRAT";
s_params = (boost::format("2* %s 3*") % V2S(p_gr)).str();
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' %s ", s.c_str (), s_status.c_str(), s_ctrl.c_str(), s_params.c_str());
/*
if (p_or < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_or);
if (p_wr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_wr);
if (p_gr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_gr);
if (p_lr < 0)
fprintf (fp, "2* ");
else
fprintf (fp, "%lf * ", p_lr);
if (p_bhp < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_bhp);
*/
fprintf (fp, "/\n");
}
if (wconprod_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WELTARG BHP limit for injectors
sprintf (s_buf, "SELECT well_name, lim_i_bhp, lim_p_bhp FROM well_hist WHERE d=%lf AND (lim_i_bhp > 0 OR lim_p_bhp > 0) ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint weltarg_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (weltarg_flag == 0)
{
fprintf (fp, "WELTARG\n");
weltarg_flag++;
}
double lim_i_bhp = get_sql_real (1);
double lim_p_bhp = get_sql_real (2);
if (lim_i_bhp > 0)
fprintf (fp, "\'%s\' BHP %s ", s.c_str (), V2S(lim_i_bhp));
else if (lim_p_bhp > 0)
fprintf (fp, "\'%s\' BHP %s ", s.c_str (), V2S(lim_p_bhp));
fprintf (fp, "/\n");
}
if (weltarg_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WEFAC
sprintf (s_buf, "SELECT well_name, wefac FROM well_hist WHERE d=%lf ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wefac_flag = 0;
for (; !step_sql ();)
{
double wefac = get_sql_real (1);
if (wefac == 1.0)
continue;
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wefac_flag == 0)
{
fprintf (fp, "WEFAC\n");
wefac_flag++;
}
fprintf (fp, "\'%s\' %lf", s.c_str (), wefac);
fprintf (fp, "/\n");
}
if (wefac_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
} // eof main cycle over dates
fclose (fp);
return 0;
}
#ifdef BSPY_EXPORTING_PLUGIN
std::string
sql_well::py_str () const
{
std::stringstream s;
s << file_name << "\n";
return s.str ();
}
#endif //BSPY_EXPORTING_PLUGIN
/////////////////////////////////BS Register
/////////////////////////////////Stuff//////////////////////////
BLUE_SKY_TYPE_STD_CREATE (sql_well);
BLUE_SKY_TYPE_STD_COPY (sql_well);
BLUE_SKY_TYPE_IMPL(sql_well, well_pool_iface, "sql_well", "sql_well storage", "realization of well sql_well storage");
} // blue_sky namespace
schedule fracture export fix
/**
* @file sql_well.cpp
* @brief implementation of frac storage
* @author Oleg Borschuk
* @version
* @date 2011-07-29
*/
// d REAL NOT NULL REFERENCES dates(d) ON UPDATE CASCADE ON DELETE CASCADE,
//
// d REAL NOT NULL,
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/fstream.hpp"
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include "bs_kernel.h"
#include "sql_well.h"
#include "frac_comp_ident.h"
#include "i_cant_link_2_mesh.h"
using namespace boost;
#ifdef BSPY_EXPORTING_PLUGIN
#include <boost/python.hpp>
using namespace boost::python;
#endif //BSPY_EXPORTING_PLUGIN
// shorthand macro to pass values via val2str filter
#define V2S(t) val2str::go(t).c_str()
namespace blue_sky
{
// hidden details
namespace {
// the purpose of this helper is to print '1*' if argument == -1
// otherwise number converted to string is unchanged
struct val2str {
// specialization for floating-point numbers
template< class T >
static std::string do_fix(const T& v, const boost::true_type) {
if(v == -1.0)
return "1*";
else
return boost::lexical_cast< std::string >(v);
}
// specialization for other types
template< class T >
static std::string do_fix(const T& v, const boost::false_type) {
return boost::lexical_cast< std::string >(v);
}
// main operator
template< class T >
static std::string go(const T& v) {
return do_fix(v, boost::is_floating_point< T >());
}
};
}
int clear_table (void *pData, int nColumns,
char **values, char ** /*columns*/)
{
int rc = 0;
char *zErrMsg = 0;
if (nColumns != 1)
return 1; // Error
sqlite3* db = (sqlite3*)pData;
char *stmt = sqlite3_mprintf("DELETE FROM backup.%q",
values[0]);
rc = sqlite3_exec (db, stmt, NULL, NULL, &zErrMsg);
sqlite3_free (stmt);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
int main_to_backup (void *pData, int nColumns,
char **values, char ** /*columns*/)
{
int rc = 0;
char *zErrMsg = 0;
if (nColumns != 1)
return 1; // Error
sqlite3* db = (sqlite3*)pData;
char *stmt = sqlite3_mprintf("insert into backup.%q select * from main.%q",
values[0], values[0]);
rc = sqlite3_exec (db, stmt, NULL, NULL, &zErrMsg);
sqlite3_free (stmt);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
int backup_to_main (void *pData, int nColumns,
char **values, char ** /*columns*/)
{
int rc = 0;
char *zErrMsg = 0;
if (nColumns != 1)
return 1; // Error
sqlite3* db = (sqlite3*)pData;
char *stmt = sqlite3_mprintf("insert into main.%q select * from backup.%q",
values[0], values[0]);
rc = sqlite3_exec (db, stmt, NULL, NULL, &zErrMsg);
sqlite3_free (stmt);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
sql_well::sql_well (bs_type_ctor_param)
{
db = 0;
stmp_sql = 0;
fr_file = 0;
}
sql_well::sql_well (const sql_well& rhs)
: bs_refcounter (), file_name(rhs.file_name), db(rhs.db)
{
//*this = rhs;
// don't copy pending statement
stmp_sql = 0;
fr_file = 0;
}
sql_well::~sql_well ()
{
}
int
sql_well::open_db (const std::wstring &file_)
{
int rc = 0;
char *zErrMsg = 0;
if (db)
close_db ();
std::string file = wstr2str (file_);
printf ("SQL open_db %s\n", file.c_str ());
if (!strcmp(file.c_str(),":memory:") || !boost::filesystem::exists (file))
{
rc = sqlite3_open (file.c_str (), &db);
if (rc)
{
fprintf (stderr, "Can't open database: %s (%s)\n", sqlite3_errmsg (db), file.c_str());
sqlite3_close (db);
db = 0;
return -1;
}
create_db (db);
rc = sqlite3_exec (db, "INSERT INTO groups(name) VALUES ('field');", NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
//sqlite3_close (db);
}
else
{
rc = sqlite3_open (file.c_str (), &db);
if (rc)
{
fprintf (stderr, "Can't open database: %s (%s) - 2\n", sqlite3_errmsg (db), file.c_str());
sqlite3_close (db);
db = 0;
return -1;
}
}
file_name = file;
#if 0
char buf[2048];
rc = sqlite3_open (":memory:", &db);
if (rc)
{
fprintf (stderr, "Can't open database: %s\n", sqlite3_errmsg (db));
sqlite3_close (db);
db = 0;
return -1;
}
file_name = file;
// load from file to memory
rc = create_db (db);
if (rc)
return rc;
sprintf (buf, "ATTACH DATABASE '%s' as backup; BEGIN", file.c_str ());
rc = sqlite3_exec (db, buf, NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
rc = sqlite3_exec(db, "SELECT name FROM backup.sqlite_master WHERE type='table'",
&backup_to_main, db, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
sqlite3_exec(db, "COMMIT; DETACH DATABASE backup", NULL, NULL, NULL);
#else //0
#endif //0
return 0;
}
void
sql_well::backup_to_file (const std::wstring &filename)
{
if (!db)
return;
sqlite3 *ddb = 0;
int rc = sqlite3_open (wstr2str (filename).c_str (), &ddb);
if (rc)
{
fprintf (stderr, "Can't open database: %s\n", sqlite3_errmsg (ddb));
sqlite3_close (ddb);
ddb = 0;
return;
}
sqlite3_backup *b = sqlite3_backup_init(ddb, "main", db, "main");
if (b)
{
while(sqlite3_backup_step(b, -1) == SQLITE_OK) {}
//while (sqlite3_backup_remaining(b) > 0)
sqlite3_backup_finish(b);
}
rc = sqlite3_errcode(ddb);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error with backup_to_file: %d\n", rc);
}
sqlite3_close(ddb);
//db->sqlite_backup_to_file(filename);
}
int
sql_well::merge_with_db(const std::wstring& dbname_)
{
if (!db)
return 0;
if (stmp_sql)
finalize_sql ();
std::string dbname = wstr2str (dbname_);
int rc = 0;
char *zErrMsg = 0;
std::string sql = "attach '" + dbname + "' as tomerge; insert or ignore into groups select * from tomerge.groups; \
insert or ignore into dates select * from tomerge.dates; \
insert or ignore into wells select * from tomerge.wells; \
insert or replace into branches select * from tomerge.branches; \
insert or ignore into completions select * from tomerge.completions; \
insert or ignore into fractures select * from tomerge.fractures; \
insert or ignore into permfrac select * from tomerge.permfrac; \
insert or ignore into well_hist select * from tomerge.well_hist; \
insert or ignore into wells_in_group select * from tomerge.wells_in_group; \
detach database tomerge";
rc = sqlite3_exec (db, sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error with tomerge: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
return 0;
}
int
sql_well::create_db (sqlite3 *db_in)
{
int rc = 0;
char *zErrMsg = 0;
const char *sql = \
"\
PRAGMA foreign_keys=ON;\
BEGIN;\
CREATE TABLE wells(name TEXT UNIQUE PRIMARY KEY, \
x REAL DEFAULT -1, \
y REAL DEFAULT -1, \
horiz INTEGER DEFAULT 0);\
CREATE TABLE groups(name TEXT UNIQUE PRIMARY KEY);\
CREATE TABLE wells_in_group(gr_name TEXT NOT NULL REFERENCES groups(name) ON UPDATE CASCADE ON DELETE CASCADE,\
well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE);\
CREATE INDEX i4 ON wells_in_group (gr_name ASC);\
CREATE INDEX i5 ON wells_in_group (well_name ASC);\
CREATE TABLE dates(d REAL UNIQUE PRIMARY KEY);\
CREATE TABLE well_hist(well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE,\
d REAL NOT NULL, \
p_or REAL DEFAULT -1,\
p_wr REAL DEFAULT -1,\
p_gr REAL DEFAULT -1,\
p_lr REAL DEFAULT -1,\
p_bhp REAL DEFAULT -1,\
p_fgr REAL DEFAULT -1,\
i_or REAL DEFAULT -1,\
i_wr REAL DEFAULT -1,\
i_gr REAL DEFAULT -1,\
i_bhp REAL DEFAULT -1,\
wefac REAL DEFAULT 1.0,\
ctrl INTEGER DEFAULT 0,\
status INTEGER DEFAULT 0,\
lim_p_or REAL DEFAULT -1,\
lim_p_wr REAL DEFAULT -1,\
lim_p_gr REAL DEFAULT -1,\
lim_p_lr REAL DEFAULT -1,\
lim_p_bhp REAL DEFAULT -1,\
lim_i_or REAL DEFAULT -1,\
lim_i_wr REAL DEFAULT -1,\
lim_i_gr REAL DEFAULT -1,\
lim_i_bhp REAL DEFAULT -1);\
CREATE INDEX i1 ON well_hist (well_name ASC);\
CREATE INDEX i2 ON well_hist (d ASC);\
CREATE UNIQUE INDEX i3 ON well_hist (well_name, d ASC);\
CREATE TABLE well_res(well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE,\
d REAL NOT NULL, \
p_or REAL DEFAULT -1,\
p_wr REAL DEFAULT -1,\
p_gr REAL DEFAULT -1,\
p_bhp REAL DEFAULT -1,\
i_or REAL DEFAULT -1,\
i_wr REAL DEFAULT -1,\
i_gr REAL DEFAULT -1,\
i_bhp REAL DEFAULT -1,\
wefac REAL DEFAULT 1,\
p_gor REAL DEFAULT -1,\
p_fgr REAL DEFAULT -1,\
ctrl INTEGER DEFAULT 0,\
status INTEGER DEFAULT 0,\
tot_p_or REAL DEFAULT -1,\
tot_p_wr REAL DEFAULT -1,\
tot_p_gr REAL DEFAULT -1,\
tot_p_fgr REAL DEFAULT -1,\
tot_i_or REAL DEFAULT -1,\
tot_i_wr REAL DEFAULT -1,\
tot_i_gr REAL DEFAULT -1);\
CREATE INDEX i6 ON well_res (well_name ASC);\
CREATE INDEX i7 ON well_res (d ASC);\
CREATE UNIQUE INDEX i8 ON well_res (well_name, d ASC);\
CREATE TABLE branches(well_name TEXT NOT NULL REFERENCES wells(name) ON UPDATE CASCADE ON DELETE CASCADE,\
branch_name TEXT NOT NULL DEFAULT 'main', \
md REAL DEFAULT -1,\
parent TEXT DEFAULT '',\
traj BLOB, \
well_log BLOB,\
PRIMARY KEY (well_name, branch_name));\
CREATE INDEX i9 ON branches (well_name ASC);\
CREATE UNIQUE INDEX i10 ON branches (well_name, branch_name ASC);\
CREATE TRIGGER tr1 AFTER INSERT ON wells\
BEGIN\
INSERT INTO branches(well_name, branch_name) VALUES(new.name, 'main');\
END;\
CREATE TRIGGER tr2 AFTER INSERT ON wells\
BEGIN\
INSERT INTO wells_in_group(gr_name, well_name) VALUES ('field', new.name);\
END;\
CREATE TABLE fractures(well_name TEXT NOT NULL,\
branch_name TEXT DEFAULT 'main', \
md REAL NOT NULL, \
d REAL NOT NULL, \
status INTEGER DEFAULT 0,\
half_up REAL DEFAULT 5,\
half_down REAL DEFAULT 5,\
angle REAL DEFAULT 0,\
half_length_1 REAL DEFAULT 50,\
half_length_2 REAL DEFAULT 50,\
perm REAL DEFAULT -1,\
half_thin REAL DEFAULT 0.005,\
skin REAL DEFAULT 0,\
FOREIGN KEY (well_name, branch_name) REFERENCES branches(well_name, branch_name) ON UPDATE CASCADE ON DELETE CASCADE\
);\
CREATE INDEX i11 ON fractures (well_name ASC);\
CREATE INDEX i12 ON fractures (well_name, branch_name ASC);\
CREATE TABLE completions(well_name TEXT NOT NULL, \
branch_name TEXT NOT NULL DEFAULT 'main', \
md REAL NOT NULL, \
d REAL NOT NULL, \
status INTEGER DEFAULT 0,\
length REAL DEFAULT 1,\
rw REAL DEFAULT 0.08,\
r0 REAL DEFAULT -1,\
kh REAL DEFAULT -1,\
kh_mult REAL DEFAULT 1,\
skin REAL DEFAULT 0,\
FOREIGN KEY (well_name, branch_name) REFERENCES branches(well_name, branch_name) ON UPDATE CASCADE ON DELETE CASCADE\
); \
CREATE INDEX i13 ON completions (well_name ASC);\
CREATE INDEX i14 ON completions (well_name, branch_name ASC);\
CREATE TRIGGER tr3 BEFORE INSERT ON fractures\
BEGIN\
INSERT OR REPLACE INTO dates(d) VALUES(new.d);\
END;\
CREATE TRIGGER tr4 BEFORE INSERT ON completions\
BEGIN\
INSERT OR REPLACE INTO dates(d) VALUES(new.d);\
END;\
CREATE TRIGGER tr5 BEFORE INSERT ON well_hist\
BEGIN\
INSERT OR REPLACE INTO dates(d) VALUES(new.d);\
END;\
CREATE TABLE permfrac(d REAL NOT NULL, \
status INTEGER DEFAULT 0,\
x1 REAL NOT NULL,\
y1 REAL NOT NULL,\
x2 REAL NOT NULL,\
y2 REAL NOT NULL,\
z_top REAL NOT NULL,\
z_bottom REAL NOT NULL,\
dx REAL DEFAULT 0.01,\
dy REAL DEFAULT 0.01,\
perm REAL NOT NULL,\
i1 INTEGER DEFAULT -1,\
j1 INTEGER DEFAULT -1,\
i2 INTEGER DEFAULT -1,\
j2 INTEGER DEFAULT -1,\
k1 INTEGER DEFAULT -1,\
k2 INTEGER DEFAULT -1);\
COMMIT;\
";
if (!db_in)
return -1;
rc = sqlite3_exec (db_in, sql, NULL, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
void
sql_well::close_db ()
{
if (db)
{
if (stmp_sql)
finalize_sql ();
#if 0
int rc = 0;
char *zErrMsg = 0;
char buf[2048];
sprintf (buf, "ATTACH DATABASE '%s' as backup; BEGIN", file_name.c_str ());
rc = sqlite3_exec (db, buf, NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
rc = sqlite3_exec (db, "SELECT name FROM backup.sqlite_master WHERE type='table'",
&clear_table, db, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
rc = sqlite3_exec (db, "SELECT name FROM main.sqlite_master WHERE type='table'",
&main_to_backup, db, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
sqlite3_exec(db, "COMMIT; DETACH DATABASE backup", NULL, NULL, NULL);
#endif //0
sqlite3_close (db);
}
db = 0;
file_name = "";
}
int
sql_well::create_db_struct ()
{
return create_db (db);
}
void
sql_well::fill_db ()
{
//int rc = 0;
//char *zErrMsg = 0;
char sw_name[4096];
char sw_sel[4096];
char sw_ins[4096];
char sw_up[4096];
if (!db)
return;
if (stmp_sql)
finalize_sql ();
//rc = sqlite3_exec (db, "BEGIN TRANSACTION", NULL, 0, &zErrMsg);
for (int i = 0; i < 500; ++i)
{
sprintf (sw_name, "well_%d", i);
add_well (std::string (sw_name));
for (double j = 0; j < 240; j = j + 1.0)
{
sprintf (sw_ins, "INSERT INTO well_dynamic (well_name, date, h_wrate) VALUES ('well_%d', %lf, %lf)",
i, j, 50.0);
sprintf (sw_up, "UPDATE well_dynamic SET h_orate = %lf WHERE well_name='well_%d' and date=%lf",
j, i, j);
sprintf (sw_sel, "SELECT * FROM well_dynamic WHERE well_name='well_%d' and date=%lf",
i, j);
//printf ("%s\n", sw);
if (insert_or_update (std::string (sw_sel),
std::string (sw_ins),
std::string (sw_up)))
{
return;
}
}
}
//rc = sqlite3_exec (db, "COMMIT TRANSACTION", NULL, 0, &zErrMsg);
return;
}
int
sql_well::insert_or_update (const std::string &select_sql,
const std::string &insert_sql,
const std::string &update_sql)
{
if (!db)
return -2;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
rc = sqlite3_prepare_v2 (db, select_sql.c_str (), select_sql.length () + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -1;
}
if (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
sqlite3_finalize (stmp);
rc = sqlite3_exec (db, update_sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
}
else
{
sqlite3_finalize (stmp);
rc = sqlite3_exec (db, insert_sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
}
return 0;
}
int
sql_well::add_well (const std::string &well_name)
{
if (!db)
return -2;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
char buf[2048];
sprintf (buf, "INSERT INTO wells (name) VALUES('%s');",
well_name.c_str ());
rc = sqlite3_exec (db, buf, NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error (add_well): %s\n", zErrMsg);
sqlite3_free (zErrMsg);
}
return 0;
}
sql_well::list_t
sql_well::get_well_names () const
{
list_t lst;
if (!db)
return lst;
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
std::string sql = "SELECT name FROM wells ORDER BY name ASC";
rc = sqlite3_prepare_v2 (db, sql.c_str (), sql.length () + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return lst;
}
while (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
lst.push_back (std::string ((const char *)sqlite3_column_text (stmp, 0)));
}
sqlite3_finalize (stmp);
return lst;
}
int
sql_well::add_branch_gis (const std::string &wname, const std::string &branch,
sp_gis_t g)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "UPDATE branches SET well_log = @q WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf), &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -1;
}
std::string s = g->to_str();
std::vector<char> ch (s.begin (), s.end ());
//printf ("GIS\n%s\n", s.c_str ());
//printf ("GIS INT %d %d\n", (int)strlen (s.c_str ()), (int)s.length ());
rc = sqlite3_bind_blob (stmp, 1, &ch[0], ch.size (), SQLITE_STATIC);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -3;
}
sqlite3_step (stmp); // UPDATE
sqlite3_finalize (stmp);
return 0;
}
sql_well::sp_gis_t
sql_well::get_branch_gis (const std::string &wname, const std::string &branch) const
{
sp_gis_t sp_gis = BS_KERNEL.create_object ("gis");
if (!db)
return sp_gis_t ();
if (stmp_sql)
return sp_gis_t ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "SELECT well_log FROM branches WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
sqlite3_finalize (stmp);
return sp_gis_t ();
}
if (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
int n = sqlite3_column_bytes (stmp, 0);
if (n < 1)
{
sqlite3_finalize (stmp);
return sp_gis_t ();
}
const char *b = (const char *)sqlite3_column_blob (stmp, 0);
//std::string s = (const char *)sqlite3_column_text (stmp, 0);
std::string s;
s.assign (b, n);
printf ("READ GIS %d\n", (int)s.length ());
sp_gis->from_str(s);
}
else
{
return sp_gis_t ();
}
sqlite3_finalize (stmp);
return sp_gis;
}
int
sql_well::add_branch_traj (const std::string &wname, const std::string &branch,
sp_traj_t t)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "UPDATE branches SET traj = @w WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -1;
}
std::string s = t->to_str();
std::vector<char> ch (s.begin (), s.end ());
rc = sqlite3_bind_blob (stmp, 1, &ch[0], ch.size (), SQLITE_STATIC);
//printf ("TRAJ\n%s\n", s.c_str ());
//printf ("TRAJ INT %d %d\n", (int)strlen (s.c_str ()), (int)s.length ());
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
return -3;
}
sqlite3_step (stmp); // UPDATE
sqlite3_finalize (stmp);
return 0;
}
sql_well::sp_traj_t
sql_well::get_branch_traj (const std::string &wname, const std::string &branch) const
{
sp_traj_t sp_traj = BS_KERNEL.create_object ("traj");
if (!db)
return sp_traj_t ();
if (stmp_sql)
return sp_traj_t ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "SELECT traj FROM branches WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
sqlite3_finalize (stmp);
return sp_traj_t ();
}
if (sqlite3_step (stmp) == SQLITE_ROW) // UPDATE
{
int n = sqlite3_column_bytes (stmp, 0);
if (!n)
{
sqlite3_finalize (stmp);
return sp_traj_t ();
}
const char *b = (const char *)sqlite3_column_blob (stmp, 0);
//std::string s = (const char *)sqlite3_column_text (stmp, 0);
std::string s;
s.assign (b, n);
printf ("READ TRAJ %d\n", (int)s.length ());
sp_traj->from_str(s);
}
else
{
return sp_traj_t ();
}
sqlite3_finalize (stmp);
return sp_traj;
}
int
sql_well::update_branch_traj (const std::string &wname, const std::string &branch,
sp_traj_t t)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
int rc = 0;
//char *zErrMsg = 0;
const char *ttt;
sqlite3_stmt *stmp;
char buf[4096];
sprintf (buf, "SELECT traj FROM branches WHERE well_name = '%s' AND branch_name = '%s'",
wname.c_str (), branch.c_str ());
rc = sqlite3_prepare_v2 (db, buf, strlen (buf) + 1, &stmp, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
if(stmp) sqlite3_finalize (stmp);
return -1;
}
std::string s = t->to_str();
std::vector<char> ch (s.begin (), s.end ());
rc = sqlite3_bind_blob (stmp, 1, &ch[0], ch.size (), SQLITE_STATIC);
//printf ("TRAJ\n%s\n", s.c_str ());
//printf ("TRAJ INT %d %d\n", (int)strlen (s.c_str ()), (int)s.length ());
if (rc)
{
fprintf (stderr, "Can't make select: %s\n", sqlite3_errmsg (db));
if(stmp) sqlite3_finalize (stmp);
return -3;
}
sqlite3_step (stmp); // UPDATE
sqlite3_finalize (stmp);
return 0;
}
int
sql_well::prepare_sql (const std::string &sql)
{
if (!db)
return -1;
if (stmp_sql)
finalize_sql ();
const char *ttt;
int rc = 0;
rc = sqlite3_prepare_v2 (db, sql.c_str (), sql.length () + 1, &stmp_sql, &ttt);
if (rc)
{
fprintf (stderr, "Can't make select: %s (%d)\n", sqlite3_errmsg (db), rc);
fprintf (stderr, "Query: %s\n", sql.c_str());
return -1;
}
return 0;
}
//#ifdef BSPY_EXPORTING_PLUGIN
spv_double
sql_well::get_table (const std::string &table_name, boost::python::list &table_columns, const std::string &filter)
{
std::string request_str = "SELECT COUNT(*) FROM " + table_name + " " + filter;
prepare_sql (request_str);
step_sql ();
int n_rows = get_sql_int(0);
finalize_sql ();
if (n_rows < 1)
return BS_KERNEL.create_object (v_double::bs_type());
int n_cols = boost::python::len (table_columns);
spv_double table = BS_KERNEL.create_object (v_double::bs_type());
table->resize (n_rows * n_cols);
double *table_values = &(*table)[0];
request_str = "SELECT ";
for (int j = 0; j < n_cols; j++)
{
std::string col_name = extract<std::string>(table_columns[j]);
//TODO: check col_name
request_str = request_str + col_name;
if (j < n_cols - 1)
request_str = request_str + ", ";
}
request_str = request_str + " FROM " + table_name + " " + filter;
prepare_sql (request_str);
for (int i = 0; (i < n_rows) && (!step_sql ()); ++i)
{
for (int j = 0; j < n_cols; j++)
{
table_values[i * n_cols + j] = get_sql_real(j);
}
}
finalize_sql ();
npy_intp dims[] = {n_rows, n_cols};
table->reshape (2, dims);
return table;
}
//#endif //BSPY_EXPORTING_PLUGIN
int
sql_well::step_sql ()
{
if (!db)
return -1;
if (!stmp_sql)
return -1;
if (sqlite3_step (stmp_sql) == SQLITE_ROW) // UPDATE
return 0;
else
return 2;
}
int
sql_well::finalize_sql ()
{
if (stmp_sql)
{
sqlite3_finalize (stmp_sql);
stmp_sql = 0;
}
return 0;
}
t_int
sql_well::get_sql_int (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return (t_int)sqlite3_column_int (stmp_sql, (int)col);
}
t_double
sql_well::get_sql_real (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return (t_double)sqlite3_column_double (stmp_sql, (int)col);
}
bool
sql_well::get_sql_bool (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return (bool)sqlite3_column_int (stmp_sql, (int)col);
}
std::string
sql_well::get_sql_str (t_int col)
{
if (!db)
return 0;
if (!stmp_sql)
return 0;
return std::string ((const char *)sqlite3_column_text (stmp_sql, (int)col));
}
bool
sql_well::get_sql_exist (t_int col)
{
if (!db)
return false;
if (!stmp_sql)
return false;
int n = sqlite3_column_bytes(stmp_sql, (int)col);
return (bool)n;
}
int
sql_well::exec_sql (const std::string &sql)
{
if (!db)
return 0;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
rc = sqlite3_exec (db, sql.c_str (), NULL, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s, when query \"%s\"\n", zErrMsg, sql.c_str());
sqlite3_free (zErrMsg);
return -4;
}
return 0;
}
int
sql_well::exec_sql_and_return_rowid (const std::string &sql)
{
if (!db)
return 0;
if (stmp_sql)
finalize_sql ();
int rc = 0;
char *zErrMsg = 0;
int rowid = -1;
rc = sqlite3_exec (db, sql.c_str (), NULL, 0, &zErrMsg);
rowid = sqlite3_last_insert_rowid(db);
if( rc != SQLITE_OK )
{
fprintf (stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free (zErrMsg);
return -4;
}
return rowid;
}
int
sql_well::read_from_ascii_file (const std::string &fname, double starting_date)
{
//if (fr_file)
// delete fr_file;
//fr_file = new FRead (fname.c_str (), fname.c_str ());
fr_file = BS_KERNEL.create_object ("bos_reader");
fr_file->open (fname.c_str (), fname.c_str ());
int rc = 0;
char buf[4096];
char *id = 0;
char *other = 0;
double d = 0;
for (;;)
{
rc = fr_file->read_line (buf, 4096, FREAD_DONT_CONVERT_CASE);
//printf ("%s\n", buf);
if (rc <= 0)
break;
d = starting_date;
// read date and time
rc = read_date_and_time (buf, &id, &d);
if (rc)
return -4;
// read id
fr_file->trim_left (&id);
other = id;
rc |= fr_file->get_phrase (&other);
if (rc)
return -1;
//trim_right_s (id);
fr_file->locale_ucase (id);
if (!strcmp (id, "W_SPEC"))
{
rc = read_w_spec (other);
if (rc)
return rc;
}
else if (!strcmp (id, "W_BRANCH_F"))
{
rc = read_w_branch_f (other);
if (rc)
return rc;
}
else if (!strcmp (id, "W_COMP"))
{
rc = read_w_comp (other, d);
if (rc)
return rc;
}
else if (!strcmp (id, "W_FRAC"))
{
rc = read_w_frac (other, d);
if (rc)
return rc;
}
else if (!strcmp (id, "W_PROD"))
{
rc = read_w_prod (other, d);
if (rc)
return rc;
}
else if (!strcmp (id, "W_INJ"))
{
rc = read_w_inj (other, d);
if (rc)
return rc;
}
//printf ("date %lf\n", d);
//printf ("next: %s\n", next);
}
return 0;
}
int
sql_well::read_w_branch_f (char *buf)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char branch[1024];
char parent[1024];
char fname[1024];
char fname2[1024];
char sql[1024];
double md = -1;
// read well name
wname[0] = '\0';
nx = buf;
// read well name
rc = fr_file->get_phrase_str (&nx, wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_BRANCH_F can not be set by default\n");
return -1;
}
// read branch
strcpy (branch, "main");
rc = fr_file->get_phrase_str (&nx, branch);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read branch name\n");
return -1;
}
// read parent
parent[0] = '\0';
rc = fr_file->get_phrase_str (&nx, parent);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read parent name\n");
return -1;
}
//read md
rc = fr_file->get_phrase_double (&nx, &md);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F\n");
return -1;
}
// read file name
fname[0] = '\0';
rc = fr_file->get_phrase_filepath (&nx, fname);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read file name\n");
return -1;
}
// read well_log file name
fname2[0] = '\0';
rc = fr_file->get_phrase_filepath (&nx, fname2);
if (rc)
{
fprintf (stderr, "Error: W_BRANCH_F can not read file name\n");
return -1;
}
// add to data base
sprintf (sql, "INSERT OR REPLACE INTO branches(well_name, branch_name, md, parent) VALUES ('%s', '%s', %lf, '%s')",
wname, branch, md, parent);
printf ("SQL: %s\n", sql);
if (exec_sql (sql))
return -1;
if (fname[0] != '\0')
{
sp_traj_t sp_traj = BS_KERNEL.create_object ("traj");
rc = sp_traj->read_from_dev_file (fr_file->get_incdir() + std::string(fname));
if (rc)
{
return rc;
}
if (add_branch_traj (wname, branch, sp_traj))
return -6;
printf ("TRAJ\n %s\n", sp_traj->py_str ().c_str ());
}
if (fname2[0] != '\0')
{
sp_gis_t sp_gis = BS_KERNEL.create_object ("gis");
rc = sp_gis->read_from_las_file (fr_file->get_incdir() + std::string(fname2));
if (rc)
{
return rc;
}
if (add_branch_gis (wname, branch, sp_gis))
return -6;
}
printf ("W_BRANCH_F %s %s %s %lf\n", wname, branch, parent, md);
return 0;
}
int
sql_well::read_w_spec (char *buf)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char sql[1024];
double x = -1, y = -1;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_SPEC can not be set by default\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &x);
//printf ("rc: %lf\n", x);
rc |= fr_file->get_phrase_double (&nx, &y);
//printf ("rc: %lf\n", y);
if (rc)
{
fprintf (stderr, "Error: W_SPEC\n");
return -1;
}
printf ("W_SPEC %s %lf %lf\n", wname, x, y);
// add to data base
sprintf (sql, "INSERT INTO wells(name, x, y) VALUES ('%s', %lf, %lf)",
wname, x, y);
return exec_sql (sql);
}
int
sql_well::read_w_frac (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char branch[1024];
char status[1024];
int i_status;
char sql[1024];
double md = -1;
double angle = 0;
double half_length_1 = 50.0;
double half_length_2 = 50.0;
double half_up = 5.0;
double half_down = 5.0;
double perm = -1;
double half_thin = 0.005;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_FRAC can not be set by default\n");
return -1;
}
strcpy (branch, "main");
rc = fr_file->get_phrase_str (&nx, branch);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well branch name in keyword W_FRAC\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_FRAC\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &md);
rc |= fr_file->get_phrase_double (&nx, &angle);
rc |= fr_file->get_phrase_double (&nx, &half_length_1);
rc |= fr_file->get_phrase_double (&nx, &half_length_2);
rc |= fr_file->get_phrase_double (&nx, &half_up);
rc |= fr_file->get_phrase_double (&nx, &half_down);
rc |= fr_file->get_phrase_double (&nx, &perm);
rc |= fr_file->get_phrase_double (&nx, &half_thin);
if (rc)
{
fprintf (stderr, "Error: W_SPEC\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
if (status[0] == 'S')
i_status = STATUS_CON_SHUT;
//else if (status[0] == 'C') // close
// i_status = 1;
else if (status[0] == 'O') // OPEN
i_status = STATUS_CON_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_FRAC not aloowed\n", status);
return -9;
}
if (md < 0)
{
fprintf (stderr, "Error: you should specify md for W_FRAC \n");
return -9;
}
if (half_length_1 <= 0)
{
fprintf (stderr, "Error: HALF_LENGTH_1 should be > 0 for W_FRAC \n");
return -9;
}
if (half_length_2 <= 0)
{
fprintf (stderr, "Error: HALF_LENGTH_2 should be > 0 for W_FRAC \n");
return -9;
}
if (half_up <= 0)
{
fprintf (stderr, "Error: HALF_UP should be > 0 for W_FRAC \n");
return -9;
}
if (half_down <= 0)
{
fprintf (stderr, "Error: HALF_DOWN should be > 0 for W_FRAC \n");
return -9;
}
if (half_thin <= 0)
{
fprintf (stderr, "Error: HALF_THIN should be > 0 for W_FRAC \n");
return -9;
}
printf ("W_FRAC %s %s %s %lf %lf %lf %lf %lf %lf %lf %lf\n",
wname, branch, status, md, angle, half_length_1, half_length_2,
half_up, half_down, perm, half_thin);
// add to data base
sprintf (sql, "INSERT INTO fractures(well_name, branch_name, md, d, status, \
half_up, half_down, angle, half_length_1, half_length_2, perm, half_thin) \
VALUES ('%s', '%s', %lf, %lf, %d, %lf, %lf, %lf, %lf, %lf, %lf, %lf)",
wname, branch, md, d, i_status, half_up, half_down, angle,
half_length_1, half_length_2, perm, half_thin);
return exec_sql (sql);
return 0;
}
int
sql_well::read_w_comp (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char branch[1024];
char status[1024];
int i_status;
char sql[1024];
double md = -1, length = 1, rw = 0.08, skin = 0, khmult = 1.0;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_COMP can not be set by default\n");
return -1;
}
strcpy (branch, "main");
rc = fr_file->get_phrase_str (&nx, branch);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well branch name in keyword W_COMP\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_COMP\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &md);
rc |= fr_file->get_phrase_double (&nx, &length);
rc |= fr_file->get_phrase_double (&nx, &rw);
rc |= fr_file->get_phrase_double (&nx, &skin);
rc |= fr_file->get_phrase_double (&nx, &khmult);
if (rc)
{
fprintf (stderr, "Error: W_SPEC\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
if (status[0] == 'S')
i_status = STATUS_CON_SHUT;
//else if (status[0] == 'C') // close
// i_status = 1;
else if (status[0] == 'O') // OPEN
i_status = STATUS_CON_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_COMP not aloowed\n", status);
return -9;
}
if (md < 0)
{
fprintf (stderr, "Error: you should specify md for W_COMP \n");
return -9;
}
if (length <= 0)
{
fprintf (stderr, "Error: length should be > 0 for W_COMP \n");
return -9;
}
if (rw <= 0)
{
fprintf (stderr, "Error: rw should be > 0 for W_COMP \n");
return -9;
}
if (khmult <= 0)
{
fprintf (stderr, "Error: khmult should be > 0 for W_COMP \n");
return -9;
}
printf ("W_COMP %s %s %lf %lf %lf %lf %lf\n",
wname, branch, md, length, rw, skin, khmult);
// add to data base
sprintf (sql, "INSERT INTO completions(well_name, branch_name, md, d, length, status, rw, kh_mult) VALUES ('%s', '%s', %lf, %lf, %lf, %d, %lf, %lf)",
wname, branch, md, d, length, i_status, rw, khmult);
return exec_sql (sql);
return 0;
}
int
sql_well::read_w_inj (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char status[1024];
char ctrl[1024];
char fluid[1024];
int i_status = 0;
int i_ctrl = 0;
char sql[1024];
double bhp = -1;
double rate = -1;
double orate = -1;
double wrate = -1;
double grate = -1;
double lim_bhp = -1;
double lim_rate = -1;
double lim_orate = -1;
double lim_wrate = -1;
double lim_grate = -1;
double wefac = 1.0;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_INJ can not be set by default\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_INJ\n");
return -1;
}
strcpy (ctrl, "BHP");
rc = fr_file->get_phrase_str (&nx, ctrl);
if (rc)
{
fprintf (stderr, "Error: well control in keyword W_INJ\n");
return -1;
}
strcpy (fluid, "WATER");
rc = fr_file->get_phrase_str (&nx, ctrl);
if (rc)
{
fprintf (stderr, "Error: well control in keyword W_INJ\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &bhp);
rc |= fr_file->get_phrase_double (&nx, &rate);
rc = fr_file->get_phrase_double (&nx, &lim_bhp);
rc |= fr_file->get_phrase_double (&nx, &lim_rate);
rc |= fr_file->get_phrase_double (&nx, &wefac);
if (rc)
{
fprintf (stderr, "Error: W_PROD\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
fr_file->locale_ucase (ctrl);
fr_file->locale_ucase (fluid);
if (status[0] == 'S')
i_status = STATUS_SHUT;
else if (status[0] == 'C') // close
i_status = STATUS_CLOSE;
else if (status[0] == 'O') // OPEN
i_status = STATUS_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_COMP not aloowed\n", status);
return -9;
}
if (ctrl[0] == 'B')
{
i_ctrl = CTRL_I_BHP;
if (i_status == 2 && bhp <= 0)
{
fprintf (stderr, "Error: BHP = %lf for CONTROL %s in keyword W_INJ",
bhp, ctrl);
return -1;
}
}
else if (ctrl[0] == 'R') // rate
{
if (i_status == STATUS_OPEN && rate <= 0)
{
fprintf (stderr, "Error: RATE = %lf for CONTROL %s in keyword W_INJ",
wrate, ctrl);
return -1;
}
if (fluid[0] == 'W')
{
i_ctrl = CTRL_I_WRATE;
wrate = rate;
lim_wrate = lim_rate;
}
else if (fluid[0] == 'O')
{
i_ctrl = -CTRL_I_ORATE;
orate = rate;
lim_orate = lim_rate;
}
else if (fluid[0] == 'G')
{
i_ctrl = CTRL_I_GRATE;
grate = rate;
lim_grate = lim_rate;
}
else
{
fprintf (stderr, "Error: FLUID = %s not allowed in keyword W_INJ",
fluid);
return -1;
}
}
else
{
fprintf (stderr, "Error: control %s for W_INJ not aloowed\n", ctrl);
return -9;
}
if (i_status == STATUS_OPEN && wefac <= 0)
{
fprintf (stderr, "Error: WEFAC = %lf in keyword W_INJ",
wefac);
return -1;
}
printf ("W_INJ %s %s %s %s %lf %lf %lf %lf %lf\n",
wname, status, ctrl, fluid, bhp, rate, lim_bhp, lim_rate, wefac);
// add to data base
sprintf (sql, "INSERT INTO well_hist(well_name, d, i_or, i_wr, i_gr, \
i_bhp, wefac, ctrl, status, lim_i_or, lim_i_wr, lim_i_gr, lim_i_bhp) \
VALUES ('%s', %lf, %lf, %lf, %lf, %lf, %lf, %d, %d, %lf, %lf, %lf, %lf)",
wname, d, orate, wrate, grate, bhp, wefac, i_ctrl, i_status,
lim_orate, lim_wrate, lim_grate, lim_bhp);
return exec_sql (sql);
return 0;
}
int
sql_well::read_w_prod (char *buf, double d)
{
int rc = 0;
char *nx = 0;
char wname[1024];
char status[1024];
char ctrl[1024];
int i_status = 0;
int i_ctrl = 0;
char sql[1024];
double bhp = -1;
double orate = -1;
double wrate = -1;
double grate = -1;
double lrate = -1;
double lim_bhp = -1;
double lim_orate = -1;
double lim_wrate = -1;
double lim_grate = -1;
double lim_lrate = -1;
double wefac = 1.0;
// read well name
wname[0] = '\0';
nx = buf;
rc = fr_file->get_phrase_str (&nx, wname);
//printf ("WNAME: %s\n", wname);
if (rc || wname[0] == '\0')
{
fprintf (stderr, "Error: well name in keyword W_PROD can not be set by default\n");
return -1;
}
strcpy (status, "SHUT");
rc = fr_file->get_phrase_str (&nx, status);
//printf ("WNAME: %s\n", wname);
if (rc)
{
fprintf (stderr, "Error: well status in keyword W_PROD\n");
return -1;
}
strcpy (ctrl, "BHP");
rc = fr_file->get_phrase_str (&nx, ctrl);
if (rc)
{
fprintf (stderr, "Error: well control in keyword W_PROD\n");
return -1;
}
rc = fr_file->get_phrase_double (&nx, &bhp);
rc |= fr_file->get_phrase_double (&nx, &wrate);
rc |= fr_file->get_phrase_double (&nx, &orate);
rc |= fr_file->get_phrase_double (&nx, &grate);
rc |= fr_file->get_phrase_double (&nx, &lrate);
rc = fr_file->get_phrase_double (&nx, &lim_bhp);
rc |= fr_file->get_phrase_double (&nx, &lim_wrate);
rc |= fr_file->get_phrase_double (&nx, &lim_orate);
rc |= fr_file->get_phrase_double (&nx, &lim_grate);
rc |= fr_file->get_phrase_double (&nx, &lim_lrate);
rc |= fr_file->get_phrase_double (&nx, &wefac);
if (rc)
{
fprintf (stderr, "Error: W_PROD\n");
return -1;
}
// check input data
fr_file->locale_ucase (status);
fr_file->locale_ucase (ctrl);
if (status[0] == 'S')
i_status = STATUS_SHUT;
else if (status[0] == 'C') // close
i_status = STATUS_CLOSE;
else if (status[0] == 'O') // OPEN
i_status = STATUS_OPEN;
else
{
fprintf (stderr, "Error: status %s for W_COMP not aloowed\n", status);
return -9;
}
if (ctrl[0] == 'B')
{
i_ctrl = CTRL_P_BHP;
if (i_status == 2 && bhp <= 0)
{
fprintf (stderr, "Error: BHP = %lf for CONTROL %s in keyword W_PROD",
bhp, ctrl);
return -1;
}
}
else if (ctrl[0] == 'W') // close
{
i_ctrl = CTRL_P_WRATE;
if (i_status == 2 && wrate <= 0)
{
fprintf (stderr, "Error: WRATE = %lf for CONTROL %s in keyword W_PROD",
wrate, ctrl);
return -1;
}
}
else if (ctrl[0] == 'O') // close
{
i_ctrl = CTRL_P_ORATE;
if (i_status == 2 && orate <= 0)
{
fprintf (stderr, "Error: ORATE = %lf for CONTROL %s in keyword W_PROD",
orate, ctrl);
return -1;
}
}
else if (ctrl[0] == 'G') // close
{
i_ctrl = CTRL_P_GRATE;
if (i_status == 2 && grate <= 0)
{
fprintf (stderr, "Error: GRATE = %lf for CONTROL %s in keyword W_PROD",
grate, ctrl);
return -1;
}
}
else if (ctrl[0] == 'L') // close
{
i_ctrl = CTRL_P_LRATE;
if (i_status == 2 && lrate <= 0)
{
fprintf (stderr, "Error: LRATE = %lf for CONTROL %s in keyword W_PROD",
lrate, ctrl);
return -1;
}
}
else
{
fprintf (stderr, "Error: control %s for W_PROD not aloowed\n", status);
return -9;
}
if (i_status == STATUS_OPEN && wefac <= 0)
{
fprintf (stderr, "Error: WEFAC = %lf in keyword W_PROD",
wefac);
return -1;
}
printf ("W_PROD %s %s %s %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\n",
wname, status, ctrl, bhp, wrate, orate, grate, lrate, lim_bhp,
lim_wrate, lim_orate, lim_grate, lim_lrate, wefac);
// add to data base
sprintf (sql, "INSERT INTO well_hist(well_name, d, p_or, p_wr, p_gr, p_lr, \
p_bhp, wefac, ctrl, status, lim_p_or, lim_p_wr, lim_p_gr, lim_p_lr, lim_p_bhp) \
VALUES ('%s', %lf, %lf, %lf, %lf, %lf, %lf, %lf, %d, %d, %lf, %lf, %lf, %lf, %lf)",
wname, d, orate, wrate, grate, lrate, bhp, wefac, i_ctrl, i_status,
lim_orate, lim_wrate, lim_grate, lim_lrate, lim_bhp);
return exec_sql (sql);
return 0;
}
int
sql_well::read_date_and_time (char *buf, char **next_start, double *dd)
{
int rc = 0;
double days;
double t;
char *nx;
*next_start = buf;
fr_file->trim_left (next_start);
nx = *next_start;
rc |= fr_file->get_phrase (&nx);
if (**next_start == '*')
days = 0;
else
{
rc |= fr_file->get_dt ()->cstr2d (*next_start, days);
*dd = (double)days;
}
*next_start = nx;
fr_file->trim_left (next_start);
nx = *next_start;
rc |= fr_file->get_phrase (&nx);
if (**next_start == '*')
t = 0;
else
{
rc |= fr_file->get_dt ()->cstr2t (*next_start, t);
}
*next_start = nx;
*dd += (double)t;
return rc;
}
int
sql_well::save_to_bos_ascii_file (const std::wstring &fname_, sp_pool_t pool, sp_prop_t prop)
{
#ifdef UNIX
std::string fname = wstr2str (fname_);
#else
std::string fname = wstr2str (fname_, "ru_RU.CP1251");
#endif
FILE *fp = fopen (fname.c_str (), "w");
char s_buf[2048];
// interface to mesh
sp_himesh himesh = BS_KERNEL.create_object("handy_mesh_iface");
BS_ASSERT(himesh);
//const double eps = 1e-10;
sp_dt_t dt_t = BS_KERNEL.create_object ("dt_tools");
if (!fp)
{
printf ("Error: Can not open destination file %s\n", fname.c_str ());
return -1;
}
// obtain model dimensions
boost::python::list dims;
dims = pool->py_get_pool_dims();
t_long nx = boost::python::extract<int>(dims[0]);
t_long ny = boost::python::extract<int>(dims[1]);
//nz = boost::python::extract<int>(dims[2]);
//unsigned long nx_ny = nx * ny;
BS_SP (well_pool_iface) sp_wp = this;
// precalc trimesh backend to share among all compl & frac builders
sp_obj trim_backend = fci::wpi_algo::trimesh::create_backend(nx, ny,
pool->get_fp_data("COORD"), pool->get_fp_data("ZCORN"));
// here we wil store builders on every date
typedef std::list< fci::compl_n_frac_builder > cfb_storage_t;
typedef cfb_storage_t::iterator cfb_iterator;
typedef cfb_storage_t::const_iterator cfb_citerator;
cfb_storage_t cfb_storage;
// get dates list
std::string sql = "SELECT d FROM dates ORDER BY d ASC";
if (prepare_sql (sql.c_str ()))
return -1;
// fill dates array & calc COMPDATs on every date
std::list<double> dates;
for (; !step_sql ();)
{
double d = get_sql_real (0);
dates.push_back (d);
// prepare builder
fci::compl_n_frac_builder cfb;
cfb.init(nx, ny, trim_backend);
cfb.init(sp_wp);
if(cfb_storage.size() != 0)
cfb.share_cache_with(cfb_storage.front());
// find completions & save
cfb.compl_build(d);
cfb_storage.push_back(cfb);
}
finalize_sql ();
// wells in mesh come here
std::set< std::string > good_wells;
// check how many wells do we have
prepare_sql("SELECT COUNT(*) FROM wells");
if (!step_sql ())
{
BSOUT << "Wells count " << get_sql_int(0) << bs_end;
//point->resize (3 * get_sql_int(0));
}
else {
finalize_sql();
return -1;
}
finalize_sql();
/*-----------------------------------------------------------------
* Main cycle - iterate over all dates
*----------------------------------------------------------------*/
cfb_iterator p_cfb = cfb_storage.begin();
for (std::list<double>::const_iterator di = dates.begin(), de = dates.end(); di != de; ++di, ++p_cfb)
{
char d_buf[1024];
if (*di - int(*di) == 0) // if *di is integer
{
dt_t->d2ecl (*di, d_buf);
printf ("DATE %s\n", d_buf);
fprintf (fp, "DATES\n%s\n/\n\n", d_buf);
}
else
{
std::list<double>::const_iterator di_prev = di;
di_prev--;
double dt = *di - *di_prev;
printf ("TSTEP %.10lf \t DATETIME %.10lf\n", dt, *di);
fprintf (fp, "TSTEP\n%.10lf\n/\n\n", dt);
}
// WELSPECS only on first date
if(di == dates.begin()) {
fprintf (fp, "WELSPECS\n");
if (prepare_sql ("SELECT name FROM wells ORDER BY name ASC"))
return -1;
for (int i = 0; !step_sql (); i++)
{
// obtain well name
std::string s = get_sql_str (0);
// we can really just skip wells without any COMPDATs
// so we need to check compdats on every date
for(cfb_citerator p_cfb = cfb_storage.begin(), cfb_end = cfb_storage.end(); p_cfb != cfb_end; ++p_cfb) {
const fci::cd_storage& cd = p_cfb->storage_compdat();
fci::cd_storage::const_iterator p_cd = fci::compdat::find_first_cd(cd, s);
if(p_cd != cd.end()) {
// well has at least one COMPDAT, so write it to WELLSPEC
// using first COMPDAT cell_id as well's position
BSOUT << "Exporting well " << s << bs_end;
fprintf (fp,
(boost::format("\'%s\' \'FIELD\' %u %u /\n") % s %
(p_cd->cell_pos[0] + 1) % (p_cd->cell_pos[1] + 1)).str().c_str());
// remember well as good -- not really needed now
good_wells.insert(s);
break;
}
}
// quick and dirty check if well is good enough
if(good_wells.find(s) == good_wells.end()) {
BSOUT << "Warning! Well " << s << " has no active COMPDATs on any date and won't be exported!" << bs_end;
}
}
fprintf (fp, "/\n\n");
finalize_sql ();
}
// COMPDAT
// Building compdat to put first completion I, J to WELLSPECS
const fci::cd_storage& cd = p_cfb->storage_compdat();
const fci::cd_storage::const_iterator cde = cd.end();
const double eps = 1.0e-5;
const std::set< std::string >::const_iterator good_wells_end = good_wells.end();
if (!cd.empty ())
{
fprintf (fp, "COMPDAT\n");
for (fci::cd_storage::const_iterator cdi = cd.begin(); cdi != cde; ++cdi)
{
// skip out of mesh wells
if (fabs(cdi->kh_mult) > eps && good_wells.find(cdi->well_name) != good_wells_end)
{
if (cdi->status)
fprintf (fp,
(boost::format("\'%s\' %u %u %u %u \'OPEN\' 2* %lf 1* %lf 1* \'%c\' /\n") %
cdi->well_name % (cdi->cell_pos[0] + 1) % (cdi->cell_pos[1] + 1) % (cdi->cell_pos[2] + 1) %
(cdi->cell_pos[3] + 1) % cdi->diam % cdi->skin % cdi->dir).str().c_str());
else
fprintf (fp,
(boost::format("\'%s\' %u %u %u %u \'SHUT\' 2* %lf 1* %lf 1* \'%c\' /\n") %
cdi->well_name % (cdi->cell_pos[0] + 1) % (cdi->cell_pos[1] + 1) %
(cdi->cell_pos[2] + 1) % (cdi->cell_pos[3] + 1) % cdi->diam % cdi->skin % cdi->dir).str().c_str());
}
}
fprintf (fp, "/\n\n");
}
// WPIMULT
if (!cd.empty ())
{
int wpimult_exist = 0;
for (fci::cd_storage::const_iterator cdi = cd.begin(); cdi != cde; ++cdi)
{
if (fabs(cdi->kh_mult - 1.0) > 1e-6 && std::abs(cdi->kh_mult) > eps && good_wells.find(cdi->well_name) != good_wells_end)
{
if (!wpimult_exist)
fprintf (fp, "WPIMULT\n");
wpimult_exist = 1;
fprintf (fp,
(boost::format("\'%s\' %lf %u %u %u /\n") % cdi->well_name % cdi->kh_mult % (cdi->cell_pos[0] + 1) %
(cdi->cell_pos[1] + 1) % (cdi->cell_pos[2] + 1)).str().c_str());
}
}
if (wpimult_exist)
fprintf (fp, "/\n\n");
}
// FRACTURES
const fci::frac_storage& ft = p_cfb->frac_build(*di);
const fci::frac_storage::const_iterator fte = ft.end();
if (!ft.empty ())
{
char main_k_str[1024];
char perm_str[1024];
fprintf (fp, "FRACTURE\n");
for (fci::frac_storage::const_iterator fti = ft.begin (); fti != fte; ++fti)
{
// skip out-of-mesh wells
if(good_wells.find(fti->well_name) == good_wells_end)
continue;
if (fti->frac_perm > 0)
sprintf (perm_str, "%lf", fti->frac_perm);
else
sprintf (perm_str, " * ");
int horiz = 0;
std::string sql = "SELECT name, horiz FROM wells WHERE name = ";
sql += std::string("'") + fti->well_name + std::string("'");
if (prepare_sql (sql.c_str ()))
return -1;
if (!step_sql ())
{
horiz = get_sql_int (1);
}
finalize_sql ();
if (horiz)
sprintf (main_k_str, "%d", fti->frac_main_k + 1);
else
sprintf (main_k_str, " * ");
fprintf (fp,
(boost::format("\'%s\' %u %u %u %u %lf %lf %lf \'%s\' %lf %s %s %s %s /\n") %
fti->well_name % (fti->cell_pos[0] + 1) % (fti->cell_pos[1] + 1) % (fti->cell_pos[2] + 1) %
(fti->cell_pos[3] + 1) % fti->frac_half_length_1 % (fti->frac_angle - 90) % fti->frac_skin %
(fti->frac_status == 0 ? "SHUT" : "OPEN") % fti->frac_half_thin % perm_str % " * " % " * " %
main_k_str).str().c_str()
);
}
fprintf (fp, "/\n\n");
}
// WCONINJH
// Injector wells with rate control having historical bhp value
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND ctrl < -1 AND i_bhp >= 0 ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconinjh_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconinjh_flag == 0)
{
fprintf (fp, "WCONINJH\n");
wconinjh_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double i_or = get_sql_real (8);
double i_wr = get_sql_real (9);
double i_gr = get_sql_real (10);
double i_bhp = get_sql_real (11);
double rate = i_wr;
std::string s_status;
std::string s_phase = "WATER";
std::string s_rate;
std::string s_bhp;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
if (ctrl == CTRL_I_ORATE)
{
s_phase = "OIL";
rate = i_or;
}
else if (ctrl == CTRL_I_GRATE)
{
s_phase = "GAS";
rate = i_gr;
}
if (rate > 0)
{
s_rate = V2S(rate);
}
else
{
s_rate = "*";
}
if (i_bhp > 0)
{
s_bhp = V2S(i_bhp);
}
else
{
s_bhp = "*";
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' %s %s ", s.c_str (), s_phase.c_str(), s_status.c_str(), s_rate.c_str(), s_bhp.c_str());
fprintf (fp, "/\n");
}
if (wconinjh_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WCONINJE
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND (i_bhp < 0 AND ctrl < -1 OR ctrl = -1) ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconinje_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconinje_flag == 0)
{
fprintf (fp, "WCONINJE\n");
wconinje_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double i_or = get_sql_real (8);
double i_wr = get_sql_real (9);
double i_gr = get_sql_real (10);
double i_bhp = get_sql_real (11);
double lim_bhp = get_sql_real (11);
double rate = i_wr;
std::string s_status;
std::string s_ctrl;
std::string s_phase;
std::string s_params;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
s_ctrl = "BHP";
// TODO: add injection phase into DB
s_phase = "WATER";
s_params = (boost::format("2* %lf") % i_bhp).str();
if (ctrl == CTRL_I_BHP)
{
s_ctrl = "BHP";
// TODO: add injection phase into DB
s_phase = "WATER";
s_params = (boost::format("2* %lf") % i_bhp).str();
}
else
{
s_ctrl = "RATE";
if (ctrl == CTRL_I_WRATE)
s_phase = "WATER";
else if (ctrl == CTRL_I_ORATE)
{
s_phase = "OIL";
rate = i_or;
}
else if (ctrl == CTRL_I_GRATE)
{
s_phase = "GAS";
rate = i_gr;
}
else
s_phase = "WATER";
s_params = (boost::format("%s 2*") % V2S(rate)).str();
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' \'%s\' %s ", s.c_str (), s_phase.c_str(), s_status.c_str(),
s_ctrl.c_str(), s_params.c_str());
/*
if (rate < 0)
fprintf (fp, "2* ");
else
fprintf (fp, "%lf 1* ", rate);
if (i_bhp < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", i_bhp);
*/
fprintf (fp, "/\n");
}
if (wconinje_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WCONHIST
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND p_bhp >= 0 AND ctrl > 1 ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconhist_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconhist_flag == 0)
{
fprintf (fp, "WCONHIST\n");
wconhist_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double p_or = get_sql_real (2);
double p_wr = get_sql_real (3);
double p_gr = get_sql_real (4);
double p_bhp = get_sql_real (6);
std::string s_status;
std::string s_ctrl;
std::string s_params;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
if (ctrl == CTRL_P_LRATE)
{
s_ctrl = "LRAT";
if (status == STATUS_OPEN && (p_or + p_wr == 0))
continue;
}
else if (ctrl == CTRL_P_ORATE)
{
s_ctrl = "ORAT";
if (status == STATUS_OPEN && (p_or == 0))
continue;
}
else if (ctrl == CTRL_P_WRATE)
{
s_ctrl = "WRAT";
if (status == STATUS_OPEN && (p_wr == 0))
continue;
}
else if (ctrl == CTRL_P_GRATE)
{
s_ctrl = "GRAT";
if (status == STATUS_OPEN && (p_gr == 0))
continue;
}
if (p_bhp > 0)
{
s_params = (boost::format("%s %s %s 3* %s") % V2S(p_or) % V2S(p_wr)% V2S(p_gr) % V2S(p_bhp)).str();
}
else
{
s_params = (boost::format("%s %s %s 4*") % V2S(p_or) % V2S(p_wr)% V2S(p_gr)).str();
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' %s ", s.c_str (), s_status.c_str(), s_ctrl.c_str(), s_params.c_str());
/*
if (p_or < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_or);
if (p_wr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_wr);
if (p_gr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_gr);
if (p_lr < 0)
fprintf (fp, "2* ");
else
fprintf (fp, "%lf * ", p_lr);
if (p_bhp < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_bhp);
*/
fprintf (fp, "/\n");
}
if (wconhist_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WCONPROD
sprintf (s_buf, "SELECT * FROM well_hist WHERE d=%lf AND (p_bhp < 0 AND ctrl > 1 OR ctrl = 1) ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wconprod_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wconprod_flag == 0)
{
fprintf (fp, "WCONPROD\n");
wconprod_flag++;
}
int status = get_sql_int (14);
int ctrl = get_sql_int (13);
double p_or = get_sql_real (2);
double p_wr = get_sql_real (3);
double p_gr = get_sql_real (4);
double p_lr = get_sql_real (5);
double p_bhp = get_sql_real (6);
std::string s_status;
std::string s_ctrl;
std::string s_params;
if (status == STATUS_OPEN)
s_status = "OPEN";
else
s_status = "SHUT";
if (ctrl == CTRL_P_LRATE)
{
s_ctrl = "LRAT";
s_params = (boost::format("3* %s 2*") % V2S(p_lr)).str();
}
else if (ctrl == CTRL_P_BHP)
{
s_ctrl = "BHP";
s_params = (boost::format("5* %s") % V2S(p_bhp)).str();
}
else if (ctrl == CTRL_P_ORATE)
{
s_ctrl = "ORAT";
s_params = (boost::format("%s 5*") % V2S(p_or)).str();
}
else if (ctrl == CTRL_P_WRATE)
{
s_ctrl = "WRAT";
s_params = (boost::format("1* %s 4*") % V2S(p_wr)).str();
}
else if (ctrl == CTRL_P_GRATE)
{
s_ctrl = "GRAT";
s_params = (boost::format("2* %s 3*") % V2S(p_gr)).str();
}
fprintf (fp, "\'%s\' \'%s\' \'%s\' %s ", s.c_str (), s_status.c_str(), s_ctrl.c_str(), s_params.c_str());
/*
if (p_or < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_or);
if (p_wr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_wr);
if (p_gr < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_gr);
if (p_lr < 0)
fprintf (fp, "2* ");
else
fprintf (fp, "%lf * ", p_lr);
if (p_bhp < 0)
fprintf (fp, "1* ");
else
fprintf (fp, "%lf ", p_bhp);
*/
fprintf (fp, "/\n");
}
if (wconprod_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WELTARG BHP limit for injectors
sprintf (s_buf, "SELECT well_name, lim_i_bhp, lim_p_bhp FROM well_hist WHERE d=%lf AND (lim_i_bhp > 0 OR lim_p_bhp > 0) ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint weltarg_flag = 0;
for (; !step_sql ();)
{
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (weltarg_flag == 0)
{
fprintf (fp, "WELTARG\n");
weltarg_flag++;
}
double lim_i_bhp = get_sql_real (1);
double lim_p_bhp = get_sql_real (2);
if (lim_i_bhp > 0)
fprintf (fp, "\'%s\' BHP %s ", s.c_str (), V2S(lim_i_bhp));
else if (lim_p_bhp > 0)
fprintf (fp, "\'%s\' BHP %s ", s.c_str (), V2S(lim_p_bhp));
fprintf (fp, "/\n");
}
if (weltarg_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
// WEFAC
sprintf (s_buf, "SELECT well_name, wefac FROM well_hist WHERE d=%lf ORDER BY well_name ASC", *di);
if (prepare_sql (s_buf))
return -1;
t_uint wefac_flag = 0;
for (; !step_sql ();)
{
double wefac = get_sql_real (1);
if (wefac == 1.0)
continue;
std::string s = get_sql_str (0);
// skip out-of-mesh wells
if(good_wells.find(s) == good_wells_end)
continue;
if (wefac_flag == 0)
{
fprintf (fp, "WEFAC\n");
wefac_flag++;
}
fprintf (fp, "\'%s\' %lf", s.c_str (), wefac);
fprintf (fp, "/\n");
}
if (wefac_flag)
fprintf (fp, "/\n\n");
finalize_sql ();
} // eof main cycle over dates
fclose (fp);
return 0;
}
#ifdef BSPY_EXPORTING_PLUGIN
std::string
sql_well::py_str () const
{
std::stringstream s;
s << file_name << "\n";
return s.str ();
}
#endif //BSPY_EXPORTING_PLUGIN
/////////////////////////////////BS Register
/////////////////////////////////Stuff//////////////////////////
BLUE_SKY_TYPE_STD_CREATE (sql_well);
BLUE_SKY_TYPE_STD_COPY (sql_well);
BLUE_SKY_TYPE_IMPL(sql_well, well_pool_iface, "sql_well", "sql_well storage", "realization of well sql_well storage");
} // blue_sky namespace
|
#include"all_defines.hpp"
#include"aio.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include"objects.hpp"
#include"processes.hpp"
#include"workers.hpp"
#include"bytecodes.hpp"
#include"symbols.hpp"
/*Generic code for AIO*/
/*This contains code that is shared across AIO implementations*/
/*internal function for sending a message to a process*/
/*
preconditions:
stack.top() = message to send
postconditions:
stack.top() has been popped
*/
static inline void send_message_to(Process* P, ProcessStack& stack) {
/*prepare message*/
ValueHolderRef m;
ValueHolder::copy_object(m, stack.top());
stack.pop();
bool is_waiting = 0;
/*keep sending until we definitely go through any locks or whatnot*/
while(!P->receive_message(m, is_waiting)) /*do nothing*/;
if(is_waiting) {
workers->workqueue_push(P);
}
}
ProcessInvoker::ProcessInvoker(Process* nP) : P(nP) {
/*TODO: notify workers of one more process-gc root*/
}
ProcessInvoker::~ProcessInvoker() {
/*TODO: notify workers of loss of root*/
}
void ProcessInvoker::io_respond(
Process& host,
boost::shared_ptr<IOPort> port,
boost::shared_ptr<std::vector<unsigned char> >& dat) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = port;
stack.push(Object::to_ref<Generic*>(io));
/*any data?*/
if(!dat || dat->size() == 0) {
stack.push(Object::nil());
} else {
BinObj* e = BinObj::create(hp, dat);
stack.push(Object::to_ref<Generic*>(e));
}
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::nil_respond(
Process& host,
boost::shared_ptr<IOPort> port) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = port;
stack.push(Object::to_ref<Generic*>(io));
stack.push(Object::nil());
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::accept_respond(
Process& host,
boost::shared_ptr<IOPort> socket,
boost::shared_ptr<IOPort> new_socket){
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = socket;
stack.push(Object::to_ref<Generic*>(io));
io = hp.create<HlIOPort>();
io->p = new_socket;
stack.push(Object::to_ref<Generic*>(io));
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::connect_respond(
Process& host,
boost::shared_ptr<Event> event,
boost::shared_ptr<IOPort> new_socket) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlEvent* ev = hp.create<HlEvent>();
ev->p = event;
stack.push(Object::to_ref<Generic*>(ev));
HlIOPort* io = hp.create<HlIOPort>();
io->p = new_socket;
stack.push(Object::to_ref<Generic*>(io));
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::sleep_respond(
Process& host,
boost::shared_ptr<Event> event,
size_t time) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlEvent* ev = hp.create<HlEvent>();
ev->p = event;
stack.push(Object::to_ref<Generic*>(ev));
stack.push(Object::to_ref<int>(time));
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::io_error_respond(
Process& host,
boost::shared_ptr<IOPort> port,
std::string const& msg) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = port;
stack.push(Object::to_ref<Generic*>(io));
/*slow lookup is OK, we don't expect error handling
to be fast.
*/
stack.push(Object::to_ref(symbols->lookup("<hl>i/o")));
/*assume ASCII string for now*/
for(size_t i = 0; i < msg.size(); ++i) {
stack.push(Object::to_ref(UnicodeChar(msg[i])));
}
HlString::stack_create(hp, stack, msg.size());
bytecode_tag(host, stack);
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::other_error_respond(
Process& host,
boost::shared_ptr<Event> event,
std::string const& msg) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlEvent* ev = hp.create<HlEvent>();
ev->p = event;
stack.push(Object::to_ref<Generic*>(ev));
/*slow lookup is OK, we don't expect error handling
to be fast.
*/
stack.push(Object::to_ref(symbols->lookup("<hl>i/o")));
/*assume ASCII string for now*/
for(size_t i = 0; i < msg.size(); ++i) {
stack.push(Object::to_ref(UnicodeChar(msg[i])));
}
HlString::stack_create(hp, stack, msg.size());
bytecode_tag(host, stack);
bytecode_cons(host, stack);
send_message_to(P, stack);
}
src/aio.cpp: Removed unnecessary comments.
Previous commit already changed hook for aio <-> workers
integration
#include"all_defines.hpp"
#include"aio.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include"objects.hpp"
#include"processes.hpp"
#include"workers.hpp"
#include"bytecodes.hpp"
#include"symbols.hpp"
/*Generic code for AIO*/
/*This contains code that is shared across AIO implementations*/
/*internal function for sending a message to a process*/
/*
preconditions:
stack.top() = message to send
postconditions:
stack.top() has been popped
*/
static inline void send_message_to(Process* P, ProcessStack& stack) {
/*prepare message*/
ValueHolderRef m;
ValueHolder::copy_object(m, stack.top());
stack.pop();
bool is_waiting = 0;
/*keep sending until we definitely go through any locks or whatnot*/
while(!P->receive_message(m, is_waiting)) /*do nothing*/;
if(is_waiting) {
workers->workqueue_push(P);
}
}
ProcessInvoker::ProcessInvoker(Process* nP) : P(nP) {
}
ProcessInvoker::~ProcessInvoker() {
}
void ProcessInvoker::io_respond(
Process& host,
boost::shared_ptr<IOPort> port,
boost::shared_ptr<std::vector<unsigned char> >& dat) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = port;
stack.push(Object::to_ref<Generic*>(io));
/*any data?*/
if(!dat || dat->size() == 0) {
stack.push(Object::nil());
} else {
BinObj* e = BinObj::create(hp, dat);
stack.push(Object::to_ref<Generic*>(e));
}
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::nil_respond(
Process& host,
boost::shared_ptr<IOPort> port) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = port;
stack.push(Object::to_ref<Generic*>(io));
stack.push(Object::nil());
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::accept_respond(
Process& host,
boost::shared_ptr<IOPort> socket,
boost::shared_ptr<IOPort> new_socket){
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = socket;
stack.push(Object::to_ref<Generic*>(io));
io = hp.create<HlIOPort>();
io->p = new_socket;
stack.push(Object::to_ref<Generic*>(io));
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::connect_respond(
Process& host,
boost::shared_ptr<Event> event,
boost::shared_ptr<IOPort> new_socket) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlEvent* ev = hp.create<HlEvent>();
ev->p = event;
stack.push(Object::to_ref<Generic*>(ev));
HlIOPort* io = hp.create<HlIOPort>();
io->p = new_socket;
stack.push(Object::to_ref<Generic*>(io));
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::sleep_respond(
Process& host,
boost::shared_ptr<Event> event,
size_t time) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlEvent* ev = hp.create<HlEvent>();
ev->p = event;
stack.push(Object::to_ref<Generic*>(ev));
stack.push(Object::to_ref<int>(time));
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::io_error_respond(
Process& host,
boost::shared_ptr<IOPort> port,
std::string const& msg) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlIOPort* io = hp.create<HlIOPort>();
io->p = port;
stack.push(Object::to_ref<Generic*>(io));
/*slow lookup is OK, we don't expect error handling
to be fast.
*/
stack.push(Object::to_ref(symbols->lookup("<hl>i/o")));
/*assume ASCII string for now*/
for(size_t i = 0; i < msg.size(); ++i) {
stack.push(Object::to_ref(UnicodeChar(msg[i])));
}
HlString::stack_create(hp, stack, msg.size());
bytecode_tag(host, stack);
bytecode_cons(host, stack);
send_message_to(P, stack);
}
void ProcessInvoker::other_error_respond(
Process& host,
boost::shared_ptr<Event> event,
std::string const& msg) {
Heap& hp = host; ProcessStack& stack = host.stack;
/*build objects*/
HlEvent* ev = hp.create<HlEvent>();
ev->p = event;
stack.push(Object::to_ref<Generic*>(ev));
/*slow lookup is OK, we don't expect error handling
to be fast.
*/
stack.push(Object::to_ref(symbols->lookup("<hl>i/o")));
/*assume ASCII string for now*/
for(size_t i = 0; i < msg.size(); ++i) {
stack.push(Object::to_ref(UnicodeChar(msg[i])));
}
HlString::stack_create(hp, stack, msg.size());
bytecode_tag(host, stack);
bytecode_cons(host, stack);
send_message_to(P, stack);
}
|
#include <vast/comm/broccoli.h>
#include <ze/event.h>
#include <vast/comm/connection.h>
#include <vast/comm/exception.h>
#include <vast/util/logger.h>
namespace vast {
namespace comm {
/// Converts a Broccoli type to the corresponding 0event type.
static ze::value_type to_ze_type(int broccoli_type)
{
switch (broccoli_type)
{
default:
return ze::invalid_type;
case BRO_TYPE_BOOL:
return ze::bool_type;
case BRO_TYPE_INT:
return ze::int_type;
case BRO_TYPE_COUNT:
case BRO_TYPE_COUNTER:
return ze::uint_type;
case BRO_TYPE_DOUBLE:
return ze::double_type;
case BRO_TYPE_TIME:
return ze::timepoint_type;
case BRO_TYPE_INTERVAL:
return ze::duration_type;
case BRO_TYPE_STRING:
return ze::string_type;
case BRO_TYPE_PATTERN:
return ze::regex_type;
case BRO_TYPE_VECTOR:
return ze::vector_type;
case BRO_TYPE_SET:
return ze::set_type;
case BRO_TYPE_TABLE:
return ze::table_type;
case BRO_TYPE_RECORD:
return ze::record_type;
case BRO_TYPE_IPADDR:
return ze::address_type;
case BRO_TYPE_SUBNET:
return ze::prefix_type;
case BRO_TYPE_PORT:
return ze::port_type;
}
}
bool broccoli::initialized = false;
void broccoli::init(bool messages, bool calltrace)
{
if (calltrace)
{
bro_debug_calltrace = 1;
LOG(verbose, broccoli) << "enabling call trace debugging";
}
if (messages)
{
bro_debug_messages = 1;
LOG(verbose, broccoli) << "enabling extra debug messages";
}
LOG(verbose, broccoli) << "initializing SSL context";
BroCtx ctx;
bro_ctx_init(&ctx);
bro_init(&ctx);
initialized = true;
}
broccoli::broccoli(std::shared_ptr<connection> conn, event_handler handler)
: bc_(nullptr)
, conn_(std::move(conn))
, strand_(conn_->socket().get_io_service())
, event_handler_(std::move(handler))
{
assert(initialized);
auto& socket = conn_->socket();
boost::asio::ip::tcp::socket::non_blocking_io non_blocking_io(true);
socket.io_control(non_blocking_io);
LOG(debug, broccoli) << *conn_ << ": creating broccoli handle";
bc_ = bro_conn_new_socket(socket.native(), BRO_CFLAG_DONTCACHE);
if (bc_ < 0)
throw broccoli_exception("bro_conn_new_socket");
}
broccoli::~broccoli()
{
if (bc_)
bro_conn_delete(bc_);
}
void broccoli::subscribe(std::string const& event)
{
bro_event_registry_add_compact(bc_,
event.data(),
&callback,
&event_handler_);
}
void broccoli::send(std::vector<uint8_t> const& raw)
{
LOG(debug, broccoli) << "sending raw event of size " << raw.size();
bro_event_send_raw(bc_, raw.data(), raw.size());
}
void broccoli::send(ze::event const& event)
{
auto bro_event = reverse_factory::make_event(event);
if (! bro_event_send(bc_, bro_event))
LOG(error, broccoli)
<< *conn_ << ": error sending event " << event.name();
bro_event_free(bro_event);
}
void broccoli::run(error_handler handler)
{
error_handler_ = std::move(handler);
bro_event_registry_request(bc_);
if (! bro_conn_connect(bc_))
{
LOG(error, broccoli) << *conn_ << ": unable to attach broccoli";
throw broccoli_exception("bro_conn_connect");
}
LOG(debug, broccoli) << *conn_ << ": successfully attached to socket";
async_read();
}
void broccoli::stop()
{
LOG(verbose, broccoli) << *conn_ << ": shutting down";
terminate_ = true;
}
int broccoli::factory::table_callback(void *key_data, void *val_data,
table_data const* data)
{
ze::value key = make_value(data->key_type, key_data);
ze::value value = make_value(data->val_type, val_data);
auto x = ze::table::value_type(std::move(key), std::move(value));
data->table->insert(std::move(x));
return 1;
}
int broccoli::factory::set_callback(void *key_data, set_data const* data)
{
ze::value key = make_value(data->key_type, key_data);
data->set->insert(std::move(key));
return 1;
}
void broccoli::factory::make_event(ze::event& event, BroEvMeta* meta)
{
event.name(meta->ev_name);
event.timestamp(meta->ev_ts);
event.reserve(meta->ev_numargs);
for (int i = 0; i < meta->ev_numargs; ++i)
event.emplace_back(
make_value(meta->ev_args[i].arg_type,
meta->ev_args[i].arg_data));
event.shrink_to_fit();
}
ze::value broccoli::factory::make_value(int type, void* bro_val)
{
switch (type)
{
default:
LOG(warn, broccoli) << "type " << type << " does not exist";
break;
case BRO_TYPE_UNKNOWN:
LOG(warn, broccoli) << "unknown broccoli type (" << type << ")";
break;
case BRO_TYPE_PATTERN:
case BRO_TYPE_TIMER:
case BRO_TYPE_ANY:
case BRO_TYPE_UNION:
case BRO_TYPE_LIST:
case BRO_TYPE_FUNC:
case BRO_TYPE_FILE:
case BRO_TYPE_VECTOR:
case BRO_TYPE_ERROR:
case BRO_TYPE_PACKET:
LOG(warn, broccoli) << "unsupported broccoli type (" << type << ")";
break;
case BRO_TYPE_BOOL:
return *static_cast<bool*>(bro_val);
case BRO_TYPE_INT:
return *static_cast<int64_t*>(bro_val);
case BRO_TYPE_COUNT:
case BRO_TYPE_COUNTER:
return *static_cast<uint64_t*>(bro_val);
case BRO_TYPE_DOUBLE:
return *static_cast<double*>(bro_val);
case BRO_TYPE_TIME:
{
ze::double_seconds secs(*static_cast<double*>(bro_val));
auto duration = std::chrono::duration_cast<ze::duration>(secs);
return ze::time_point(duration);
}
case BRO_TYPE_INTERVAL:
{
ze::double_seconds secs(*static_cast<double*>(bro_val));
auto duration = std::chrono::duration_cast<ze::duration>(secs);
return duration;
}
case BRO_TYPE_STRING:
{
BroString* s = static_cast<BroString*>(bro_val);
return {reinterpret_cast<char const*>(s->str_val), s->str_len};
}
case BRO_TYPE_PORT:
{
BroPort* p = static_cast<BroPort*>(bro_val);
switch (p->port_proto)
{
default:
LOG(warn, broccoli) << "invalid port type";
return ze::port(p->port_num, ze::port::unknown);
case IPPROTO_TCP:
return ze::port(p->port_num, ze::port::tcp);
case IPPROTO_UDP:
return ze::port(p->port_num, ze::port::udp);
case IPPROTO_ICMP:
return ze::port(p->port_num, ze::port::icmp);
}
}
case BRO_TYPE_IPADDR:
{
BroAddr* addr = static_cast<BroAddr*>(bro_val);
auto is_v4 = bro_util_is_v4_addr(addr);
return ze::address(
addr->addr,
is_v4 ? ze::address::ipv4 : ze::address::ipv6,
ze::address::network);
}
case BRO_TYPE_SUBNET:
{
BroSubnet* sn = static_cast<BroSubnet*>(bro_val);
auto is_v4 = bro_util_is_v4_addr(&sn->sn_net);
ze::address addr(
sn->sn_net.addr,
is_v4 ? ze::address::ipv4 : ze::address::ipv6,
ze::address::network);
return ze::prefix(std::move(addr), sn->sn_width);
}
case BRO_TYPE_SET:
{
BroSet* bro_set = static_cast<BroSet*>(bro_val);
if (! bro_set_get_size(bro_set))
return ze::set();
// Empty sets have BRO_TYPE_UNKNOWN. At this point, we know
// that the set has a valid type becuase it is not empty.
int key_type;
bro_set_get_type(bro_set, &key_type);
ze::set set(to_ze_type(key_type));
set_data data{key_type, &set};
bro_set_foreach(bro_set, (BroSetCallback)set_callback, &data);
return set;
}
case BRO_TYPE_TABLE:
{
BroTable* bro_table = static_cast<BroTable*>(bro_val);
if (! bro_table_get_size(bro_table))
return ze::table();
int key_type, val_type;
bro_table_get_types(bro_table, &key_type, &val_type);
ze::table table(to_ze_type(key_type), to_ze_type(val_type));
table_data data{key_type, val_type, &table};
bro_table_foreach(bro_table, (BroTableCallback)table_callback, &data);
return table;
}
case BRO_TYPE_RECORD:
{
ze::record record;
BroRecord *rec = static_cast<BroRecord*>(bro_val);
void* bro_val;
int bro_val_type = BRO_TYPE_UNKNOWN;
int cnt = 0;
while ((bro_val = bro_record_get_nth_val(rec, cnt, &bro_val_type)))
{
auto val = make_value(bro_val_type, bro_val);
record.push_back(std::move(val));
bro_val_type = BRO_TYPE_UNKNOWN;
++cnt;
}
return record;
}
}
throw broccoli_type_exception("invalid broccoli type", type);
}
struct broccoli::reverse_factory::builder
{
typedef bro_val result_type;
result_type operator()(ze::invalid_value i) const;
result_type operator()(ze::nil_value n) const;
result_type operator()(bool b) const;
result_type operator()(int64_t i) const;
result_type operator()(uint64_t i) const;
result_type operator()(double d) const;
result_type operator()(ze::duration d) const;
result_type operator()(ze::time_point t) const;
result_type operator()(ze::string const& s) const;
result_type operator()(ze::regex const& s) const;
result_type operator()(ze::vector const& v) const;
result_type operator()(ze::set const& s) const;
result_type operator()(ze::table const& t) const;
result_type operator()(ze::record const& r) const;
result_type operator()(ze::address const& a) const;
result_type operator()(ze::prefix const& s) const;
result_type operator()(ze::port const& p) const;
};
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::invalid_value i) const
{
return { BRO_TYPE_UNKNOWN, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::nil_value n) const
{
return { BRO_TYPE_UNKNOWN, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(bool b) const
{
return { BRO_TYPE_BOOL, const_cast<bool*>(&b) };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(int64_t i) const
{
// FIXME: perform narrowing check.
return { BRO_TYPE_INT, &i };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(uint64_t i) const
{
// FIXME: perform narrowing check.
return { BRO_TYPE_INT, &i };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(double d) const
{
return { BRO_TYPE_DOUBLE, const_cast<double*>(&d) };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::string const& s) const
{
// Caller must free the memory of the BroString!
BroString* bs = new BroString;
bro_string_set_data(
bs, reinterpret_cast<const unsigned char*>(s.data()), s.size());
return { BRO_TYPE_STRING, bs };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::regex const& r) const
{
assert(! "Broccoli does not yet support regular expressions");
return { BRO_TYPE_PATTERN, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::duration d) const
{
double secs = std::chrono::duration_cast<ze::double_seconds>(d).count();
bro_val b;
b.type = BRO_TYPE_INTERVAL;
b.value = *reinterpret_cast<double**>(&secs);
return b;
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::time_point t) const
{
return { BRO_TYPE_TIME, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::vector const& v) const
{
assert(! "Broccoli does not yet support vectors");
return { BRO_TYPE_VECTOR, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::set const& s) const
{
// Caller must free the memory of the BroSet!
BroSet* set = bro_set_new();
for (auto const& x : s)
{
bro_val bv = ze::value::visit(x, *this);
bro_set_insert(set, bv.type, bv.value);
free(bv);
}
return { BRO_TYPE_SET, set };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::table const& t) const
{
// Caller must free the memory of the BroTable!
BroTable* table = bro_table_new();
for (auto const& x : t)
{
bro_val key = ze::value::visit(x.first, *this);
bro_val val = ze::value::visit(x.second, *this);
// If the table key is a compound type (i.e., record), we need to
// use BRO_TYPE_LIST instead of BRO_TYPE_RECORD.
bro_table_insert(
table,
key.type == BRO_TYPE_RECORD ? BRO_TYPE_LIST : key.type,
key.value, val.type, val.value);
free(key);
free(val);
}
return { BRO_TYPE_TABLE, table };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::record const& r) const
{
// Caller must free the memory of the BroRecord!
BroRecord* rec = bro_record_new();
for (auto const& val : r)
{
bro_val bv = ze::value::visit(val, *this);
bro_record_add_val(rec, NULL, bv.type, NULL, &bv.value);
free(bv);
}
return { BRO_TYPE_RECORD, rec };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::address const& a) const
{
// Caller must free the memory of the BroAddr!
BroAddr* addr = new BroAddr;
std::copy(a.data().begin(), a.data().end(),
reinterpret_cast<uint8_t*>(&addr->addr));
return { BRO_TYPE_IPADDR, addr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::prefix const& p) const
{
// Caller must free the memory of the BroSubnet!
BroSubnet* bs = new BroSubnet;
bs->sn_width = p.length();
auto net = operator()(p.network());
auto addr = reinterpret_cast<BroAddr*>(net.value);
std::copy(addr, addr + sizeof(BroAddr), &bs->sn_net);
free(net);
return { BRO_TYPE_PORT, bs };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::port const& p) const
{
// Caller must free the memory of the BroPort!
BroPort* bp = new BroPort;
bp->port_num = p.number();
switch (p.type())
{
default:
{
bp->port_proto = 0;
LOG(debug, broccoli) << "unsupported port type";
}
break;
case ze::port::tcp:
bp->port_proto = IPPROTO_TCP;
break;
case ze::port::udp:
bp->port_proto = IPPROTO_UDP;
break;
case ze::port::icmp:
bp->port_proto = IPPROTO_ICMP;
break;
}
return { BRO_TYPE_PORT, bp };
}
void broccoli::reverse_factory::free(bro_val const& v)
{
switch (v.type)
{
case BRO_TYPE_STRING:
delete static_cast<BroString*>(v.value);
break;
case BRO_TYPE_IPADDR:
delete static_cast<BroAddr*>(v.value);
break;
case BRO_TYPE_PORT:
delete static_cast<BroPort*>(v.value);
break;
case BRO_TYPE_SUBNET:
delete static_cast<BroSubnet*>(v.value);
break;
case BRO_TYPE_RECORD:
bro_record_free(static_cast<BroRecord*>(v.value));
break;
case BRO_TYPE_TABLE:
bro_table_free(static_cast<BroTable*>(v.value));
break;
case BRO_TYPE_SET:
bro_set_free(static_cast<BroSet*>(v.value));
break;
}
}
BroEvent* broccoli::reverse_factory::make_event(ze::event const& event)
{
LOG(debug, event) << "building broccoli event " << event.name();
BroEvent* bro_event = bro_event_new(event.name().c_str());
if (! bro_event)
{
LOG(error, broccoli) << "could not create bro_event " << event.name();
throw broccoli_exception("bro_event_new");
}
for (auto& arg : event)
{
LOG(debug, event) << "adding argument: " << arg;
bro_val val = ze::value::visit(arg, builder());
bro_event_add_val(bro_event, val.type, NULL, val.value);
free(val);
}
return bro_event;
}
void broccoli::callback(BroConn* bc, void* user_data, BroEvMeta* meta)
{
try
{
ze::event event;
event.id(ze::uuid::random());
factory::make_event(event, meta);
auto f = static_cast<event_handler*>(user_data);
(*f)(std::move(event));
}
catch (ze::exception const& e)
{
LOG(error, broccoli)
<< "could not create ze::event from broccoli event '"
<< meta->ev_name << "' (" << e.what() << ')';
}
catch (exception const& e)
{
LOG(error, broccoli)
<< "error with broccoli event '"
<< meta->ev_name << "' (" << e.what() << ')';
}
}
void broccoli::async_read()
{
conn_->socket().async_read_some(
boost::asio::null_buffers(),
strand_.wrap(
std::bind(&broccoli::handle_read,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void broccoli::handle_read(boost::system::error_code const& ec,
size_t bytes_transferred)
{
if (terminate_)
return;
if (! ec)
bro_conn_process_input(bc_);
if (! ec || ec == boost::asio::error::would_block)
{
async_read();
return;
}
else if (ec == boost::asio::error::eof)
{
LOG(info, broccoli) << *conn_ << ": remote broccoli disconnected";
}
else
{
LOG(error, broccoli) << *conn_ << ": " << ec.message();
}
stop();
error_handler_(shared_from_this());
}
} // namespace comm
} // namespace vast
Use new 0event helpers.
#include <vast/comm/broccoli.h>
#include <ze/event.h>
#include <vast/comm/connection.h>
#include <vast/comm/exception.h>
#include <vast/util/logger.h>
namespace vast {
namespace comm {
/// Converts a Broccoli type to the corresponding 0event type.
static ze::value_type to_ze_type(int broccoli_type)
{
switch (broccoli_type)
{
default:
return ze::invalid_type;
case BRO_TYPE_BOOL:
return ze::bool_type;
case BRO_TYPE_INT:
return ze::int_type;
case BRO_TYPE_COUNT:
case BRO_TYPE_COUNTER:
return ze::uint_type;
case BRO_TYPE_DOUBLE:
return ze::double_type;
case BRO_TYPE_TIME:
return ze::timepoint_type;
case BRO_TYPE_INTERVAL:
return ze::duration_type;
case BRO_TYPE_STRING:
return ze::string_type;
case BRO_TYPE_PATTERN:
return ze::regex_type;
case BRO_TYPE_VECTOR:
return ze::vector_type;
case BRO_TYPE_SET:
return ze::set_type;
case BRO_TYPE_TABLE:
return ze::table_type;
case BRO_TYPE_RECORD:
return ze::record_type;
case BRO_TYPE_IPADDR:
return ze::address_type;
case BRO_TYPE_SUBNET:
return ze::prefix_type;
case BRO_TYPE_PORT:
return ze::port_type;
}
}
bool broccoli::initialized = false;
void broccoli::init(bool messages, bool calltrace)
{
if (calltrace)
{
bro_debug_calltrace = 1;
LOG(verbose, broccoli) << "enabling call trace debugging";
}
if (messages)
{
bro_debug_messages = 1;
LOG(verbose, broccoli) << "enabling extra debug messages";
}
LOG(verbose, broccoli) << "initializing SSL context";
BroCtx ctx;
bro_ctx_init(&ctx);
bro_init(&ctx);
initialized = true;
}
broccoli::broccoli(std::shared_ptr<connection> conn, event_handler handler)
: bc_(nullptr)
, conn_(std::move(conn))
, strand_(conn_->socket().get_io_service())
, event_handler_(std::move(handler))
{
assert(initialized);
auto& socket = conn_->socket();
boost::asio::ip::tcp::socket::non_blocking_io non_blocking_io(true);
socket.io_control(non_blocking_io);
LOG(debug, broccoli) << *conn_ << ": creating broccoli handle";
bc_ = bro_conn_new_socket(socket.native(), BRO_CFLAG_DONTCACHE);
if (bc_ < 0)
throw broccoli_exception("bro_conn_new_socket");
}
broccoli::~broccoli()
{
if (bc_)
bro_conn_delete(bc_);
}
void broccoli::subscribe(std::string const& event)
{
bro_event_registry_add_compact(bc_,
event.data(),
&callback,
&event_handler_);
}
void broccoli::send(std::vector<uint8_t> const& raw)
{
LOG(debug, broccoli) << "sending raw event of size " << raw.size();
bro_event_send_raw(bc_, raw.data(), raw.size());
}
void broccoli::send(ze::event const& event)
{
auto bro_event = reverse_factory::make_event(event);
if (! bro_event_send(bc_, bro_event))
LOG(error, broccoli)
<< *conn_ << ": error sending event " << event.name();
bro_event_free(bro_event);
}
void broccoli::run(error_handler handler)
{
error_handler_ = std::move(handler);
bro_event_registry_request(bc_);
if (! bro_conn_connect(bc_))
{
LOG(error, broccoli) << *conn_ << ": unable to attach broccoli";
throw broccoli_exception("bro_conn_connect");
}
LOG(debug, broccoli) << *conn_ << ": successfully attached to socket";
async_read();
}
void broccoli::stop()
{
LOG(verbose, broccoli) << *conn_ << ": shutting down";
terminate_ = true;
}
int broccoli::factory::table_callback(void *key_data, void *val_data,
table_data const* data)
{
ze::value key = make_value(data->key_type, key_data);
ze::value value = make_value(data->val_type, val_data);
auto x = ze::table::value_type(std::move(key), std::move(value));
data->table->insert(std::move(x));
return 1;
}
int broccoli::factory::set_callback(void *key_data, set_data const* data)
{
ze::value key = make_value(data->key_type, key_data);
data->set->insert(std::move(key));
return 1;
}
void broccoli::factory::make_event(ze::event& event, BroEvMeta* meta)
{
event.name(meta->ev_name);
event.timestamp(meta->ev_ts);
event.reserve(meta->ev_numargs);
for (int i = 0; i < meta->ev_numargs; ++i)
event.emplace_back(
make_value(meta->ev_args[i].arg_type,
meta->ev_args[i].arg_data));
event.shrink_to_fit();
}
ze::value broccoli::factory::make_value(int type, void* bro_val)
{
switch (type)
{
default:
LOG(warn, broccoli) << "type " << type << " does not exist";
break;
case BRO_TYPE_UNKNOWN:
LOG(warn, broccoli) << "unknown broccoli type (" << type << ")";
break;
case BRO_TYPE_PATTERN:
case BRO_TYPE_TIMER:
case BRO_TYPE_ANY:
case BRO_TYPE_UNION:
case BRO_TYPE_LIST:
case BRO_TYPE_FUNC:
case BRO_TYPE_FILE:
case BRO_TYPE_VECTOR:
case BRO_TYPE_ERROR:
case BRO_TYPE_PACKET:
LOG(warn, broccoli) << "unsupported broccoli type (" << type << ")";
break;
case BRO_TYPE_BOOL:
return *static_cast<bool*>(bro_val);
case BRO_TYPE_INT:
return *static_cast<int64_t*>(bro_val);
case BRO_TYPE_COUNT:
case BRO_TYPE_COUNTER:
return *static_cast<uint64_t*>(bro_val);
case BRO_TYPE_DOUBLE:
return *static_cast<double*>(bro_val);
case BRO_TYPE_TIME:
return ze::time_point(ze::to_duration(*static_cast<double*>(bro_val)));
case BRO_TYPE_INTERVAL:
return ze::to_duration(*static_cast<double*>(bro_val));;
case BRO_TYPE_STRING:
{
BroString* s = static_cast<BroString*>(bro_val);
return {reinterpret_cast<char const*>(s->str_val), s->str_len};
}
case BRO_TYPE_PORT:
{
BroPort* p = static_cast<BroPort*>(bro_val);
switch (p->port_proto)
{
default:
LOG(warn, broccoli) << "invalid port type";
return ze::port(p->port_num, ze::port::unknown);
case IPPROTO_TCP:
return ze::port(p->port_num, ze::port::tcp);
case IPPROTO_UDP:
return ze::port(p->port_num, ze::port::udp);
case IPPROTO_ICMP:
return ze::port(p->port_num, ze::port::icmp);
}
}
case BRO_TYPE_IPADDR:
{
BroAddr* addr = static_cast<BroAddr*>(bro_val);
auto is_v4 = bro_util_is_v4_addr(addr);
return ze::address(
addr->addr,
is_v4 ? ze::address::ipv4 : ze::address::ipv6,
ze::address::network);
}
case BRO_TYPE_SUBNET:
{
BroSubnet* sn = static_cast<BroSubnet*>(bro_val);
auto is_v4 = bro_util_is_v4_addr(&sn->sn_net);
ze::address addr(
sn->sn_net.addr,
is_v4 ? ze::address::ipv4 : ze::address::ipv6,
ze::address::network);
return ze::prefix(std::move(addr), sn->sn_width);
}
case BRO_TYPE_SET:
{
BroSet* bro_set = static_cast<BroSet*>(bro_val);
if (! bro_set_get_size(bro_set))
return ze::set();
// Empty sets have BRO_TYPE_UNKNOWN. At this point, we know
// that the set has a valid type becuase it is not empty.
int key_type;
bro_set_get_type(bro_set, &key_type);
ze::set set(to_ze_type(key_type));
set_data data{key_type, &set};
bro_set_foreach(bro_set, (BroSetCallback)set_callback, &data);
return set;
}
case BRO_TYPE_TABLE:
{
BroTable* bro_table = static_cast<BroTable*>(bro_val);
if (! bro_table_get_size(bro_table))
return ze::table();
int key_type, val_type;
bro_table_get_types(bro_table, &key_type, &val_type);
ze::table table(to_ze_type(key_type), to_ze_type(val_type));
table_data data{key_type, val_type, &table};
bro_table_foreach(bro_table, (BroTableCallback)table_callback, &data);
return table;
}
case BRO_TYPE_RECORD:
{
ze::record record;
BroRecord *rec = static_cast<BroRecord*>(bro_val);
void* bro_val;
int bro_val_type = BRO_TYPE_UNKNOWN;
int cnt = 0;
while ((bro_val = bro_record_get_nth_val(rec, cnt, &bro_val_type)))
{
auto val = make_value(bro_val_type, bro_val);
record.push_back(std::move(val));
bro_val_type = BRO_TYPE_UNKNOWN;
++cnt;
}
return record;
}
}
throw broccoli_type_exception("invalid broccoli type", type);
}
struct broccoli::reverse_factory::builder
{
typedef bro_val result_type;
result_type operator()(ze::invalid_value i) const;
result_type operator()(ze::nil_value n) const;
result_type operator()(bool b) const;
result_type operator()(int64_t i) const;
result_type operator()(uint64_t i) const;
result_type operator()(double d) const;
result_type operator()(ze::duration d) const;
result_type operator()(ze::time_point t) const;
result_type operator()(ze::string const& s) const;
result_type operator()(ze::regex const& s) const;
result_type operator()(ze::vector const& v) const;
result_type operator()(ze::set const& s) const;
result_type operator()(ze::table const& t) const;
result_type operator()(ze::record const& r) const;
result_type operator()(ze::address const& a) const;
result_type operator()(ze::prefix const& s) const;
result_type operator()(ze::port const& p) const;
};
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::invalid_value i) const
{
return { BRO_TYPE_UNKNOWN, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::nil_value n) const
{
return { BRO_TYPE_UNKNOWN, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(bool b) const
{
return { BRO_TYPE_BOOL, const_cast<bool*>(&b) };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(int64_t i) const
{
// FIXME: perform narrowing check.
return { BRO_TYPE_INT, &i };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(uint64_t i) const
{
// FIXME: perform narrowing check.
return { BRO_TYPE_INT, &i };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(double d) const
{
return { BRO_TYPE_DOUBLE, const_cast<double*>(&d) };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::string const& s) const
{
// Caller must free the memory of the BroString!
BroString* bs = new BroString;
bro_string_set_data(
bs, reinterpret_cast<const unsigned char*>(s.data()), s.size());
return { BRO_TYPE_STRING, bs };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::regex const& r) const
{
assert(! "Broccoli does not yet support regular expressions");
return { BRO_TYPE_PATTERN, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::duration d) const
{
double secs = ze::to_double(d);
bro_val b;
b.type = BRO_TYPE_INTERVAL;
b.value = *reinterpret_cast<double**>(&secs);
return b;
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::time_point t) const
{
return { BRO_TYPE_TIME, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::vector const& v) const
{
assert(! "Broccoli does not yet support vectors");
return { BRO_TYPE_VECTOR, nullptr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::set const& s) const
{
// Caller must free the memory of the BroSet!
BroSet* set = bro_set_new();
for (auto const& x : s)
{
bro_val bv = ze::value::visit(x, *this);
bro_set_insert(set, bv.type, bv.value);
free(bv);
}
return { BRO_TYPE_SET, set };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::table const& t) const
{
// Caller must free the memory of the BroTable!
BroTable* table = bro_table_new();
for (auto const& x : t)
{
bro_val key = ze::value::visit(x.first, *this);
bro_val val = ze::value::visit(x.second, *this);
// If the table key is a compound type (i.e., record), we need to
// use BRO_TYPE_LIST instead of BRO_TYPE_RECORD.
bro_table_insert(
table,
key.type == BRO_TYPE_RECORD ? BRO_TYPE_LIST : key.type,
key.value, val.type, val.value);
free(key);
free(val);
}
return { BRO_TYPE_TABLE, table };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::record const& r) const
{
// Caller must free the memory of the BroRecord!
BroRecord* rec = bro_record_new();
for (auto const& val : r)
{
bro_val bv = ze::value::visit(val, *this);
bro_record_add_val(rec, NULL, bv.type, NULL, &bv.value);
free(bv);
}
return { BRO_TYPE_RECORD, rec };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::address const& a) const
{
// Caller must free the memory of the BroAddr!
BroAddr* addr = new BroAddr;
std::copy(a.data().begin(), a.data().end(),
reinterpret_cast<uint8_t*>(&addr->addr));
return { BRO_TYPE_IPADDR, addr };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::prefix const& p) const
{
// Caller must free the memory of the BroSubnet!
BroSubnet* bs = new BroSubnet;
bs->sn_width = p.length();
auto net = operator()(p.network());
auto addr = reinterpret_cast<BroAddr*>(net.value);
std::copy(addr, addr + sizeof(BroAddr), &bs->sn_net);
free(net);
return { BRO_TYPE_PORT, bs };
}
broccoli::reverse_factory::bro_val
broccoli::reverse_factory::builder::operator()(ze::port const& p) const
{
// Caller must free the memory of the BroPort!
BroPort* bp = new BroPort;
bp->port_num = p.number();
switch (p.type())
{
default:
{
bp->port_proto = 0;
LOG(debug, broccoli) << "unsupported port type";
}
break;
case ze::port::tcp:
bp->port_proto = IPPROTO_TCP;
break;
case ze::port::udp:
bp->port_proto = IPPROTO_UDP;
break;
case ze::port::icmp:
bp->port_proto = IPPROTO_ICMP;
break;
}
return { BRO_TYPE_PORT, bp };
}
void broccoli::reverse_factory::free(bro_val const& v)
{
switch (v.type)
{
case BRO_TYPE_STRING:
delete static_cast<BroString*>(v.value);
break;
case BRO_TYPE_IPADDR:
delete static_cast<BroAddr*>(v.value);
break;
case BRO_TYPE_PORT:
delete static_cast<BroPort*>(v.value);
break;
case BRO_TYPE_SUBNET:
delete static_cast<BroSubnet*>(v.value);
break;
case BRO_TYPE_RECORD:
bro_record_free(static_cast<BroRecord*>(v.value));
break;
case BRO_TYPE_TABLE:
bro_table_free(static_cast<BroTable*>(v.value));
break;
case BRO_TYPE_SET:
bro_set_free(static_cast<BroSet*>(v.value));
break;
}
}
BroEvent* broccoli::reverse_factory::make_event(ze::event const& event)
{
LOG(debug, event) << "building broccoli event " << event.name();
BroEvent* bro_event = bro_event_new(event.name().c_str());
if (! bro_event)
{
LOG(error, broccoli) << "could not create bro_event " << event.name();
throw broccoli_exception("bro_event_new");
}
for (auto& arg : event)
{
LOG(debug, event) << "adding argument: " << arg;
bro_val val = ze::value::visit(arg, builder());
bro_event_add_val(bro_event, val.type, NULL, val.value);
free(val);
}
return bro_event;
}
void broccoli::callback(BroConn* bc, void* user_data, BroEvMeta* meta)
{
try
{
ze::event event;
event.id(ze::uuid::random());
factory::make_event(event, meta);
auto f = static_cast<event_handler*>(user_data);
(*f)(std::move(event));
}
catch (ze::exception const& e)
{
LOG(error, broccoli)
<< "could not create ze::event from broccoli event '"
<< meta->ev_name << "' (" << e.what() << ')';
}
catch (exception const& e)
{
LOG(error, broccoli)
<< "error with broccoli event '"
<< meta->ev_name << "' (" << e.what() << ')';
}
}
void broccoli::async_read()
{
conn_->socket().async_read_some(
boost::asio::null_buffers(),
strand_.wrap(
std::bind(&broccoli::handle_read,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void broccoli::handle_read(boost::system::error_code const& ec,
size_t bytes_transferred)
{
if (terminate_)
return;
if (! ec)
bro_conn_process_input(bc_);
if (! ec || ec == boost::asio::error::would_block)
{
async_read();
return;
}
else if (ec == boost::asio::error::eof)
{
LOG(info, broccoli) << *conn_ << ": remote broccoli disconnected";
}
else
{
LOG(error, broccoli) << *conn_ << ": " << ec.message();
}
stop();
error_handler_(shared_from_this());
}
} // namespace comm
} // namespace vast
|
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MWidgetRecycler>
#include <MSeparator>
#include <MList>
#include <MPannableViewport>
#include <MAbstractItemModel>
#include <QItemSelectionModel>
#include <QParallelAnimationGroup>
#include <QPropertyAnimation>
#include "mcontentitem.h"
#include "mlistindex.h"
#include "mabstractcellcreator.h"
#include "mlistview_p.h"
#include "mapplicationpageview_p.h"
#include "mlistview.h"
#include "animations/mbasiclistitemdeletionanimation.h"
using namespace MListViewPrivateNamespace;
static const int MOVINGDETECTORTIMEOUT = 500;
static const int SCROLLTOANIMATIONSNAPDISTANCE = 100;
MListViewPrivate::MListViewPrivate() : recycler(new MWidgetRecycler)
{
itemHeight = 0;
rowCount = 0;
viewWidth = 0;
model = NULL;
selectionModel = NULL;
moving = false;
hseparator = NULL;
headersCreator = NULL;
hdrHeight = 0;
forceRepaint = false;
viewportTopLeft = QPointF();
viewportVisibleHeight = 0;
hseparatorHeight = 0;
pannableViewport = NULL;
clearVisibleOnRelayout = false;
scrollToAnimation = new QPropertyAnimation(this);
isDeleted = false;
itemDeletionAnimation = NULL;
movingDetectorTimer.setSingleShot(true);
connect(&movingDetectorTimer, SIGNAL(timeout()), this, SLOT(movingDetectionTimerTimeout()));
}
MListViewPrivate::~MListViewPrivate()
{
deleteVisibleItemsArray();
if(controllerModel)
clearFirstAndLastVisibleRows();
movingDetectorTimer.stop();
delete hseparator;
delete recycler;
delete itemDeletionAnimation;
}
void MListViewPrivate::setSeparator(MWidget *separator)
{
if(hseparator)
delete hseparator;
hseparator = separator;
if(separator)
hseparatorHeight = separator->preferredHeight();
else
hseparatorHeight = 0;
}
void MListViewPrivate::createSeparators()
{
setSeparator(new MSeparator);
}
void MListViewPrivate::updateSeparators()
{
if (hseparator)
hseparator->setObjectName(q_ptr->style()->horizontalSeparatorObjectName());
}
void MListViewPrivate::updateHeaders()
{
MDefaultHeadersCreator *defaultCreator = dynamic_cast<MDefaultHeadersCreator*>(headersCreator);
if (defaultCreator)
defaultCreator->setHeaderStyleName(q_ptr->style()->groupHeaderObjectName());
}
void MListViewPrivate::updateHeaderHeight()
{
}
void MListViewPrivate::updateRecyclerMaxItemsCount()
{
if (itemHeight > 0)
recycler->setMaxItemsPerClass(viewportVisibleHeight / itemHeight + 2);
}
void MListViewPrivate::setHeadersCreator(MCellCreator *creator)
{
delete headersCreator;
hdrHeight = 0;
headersCreator = creator;
}
void MListViewPrivate::movingDetectionTimerTimeout()
{
if (isAnimating())
return;
moving = false;
controllerModel->setListIsMoving(false);
movingDetectorTimer.stop();
}
void MListViewPrivate::clearVisibleItemsArray()
{
foreach(MWidget * item, visibleItems) {
deleteItem(item);
}
visibleItems.clear();
}
void MListViewPrivate::deleteVisibleItemsArray()
{
qDeleteAll(visibleItems);
visibleItems.clear();
}
void MListViewPrivate::destroy()
{
isDeleted = true;
deleteLater();
}
void MListViewPrivate::clearFirstAndLastVisibleRows()
{
updateFirstVisibleRow(QModelIndex());
updateLastVisibleRow(QModelIndex());
}
void MListViewPrivate::cellClicked(MWidget *source)
{
MWidget *widget = source;
QModelIndex cellIndex(locateVisibleIndexAt(widget->pos().y()));
controller->selectItem(cellIndex);
}
void MListViewPrivate::cellLongTapped(const QModelIndex &index, const QPointF &position)
{
controller->longTapItem(index, position);
}
void MListViewPrivate::selectionChange(const QItemSelection &selected, const QItemSelection &deselected)
{
for (QHash<QModelIndex, MWidget *>::iterator iter = visibleItems.begin(); iter != visibleItems.end(); ++iter) {
if (selected.contains(iter.key()))
iter.value()->setSelected(true);
if (deselected.contains(iter.key()))
iter.value()->setSelected(false);
}
}
bool MListViewPrivate::isAnimating()
{
return (itemDeletionAnimation && itemDeletionAnimation->state() == QParallelAnimationGroup::Running);
}
void MListViewPrivate::removeRows(const QModelIndex &parent, int start, int end, bool animated)
{
if (!animated || isAnimating() || !itemDeletionAnimation)
return;
int first = indexToFlatRow(controllerModel->firstVisibleItem());
int last = indexToFlatRow(controllerModel->lastVisibleItem());
if (parent.isValid()) {
int parentFlatRow = indexToFlatRow(parent);
start += parentFlatRow + 1;
end += parentFlatRow + 1;
}
if (start > last || !controller->isVisible())
return;
start = first > start ? first : start;
end = end > last ? last : end;
// Set targets for deletion animation
appendTargetsToDeleteAnimation(start, end, first, last);
// Start item deletion animation
itemDeletionAnimation->start();
}
void MListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
QPointF offset(0,0);
for (int flatRow = first; flatRow <= last; flatRow ++) {
MWidget *cell = findCellAtRow(flatRow);
if (cell) {
if (flatRow < start)
itemDeletionAnimation->appendBeforeTarget(cell);
else if (flatRow > end) {
itemDeletionAnimation->appendAfterTarget(cell, cell->pos() - offset);
}
else {
itemDeletionAnimation->appendDeleteTarget(cell);
offset += QPointF(0, cellSize(flatRow).height() + hseparatorHeight);
}
}
}
animatingItems = visibleItems.values().toVector();
visibleItems.clear();
}
void MListViewPrivate::resetAnimatedWidgets()
{
while (!animatingItems.isEmpty()) {
delete animatingItems.front();
animatingItems.pop_front();
}
q_ptr->layoutChanged();
_q_relayoutItemsIfNeeded();
}
void MListViewPrivate::deleteItem(MWidget *widget)
{
recycler->recycle(widget);
}
MWidget *MListViewPrivate::createCell(int row)
{
QModelIndex index(flatRowToIndex(row));
MWidget *cell = controllerModel->cellCreator()->createCell(index, *recycler);
cell->setParent(NULL);
cell->setParentItem(controller);
cell->setVisible(true);
if(cell->maximumHeight() < itemHeight)
{
cell->setMaximumSize(cell->maximumWidth(), itemHeight);
} else if(cell->minimumHeight() > itemHeight)
{
cell->setMinimumSize(cell->minimumWidth(), itemHeight);
}
cell->resize(cellSize(row));
// TODO this is not optimal, I'm pretty sure, need to find better way to keep
// selection. Refactor into its own function.
QItemSelectionModel *selectionModel = controllerModel->selectionModel();
cell->setSelected(selectionModel->isSelected(index));
// TODO this code can be executed only when panning is stopped. Refactor into
// its own function
if (cell->metaObject()->indexOfSignal("clicked()") != -1) {
QObject::connect(cell, SIGNAL(clicked()), q_ptr, SLOT(itemClick()), Qt::UniqueConnection);
}
updateItemLongTapConnection(cell);
return cell;
}
void MListViewPrivate::viewportRectChanged(const QRectF &viewportRect)
{
if (isDeleted)
return;
if (viewportRect.topLeft() != oldViewportRectPosition) {
movingDetectorTimer.start(MOVINGDETECTORTIMEOUT);
if (!moving) {
moving = true;
controllerModel->setListIsMoving(true);
}
oldViewportRectPosition = viewportRect.topLeft();
}
}
void MListViewPrivate::viewportPositionChanged(const QPointF &position)
{
if (isDeleted)
return;
updateViewportRect(position - listPosition, QSizeF(viewWidth, pannableViewport->size().height()));
}
void MListViewPrivate::viewportSizeChanged(const QSizeF &size)
{
if (isDeleted)
return;
updateViewportRect(viewportTopLeft, QSizeF(viewWidth, size.height()));
updateScrollToTargetPosition();
updateRecyclerMaxItemsCount();
}
void MListViewPrivate::viewportRangeChanged(const QRectF &range)
{
Q_UNUSED(range);
if (isDeleted)
return;
updateScrollToTargetPosition();
}
void MListViewPrivate::connectPannableViewport()
{
disconnect(controller, SIGNAL(parentChanged()), this, SLOT(controllerParentChanged()));
if (pannableViewport)
pannableViewport->disconnect(this);
connect(controller, SIGNAL(parentChanged()), SLOT(controllerParentChanged()));
pannableViewport = MListViewPrivateNamespace::findParentWidgetOfType<MPannableViewport>(controller);
if(pannableViewport) {
updatePannableViewportPosition();
connect(pannableViewport, SIGNAL(positionChanged(QPointF)), SLOT(viewportPositionChanged(QPointF)));
connect(pannableViewport, SIGNAL(viewportSizeChanged(QSizeF)), SLOT(viewportSizeChanged(QSizeF)));
connect(pannableViewport, SIGNAL(rangeChanged(QRectF)), SLOT(viewportRangeChanged(QRectF)));
viewportTopLeft = pannableViewport->position() - listPosition;
viewportVisibleHeight = pannableViewport->size().height();
scrollToAnimation->setTargetObject(pannableViewport);
scrollToAnimation->setPropertyName("position");
}
}
void MListViewPrivate::controllerParentChanged()
{
disconnect(this, SLOT(controllerParentChanged()));
connectPannableViewport();
}
void MListViewPrivate::updateListGeometry()
{
if(q_ptr)
q_ptr->updateGeometry();
}
void MListViewPrivate::updateViewportRect(const QPointF &position, const QSizeF &size)
{
if (isDeleted)
return;
if ((viewportTopLeft != position) || (viewportVisibleHeight < size.height()) || (forceRepaint)) {
forceRepaint = false;
viewportTopLeft = position;
viewportVisibleHeight = size.height();
viewportRectChanged(QRectF(position, size));
_q_relayoutItemsIfNeeded();
}
}
void MListViewPrivate::updatePannableViewportPosition()
{
if(!pannableViewport)
connectPannableViewport();
if(pannableViewport && controller) {
QPointF oldListPosition = listPosition;
listPosition = controller->mapToItem(pannableViewport->widget(), 0, 0);
viewportTopLeft += (oldListPosition - listPosition);
listOffset = calculatePannableViewportOffset(listPosition);
updateListIndexOffset();
}
else
listPosition = QPointF(0,0);
}
QPointF MListViewPrivate::calculatePannableViewportOffset(const QPointF &listPosition)
{
QPointF listOffset = listPosition;
if (pannableViewport->widget() && pannableViewport->widget() != controller) {
QList<QGraphicsItem *> pannableViewportWidgetChildren = pannableViewport->widget()->childItems();
foreach (QGraphicsItem *item, pannableViewportWidgetChildren) {
if (item->isWidget()) {
MWidget *widget = dynamic_cast<MWidget *>(item);
if (widget && widget->objectName() == MApplicationPageViewPrivate::TopSpacerName) {
listOffset.setY(listPosition.y() - widget->size().height());
break;
}
}
}
}
return listOffset;
}
void MListViewPrivate::updateAnimations()
{
delete itemDeletionAnimation;
itemDeletionAnimation = 0;
if (q_ptr->style()->deleteItemAnimation().isEmpty())
return;
itemDeletionAnimation = qobject_cast<MBasicListItemDeletionAnimation*>(MTheme::animation(q_ptr->style()->deleteItemAnimation()));
if (itemDeletionAnimation)
connect(itemDeletionAnimation, SIGNAL(finished()), this, SLOT(resetAnimatedWidgets()));
}
void MListViewPrivate::updateItemHeight()
{
if (controllerModel->cellCreator()) {
itemHeight = controllerModel->cellCreator()->cellSize().height();
updateRecyclerMaxItemsCount();
}
}
void MListViewPrivate::removeInvisibleItems(const QPoint &firstVisibleItemCoord,
const QPoint &lastVisibleItemCoord)
{
for (ModelIndexWidgetHash::iterator iter = visibleItems.begin(); iter != visibleItems.end();) {
MWidget *cell = *iter;
qreal cellPosY = cell->pos().y();
if (cellPosY < firstVisibleItemCoord.y() || cellPosY > lastVisibleItemCoord.y()) {
deleteItem(*iter);
iter = visibleItems.erase(iter);
} else {
++iter;
}
}
}
MWidget *MListViewPrivate::findCellAtRow(int row)
{
foreach (MWidget * widget, visibleItems) {
QPointF pos(widget->pos());
int widgetRow = locateVisibleRowAt(pos.y(), pos.x());
if (widgetRow == row)
return widget;
}
return NULL;
}
void MListViewPrivate::createVisibleItems(int firstVisibleRow, int lastVisibleRow)
{
for (int currentRow = firstVisibleRow; currentRow <= lastVisibleRow; currentRow++) {
QModelIndex index = flatRowToIndex(currentRow);
MWidget *cell = visibleItems.value(index, NULL);
if (!cell) {
cell = createItem(currentRow);
visibleItems[index] = cell;
}
cell->setPos(QPointF(0, locatePosOfItem(currentRow)));
}
}
void MListViewPrivate::disconnectSignalsFromModelToListView()
{
if (model)
model->disconnect(q_ptr);
}
void MListViewPrivate::connectSignalsFromModelToListView()
{
if (model) {
connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), q_ptr, SLOT(dataChanged(QModelIndex, QModelIndex)));
if (model->inherits("MAbstractItemModel") || model->inherits("MSortFilterProxyModel")) {
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int, bool)), q_ptr, SLOT(rowsInserted(QModelIndex, int, int, bool)));
connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int, bool)), q_ptr, SLOT(rowsRemoved(QModelIndex, int, int, bool)));
} else {
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), q_ptr, SLOT(rowsInserted(QModelIndex, int, int)));
connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)), q_ptr, SLOT(rowsRemoved(QModelIndex, int, int)));
}
connect(model, SIGNAL(layoutChanged()), q_ptr, SLOT(layoutChanged()));
connect(model, SIGNAL(modelReset()), q_ptr, SLOT(modelReset()));
connect(model, SIGNAL(rowsMoved(QModelIndex, int, int, QModelIndex, int)), q_ptr, SLOT(rowsMoved(QModelIndex, int, int, QModelIndex, int)));
connect(controller, SIGNAL(visibleChanged()), q_ptr, SLOT(_q_relayoutItemsIfNeeded()));
}
}
void MListViewPrivate::updateItemConnections()
{
foreach (MWidget *cell, visibleItems) {
updateItemLongTapConnection(cell);
}
}
void MListViewPrivate::updateItemLongTapConnection(MWidget *cell)
{
if (cell->metaObject()->indexOfSignal("longTapped(QPointF)") != -1) {
if (controllerModel->longTapEnabled())
QObject::connect(cell, SIGNAL(longTapped(QPointF)), q_ptr, SLOT(_q_itemLongTapped(QPointF)), Qt::UniqueConnection);
else
QObject::disconnect(cell, SIGNAL(longTapped(QPointF)), q_ptr, SLOT(_q_itemLongTapped(QPointF)));
}
}
void MListViewPrivate::resetModel(MListModel *mListModel)
{
forceRepaint = true;
rowCount = 0;
disconnectSignalsFromModelToListView();
controllerModel = mListModel;
model = mListModel->itemModel();
if(model)
rowCount = model->rowCount();
clearVisibleItemsArray();
updateItemHeight();
clearFirstAndLastVisibleRows();
connectSignalsFromModelToListView();
}
void MListViewPrivate::updateItemSize()
{
foreach(MWidget * cell, visibleItems) {
cell->resize(cellSize(0));
}
}
QSizeF MListViewPrivate::cellSize(int row) const
{
Q_UNUSED(row);
return QSizeF(viewWidth, itemHeight);
}
void MListViewPrivate::updateSeparatorSize()
{
if (hseparator) {
hseparatorHeight = hseparator->preferredHeight();
hseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(viewWidth, hseparatorHeight)));
}
}
void MListViewPrivate::updateFirstVisibleRow(const QModelIndex &index)
{
if (isDeleted)
return;
q_ptr->model()->setFirstVisibleItem(index);
}
void MListViewPrivate::updateLastVisibleRow(const QModelIndex &index)
{
if (isDeleted)
return;
q_ptr->model()->setLastVisibleItem(index);
}
void MListViewPrivate::createVisibleItems()
{
QModelIndex firstVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y()));
int firstVisibleRow = indexToFlatRow(firstVisibleIndex);
QModelIndex lastVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y() + viewportVisibleHeight));
int lastVisibleRow = indexToFlatRow(lastVisibleIndex);
createVisibleItems(firstVisibleRow, lastVisibleRow);
}
QModelIndex MListViewPrivate::locateLastVisibleIndexInRowAt(int pos)
{
return locateVisibleIndexAt(pos);
}
void MListViewPrivate::replaceItem(MWidget* item, MWidget* newItem)
{
newItem->setPos(item->pos());
visibleItems[visibleItems.key(item)] = newItem;
deleteItem(item);
}
bool MListViewPrivate::isGroupHeader(const QModelIndex &index)
{
Q_UNUSED(index);
return false;
}
void MListViewPrivate::layoutChanged()
{
if(model)
rowCount = model->rowCount();
else
rowCount = 0;
}
void MListViewPrivate::drawSeparators(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if (!controllerModel->firstVisibleItem().isValid() || !controllerModel->lastVisibleItem().isValid() || isAnimating())
return;
int firstRow = indexToFlatRow(controllerModel->firstVisibleItem());
int lastRow = indexToFlatRow(controllerModel->lastVisibleItem());
for (int currentRow = firstRow; currentRow <= lastRow; currentRow++) {
drawSeparator(currentRow, painter, option);
}
}
void MListViewPrivate::drawSeparator(const int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
drawHorizontalSeparator(row, painter, option);
}
void MListViewPrivate::drawHorizontalSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(row == 0 || hseparatorHeight == 0)
return;
QPointF pos(-q_ptr->marginLeft(), locatePosOfItem(row) - hseparatorHeight - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
hseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
QPointF MListViewPrivate::locateScrollToPosition(const QModelIndex &index, MList::ScrollHint hint)
{
if (!pannableViewport)
return QPointF(0,0);
int cellPosition = locatePosOfItem(index);
QPointF targetPosition = pannableViewport->position();
qreal pannableViewportHeight = pannableViewport->boundingRect().height() - listOffset.y();
switch (hint) {
case MList::PositionAtTopHint:
targetPosition.setY(listOffset.y() + cellPosition);
break;
case MList::PositionAtBottomHint:
targetPosition.setY(cellPosition + itemHeight + listOffset.y() - pannableViewportHeight);
break;
case MList::PositionAtCenterHint:
targetPosition.setY(listOffset.y() + cellPosition + itemHeight / 2 - pannableViewportHeight / 2);
break;
case MList::EnsureVisibleHint:
if (cellPosition <= pannableViewport->position().y()) {
targetPosition.setY(listOffset.y() + cellPosition);
} else if (cellPosition + itemHeight > pannableViewport->position().y() + pannableViewportHeight) {
targetPosition.setY(cellPosition + itemHeight + listOffset.y() - pannableViewportHeight);
}
break;
}
int pannableWidgetBoundingHeight = pannableViewport->widget()->boundingRect().height();
targetPosition.setY(qMax(targetPosition.y(), (qreal)0));
if (pannableWidgetBoundingHeight > pannableViewportHeight)
targetPosition.setY(qMin(targetPosition.y(), pannableWidgetBoundingHeight - pannableViewportHeight));
else
targetPosition = pannableViewport->position();
return targetPosition;
}
void MListViewPrivate::_q_itemLongTapped(const QPointF &pos)
{
q_ptr->longTap(pos);
}
void MListViewPrivate::_q_relayoutItemsIfNeeded()
{
if (isDeleted)
return;
if (controller->isVisible())
q_ptr->relayoutItemsInViewportRect();
}
void MListViewPrivate::updateScrollToTargetPosition()
{
if (scrollToAnimation->state() == QPropertyAnimation::Running) {
QPointF targetPosition = locateScrollToPosition(controllerModel->scrollToIndex(), static_cast<MList::ScrollHint>(controllerModel->scrollHint()));
if (targetPosition != scrollToAnimation->endValue().toPointF()) {
if (targetPosition.y() > pannableViewport->position().y())
scrollToAnimation->setStartValue(targetPosition + QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
else
scrollToAnimation->setStartValue(targetPosition - QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
scrollToAnimation->setEndValue(targetPosition);
}
}
}
void MListViewPrivate::scrollToPos(const QPointF &targetPosition, MList::AnimationMode mode)
{
if (mode == MList::Animated) {
if (targetPosition.y() > pannableViewport->position().y())
scrollToAnimation->setStartValue(targetPosition + QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
else
scrollToAnimation->setStartValue(targetPosition - QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
scrollToAnimation->setEndValue(targetPosition);
scrollToAnimation->setEasingCurve(QEasingCurve::OutCubic);
scrollToAnimation->setDuration(100);
scrollToAnimation->start();
}
else
pannableViewport->setPosition(targetPosition);
}
void MListViewPrivate::updateListIndexVisibility()
{
}
void MListViewPrivate::updateListIndexOffset()
{
}
void MListViewPrivate::updateListIndexStyle()
{
}
////////////
// Plain list
////////////
MPlainListViewPrivate::MPlainListViewPrivate()
{
}
MPlainListViewPrivate::~MPlainListViewPrivate()
{
}
int MPlainListViewPrivate::hseparatorsCount() const
{
return itemsCount() - 1;
}
int MPlainListViewPrivate::totalHeight()
{
int itemsCount = this->itemsCount();
int separatorsCount = this->hseparatorsCount();
int totalHeight = itemsCount * itemHeight + separatorsCount * hseparatorHeight;
return totalHeight;
}
int MPlainListViewPrivate::itemsCount() const
{
if (model == 0)
return 0;
return rowCount;
}
MWidget *MPlainListViewPrivate::createItem(int row)
{
return createCell(row);
}
int MPlainListViewPrivate::indexToFlatRow(const QModelIndex &index) const
{
return index.row();
}
QModelIndex MPlainListViewPrivate::flatRowToIndex(int row) const
{
return model->index(row, 0);
}
int MPlainListViewPrivate::locateVisibleRowAt(int y, int x)
{
Q_UNUSED(x);
if (itemHeight == 0)
return 0;
// Formula for calculating position of specific row is following:
// row * itemHeight + row * hseparatorHeight = pos
// to calculate row lets do basic math:
// row = pos / (hseparatorHeight + itemHeight)
int row = y / (hseparatorHeight + itemHeight);
int modelRowCount = rowCount;
if (row >= modelRowCount)
row = modelRowCount - 1;
return row;
}
// TODO write unit test for this
int MPlainListViewPrivate::locatePosOfItem(int row)
{
int itemHeights = row * itemHeight;
int hseparatorHeights = 0;
if (row > 0)
hseparatorHeights = row * hseparatorHeight;
return itemHeights + hseparatorHeights;
}
int MPlainListViewPrivate::locatePosOfItem(const QModelIndex &index)
{
return locatePosOfItem(index.row());
}
QModelIndex MPlainListViewPrivate::locateVisibleIndexAt(int pos)
{
int row = locateVisibleRowAt(pos);
if (row < 0)
return model->index(0, 0);
return model->index(row, 0);
}
void MPlainListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
MListViewPrivate::createVisibleItems(firstVisibleRow.row(), lastVisibleRow.row());
}
////////////
// Plain list MultiColumn
////////////
MPlainMultiColumnListViewPrivate::MPlainMultiColumnListViewPrivate()
{
vseparatorWidth = 0;
vseparator = NULL;
}
MPlainMultiColumnListViewPrivate::~MPlainMultiColumnListViewPrivate()
{
if(vseparator)
delete vseparator;
}
void MPlainMultiColumnListViewPrivate::createSeparators()
{
MListViewPrivate::createSeparators();
//create vertical separators
setVerticalSeparator(new MSeparator(NULL, Qt::Vertical));
}
void MPlainMultiColumnListViewPrivate::updateSeparators()
{
MListViewPrivate::updateSeparators();
if (vseparator)
vseparator->setObjectName(q_ptr->style()->verticalSeparatorObjectName());
}
void MPlainMultiColumnListViewPrivate::updateRecyclerMaxItemsCount()
{
if (itemHeight > 0)
recycler->setMaxItemsPerClass((viewportVisibleHeight / itemHeight + 2) * controllerModel->columns());
}
void MPlainMultiColumnListViewPrivate::setVerticalSeparator(MWidget *separator)
{
if(vseparator)
delete vseparator;
vseparator = separator;
if(vseparator)
vseparatorWidth = vseparator->preferredWidth();
else
vseparatorWidth = 0;
}
int MPlainMultiColumnListViewPrivate::itemsToRows(int items) const
{
int columns = controllerModel->columns();
int rows = items / columns;
if (items > rows * columns)
rows++;
return rows;
}
int MPlainMultiColumnListViewPrivate::flatRowToColumn(int row) const
{
int columns = controllerModel->columns();
int itemRow = row / columns;
int flatRowColumn = row - itemRow * columns;
return flatRowColumn;
}
int MPlainMultiColumnListViewPrivate::locatePosOfItem(int row)
{
int columns = controllerModel->columns();
int rows = row / columns;
int itemHeights = rows * itemHeight;
int hseparatorHeights = 0;
if (rows > 0)
hseparatorHeights = rows * hseparatorHeight;
return itemHeights + hseparatorHeights;
}
int MPlainMultiColumnListViewPrivate::hseparatorsCount() const
{
return itemsToRows(itemsCount()) - 1;
}
int MPlainMultiColumnListViewPrivate::totalHeight()
{
int rowsCount = itemsToRows(itemsCount());
int hseparatorsCount = this->hseparatorsCount();
int totalHeight = rowsCount * itemHeight + hseparatorsCount * hseparatorHeight;
return totalHeight;
}
MWidget *MPlainMultiColumnListViewPrivate::createItem(int row)
{
MWidget *cell = createCell(row);
return cell;
}
QModelIndex MPlainMultiColumnListViewPrivate::locateLastVisibleIndexInRowAt(int pos)
{
int lastVisibleFlatRow = locateVisibleRowAt(pos, viewWidth-1);
return flatRowToIndex(lastVisibleFlatRow);
}
void MPlainMultiColumnListViewPrivate::replaceItem(MWidget* item, MWidget* newItem)
{
MListViewPrivate::replaceItem(item, newItem);
widgetFlatRows[newItem] = widgetFlatRows[item];
widgetFlatRows[item] = 0;
}
int MPlainMultiColumnListViewPrivate::locateVisibleRowAt(int y, int x)
{
if (itemHeight == 0)
return 0;
int columns = controllerModel->columns();
int row = y / (hseparatorHeight + itemHeight) * columns;
if (row >= itemsCount())
row = itemsCount() - 1;
int column = 0;
if (viewWidth)
column = qMin(x / (viewWidth / columns), columns - 1);
int flatRow = row + column;
if (flatRow >= itemsCount())
flatRow = itemsCount() - 1;
return flatRow;
}
void MPlainMultiColumnListViewPrivate::updateItemSize()
{
foreach(MWidget * cell, visibleItems) {
int cellRow = widgetFlatRows[cell] - 1;
int cellColumn = flatRowToColumn(cellRow);
cell->resize(cellSize(cellRow));
cell->setPos(QPointF(cellColumn * viewWidth / controllerModel->columns(), cell->pos().y()));
}
}
void MPlainMultiColumnListViewPrivate::updateSeparatorSize()
{
MListViewPrivate::updateSeparatorSize();
if (vseparator) {
vseparatorWidth = vseparator->preferredWidth();
vseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(vseparatorWidth, itemHeight)));
}
}
QSizeF MPlainMultiColumnListViewPrivate::cellSize(int row) const
{
Q_UNUSED(row);
int columns = controllerModel->columns();
return QSizeF(viewWidth / columns - vseparatorWidth, itemHeight);
}
void MPlainMultiColumnListViewPrivate::cellClicked(MWidget *source)
{
int clickedFlatRow = widgetFlatRows.value(source) - 1;
QModelIndex cellIndex(flatRowToIndex(clickedFlatRow));
controller->selectItem(cellIndex);
}
void MPlainMultiColumnListViewPrivate::selectionChange(const QItemSelection &selected, const QItemSelection &deselected)
{
foreach(MWidget * widget, visibleItems) {
int widgetFlatRow = widgetFlatRows.value(widget) - 1;
QModelIndex widgetIndex(flatRowToIndex(widgetFlatRow));
if (selected.contains(widgetIndex))
widget->setSelected(true);
if (deselected.contains(widgetIndex))
widget->setSelected(false);
}
}
void MPlainMultiColumnListViewPrivate::createVisibleItems()
{
QModelIndex firstVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y()));
QModelIndex lastVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y() + viewportVisibleHeight));
createVisibleItems(firstVisibleIndex, lastVisibleIndex);
}
void MPlainMultiColumnListViewPrivate::clearVisibleItemsArray()
{
MListViewPrivate::clearVisibleItemsArray();
widgetFlatRows.clear();
}
void MPlainMultiColumnListViewPrivate::removeInvisibleItems(const QPoint &firstVisibleItemCoord,
const QPoint &lastVisibleItemCoord)
{
for (ModelIndexWidgetHash::iterator iter = visibleItems.begin(); iter != visibleItems.end();) {
MWidget *cell = *iter;
qreal cellPosY = cell->pos().y();
if (cellPosY < firstVisibleItemCoord.y() || cellPosY > lastVisibleItemCoord.y() || widgetFlatRows[*iter] > itemsCount()) {
widgetFlatRows[*iter] = 0;
deleteItem(*iter);
iter = visibleItems.erase(iter);
} else {
++iter;
}
}
}
void MPlainMultiColumnListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
int firstRow = firstVisibleRow.row();
int lastRow = lastVisibleRow.row();
if (!viewWidth || (!firstRow&&!lastRow&&itemsCount()>1)) // required for x position
return;
for (int currentRow = firstRow; currentRow <= lastRow; currentRow++) {
MWidget *cell = findCellAtRow(currentRow);
if (!widgetFlatRows[cell] && flatRowToColumn(currentRow) == 0) {
// Create widgets to all columns in this row
for (int column = 0; column < controllerModel->columns(); ++column) {
QModelIndex index = flatRowToIndex(currentRow + column);
cell = visibleItems.value(index, NULL);
if (!cell) {
cell = createItem(currentRow + column);
visibleItems[index] = cell;
}
widgetFlatRows[cell] = currentRow + column + 1;
cell->setPos(QPointF(column*(viewWidth / controllerModel->columns()), locatePosOfItem(currentRow + column)));
if (currentRow + column + 1 == itemsCount() || flatRowToColumn(currentRow + column + 1) == 0)
break;
}
}
}
}
void MPlainMultiColumnListViewPrivate::drawSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int columns = controllerModel->columns();
int column = flatRowToColumn(row);
if(row >= columns && column == 0) {
drawHorizontalSeparator(row, painter, option);
return;
}
if(column > 0)
drawVerticalSeparator(row, column, painter, option);
}
void MPlainMultiColumnListViewPrivate::drawVerticalSeparator(int row, int column, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(vseparatorWidth == 0)
return;
int itemWidth = viewWidth / controllerModel->columns();
QPointF pos(column*itemWidth - q_ptr->marginLeft() - vseparatorWidth, locatePosOfItem(row) - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
vseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
void MPlainMultiColumnListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
QPointF destination = findCellAtRow(start)->pos();
for (int flatRow = first; flatRow <= last; flatRow ++) {
MWidget *cell = findCellAtRow(flatRow);
if (cell) {
if (flatRow < start)
itemDeletionAnimation->appendBeforeTarget(cell);
else if (flatRow > end) {
itemDeletionAnimation->appendAfterTarget(cell, destination);
destination = cell->pos();
}
else
itemDeletionAnimation->appendDeleteTarget(cell);
}
}
animatingItems = visibleItems.values().toVector();
visibleItems.clear();
}
////////////
// Group Header
////////////
MGroupHeaderListViewPrivate::MGroupHeaderListViewPrivate()
{
listIndexWidget = NULL;
gseparator = NULL;
gseparatorHeight = 0;
}
MGroupHeaderListViewPrivate::~MGroupHeaderListViewPrivate()
{
delete listIndexWidget;
if (gseparator)
delete gseparator;
}
void MGroupHeaderListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
MListViewPrivate::createVisibleItems(indexToFlatRow(firstVisibleRow), indexToFlatRow(lastVisibleRow));
}
QModelIndex MGroupHeaderListViewPrivate::locateVisibleIndexAt(int pos)
{
int row = locateVisibleRowAt(pos);
if (row < 0)
return model->index(0, 0);
return flatRowToIndex(row);
}
int MGroupHeaderListViewPrivate::hseparatorsCount() const
{
int itemsCount = this->headersCount();
int hseparators = 0;
for (int i = 0; i < itemsCount; i++) {
int itemsCountInGroup = this->itemsCount(i);
if (itemsCountInGroup == 0)
continue;
hseparators += itemsCountInGroup - 1;
}
return hseparators;
}
void MGroupHeaderListViewPrivate::resetModel(MListModel *mListModel)
{
MListViewPrivate::resetModel(mListModel);
if (!listIndexWidget) {
listIndexWidget = new MListIndex(controller);
updateListIndexVisibility();
updateListIndexStyle();
}
if (!controllerModel->headerCreator()) {
if (!headersCreator)
headersCreator = new MDefaultHeadersCreator(q_ptr->style()->groupHeaderObjectName());
else
updateHeaders();
}
headersPositions.resize(this->headersCount());
updateHeaderHeight();
}
int MGroupHeaderListViewPrivate::locatePosOfItem(const QModelIndex &index)
{
if (index.parent().isValid()) {
return locatePosOfItem(index.parent().row(), index.row());
} else {
return locatePosOfItem(index.row(), -1);
}
}
int MGroupHeaderListViewPrivate::locatePosOfItem(int headerIndex, int itemIndex)
{
if (itemIndex == -1) {
// we hitted header
return headersPositions[headerIndex];
}
int pos = headersPositions[headerIndex] + headerHeight();
if (itemIndex == 0)
return pos;
int itemHeights = itemIndex * itemHeight;
int hseparatorHeights = 0;
hseparatorHeights = itemIndex * hseparatorHeight;
pos += hseparatorHeights + itemHeights;
return pos;
}
int MGroupHeaderListViewPrivate::locatePosOfItem(int row)
{
int headerIndex = dFindLowerIndex(headersRows, row);
int relativeRow = row - headersRows[headerIndex] - 1; // we have to subtruct header
return locatePosOfItem(headerIndex, relativeRow);
}
int MGroupHeaderListViewPrivate::locateVisibleRowAt(int y, int x)
{
Q_UNUSED(x);
if (itemHeight == 0)
return 0;
if (headersPositions.size() == 0)
return 0;
int headerIndex = dFindLowerIndex(headersPositions, y);
int headerPosition = headersPositions[headerIndex];
int headerRow = headersRows[headerIndex];
int relativePos = y - headerPosition;
int headerHeight = this->headerHeight();
if (relativePos < headerHeight)
return headerRow;
int row = (relativePos - headerHeight) / (itemHeight + hseparatorHeight) + headerRow + 1;
return row;
}
QModelIndex MGroupHeaderListViewPrivate::flatRowToIndex(int row) const
{
if (!headersRows.contains(row)) {
int headerIndex = dFindLowerIndex(headersRows, row);
QModelIndex parent(model->index(headerIndex, 0));
int relativeRow = row - headersRows[headerIndex] - 1;
int itemsCount = this->itemsCount(headerIndex);
// Check if header doesn't have any children
if(itemsCount == 0)
return parent;
if (relativeRow >= itemsCount)
relativeRow = itemsCount - 1;
QModelIndex index(model->index(relativeRow, 0, parent));
return index;
}
int headerIndex = headersRows.indexOf(row);
return model->index(headerIndex, 0);
}
void MGroupHeaderListViewPrivate::updateHeadersPositions()
{
int headersCount = this->headersCount();
headersPositions.clear();
if (headersCount == 0)
return;
int headerHeight = this->headerHeight();
headersPositions << 0;
int previousIndexPosition = 0;
for (int i = 1; i < headersCount; i++) {
int groupSize = this->groupSize(i - 1);
headersPositions << previousIndexPosition + headerHeight + groupSize + gseparatorHeight;
previousIndexPosition += headerHeight + groupSize + gseparatorHeight;
}
}
void MGroupHeaderListViewPrivate::updateHeadersRows()
{
int headersCount = this->headersCount();
headersRows.clear();
if (headersCount == 0)
return;
headersRows << 0;
int prevGroupSize = 0;
for (int i = 1; i < headersCount; i++) {
prevGroupSize += itemsCount(i - 1);
headersRows << (i + prevGroupSize);
}
}
void MGroupHeaderListViewPrivate::updateHeadersIndexes()
{
if(listIndexWidget) {
QMap<QModelIndex, QString> shortcuts;
for (int i = 0; i < headersCount(); i++) {
QModelIndex headerRowIndex = flatRowToIndex(headersRows[i]);
shortcuts[headerRowIndex] = model->data(headerRowIndex).toString();
}
listIndexWidget->setShortcuts(shortcuts);
}
}
void MGroupHeaderListViewPrivate::setGroupSeparator(MWidget *separator)
{
if(gseparator)
delete gseparator;
gseparator = separator;
if(gseparator)
gseparatorHeight = gseparator->preferredHeight();
else
gseparatorHeight = 0;
}
void MGroupHeaderListViewPrivate::createSeparators()
{
MListViewPrivate::createSeparators();
setGroupSeparator(new MSeparator);
}
void MGroupHeaderListViewPrivate::updateSeparators()
{
MListViewPrivate::updateSeparators();
if (gseparator)
gseparator->setObjectName(q_ptr->style()->groupSeparatorObjectName());
}
void MGroupHeaderListViewPrivate::updateSeparatorSize()
{
MListViewPrivate::updateSeparatorSize();
if (gseparator) {
gseparatorHeight = gseparator->preferredHeight();
gseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(viewWidth, gseparatorHeight)));
}
}
void MGroupHeaderListViewPrivate::updateHeaderHeight()
{
updateHeadersPositions();
updateHeadersRows();
updateHeadersIndexes();
}
int MGroupHeaderListViewPrivate::indexToFlatRow(const QModelIndex &index) const
{
if (!index.isValid())
return -1;
if (index.parent().isValid()) {
// always need to add 1 because of parent.
return headersRows[index.parent().row()] + index.row() + 1;
}
return headersRows[index.row()];
}
MWidget *MGroupHeaderListViewPrivate::createItem(int row)
{
if (!headersRows.contains(row)) {
return createCell(row);
} else {
int headerIndex = dFindLowerIndex(headersRows, row);
return createHeader(headerIndex);
}
}
MWidget *MGroupHeaderListViewPrivate::createHeader(int headerIndex)
{
MWidget *header = headersCreator->createCell(model->index(headerIndex, 0), *recycler);
header->setParent(NULL);
header->setParentItem(controller);
header->setVisible(true);
header->resize(viewWidth, header->preferredHeight());
return header;
}
int MGroupHeaderListViewPrivate::headerHeight()
{
if (!hdrHeight) {
MWidget *header = createHeader(0);
hdrHeight = header->boundingRect().height();
deleteItem(header);
}
return hdrHeight;
}
int MGroupHeaderListViewPrivate::headersCount() const
{
return rowCount;
}
int MGroupHeaderListViewPrivate::itemsCount(int headerIndex) const
{
QModelIndex index(model->index(headerIndex, 0));
return model->rowCount(index);
}
int MGroupHeaderListViewPrivate::itemsCount() const
{
if (!controllerModel->showGroups())
return rowCount;
int groupsCount = rowCount;
int totalItemsCount = 0;
for (int i = 0; i < groupsCount; i++) {
totalItemsCount += itemsCount(i);
}
return totalItemsCount;
}
int MGroupHeaderListViewPrivate::groupSize(int headerIndex) const
{
int itemsCount = this->itemsCount(headerIndex);
return ((itemsCount * itemHeight) + (itemsCount - 1) * hseparatorHeight);
}
int MGroupHeaderListViewPrivate::totalHeight()
{
int headersCount = this->headersCount();
int itemsCount = this->itemsCount();
int hseparatorsCount = this->hseparatorsCount();
int totalHeight = headersCount * headerHeight() + itemsCount * itemHeight + hseparatorsCount * hseparatorHeight + gseparatorHeight * headersCount;
return totalHeight;
}
QSizeF MGroupHeaderListViewPrivate::cellSize(int row) const
{
if(headersRows.contains(row)) {
return QSizeF(viewWidth, hdrHeight);
}
return MListViewPrivate::cellSize(row);
}
bool MGroupHeaderListViewPrivate::isGroupHeader(const QModelIndex &index)
{
return !index.parent().isValid();
}
void MGroupHeaderListViewPrivate::createVisibleItems(int firstVisibleRow, int lastVisibleRow)
{
MListViewPrivate::createVisibleItems(firstVisibleRow, lastVisibleRow);
}
void MGroupHeaderListViewPrivate::layoutChanged()
{
MListViewPrivate::layoutChanged();
updateHeaderHeight();
}
void MGroupHeaderListViewPrivate::drawSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(headersRows.contains(row) || headersRows.contains(row - 1)) {
if (headersRows.contains(row))
drawGroupSeparator(row, painter, option);
return;
}
drawHorizontalSeparator(row, painter, option);
}
void MGroupHeaderListViewPrivate::drawGroupSeparator(const int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(row == 0 || gseparatorHeight == 0)
return;
QPointF pos(-q_ptr->marginLeft(), locatePosOfItem(row) - gseparatorHeight - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
gseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
void MGroupHeaderListViewPrivate::updateListIndexVisibility()
{
if (listIndexWidget)
listIndexWidget->setDisplayMode((MList::DisplayMode)controllerModel->listIndexDisplayMode());
}
void MGroupHeaderListViewPrivate::updateListIndexOffset()
{
if (listIndexWidget)
listIndexWidget->setOffset(pannableViewport->pos());
}
void MGroupHeaderListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
MListViewPrivate::appendTargetsToDeleteAnimation(start, end, first, last);
}
void MGroupHeaderListViewPrivate::updateListIndexStyle()
{
if (listIndexWidget)
listIndexWidget->setStyleName(q_ptr->style()->listIndexStyleName());
}
////////////
// Group Header MultiColumn
////////////
MMultiColumnListViewPrivate::MMultiColumnListViewPrivate()
{
vseparatorWidth = 0;
vseparator = NULL;
}
MMultiColumnListViewPrivate::~MMultiColumnListViewPrivate()
{
if(vseparator)
delete vseparator;
}
void MMultiColumnListViewPrivate::setVerticalSeparator(MWidget *separator)
{
if(vseparator)
delete vseparator;
vseparator = separator;
if(vseparator)
vseparatorWidth = vseparator->preferredWidth();
else
vseparatorWidth = 0;
}
void MMultiColumnListViewPrivate::createSeparators()
{
MGroupHeaderListViewPrivate::createSeparators();
setVerticalSeparator(new MSeparator(NULL, Qt::Vertical));
}
void MMultiColumnListViewPrivate::updateSeparators()
{
MGroupHeaderListViewPrivate::updateSeparators();
if (vseparator)
vseparator->setObjectName(q_ptr->style()->verticalSeparatorObjectName());
}
void MMultiColumnListViewPrivate::updateRecyclerMaxItemsCount()
{
if (itemHeight > 0)
recycler->setMaxItemsPerClass((viewportVisibleHeight / itemHeight + 2) * controllerModel->columns());
}
int MMultiColumnListViewPrivate::itemsToRows(int items) const
{
int columns = controllerModel->columns();
int rows = items / columns;
if (items > rows * columns)
rows++;
return rows;
}
int MMultiColumnListViewPrivate::rowsInGroup(int headerIndex) const
{
int itemsInGroup = itemsCount(headerIndex);
int rowsInGroup = itemsToRows(itemsInGroup);
return rowsInGroup;
}
int MMultiColumnListViewPrivate::flatRowToColumn(int row) const
{
if (headersRows.contains(row))
return 0; // group headers are always in column 0
int headerIndex = dFindLowerIndex(headersRows, row);
if(headersRows.count() <= headerIndex)
return 0;
int relativeRow = row - headersRows[headerIndex] - 1;
int columns = controllerModel->columns();
int itemRow = relativeRow / columns;
int flatRowColumn = relativeRow - itemRow * columns;
return flatRowColumn;
}
void MMultiColumnListViewPrivate::updateItemSize()
{
foreach(MWidget * cell, visibleItems) {
int cellFlatRow = widgetFlatRows[cell] - 1;
int cellColumn = flatRowToColumn(cellFlatRow);
cell->resize(cellSize(cellFlatRow));
cell->setPos(QPointF(cellColumn * viewWidth / controllerModel->columns(), cell->pos().y()));
}
}
void MMultiColumnListViewPrivate::updateSeparatorSize()
{
MGroupHeaderListViewPrivate::updateSeparatorSize();
if (vseparator) {
vseparatorWidth = vseparator->preferredWidth();
vseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(vseparatorWidth, itemHeight)));
}
}
QSizeF MMultiColumnListViewPrivate::cellSize(int row) const
{
if(headersRows.contains(row)) {
return MGroupHeaderListViewPrivate::cellSize(row);
}
int columns = controllerModel->columns();
return QSizeF(viewWidth / columns - vseparatorWidth, itemHeight);
}
void MMultiColumnListViewPrivate::cellClicked(MWidget *source)
{
int clickedFlatRow = widgetFlatRows.value(source) - 1;
QModelIndex cellIndex(flatRowToIndex(clickedFlatRow));
controller->selectItem(cellIndex);
}
void MMultiColumnListViewPrivate::selectionChange(const QItemSelection &selected, const QItemSelection &deselected)
{
foreach(MWidget * widget, visibleItems) {
int widgetFlatRow = widgetFlatRows.value(widget) - 1;
QModelIndex widgetIndex(flatRowToIndex(widgetFlatRow));
if (selected.contains(widgetIndex))
widget->setSelected(true);
if (deselected.contains(widgetIndex))
widget->setSelected(false);
}
}
void MMultiColumnListViewPrivate::createVisibleItems()
{
QModelIndex firstVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y()));
QModelIndex lastVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y() + viewportVisibleHeight));
createVisibleItems(firstVisibleIndex, lastVisibleIndex);
}
void MMultiColumnListViewPrivate::clearVisibleItemsArray()
{
MListViewPrivate::clearVisibleItemsArray();
widgetFlatRows.clear();
}
void MMultiColumnListViewPrivate::removeInvisibleItems(const QPoint &firstVisibleItemCoord,
const QPoint &lastVisibleItemCoord)
{
for (ModelIndexWidgetHash::iterator iter = visibleItems.begin(); iter != visibleItems.end();) {
MWidget *cell = *iter;
qreal cellPosY = cell->pos().y();
if (cellPosY < firstVisibleItemCoord.y() || cellPosY > lastVisibleItemCoord.y()/* || widgetFlatRows[*iter] > itemsCount()*/) {
widgetFlatRows[*iter] = 0;
deleteItem(*iter);
iter = visibleItems.erase(iter);
} else {
++iter;
}
}
}
void MMultiColumnListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
int firstRow = indexToFlatRow(firstVisibleRow);
int lastRow = indexToFlatRow(lastVisibleRow);
if (!viewWidth || (!firstRow&&!lastRow&&itemsCount()>1)) { // required for x position
return;
}
for (int currentRow = firstRow; currentRow <= lastRow; currentRow++) {
MWidget *cell = findCellAtRow(currentRow);
if (!widgetFlatRows[cell] && flatRowToColumn(currentRow) == 0) {
// Create widgets to all columns in this row
for (int column = 0; column < controllerModel->columns(); ++column) {
QModelIndex index = flatRowToIndex(currentRow + column);
cell = visibleItems.value(index, NULL);
if (!cell) {
cell = createItem(currentRow + column);
visibleItems[index] = cell;
}
widgetFlatRows[cell] = currentRow + column + 1;
cell->setPos(QPointF(column*(viewWidth / controllerModel->columns()), locatePosOfItem(currentRow + column)));
if (currentRow + column + 1 == itemsCount() + rowCount || flatRowToColumn(currentRow + column + 1) == 0)
break;
}
}
}
}
int MMultiColumnListViewPrivate::locatePosOfItem(int headerIndex, int itemIndex)
{
if (itemIndex == -1)
return headersPositions[headerIndex];
int pos = headersPositions[headerIndex] + headerHeight();
if (itemIndex == 0)
return pos;
int rows = itemsToRows(itemIndex + 1) - 1; // rows after the 1st one
int itemHeights = rows * itemHeight;
int hseparatorHeights = rows * hseparatorHeight;
pos += hseparatorHeights + itemHeights;
return pos;
}
int MMultiColumnListViewPrivate::locatePosOfItem(int row)
{
int headerIndex = dFindLowerIndex(headersRows, row);
int relativeRow = row - headersRows[headerIndex] - 1;
return locatePosOfItem(headerIndex, relativeRow);
}
int MMultiColumnListViewPrivate::locatePosOfItem(const QModelIndex &index)
{
return MGroupHeaderListViewPrivate::locatePosOfItem(index);
}
int MMultiColumnListViewPrivate::hseparatorsCount() const
{
int hseparatorsCount = 0;
for (int i = 0; i < headersCount(); ++i) {
hseparatorsCount += rowsInGroup(i) - 1;
}
return hseparatorsCount;
}
QModelIndex MMultiColumnListViewPrivate::locateLastVisibleIndexInRowAt(int pos)
{
int lastVisibleFlatRow = locateVisibleRowAt(pos, viewWidth-1);
return flatRowToIndex(lastVisibleFlatRow);
}
int MMultiColumnListViewPrivate::locateVisibleRowAt(int y, int x)
{
Q_UNUSED(x);
if (itemHeight == 0)
return 0;
int headerIndex = dFindLowerIndex(headersPositions, y);
int headerRow = headersRows[headerIndex];
int relativePos = y - headersPositions[headerIndex];
int headerHeight = this->headerHeight();
if (relativePos < headerHeight)
return headerRow;
relativePos -= headerHeight;
int columns = controllerModel->columns();
// row/columns * itemHeight + row/columns * hseparatorHeight = pos -> r/c*i + r/c*s = p -> r = p*c/(s+i)
int row = relativePos / (hseparatorHeight + itemHeight) * columns;
int column = 0;
if (viewWidth)
column = qMin(x / (viewWidth / columns), columns - 1);
return headerRow + row + column + 1;
}
MWidget *MMultiColumnListViewPrivate::createItem(int row)
{
if (!headersRows.contains(row)) {
MWidget *cell = createCell(row);
return cell;
} else {
int headerIndex = dFindLowerIndex(headersRows, row);
return createHeader(headerIndex);
}
}
void MMultiColumnListViewPrivate::replaceItem(MWidget* item, MWidget* newItem)
{
MListViewPrivate::replaceItem(item, newItem);
widgetFlatRows[newItem] = widgetFlatRows[item];
widgetFlatRows[item] = 0;
}
int MMultiColumnListViewPrivate::groupSize(int headerIndex) const
{
int rows = rowsInGroup(headerIndex);
int groupSize = rows * itemHeight + (rows - 1) * hseparatorHeight;
return groupSize;
}
int MMultiColumnListViewPrivate::totalHeight()
{
int totalHeight = 0;
for (int i = 0; i < headersCount(); ++i) {
totalHeight += headerHeight() + groupSize(i) + gseparatorHeight;
}
return totalHeight;
}
void MMultiColumnListViewPrivate::drawSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(headersRows.contains(row)) {
drawGroupSeparator(row, painter, option);
return;
}
int columns = controllerModel->columns();
int column = flatRowToColumn(row);
if(row >= columns && column == 0) {
drawHorizontalSeparator(row, painter, option);
return;
}
if(column > 0) {
drawVerticalSeparator(row, column, painter, option);
}
}
void MMultiColumnListViewPrivate::drawVerticalSeparator(int row, int column, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(vseparatorWidth == 0)
return;
int itemWidth = viewWidth / controllerModel->columns();
QPointF pos(column*itemWidth - vseparatorWidth - q_ptr->marginLeft(), locatePosOfItem(row) - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
vseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
void MMultiColumnListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
QPointF offset(0,0);
QPointF destination = findCellAtRow(start)->pos();
bool shifting = false;
for (int flatRow = first; flatRow <= last; flatRow ++) {
MWidget *cell = findCellAtRow(flatRow);
if (cell) {
QModelIndex index = flatRowToIndex(flatRow);
if (flatRow < start)
itemDeletionAnimation->appendBeforeTarget(cell);
else if (flatRow > end) {
if (isGroupHeader(index) && !shifting) {
int itemsInGroup = itemsCount(index.row() - 1);
int oldGroupRows = itemsToRows(itemsInGroup + (end - start + 1));
int newGroupRows = itemsToRows(itemsInGroup);
offset = QPointF(0, (oldGroupRows - newGroupRows) * (itemHeight + hseparatorHeight));
shifting = true;
}
if (!shifting) {
itemDeletionAnimation->appendAfterTarget(cell, destination);
destination = cell->pos();
}
else
itemDeletionAnimation->appendAfterTarget(cell, cell->pos() - offset);
}
else {
itemDeletionAnimation->appendDeleteTarget(cell);
}
}
}
animatingItems = visibleItems.values().toVector();
visibleItems.clear();
}
Changes: Disconnect properly from controller parent change signal in private list view.
RevBy: Mika Wilen
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MWidgetRecycler>
#include <MSeparator>
#include <MList>
#include <MPannableViewport>
#include <MAbstractItemModel>
#include <QItemSelectionModel>
#include <QParallelAnimationGroup>
#include <QPropertyAnimation>
#include "mcontentitem.h"
#include "mlistindex.h"
#include "mabstractcellcreator.h"
#include "mlistview_p.h"
#include "mapplicationpageview_p.h"
#include "mlistview.h"
#include "animations/mbasiclistitemdeletionanimation.h"
using namespace MListViewPrivateNamespace;
static const int MOVINGDETECTORTIMEOUT = 500;
static const int SCROLLTOANIMATIONSNAPDISTANCE = 100;
MListViewPrivate::MListViewPrivate() : recycler(new MWidgetRecycler)
{
itemHeight = 0;
rowCount = 0;
viewWidth = 0;
model = NULL;
selectionModel = NULL;
moving = false;
hseparator = NULL;
headersCreator = NULL;
hdrHeight = 0;
forceRepaint = false;
viewportTopLeft = QPointF();
viewportVisibleHeight = 0;
hseparatorHeight = 0;
pannableViewport = NULL;
clearVisibleOnRelayout = false;
scrollToAnimation = new QPropertyAnimation(this);
isDeleted = false;
itemDeletionAnimation = NULL;
movingDetectorTimer.setSingleShot(true);
connect(&movingDetectorTimer, SIGNAL(timeout()), this, SLOT(movingDetectionTimerTimeout()));
}
MListViewPrivate::~MListViewPrivate()
{
deleteVisibleItemsArray();
if(controllerModel)
clearFirstAndLastVisibleRows();
movingDetectorTimer.stop();
delete hseparator;
delete recycler;
delete itemDeletionAnimation;
}
void MListViewPrivate::setSeparator(MWidget *separator)
{
if(hseparator)
delete hseparator;
hseparator = separator;
if(separator)
hseparatorHeight = separator->preferredHeight();
else
hseparatorHeight = 0;
}
void MListViewPrivate::createSeparators()
{
setSeparator(new MSeparator);
}
void MListViewPrivate::updateSeparators()
{
if (hseparator)
hseparator->setObjectName(q_ptr->style()->horizontalSeparatorObjectName());
}
void MListViewPrivate::updateHeaders()
{
MDefaultHeadersCreator *defaultCreator = dynamic_cast<MDefaultHeadersCreator*>(headersCreator);
if (defaultCreator)
defaultCreator->setHeaderStyleName(q_ptr->style()->groupHeaderObjectName());
}
void MListViewPrivate::updateHeaderHeight()
{
}
void MListViewPrivate::updateRecyclerMaxItemsCount()
{
if (itemHeight > 0)
recycler->setMaxItemsPerClass(viewportVisibleHeight / itemHeight + 2);
}
void MListViewPrivate::setHeadersCreator(MCellCreator *creator)
{
delete headersCreator;
hdrHeight = 0;
headersCreator = creator;
}
void MListViewPrivate::movingDetectionTimerTimeout()
{
if (isAnimating())
return;
moving = false;
controllerModel->setListIsMoving(false);
movingDetectorTimer.stop();
}
void MListViewPrivate::clearVisibleItemsArray()
{
foreach(MWidget * item, visibleItems) {
deleteItem(item);
}
visibleItems.clear();
}
void MListViewPrivate::deleteVisibleItemsArray()
{
qDeleteAll(visibleItems);
visibleItems.clear();
}
void MListViewPrivate::destroy()
{
isDeleted = true;
deleteLater();
}
void MListViewPrivate::clearFirstAndLastVisibleRows()
{
updateFirstVisibleRow(QModelIndex());
updateLastVisibleRow(QModelIndex());
}
void MListViewPrivate::cellClicked(MWidget *source)
{
MWidget *widget = source;
QModelIndex cellIndex(locateVisibleIndexAt(widget->pos().y()));
controller->selectItem(cellIndex);
}
void MListViewPrivate::cellLongTapped(const QModelIndex &index, const QPointF &position)
{
controller->longTapItem(index, position);
}
void MListViewPrivate::selectionChange(const QItemSelection &selected, const QItemSelection &deselected)
{
for (QHash<QModelIndex, MWidget *>::iterator iter = visibleItems.begin(); iter != visibleItems.end(); ++iter) {
if (selected.contains(iter.key()))
iter.value()->setSelected(true);
if (deselected.contains(iter.key()))
iter.value()->setSelected(false);
}
}
bool MListViewPrivate::isAnimating()
{
return (itemDeletionAnimation && itemDeletionAnimation->state() == QParallelAnimationGroup::Running);
}
void MListViewPrivate::removeRows(const QModelIndex &parent, int start, int end, bool animated)
{
if (!animated || isAnimating() || !itemDeletionAnimation)
return;
int first = indexToFlatRow(controllerModel->firstVisibleItem());
int last = indexToFlatRow(controllerModel->lastVisibleItem());
if (parent.isValid()) {
int parentFlatRow = indexToFlatRow(parent);
start += parentFlatRow + 1;
end += parentFlatRow + 1;
}
if (start > last || !controller->isVisible())
return;
start = first > start ? first : start;
end = end > last ? last : end;
// Set targets for deletion animation
appendTargetsToDeleteAnimation(start, end, first, last);
// Start item deletion animation
itemDeletionAnimation->start();
}
void MListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
QPointF offset(0,0);
for (int flatRow = first; flatRow <= last; flatRow ++) {
MWidget *cell = findCellAtRow(flatRow);
if (cell) {
if (flatRow < start)
itemDeletionAnimation->appendBeforeTarget(cell);
else if (flatRow > end) {
itemDeletionAnimation->appendAfterTarget(cell, cell->pos() - offset);
}
else {
itemDeletionAnimation->appendDeleteTarget(cell);
offset += QPointF(0, cellSize(flatRow).height() + hseparatorHeight);
}
}
}
animatingItems = visibleItems.values().toVector();
visibleItems.clear();
}
void MListViewPrivate::resetAnimatedWidgets()
{
while (!animatingItems.isEmpty()) {
delete animatingItems.front();
animatingItems.pop_front();
}
q_ptr->layoutChanged();
_q_relayoutItemsIfNeeded();
}
void MListViewPrivate::deleteItem(MWidget *widget)
{
recycler->recycle(widget);
}
MWidget *MListViewPrivate::createCell(int row)
{
QModelIndex index(flatRowToIndex(row));
MWidget *cell = controllerModel->cellCreator()->createCell(index, *recycler);
cell->setParent(NULL);
cell->setParentItem(controller);
cell->setVisible(true);
if(cell->maximumHeight() < itemHeight)
{
cell->setMaximumSize(cell->maximumWidth(), itemHeight);
} else if(cell->minimumHeight() > itemHeight)
{
cell->setMinimumSize(cell->minimumWidth(), itemHeight);
}
cell->resize(cellSize(row));
// TODO this is not optimal, I'm pretty sure, need to find better way to keep
// selection. Refactor into its own function.
QItemSelectionModel *selectionModel = controllerModel->selectionModel();
cell->setSelected(selectionModel->isSelected(index));
// TODO this code can be executed only when panning is stopped. Refactor into
// its own function
if (cell->metaObject()->indexOfSignal("clicked()") != -1) {
QObject::connect(cell, SIGNAL(clicked()), q_ptr, SLOT(itemClick()), Qt::UniqueConnection);
}
updateItemLongTapConnection(cell);
return cell;
}
void MListViewPrivate::viewportRectChanged(const QRectF &viewportRect)
{
if (isDeleted)
return;
if (viewportRect.topLeft() != oldViewportRectPosition) {
movingDetectorTimer.start(MOVINGDETECTORTIMEOUT);
if (!moving) {
moving = true;
controllerModel->setListIsMoving(true);
}
oldViewportRectPosition = viewportRect.topLeft();
}
}
void MListViewPrivate::viewportPositionChanged(const QPointF &position)
{
if (isDeleted)
return;
updateViewportRect(position - listPosition, QSizeF(viewWidth, pannableViewport->size().height()));
}
void MListViewPrivate::viewportSizeChanged(const QSizeF &size)
{
if (isDeleted)
return;
updateViewportRect(viewportTopLeft, QSizeF(viewWidth, size.height()));
updateScrollToTargetPosition();
updateRecyclerMaxItemsCount();
}
void MListViewPrivate::viewportRangeChanged(const QRectF &range)
{
Q_UNUSED(range);
if (isDeleted)
return;
updateScrollToTargetPosition();
}
void MListViewPrivate::connectPannableViewport()
{
disconnect(controller, SIGNAL(parentChanged()), this, SLOT(controllerParentChanged()));
if (pannableViewport)
pannableViewport->disconnect(this);
connect(controller, SIGNAL(parentChanged()), SLOT(controllerParentChanged()));
pannableViewport = MListViewPrivateNamespace::findParentWidgetOfType<MPannableViewport>(controller);
if(pannableViewport) {
updatePannableViewportPosition();
connect(pannableViewport, SIGNAL(positionChanged(QPointF)), SLOT(viewportPositionChanged(QPointF)));
connect(pannableViewport, SIGNAL(viewportSizeChanged(QSizeF)), SLOT(viewportSizeChanged(QSizeF)));
connect(pannableViewport, SIGNAL(rangeChanged(QRectF)), SLOT(viewportRangeChanged(QRectF)));
viewportTopLeft = pannableViewport->position() - listPosition;
viewportVisibleHeight = pannableViewport->size().height();
scrollToAnimation->setTargetObject(pannableViewport);
scrollToAnimation->setPropertyName("position");
}
}
void MListViewPrivate::controllerParentChanged()
{
disconnect(controller, SIGNAL(parentChanged()), this, SLOT(controllerParentChanged()));
connectPannableViewport();
}
void MListViewPrivate::updateListGeometry()
{
if(q_ptr)
q_ptr->updateGeometry();
}
void MListViewPrivate::updateViewportRect(const QPointF &position, const QSizeF &size)
{
if (isDeleted)
return;
if ((viewportTopLeft != position) || (viewportVisibleHeight < size.height()) || (forceRepaint)) {
forceRepaint = false;
viewportTopLeft = position;
viewportVisibleHeight = size.height();
viewportRectChanged(QRectF(position, size));
_q_relayoutItemsIfNeeded();
}
}
void MListViewPrivate::updatePannableViewportPosition()
{
if(!pannableViewport)
connectPannableViewport();
if(pannableViewport && controller) {
QPointF oldListPosition = listPosition;
listPosition = controller->mapToItem(pannableViewport->widget(), 0, 0);
viewportTopLeft += (oldListPosition - listPosition);
listOffset = calculatePannableViewportOffset(listPosition);
updateListIndexOffset();
}
else
listPosition = QPointF(0,0);
}
QPointF MListViewPrivate::calculatePannableViewportOffset(const QPointF &listPosition)
{
QPointF listOffset = listPosition;
if (pannableViewport->widget() && pannableViewport->widget() != controller) {
QList<QGraphicsItem *> pannableViewportWidgetChildren = pannableViewport->widget()->childItems();
foreach (QGraphicsItem *item, pannableViewportWidgetChildren) {
if (item->isWidget()) {
MWidget *widget = dynamic_cast<MWidget *>(item);
if (widget && widget->objectName() == MApplicationPageViewPrivate::TopSpacerName) {
listOffset.setY(listPosition.y() - widget->size().height());
break;
}
}
}
}
return listOffset;
}
void MListViewPrivate::updateAnimations()
{
delete itemDeletionAnimation;
itemDeletionAnimation = 0;
if (q_ptr->style()->deleteItemAnimation().isEmpty())
return;
itemDeletionAnimation = qobject_cast<MBasicListItemDeletionAnimation*>(MTheme::animation(q_ptr->style()->deleteItemAnimation()));
if (itemDeletionAnimation)
connect(itemDeletionAnimation, SIGNAL(finished()), this, SLOT(resetAnimatedWidgets()));
}
void MListViewPrivate::updateItemHeight()
{
if (controllerModel->cellCreator()) {
itemHeight = controllerModel->cellCreator()->cellSize().height();
updateRecyclerMaxItemsCount();
}
}
void MListViewPrivate::removeInvisibleItems(const QPoint &firstVisibleItemCoord,
const QPoint &lastVisibleItemCoord)
{
for (ModelIndexWidgetHash::iterator iter = visibleItems.begin(); iter != visibleItems.end();) {
MWidget *cell = *iter;
qreal cellPosY = cell->pos().y();
if (cellPosY < firstVisibleItemCoord.y() || cellPosY > lastVisibleItemCoord.y()) {
deleteItem(*iter);
iter = visibleItems.erase(iter);
} else {
++iter;
}
}
}
MWidget *MListViewPrivate::findCellAtRow(int row)
{
foreach (MWidget * widget, visibleItems) {
QPointF pos(widget->pos());
int widgetRow = locateVisibleRowAt(pos.y(), pos.x());
if (widgetRow == row)
return widget;
}
return NULL;
}
void MListViewPrivate::createVisibleItems(int firstVisibleRow, int lastVisibleRow)
{
for (int currentRow = firstVisibleRow; currentRow <= lastVisibleRow; currentRow++) {
QModelIndex index = flatRowToIndex(currentRow);
MWidget *cell = visibleItems.value(index, NULL);
if (!cell) {
cell = createItem(currentRow);
visibleItems[index] = cell;
}
cell->setPos(QPointF(0, locatePosOfItem(currentRow)));
}
}
void MListViewPrivate::disconnectSignalsFromModelToListView()
{
if (model)
model->disconnect(q_ptr);
}
void MListViewPrivate::connectSignalsFromModelToListView()
{
if (model) {
connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), q_ptr, SLOT(dataChanged(QModelIndex, QModelIndex)));
if (model->inherits("MAbstractItemModel") || model->inherits("MSortFilterProxyModel")) {
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int, bool)), q_ptr, SLOT(rowsInserted(QModelIndex, int, int, bool)));
connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int, bool)), q_ptr, SLOT(rowsRemoved(QModelIndex, int, int, bool)));
} else {
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), q_ptr, SLOT(rowsInserted(QModelIndex, int, int)));
connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)), q_ptr, SLOT(rowsRemoved(QModelIndex, int, int)));
}
connect(model, SIGNAL(layoutChanged()), q_ptr, SLOT(layoutChanged()));
connect(model, SIGNAL(modelReset()), q_ptr, SLOT(modelReset()));
connect(model, SIGNAL(rowsMoved(QModelIndex, int, int, QModelIndex, int)), q_ptr, SLOT(rowsMoved(QModelIndex, int, int, QModelIndex, int)));
connect(controller, SIGNAL(visibleChanged()), q_ptr, SLOT(_q_relayoutItemsIfNeeded()));
}
}
void MListViewPrivate::updateItemConnections()
{
foreach (MWidget *cell, visibleItems) {
updateItemLongTapConnection(cell);
}
}
void MListViewPrivate::updateItemLongTapConnection(MWidget *cell)
{
if (cell->metaObject()->indexOfSignal("longTapped(QPointF)") != -1) {
if (controllerModel->longTapEnabled())
QObject::connect(cell, SIGNAL(longTapped(QPointF)), q_ptr, SLOT(_q_itemLongTapped(QPointF)), Qt::UniqueConnection);
else
QObject::disconnect(cell, SIGNAL(longTapped(QPointF)), q_ptr, SLOT(_q_itemLongTapped(QPointF)));
}
}
void MListViewPrivate::resetModel(MListModel *mListModel)
{
forceRepaint = true;
rowCount = 0;
disconnectSignalsFromModelToListView();
controllerModel = mListModel;
model = mListModel->itemModel();
if(model)
rowCount = model->rowCount();
clearVisibleItemsArray();
updateItemHeight();
clearFirstAndLastVisibleRows();
connectSignalsFromModelToListView();
}
void MListViewPrivate::updateItemSize()
{
foreach(MWidget * cell, visibleItems) {
cell->resize(cellSize(0));
}
}
QSizeF MListViewPrivate::cellSize(int row) const
{
Q_UNUSED(row);
return QSizeF(viewWidth, itemHeight);
}
void MListViewPrivate::updateSeparatorSize()
{
if (hseparator) {
hseparatorHeight = hseparator->preferredHeight();
hseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(viewWidth, hseparatorHeight)));
}
}
void MListViewPrivate::updateFirstVisibleRow(const QModelIndex &index)
{
if (isDeleted)
return;
q_ptr->model()->setFirstVisibleItem(index);
}
void MListViewPrivate::updateLastVisibleRow(const QModelIndex &index)
{
if (isDeleted)
return;
q_ptr->model()->setLastVisibleItem(index);
}
void MListViewPrivate::createVisibleItems()
{
QModelIndex firstVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y()));
int firstVisibleRow = indexToFlatRow(firstVisibleIndex);
QModelIndex lastVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y() + viewportVisibleHeight));
int lastVisibleRow = indexToFlatRow(lastVisibleIndex);
createVisibleItems(firstVisibleRow, lastVisibleRow);
}
QModelIndex MListViewPrivate::locateLastVisibleIndexInRowAt(int pos)
{
return locateVisibleIndexAt(pos);
}
void MListViewPrivate::replaceItem(MWidget* item, MWidget* newItem)
{
newItem->setPos(item->pos());
visibleItems[visibleItems.key(item)] = newItem;
deleteItem(item);
}
bool MListViewPrivate::isGroupHeader(const QModelIndex &index)
{
Q_UNUSED(index);
return false;
}
void MListViewPrivate::layoutChanged()
{
if(model)
rowCount = model->rowCount();
else
rowCount = 0;
}
void MListViewPrivate::drawSeparators(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if (!controllerModel->firstVisibleItem().isValid() || !controllerModel->lastVisibleItem().isValid() || isAnimating())
return;
int firstRow = indexToFlatRow(controllerModel->firstVisibleItem());
int lastRow = indexToFlatRow(controllerModel->lastVisibleItem());
for (int currentRow = firstRow; currentRow <= lastRow; currentRow++) {
drawSeparator(currentRow, painter, option);
}
}
void MListViewPrivate::drawSeparator(const int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
drawHorizontalSeparator(row, painter, option);
}
void MListViewPrivate::drawHorizontalSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(row == 0 || hseparatorHeight == 0)
return;
QPointF pos(-q_ptr->marginLeft(), locatePosOfItem(row) - hseparatorHeight - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
hseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
QPointF MListViewPrivate::locateScrollToPosition(const QModelIndex &index, MList::ScrollHint hint)
{
if (!pannableViewport)
return QPointF(0,0);
int cellPosition = locatePosOfItem(index);
QPointF targetPosition = pannableViewport->position();
qreal pannableViewportHeight = pannableViewport->boundingRect().height() - listOffset.y();
switch (hint) {
case MList::PositionAtTopHint:
targetPosition.setY(listOffset.y() + cellPosition);
break;
case MList::PositionAtBottomHint:
targetPosition.setY(cellPosition + itemHeight + listOffset.y() - pannableViewportHeight);
break;
case MList::PositionAtCenterHint:
targetPosition.setY(listOffset.y() + cellPosition + itemHeight / 2 - pannableViewportHeight / 2);
break;
case MList::EnsureVisibleHint:
if (cellPosition <= pannableViewport->position().y()) {
targetPosition.setY(listOffset.y() + cellPosition);
} else if (cellPosition + itemHeight > pannableViewport->position().y() + pannableViewportHeight) {
targetPosition.setY(cellPosition + itemHeight + listOffset.y() - pannableViewportHeight);
}
break;
}
int pannableWidgetBoundingHeight = pannableViewport->widget()->boundingRect().height();
targetPosition.setY(qMax(targetPosition.y(), (qreal)0));
if (pannableWidgetBoundingHeight > pannableViewportHeight)
targetPosition.setY(qMin(targetPosition.y(), pannableWidgetBoundingHeight - pannableViewportHeight));
else
targetPosition = pannableViewport->position();
return targetPosition;
}
void MListViewPrivate::_q_itemLongTapped(const QPointF &pos)
{
q_ptr->longTap(pos);
}
void MListViewPrivate::_q_relayoutItemsIfNeeded()
{
if (isDeleted)
return;
if (controller->isVisible())
q_ptr->relayoutItemsInViewportRect();
}
void MListViewPrivate::updateScrollToTargetPosition()
{
if (scrollToAnimation->state() == QPropertyAnimation::Running) {
QPointF targetPosition = locateScrollToPosition(controllerModel->scrollToIndex(), static_cast<MList::ScrollHint>(controllerModel->scrollHint()));
if (targetPosition != scrollToAnimation->endValue().toPointF()) {
if (targetPosition.y() > pannableViewport->position().y())
scrollToAnimation->setStartValue(targetPosition + QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
else
scrollToAnimation->setStartValue(targetPosition - QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
scrollToAnimation->setEndValue(targetPosition);
}
}
}
void MListViewPrivate::scrollToPos(const QPointF &targetPosition, MList::AnimationMode mode)
{
if (mode == MList::Animated) {
if (targetPosition.y() > pannableViewport->position().y())
scrollToAnimation->setStartValue(targetPosition + QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
else
scrollToAnimation->setStartValue(targetPosition - QPointF(0, SCROLLTOANIMATIONSNAPDISTANCE));
scrollToAnimation->setEndValue(targetPosition);
scrollToAnimation->setEasingCurve(QEasingCurve::OutCubic);
scrollToAnimation->setDuration(100);
scrollToAnimation->start();
}
else
pannableViewport->setPosition(targetPosition);
}
void MListViewPrivate::updateListIndexVisibility()
{
}
void MListViewPrivate::updateListIndexOffset()
{
}
void MListViewPrivate::updateListIndexStyle()
{
}
////////////
// Plain list
////////////
MPlainListViewPrivate::MPlainListViewPrivate()
{
}
MPlainListViewPrivate::~MPlainListViewPrivate()
{
}
int MPlainListViewPrivate::hseparatorsCount() const
{
return itemsCount() - 1;
}
int MPlainListViewPrivate::totalHeight()
{
int itemsCount = this->itemsCount();
int separatorsCount = this->hseparatorsCount();
int totalHeight = itemsCount * itemHeight + separatorsCount * hseparatorHeight;
return totalHeight;
}
int MPlainListViewPrivate::itemsCount() const
{
if (model == 0)
return 0;
return rowCount;
}
MWidget *MPlainListViewPrivate::createItem(int row)
{
return createCell(row);
}
int MPlainListViewPrivate::indexToFlatRow(const QModelIndex &index) const
{
return index.row();
}
QModelIndex MPlainListViewPrivate::flatRowToIndex(int row) const
{
return model->index(row, 0);
}
int MPlainListViewPrivate::locateVisibleRowAt(int y, int x)
{
Q_UNUSED(x);
if (itemHeight == 0)
return 0;
// Formula for calculating position of specific row is following:
// row * itemHeight + row * hseparatorHeight = pos
// to calculate row lets do basic math:
// row = pos / (hseparatorHeight + itemHeight)
int row = y / (hseparatorHeight + itemHeight);
int modelRowCount = rowCount;
if (row >= modelRowCount)
row = modelRowCount - 1;
return row;
}
// TODO write unit test for this
int MPlainListViewPrivate::locatePosOfItem(int row)
{
int itemHeights = row * itemHeight;
int hseparatorHeights = 0;
if (row > 0)
hseparatorHeights = row * hseparatorHeight;
return itemHeights + hseparatorHeights;
}
int MPlainListViewPrivate::locatePosOfItem(const QModelIndex &index)
{
return locatePosOfItem(index.row());
}
QModelIndex MPlainListViewPrivate::locateVisibleIndexAt(int pos)
{
int row = locateVisibleRowAt(pos);
if (row < 0)
return model->index(0, 0);
return model->index(row, 0);
}
void MPlainListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
MListViewPrivate::createVisibleItems(firstVisibleRow.row(), lastVisibleRow.row());
}
////////////
// Plain list MultiColumn
////////////
MPlainMultiColumnListViewPrivate::MPlainMultiColumnListViewPrivate()
{
vseparatorWidth = 0;
vseparator = NULL;
}
MPlainMultiColumnListViewPrivate::~MPlainMultiColumnListViewPrivate()
{
if(vseparator)
delete vseparator;
}
void MPlainMultiColumnListViewPrivate::createSeparators()
{
MListViewPrivate::createSeparators();
//create vertical separators
setVerticalSeparator(new MSeparator(NULL, Qt::Vertical));
}
void MPlainMultiColumnListViewPrivate::updateSeparators()
{
MListViewPrivate::updateSeparators();
if (vseparator)
vseparator->setObjectName(q_ptr->style()->verticalSeparatorObjectName());
}
void MPlainMultiColumnListViewPrivate::updateRecyclerMaxItemsCount()
{
if (itemHeight > 0)
recycler->setMaxItemsPerClass((viewportVisibleHeight / itemHeight + 2) * controllerModel->columns());
}
void MPlainMultiColumnListViewPrivate::setVerticalSeparator(MWidget *separator)
{
if(vseparator)
delete vseparator;
vseparator = separator;
if(vseparator)
vseparatorWidth = vseparator->preferredWidth();
else
vseparatorWidth = 0;
}
int MPlainMultiColumnListViewPrivate::itemsToRows(int items) const
{
int columns = controllerModel->columns();
int rows = items / columns;
if (items > rows * columns)
rows++;
return rows;
}
int MPlainMultiColumnListViewPrivate::flatRowToColumn(int row) const
{
int columns = controllerModel->columns();
int itemRow = row / columns;
int flatRowColumn = row - itemRow * columns;
return flatRowColumn;
}
int MPlainMultiColumnListViewPrivate::locatePosOfItem(int row)
{
int columns = controllerModel->columns();
int rows = row / columns;
int itemHeights = rows * itemHeight;
int hseparatorHeights = 0;
if (rows > 0)
hseparatorHeights = rows * hseparatorHeight;
return itemHeights + hseparatorHeights;
}
int MPlainMultiColumnListViewPrivate::hseparatorsCount() const
{
return itemsToRows(itemsCount()) - 1;
}
int MPlainMultiColumnListViewPrivate::totalHeight()
{
int rowsCount = itemsToRows(itemsCount());
int hseparatorsCount = this->hseparatorsCount();
int totalHeight = rowsCount * itemHeight + hseparatorsCount * hseparatorHeight;
return totalHeight;
}
MWidget *MPlainMultiColumnListViewPrivate::createItem(int row)
{
MWidget *cell = createCell(row);
return cell;
}
QModelIndex MPlainMultiColumnListViewPrivate::locateLastVisibleIndexInRowAt(int pos)
{
int lastVisibleFlatRow = locateVisibleRowAt(pos, viewWidth-1);
return flatRowToIndex(lastVisibleFlatRow);
}
void MPlainMultiColumnListViewPrivate::replaceItem(MWidget* item, MWidget* newItem)
{
MListViewPrivate::replaceItem(item, newItem);
widgetFlatRows[newItem] = widgetFlatRows[item];
widgetFlatRows[item] = 0;
}
int MPlainMultiColumnListViewPrivate::locateVisibleRowAt(int y, int x)
{
if (itemHeight == 0)
return 0;
int columns = controllerModel->columns();
int row = y / (hseparatorHeight + itemHeight) * columns;
if (row >= itemsCount())
row = itemsCount() - 1;
int column = 0;
if (viewWidth)
column = qMin(x / (viewWidth / columns), columns - 1);
int flatRow = row + column;
if (flatRow >= itemsCount())
flatRow = itemsCount() - 1;
return flatRow;
}
void MPlainMultiColumnListViewPrivate::updateItemSize()
{
foreach(MWidget * cell, visibleItems) {
int cellRow = widgetFlatRows[cell] - 1;
int cellColumn = flatRowToColumn(cellRow);
cell->resize(cellSize(cellRow));
cell->setPos(QPointF(cellColumn * viewWidth / controllerModel->columns(), cell->pos().y()));
}
}
void MPlainMultiColumnListViewPrivate::updateSeparatorSize()
{
MListViewPrivate::updateSeparatorSize();
if (vseparator) {
vseparatorWidth = vseparator->preferredWidth();
vseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(vseparatorWidth, itemHeight)));
}
}
QSizeF MPlainMultiColumnListViewPrivate::cellSize(int row) const
{
Q_UNUSED(row);
int columns = controllerModel->columns();
return QSizeF(viewWidth / columns - vseparatorWidth, itemHeight);
}
void MPlainMultiColumnListViewPrivate::cellClicked(MWidget *source)
{
int clickedFlatRow = widgetFlatRows.value(source) - 1;
QModelIndex cellIndex(flatRowToIndex(clickedFlatRow));
controller->selectItem(cellIndex);
}
void MPlainMultiColumnListViewPrivate::selectionChange(const QItemSelection &selected, const QItemSelection &deselected)
{
foreach(MWidget * widget, visibleItems) {
int widgetFlatRow = widgetFlatRows.value(widget) - 1;
QModelIndex widgetIndex(flatRowToIndex(widgetFlatRow));
if (selected.contains(widgetIndex))
widget->setSelected(true);
if (deselected.contains(widgetIndex))
widget->setSelected(false);
}
}
void MPlainMultiColumnListViewPrivate::createVisibleItems()
{
QModelIndex firstVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y()));
QModelIndex lastVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y() + viewportVisibleHeight));
createVisibleItems(firstVisibleIndex, lastVisibleIndex);
}
void MPlainMultiColumnListViewPrivate::clearVisibleItemsArray()
{
MListViewPrivate::clearVisibleItemsArray();
widgetFlatRows.clear();
}
void MPlainMultiColumnListViewPrivate::removeInvisibleItems(const QPoint &firstVisibleItemCoord,
const QPoint &lastVisibleItemCoord)
{
for (ModelIndexWidgetHash::iterator iter = visibleItems.begin(); iter != visibleItems.end();) {
MWidget *cell = *iter;
qreal cellPosY = cell->pos().y();
if (cellPosY < firstVisibleItemCoord.y() || cellPosY > lastVisibleItemCoord.y() || widgetFlatRows[*iter] > itemsCount()) {
widgetFlatRows[*iter] = 0;
deleteItem(*iter);
iter = visibleItems.erase(iter);
} else {
++iter;
}
}
}
void MPlainMultiColumnListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
int firstRow = firstVisibleRow.row();
int lastRow = lastVisibleRow.row();
if (!viewWidth || (!firstRow&&!lastRow&&itemsCount()>1)) // required for x position
return;
for (int currentRow = firstRow; currentRow <= lastRow; currentRow++) {
MWidget *cell = findCellAtRow(currentRow);
if (!widgetFlatRows[cell] && flatRowToColumn(currentRow) == 0) {
// Create widgets to all columns in this row
for (int column = 0; column < controllerModel->columns(); ++column) {
QModelIndex index = flatRowToIndex(currentRow + column);
cell = visibleItems.value(index, NULL);
if (!cell) {
cell = createItem(currentRow + column);
visibleItems[index] = cell;
}
widgetFlatRows[cell] = currentRow + column + 1;
cell->setPos(QPointF(column*(viewWidth / controllerModel->columns()), locatePosOfItem(currentRow + column)));
if (currentRow + column + 1 == itemsCount() || flatRowToColumn(currentRow + column + 1) == 0)
break;
}
}
}
}
void MPlainMultiColumnListViewPrivate::drawSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int columns = controllerModel->columns();
int column = flatRowToColumn(row);
if(row >= columns && column == 0) {
drawHorizontalSeparator(row, painter, option);
return;
}
if(column > 0)
drawVerticalSeparator(row, column, painter, option);
}
void MPlainMultiColumnListViewPrivate::drawVerticalSeparator(int row, int column, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(vseparatorWidth == 0)
return;
int itemWidth = viewWidth / controllerModel->columns();
QPointF pos(column*itemWidth - q_ptr->marginLeft() - vseparatorWidth, locatePosOfItem(row) - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
vseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
void MPlainMultiColumnListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
QPointF destination = findCellAtRow(start)->pos();
for (int flatRow = first; flatRow <= last; flatRow ++) {
MWidget *cell = findCellAtRow(flatRow);
if (cell) {
if (flatRow < start)
itemDeletionAnimation->appendBeforeTarget(cell);
else if (flatRow > end) {
itemDeletionAnimation->appendAfterTarget(cell, destination);
destination = cell->pos();
}
else
itemDeletionAnimation->appendDeleteTarget(cell);
}
}
animatingItems = visibleItems.values().toVector();
visibleItems.clear();
}
////////////
// Group Header
////////////
MGroupHeaderListViewPrivate::MGroupHeaderListViewPrivate()
{
listIndexWidget = NULL;
gseparator = NULL;
gseparatorHeight = 0;
}
MGroupHeaderListViewPrivate::~MGroupHeaderListViewPrivate()
{
delete listIndexWidget;
if (gseparator)
delete gseparator;
}
void MGroupHeaderListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
MListViewPrivate::createVisibleItems(indexToFlatRow(firstVisibleRow), indexToFlatRow(lastVisibleRow));
}
QModelIndex MGroupHeaderListViewPrivate::locateVisibleIndexAt(int pos)
{
int row = locateVisibleRowAt(pos);
if (row < 0)
return model->index(0, 0);
return flatRowToIndex(row);
}
int MGroupHeaderListViewPrivate::hseparatorsCount() const
{
int itemsCount = this->headersCount();
int hseparators = 0;
for (int i = 0; i < itemsCount; i++) {
int itemsCountInGroup = this->itemsCount(i);
if (itemsCountInGroup == 0)
continue;
hseparators += itemsCountInGroup - 1;
}
return hseparators;
}
void MGroupHeaderListViewPrivate::resetModel(MListModel *mListModel)
{
MListViewPrivate::resetModel(mListModel);
if (!listIndexWidget) {
listIndexWidget = new MListIndex(controller);
updateListIndexVisibility();
updateListIndexStyle();
}
if (!controllerModel->headerCreator()) {
if (!headersCreator)
headersCreator = new MDefaultHeadersCreator(q_ptr->style()->groupHeaderObjectName());
else
updateHeaders();
}
headersPositions.resize(this->headersCount());
updateHeaderHeight();
}
int MGroupHeaderListViewPrivate::locatePosOfItem(const QModelIndex &index)
{
if (index.parent().isValid()) {
return locatePosOfItem(index.parent().row(), index.row());
} else {
return locatePosOfItem(index.row(), -1);
}
}
int MGroupHeaderListViewPrivate::locatePosOfItem(int headerIndex, int itemIndex)
{
if (itemIndex == -1) {
// we hitted header
return headersPositions[headerIndex];
}
int pos = headersPositions[headerIndex] + headerHeight();
if (itemIndex == 0)
return pos;
int itemHeights = itemIndex * itemHeight;
int hseparatorHeights = 0;
hseparatorHeights = itemIndex * hseparatorHeight;
pos += hseparatorHeights + itemHeights;
return pos;
}
int MGroupHeaderListViewPrivate::locatePosOfItem(int row)
{
int headerIndex = dFindLowerIndex(headersRows, row);
int relativeRow = row - headersRows[headerIndex] - 1; // we have to subtruct header
return locatePosOfItem(headerIndex, relativeRow);
}
int MGroupHeaderListViewPrivate::locateVisibleRowAt(int y, int x)
{
Q_UNUSED(x);
if (itemHeight == 0)
return 0;
if (headersPositions.size() == 0)
return 0;
int headerIndex = dFindLowerIndex(headersPositions, y);
int headerPosition = headersPositions[headerIndex];
int headerRow = headersRows[headerIndex];
int relativePos = y - headerPosition;
int headerHeight = this->headerHeight();
if (relativePos < headerHeight)
return headerRow;
int row = (relativePos - headerHeight) / (itemHeight + hseparatorHeight) + headerRow + 1;
return row;
}
QModelIndex MGroupHeaderListViewPrivate::flatRowToIndex(int row) const
{
if (!headersRows.contains(row)) {
int headerIndex = dFindLowerIndex(headersRows, row);
QModelIndex parent(model->index(headerIndex, 0));
int relativeRow = row - headersRows[headerIndex] - 1;
int itemsCount = this->itemsCount(headerIndex);
// Check if header doesn't have any children
if(itemsCount == 0)
return parent;
if (relativeRow >= itemsCount)
relativeRow = itemsCount - 1;
QModelIndex index(model->index(relativeRow, 0, parent));
return index;
}
int headerIndex = headersRows.indexOf(row);
return model->index(headerIndex, 0);
}
void MGroupHeaderListViewPrivate::updateHeadersPositions()
{
int headersCount = this->headersCount();
headersPositions.clear();
if (headersCount == 0)
return;
int headerHeight = this->headerHeight();
headersPositions << 0;
int previousIndexPosition = 0;
for (int i = 1; i < headersCount; i++) {
int groupSize = this->groupSize(i - 1);
headersPositions << previousIndexPosition + headerHeight + groupSize + gseparatorHeight;
previousIndexPosition += headerHeight + groupSize + gseparatorHeight;
}
}
void MGroupHeaderListViewPrivate::updateHeadersRows()
{
int headersCount = this->headersCount();
headersRows.clear();
if (headersCount == 0)
return;
headersRows << 0;
int prevGroupSize = 0;
for (int i = 1; i < headersCount; i++) {
prevGroupSize += itemsCount(i - 1);
headersRows << (i + prevGroupSize);
}
}
void MGroupHeaderListViewPrivate::updateHeadersIndexes()
{
if(listIndexWidget) {
QMap<QModelIndex, QString> shortcuts;
for (int i = 0; i < headersCount(); i++) {
QModelIndex headerRowIndex = flatRowToIndex(headersRows[i]);
shortcuts[headerRowIndex] = model->data(headerRowIndex).toString();
}
listIndexWidget->setShortcuts(shortcuts);
}
}
void MGroupHeaderListViewPrivate::setGroupSeparator(MWidget *separator)
{
if(gseparator)
delete gseparator;
gseparator = separator;
if(gseparator)
gseparatorHeight = gseparator->preferredHeight();
else
gseparatorHeight = 0;
}
void MGroupHeaderListViewPrivate::createSeparators()
{
MListViewPrivate::createSeparators();
setGroupSeparator(new MSeparator);
}
void MGroupHeaderListViewPrivate::updateSeparators()
{
MListViewPrivate::updateSeparators();
if (gseparator)
gseparator->setObjectName(q_ptr->style()->groupSeparatorObjectName());
}
void MGroupHeaderListViewPrivate::updateSeparatorSize()
{
MListViewPrivate::updateSeparatorSize();
if (gseparator) {
gseparatorHeight = gseparator->preferredHeight();
gseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(viewWidth, gseparatorHeight)));
}
}
void MGroupHeaderListViewPrivate::updateHeaderHeight()
{
updateHeadersPositions();
updateHeadersRows();
updateHeadersIndexes();
}
int MGroupHeaderListViewPrivate::indexToFlatRow(const QModelIndex &index) const
{
if (!index.isValid())
return -1;
if (index.parent().isValid()) {
// always need to add 1 because of parent.
return headersRows[index.parent().row()] + index.row() + 1;
}
return headersRows[index.row()];
}
MWidget *MGroupHeaderListViewPrivate::createItem(int row)
{
if (!headersRows.contains(row)) {
return createCell(row);
} else {
int headerIndex = dFindLowerIndex(headersRows, row);
return createHeader(headerIndex);
}
}
MWidget *MGroupHeaderListViewPrivate::createHeader(int headerIndex)
{
MWidget *header = headersCreator->createCell(model->index(headerIndex, 0), *recycler);
header->setParent(NULL);
header->setParentItem(controller);
header->setVisible(true);
header->resize(viewWidth, header->preferredHeight());
return header;
}
int MGroupHeaderListViewPrivate::headerHeight()
{
if (!hdrHeight) {
MWidget *header = createHeader(0);
hdrHeight = header->boundingRect().height();
deleteItem(header);
}
return hdrHeight;
}
int MGroupHeaderListViewPrivate::headersCount() const
{
return rowCount;
}
int MGroupHeaderListViewPrivate::itemsCount(int headerIndex) const
{
QModelIndex index(model->index(headerIndex, 0));
return model->rowCount(index);
}
int MGroupHeaderListViewPrivate::itemsCount() const
{
if (!controllerModel->showGroups())
return rowCount;
int groupsCount = rowCount;
int totalItemsCount = 0;
for (int i = 0; i < groupsCount; i++) {
totalItemsCount += itemsCount(i);
}
return totalItemsCount;
}
int MGroupHeaderListViewPrivate::groupSize(int headerIndex) const
{
int itemsCount = this->itemsCount(headerIndex);
return ((itemsCount * itemHeight) + (itemsCount - 1) * hseparatorHeight);
}
int MGroupHeaderListViewPrivate::totalHeight()
{
int headersCount = this->headersCount();
int itemsCount = this->itemsCount();
int hseparatorsCount = this->hseparatorsCount();
int totalHeight = headersCount * headerHeight() + itemsCount * itemHeight + hseparatorsCount * hseparatorHeight + gseparatorHeight * headersCount;
return totalHeight;
}
QSizeF MGroupHeaderListViewPrivate::cellSize(int row) const
{
if(headersRows.contains(row)) {
return QSizeF(viewWidth, hdrHeight);
}
return MListViewPrivate::cellSize(row);
}
bool MGroupHeaderListViewPrivate::isGroupHeader(const QModelIndex &index)
{
return !index.parent().isValid();
}
void MGroupHeaderListViewPrivate::createVisibleItems(int firstVisibleRow, int lastVisibleRow)
{
MListViewPrivate::createVisibleItems(firstVisibleRow, lastVisibleRow);
}
void MGroupHeaderListViewPrivate::layoutChanged()
{
MListViewPrivate::layoutChanged();
updateHeaderHeight();
}
void MGroupHeaderListViewPrivate::drawSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(headersRows.contains(row) || headersRows.contains(row - 1)) {
if (headersRows.contains(row))
drawGroupSeparator(row, painter, option);
return;
}
drawHorizontalSeparator(row, painter, option);
}
void MGroupHeaderListViewPrivate::drawGroupSeparator(const int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(row == 0 || gseparatorHeight == 0)
return;
QPointF pos(-q_ptr->marginLeft(), locatePosOfItem(row) - gseparatorHeight - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
gseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
void MGroupHeaderListViewPrivate::updateListIndexVisibility()
{
if (listIndexWidget)
listIndexWidget->setDisplayMode((MList::DisplayMode)controllerModel->listIndexDisplayMode());
}
void MGroupHeaderListViewPrivate::updateListIndexOffset()
{
if (listIndexWidget)
listIndexWidget->setOffset(pannableViewport->pos());
}
void MGroupHeaderListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
MListViewPrivate::appendTargetsToDeleteAnimation(start, end, first, last);
}
void MGroupHeaderListViewPrivate::updateListIndexStyle()
{
if (listIndexWidget)
listIndexWidget->setStyleName(q_ptr->style()->listIndexStyleName());
}
////////////
// Group Header MultiColumn
////////////
MMultiColumnListViewPrivate::MMultiColumnListViewPrivate()
{
vseparatorWidth = 0;
vseparator = NULL;
}
MMultiColumnListViewPrivate::~MMultiColumnListViewPrivate()
{
if(vseparator)
delete vseparator;
}
void MMultiColumnListViewPrivate::setVerticalSeparator(MWidget *separator)
{
if(vseparator)
delete vseparator;
vseparator = separator;
if(vseparator)
vseparatorWidth = vseparator->preferredWidth();
else
vseparatorWidth = 0;
}
void MMultiColumnListViewPrivate::createSeparators()
{
MGroupHeaderListViewPrivate::createSeparators();
setVerticalSeparator(new MSeparator(NULL, Qt::Vertical));
}
void MMultiColumnListViewPrivate::updateSeparators()
{
MGroupHeaderListViewPrivate::updateSeparators();
if (vseparator)
vseparator->setObjectName(q_ptr->style()->verticalSeparatorObjectName());
}
void MMultiColumnListViewPrivate::updateRecyclerMaxItemsCount()
{
if (itemHeight > 0)
recycler->setMaxItemsPerClass((viewportVisibleHeight / itemHeight + 2) * controllerModel->columns());
}
int MMultiColumnListViewPrivate::itemsToRows(int items) const
{
int columns = controllerModel->columns();
int rows = items / columns;
if (items > rows * columns)
rows++;
return rows;
}
int MMultiColumnListViewPrivate::rowsInGroup(int headerIndex) const
{
int itemsInGroup = itemsCount(headerIndex);
int rowsInGroup = itemsToRows(itemsInGroup);
return rowsInGroup;
}
int MMultiColumnListViewPrivate::flatRowToColumn(int row) const
{
if (headersRows.contains(row))
return 0; // group headers are always in column 0
int headerIndex = dFindLowerIndex(headersRows, row);
if(headersRows.count() <= headerIndex)
return 0;
int relativeRow = row - headersRows[headerIndex] - 1;
int columns = controllerModel->columns();
int itemRow = relativeRow / columns;
int flatRowColumn = relativeRow - itemRow * columns;
return flatRowColumn;
}
void MMultiColumnListViewPrivate::updateItemSize()
{
foreach(MWidget * cell, visibleItems) {
int cellFlatRow = widgetFlatRows[cell] - 1;
int cellColumn = flatRowToColumn(cellFlatRow);
cell->resize(cellSize(cellFlatRow));
cell->setPos(QPointF(cellColumn * viewWidth / controllerModel->columns(), cell->pos().y()));
}
}
void MMultiColumnListViewPrivate::updateSeparatorSize()
{
MGroupHeaderListViewPrivate::updateSeparatorSize();
if (vseparator) {
vseparatorWidth = vseparator->preferredWidth();
vseparator->setGeometry(QRectF(QPointF(0, 0), QSizeF(vseparatorWidth, itemHeight)));
}
}
QSizeF MMultiColumnListViewPrivate::cellSize(int row) const
{
if(headersRows.contains(row)) {
return MGroupHeaderListViewPrivate::cellSize(row);
}
int columns = controllerModel->columns();
return QSizeF(viewWidth / columns - vseparatorWidth, itemHeight);
}
void MMultiColumnListViewPrivate::cellClicked(MWidget *source)
{
int clickedFlatRow = widgetFlatRows.value(source) - 1;
QModelIndex cellIndex(flatRowToIndex(clickedFlatRow));
controller->selectItem(cellIndex);
}
void MMultiColumnListViewPrivate::selectionChange(const QItemSelection &selected, const QItemSelection &deselected)
{
foreach(MWidget * widget, visibleItems) {
int widgetFlatRow = widgetFlatRows.value(widget) - 1;
QModelIndex widgetIndex(flatRowToIndex(widgetFlatRow));
if (selected.contains(widgetIndex))
widget->setSelected(true);
if (deselected.contains(widgetIndex))
widget->setSelected(false);
}
}
void MMultiColumnListViewPrivate::createVisibleItems()
{
QModelIndex firstVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y()));
QModelIndex lastVisibleIndex(locateVisibleIndexAt(viewportTopLeft.y() + viewportVisibleHeight));
createVisibleItems(firstVisibleIndex, lastVisibleIndex);
}
void MMultiColumnListViewPrivate::clearVisibleItemsArray()
{
MListViewPrivate::clearVisibleItemsArray();
widgetFlatRows.clear();
}
void MMultiColumnListViewPrivate::removeInvisibleItems(const QPoint &firstVisibleItemCoord,
const QPoint &lastVisibleItemCoord)
{
for (ModelIndexWidgetHash::iterator iter = visibleItems.begin(); iter != visibleItems.end();) {
MWidget *cell = *iter;
qreal cellPosY = cell->pos().y();
if (cellPosY < firstVisibleItemCoord.y() || cellPosY > lastVisibleItemCoord.y()/* || widgetFlatRows[*iter] > itemsCount()*/) {
widgetFlatRows[*iter] = 0;
deleteItem(*iter);
iter = visibleItems.erase(iter);
} else {
++iter;
}
}
}
void MMultiColumnListViewPrivate::createVisibleItems(const QModelIndex &firstVisibleRow,
const QModelIndex &lastVisibleRow)
{
int firstRow = indexToFlatRow(firstVisibleRow);
int lastRow = indexToFlatRow(lastVisibleRow);
if (!viewWidth || (!firstRow&&!lastRow&&itemsCount()>1)) { // required for x position
return;
}
for (int currentRow = firstRow; currentRow <= lastRow; currentRow++) {
MWidget *cell = findCellAtRow(currentRow);
if (!widgetFlatRows[cell] && flatRowToColumn(currentRow) == 0) {
// Create widgets to all columns in this row
for (int column = 0; column < controllerModel->columns(); ++column) {
QModelIndex index = flatRowToIndex(currentRow + column);
cell = visibleItems.value(index, NULL);
if (!cell) {
cell = createItem(currentRow + column);
visibleItems[index] = cell;
}
widgetFlatRows[cell] = currentRow + column + 1;
cell->setPos(QPointF(column*(viewWidth / controllerModel->columns()), locatePosOfItem(currentRow + column)));
if (currentRow + column + 1 == itemsCount() + rowCount || flatRowToColumn(currentRow + column + 1) == 0)
break;
}
}
}
}
int MMultiColumnListViewPrivate::locatePosOfItem(int headerIndex, int itemIndex)
{
if (itemIndex == -1)
return headersPositions[headerIndex];
int pos = headersPositions[headerIndex] + headerHeight();
if (itemIndex == 0)
return pos;
int rows = itemsToRows(itemIndex + 1) - 1; // rows after the 1st one
int itemHeights = rows * itemHeight;
int hseparatorHeights = rows * hseparatorHeight;
pos += hseparatorHeights + itemHeights;
return pos;
}
int MMultiColumnListViewPrivate::locatePosOfItem(int row)
{
int headerIndex = dFindLowerIndex(headersRows, row);
int relativeRow = row - headersRows[headerIndex] - 1;
return locatePosOfItem(headerIndex, relativeRow);
}
int MMultiColumnListViewPrivate::locatePosOfItem(const QModelIndex &index)
{
return MGroupHeaderListViewPrivate::locatePosOfItem(index);
}
int MMultiColumnListViewPrivate::hseparatorsCount() const
{
int hseparatorsCount = 0;
for (int i = 0; i < headersCount(); ++i) {
hseparatorsCount += rowsInGroup(i) - 1;
}
return hseparatorsCount;
}
QModelIndex MMultiColumnListViewPrivate::locateLastVisibleIndexInRowAt(int pos)
{
int lastVisibleFlatRow = locateVisibleRowAt(pos, viewWidth-1);
return flatRowToIndex(lastVisibleFlatRow);
}
int MMultiColumnListViewPrivate::locateVisibleRowAt(int y, int x)
{
Q_UNUSED(x);
if (itemHeight == 0)
return 0;
int headerIndex = dFindLowerIndex(headersPositions, y);
int headerRow = headersRows[headerIndex];
int relativePos = y - headersPositions[headerIndex];
int headerHeight = this->headerHeight();
if (relativePos < headerHeight)
return headerRow;
relativePos -= headerHeight;
int columns = controllerModel->columns();
// row/columns * itemHeight + row/columns * hseparatorHeight = pos -> r/c*i + r/c*s = p -> r = p*c/(s+i)
int row = relativePos / (hseparatorHeight + itemHeight) * columns;
int column = 0;
if (viewWidth)
column = qMin(x / (viewWidth / columns), columns - 1);
return headerRow + row + column + 1;
}
MWidget *MMultiColumnListViewPrivate::createItem(int row)
{
if (!headersRows.contains(row)) {
MWidget *cell = createCell(row);
return cell;
} else {
int headerIndex = dFindLowerIndex(headersRows, row);
return createHeader(headerIndex);
}
}
void MMultiColumnListViewPrivate::replaceItem(MWidget* item, MWidget* newItem)
{
MListViewPrivate::replaceItem(item, newItem);
widgetFlatRows[newItem] = widgetFlatRows[item];
widgetFlatRows[item] = 0;
}
int MMultiColumnListViewPrivate::groupSize(int headerIndex) const
{
int rows = rowsInGroup(headerIndex);
int groupSize = rows * itemHeight + (rows - 1) * hseparatorHeight;
return groupSize;
}
int MMultiColumnListViewPrivate::totalHeight()
{
int totalHeight = 0;
for (int i = 0; i < headersCount(); ++i) {
totalHeight += headerHeight() + groupSize(i) + gseparatorHeight;
}
return totalHeight;
}
void MMultiColumnListViewPrivate::drawSeparator(int row, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(headersRows.contains(row)) {
drawGroupSeparator(row, painter, option);
return;
}
int columns = controllerModel->columns();
int column = flatRowToColumn(row);
if(row >= columns && column == 0) {
drawHorizontalSeparator(row, painter, option);
return;
}
if(column > 0) {
drawVerticalSeparator(row, column, painter, option);
}
}
void MMultiColumnListViewPrivate::drawVerticalSeparator(int row, int column, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
if(vseparatorWidth == 0)
return;
int itemWidth = viewWidth / controllerModel->columns();
QPointF pos(column*itemWidth - vseparatorWidth - q_ptr->marginLeft(), locatePosOfItem(row) - q_ptr->marginTop());
painter->translate(pos.x(), pos.y());
vseparator->paint(painter, option);
painter->translate(-pos.x(), -pos.y());
}
void MMultiColumnListViewPrivate::appendTargetsToDeleteAnimation(int start, int end, int first, int last)
{
QPointF offset(0,0);
QPointF destination = findCellAtRow(start)->pos();
bool shifting = false;
for (int flatRow = first; flatRow <= last; flatRow ++) {
MWidget *cell = findCellAtRow(flatRow);
if (cell) {
QModelIndex index = flatRowToIndex(flatRow);
if (flatRow < start)
itemDeletionAnimation->appendBeforeTarget(cell);
else if (flatRow > end) {
if (isGroupHeader(index) && !shifting) {
int itemsInGroup = itemsCount(index.row() - 1);
int oldGroupRows = itemsToRows(itemsInGroup + (end - start + 1));
int newGroupRows = itemsToRows(itemsInGroup);
offset = QPointF(0, (oldGroupRows - newGroupRows) * (itemHeight + hseparatorHeight));
shifting = true;
}
if (!shifting) {
itemDeletionAnimation->appendAfterTarget(cell, destination);
destination = cell->pos();
}
else
itemDeletionAnimation->appendAfterTarget(cell, cell->pos() - offset);
}
else {
itemDeletionAnimation->appendDeleteTarget(cell);
}
}
}
animatingItems = visibleItems.values().toVector();
visibleItems.clear();
}
|
#include <angles/angles.h>
#include <controller_manager_msgs/ListControllers.h>
#include <controller_manager_msgs/SwitchController.h>
#include <franka/duration.h>
#include <franka_example_controllers/pseudo_inversion.h>
#include <franka_gazebo/franka_hw_sim.h>
#include <franka_gazebo/model_kdl.h>
#include <franka_hw/franka_hw.h>
#include <franka_hw/services.h>
#include <franka_msgs/SetEEFrame.h>
#include <franka_msgs/SetForceTorqueCollisionBehavior.h>
#include <franka_msgs/SetKFrame.h>
#include <franka_msgs/SetLoad.h>
#include <gazebo_ros_control/robot_hw_sim.h>
#include <joint_limits_interface/joint_limits_urdf.h>
#include <std_msgs/Bool.h>
#include <std_srvs/SetBool.h>
#include <Eigen/Dense>
#include <boost/algorithm/clamp.hpp>
#include <boost/optional.hpp>
#include <iostream>
#include <sstream>
#include <string>
namespace franka_gazebo {
using actionlib::SimpleActionServer;
using boost::sml::state;
FrankaHWSim::FrankaHWSim() : sm_(this->robot_state_, this->joints_) {}
bool FrankaHWSim::initSim(const std::string& robot_namespace,
ros::NodeHandle model_nh,
gazebo::physics::ModelPtr parent,
const urdf::Model* const urdf,
std::vector<transmission_interface::TransmissionInfo> transmissions) {
model_nh.param<std::string>("arm_id", this->arm_id_, robot_namespace);
if (this->arm_id_ != robot_namespace) {
ROS_WARN_STREAM_NAMED(
"franka_hw_sim",
"Caution: Robot names differ! Read 'arm_id: "
<< this->arm_id_ << "' from parameter server but URDF defines '<robotNamespace>"
<< robot_namespace << "</robotNamespace>'. Will use '" << this->arm_id_ << "'!");
}
this->robot_ = parent;
this->robot_initialized_ = false;
this->robot_initialized_pub_ = model_nh.advertise<std_msgs::Bool>("initialized", 1);
std_msgs::Bool msg;
msg.data = static_cast<decltype(msg.data)>(false);
this->robot_initialized_pub_.publish(msg);
this->action_recovery_ = std::make_unique<SimpleActionServer<franka_msgs::ErrorRecoveryAction>>(
model_nh, "franka_control/error_recovery",
[&](const franka_msgs::ErrorRecoveryGoalConstPtr& goal) {
if (this->robot_state_.robot_mode == franka::RobotMode::kUserStopped) {
ROS_WARN_STREAM_NAMED("franka_hw_sim",
"Cannot recover errors since the user stop seems still pressed");
this->action_recovery_->setSucceeded();
return;
}
try {
restartControllers();
ROS_INFO_NAMED("franka_hw_sim", "Recovered from error");
this->sm_.process_event(ErrorRecovery());
this->action_recovery_->setSucceeded();
} catch (const std::runtime_error& e) {
ROS_WARN_STREAM_NAMED("franka_hw_sim", "Error recovery failed: " << e.what());
this->action_recovery_->setAborted();
}
},
false);
this->action_recovery_->start();
#if GAZEBO_MAJOR_VERSION >= 8
gazebo::physics::PhysicsEnginePtr physics = gazebo::physics::get_world()->Physics();
#else
gazebo::physics::PhysicsEnginePtr physics = gazebo::physics::get_world()->GetPhysicsEngine();
#endif
ROS_INFO_STREAM_NAMED("franka_hw_sim", "Using physics type " << physics->GetType());
// Retrieve initial gravity vector from Gazebo
// NOTE: Can be overwritten by the user via the 'gravity_vector' ROS parameter.
auto gravity = physics->World()->Gravity();
this->gravity_earth_ = {gravity.X(), gravity.Y(), gravity.Z()};
model_nh.param<double>("tau_ext_lowpass_filter", this->tau_ext_lowpass_filter_,
kDefaultTauExtLowpassFilter);
// Generate a list of franka_gazebo::Joint to store all relevant information
for (const auto& transmission : transmissions) {
if (transmission.type_ != "transmission_interface/SimpleTransmission") {
continue;
}
if (transmission.joints_.empty()) {
ROS_WARN_STREAM_NAMED("franka_hw_sim",
"Transmission " << transmission.name_ << " has no associated joints.");
return false;
}
if (transmission.joints_.size() > 1) {
ROS_WARN_STREAM_NAMED(
"franka_hw_sim",
"Transmission "
<< transmission.name_
<< " has more than one joint. Currently the franka robot hardware simulation "
<< " interface only supports one.");
return false;
}
// Fill a 'Joint' struct which holds all necessary data
auto joint = std::make_shared<franka_gazebo::Joint>();
joint->name = transmission.joints_[0].name_;
if (urdf == nullptr) {
ROS_ERROR_STREAM_NAMED(
"franka_hw_sim", "Could not find any URDF model. Was it loaded on the parameter server?");
return false;
}
auto urdf_joint = urdf->getJoint(joint->name);
if (not urdf_joint) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim",
"Could not get joint '" << joint->name << "' from URDF");
return false;
}
joint->type = urdf_joint->type;
joint_limits_interface::getJointLimits(urdf_joint, joint->limits);
joint->axis = Eigen::Vector3d(urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z);
// Get a handle to the underlying Gazebo Joint
gazebo::physics::JointPtr handle = parent->GetJoint(joint->name);
if (not handle) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", "This robot has a joint named '"
<< joint->name
<< "' which is not in the gazebo model.");
return false;
}
joint->handle = handle;
// set the control method for finger joints to effort
if (joint->name.find(arm_id_ + "_finger_joint") != std::string::npos) {
joint->control_method = EFFORT;
}
this->joints_.emplace(joint->name, joint);
}
// After the joint data containers have been fully initialized and their memory address don't
// change anymore, get the respective addresses to pass them to the handles
for (auto& pair : this->joints_) {
initJointStateHandle(pair.second);
}
// Register all supported command interfaces
for (const auto& transmission : transmissions) {
for (const auto& k_interface : transmission.joints_[0].hardware_interfaces_) {
auto joint = this->joints_[transmission.joints_[0].name_];
if (transmission.type_ == "transmission_interface/SimpleTransmission") {
ROS_INFO_STREAM_NAMED("franka_hw_sim", "Found transmission interface of joint '"
<< joint->name << "': " << k_interface);
if (k_interface == "hardware_interface/EffortJointInterface") {
initEffortCommandHandle(joint);
continue;
}
if (k_interface == "hardware_interface/PositionJointInterface") {
// Initiate position motion generator (PID controller)
joint->position_controller.initParam(robot_namespace +
"/motion_generators/position/gains/" + joint->name);
initPositionCommandHandle(joint);
continue;
}
if (k_interface == "hardware_interface/VelocityJointInterface") {
// Initiate velocity motion generator (PID controller)
joint->velocity_controller.initParam(robot_namespace +
"/motion_generators/velocity/gains/" + joint->name);
initVelocityCommandHandle(joint);
continue;
}
}
if (transmission.type_ == "franka_hw/FrankaStateInterface") {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
"Found transmission interface '" << transmission.type_ << "'");
try {
initFrankaStateHandle(this->arm_id_, *urdf, transmission);
continue;
} catch (const std::invalid_argument& e) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", e.what());
return false;
}
}
if (transmission.type_ == "franka_hw/FrankaModelInterface") {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
"Found transmission interface '" << transmission.type_ << "'");
double singularity_threshold;
model_nh.param<double>("singularity_warning_threshold", singularity_threshold, -1);
try {
initFrankaModelHandle(this->arm_id_, *urdf, transmission, singularity_threshold);
continue;
} catch (const std::invalid_argument& e) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", e.what());
return false;
}
}
ROS_WARN_STREAM_NAMED("franka_hw_sim", "Unsupported transmission interface of joint '"
<< joint->name << "': " << k_interface);
}
}
// After all handles have been assigned to interfaces, register them
assert(this->eji_.getNames().size() >= 7);
assert(this->pji_.getNames().size() == 7);
assert(this->vji_.getNames().size() == 7);
assert(this->jsi_.getNames().size() >= 7);
assert(this->fsi_.getNames().size() == 1);
assert(this->fmi_.getNames().size() == 1);
registerInterface(&this->eji_);
registerInterface(&this->pji_);
registerInterface(&this->vji_);
registerInterface(&this->jsi_);
registerInterface(&this->fsi_);
registerInterface(&this->fmi_);
// Initialize ROS Services
initServices(model_nh);
verifier_ = std::make_unique<ControllerVerifier>(joints_, arm_id_);
return readParameters(model_nh, *urdf);
}
void FrankaHWSim::initJointStateHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->jsi_.registerHandle(hardware_interface::JointStateHandle(joint->name, &joint->position,
&joint->velocity, &joint->effort));
}
void FrankaHWSim::initEffortCommandHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->eji_.registerHandle(
hardware_interface::JointHandle(this->jsi_.getHandle(joint->name), &joint->command));
}
void FrankaHWSim::initPositionCommandHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->pji_.registerHandle(
hardware_interface::JointHandle(this->jsi_.getHandle(joint->name), &joint->desired_position));
}
void FrankaHWSim::initVelocityCommandHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->vji_.registerHandle(
hardware_interface::JointHandle(this->jsi_.getHandle(joint->name), &joint->desired_velocity));
}
void FrankaHWSim::initFrankaStateHandle(
const std::string& robot,
const urdf::Model& urdf,
const transmission_interface::TransmissionInfo& transmission) {
if (transmission.joints_.size() != 7) {
throw std::invalid_argument(
"Cannot create franka_hw/FrankaStateInterface for robot '" + robot + "_robot' because " +
std::to_string(transmission.joints_.size()) +
" joints were found beneath the <transmission> tag, but 7 are required.");
}
// Initialize robot_mode to "Idle". Once a controller is started, we will switch to "Move"
this->robot_state_.robot_mode = franka::RobotMode::kIdle;
// Check if all joints defined in the <transmission> actually exist in the URDF
for (const auto& joint : transmission.joints_) {
if (not urdf.getJoint(joint.name_)) {
throw std::invalid_argument("Cannot create franka_hw/FrankaStateInterface for robot '" +
robot + "_robot' because the specified joint '" + joint.name_ +
"' in the <transmission> tag cannot be found in the URDF");
}
ROS_DEBUG_STREAM_NAMED("franka_hw_sim",
"Found joint " << joint.name_ << " to belong to a Panda robot");
}
this->fsi_.registerHandle(franka_hw::FrankaStateHandle(robot + "_robot", this->robot_state_));
}
void FrankaHWSim::initFrankaModelHandle(
const std::string& robot,
const urdf::Model& urdf,
const transmission_interface::TransmissionInfo& transmission,
double singularity_threshold) {
if (transmission.joints_.size() != 2) {
throw std::invalid_argument(
"Cannot create franka_hw/FrankaModelInterface for robot '" + robot + "_model' because " +
std::to_string(transmission.joints_.size()) +
" joints were found beneath the <transmission> tag, but 2 are required.");
}
for (const auto& joint : transmission.joints_) {
if (not urdf.getJoint(joint.name_)) {
if (not urdf.getJoint(joint.name_)) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" +
robot + "_model' because the specified joint '" + joint.name_ +
"' in the <transmission> tag cannot be found in the URDF");
}
}
}
auto root =
std::find_if(transmission.joints_.begin(), transmission.joints_.end(),
[&](const transmission_interface::JointInfo& i) { return i.role_ == "root"; });
if (root == transmission.joints_.end()) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" + robot +
"_model' because no <joint> with <role>root</root> can be found "
"in the <transmission>");
}
auto tip =
std::find_if(transmission.joints_.begin(), transmission.joints_.end(),
[&](const transmission_interface::JointInfo& i) { return i.role_ == "tip"; });
if (tip == transmission.joints_.end()) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" + robot +
"_model' because no <joint> with <role>tip</role> can be found "
"in the <transmission>");
}
try {
auto root_link = urdf.getJoint(root->name_)->parent_link_name;
auto tip_link = urdf.getJoint(tip->name_)->child_link_name;
this->model_ =
std::make_unique<franka_gazebo::ModelKDL>(urdf, root_link, tip_link, singularity_threshold);
} catch (const std::invalid_argument& e) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" + robot +
"_model'. " + e.what());
}
this->fmi_.registerHandle(
franka_hw::FrankaModelHandle(robot + "_model", *this->model_, this->robot_state_));
}
void FrankaHWSim::initServices(ros::NodeHandle& nh) {
this->service_set_ee_ =
nh.advertiseService<franka_msgs::SetEEFrame::Request, franka_msgs::SetEEFrame::Response>(
"set_EE_frame", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
this->arm_id_ << ": Setting NE_T_EE transformation");
std::copy(request.NE_T_EE.cbegin(), request.NE_T_EE.cend(),
this->robot_state_.NE_T_EE.begin());
this->updateRobotStateDynamics();
response.success = true;
return true;
});
this->service_set_k_ = franka_hw::advertiseService<franka_msgs::SetKFrame>(
nh, "set_K_frame", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim", this->arm_id_ << ": Setting EE_T_K transformation");
std::copy(request.EE_T_K.cbegin(), request.EE_T_K.cend(),
this->robot_state_.EE_T_K.begin());
this->updateRobotStateDynamics();
response.success = true;
return true;
});
this->service_set_load_ = franka_hw::advertiseService<franka_msgs::SetLoad>(
nh, "set_load", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim", this->arm_id_ << ": Setting Load");
this->robot_state_.m_load = request.mass;
std::copy(request.F_x_center_load.cbegin(), request.F_x_center_load.cend(),
this->robot_state_.F_x_Cload.begin());
std::copy(request.load_inertia.cbegin(), request.load_inertia.cend(),
this->robot_state_.I_load.begin());
this->updateRobotStateDynamics();
response.success = true;
return true;
});
this->service_collision_behavior_ =
franka_hw::advertiseService<franka_msgs::SetForceTorqueCollisionBehavior>(
nh, "set_force_torque_collision_behavior", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim", this->arm_id_ << ": Setting Collision Behavior");
for (int i = 0; i < 7; i++) {
std::string name = this->arm_id_ + "_joint" + std::to_string(i + 1);
this->joints_[name]->contact_threshold =
request.lower_torque_thresholds_nominal.at(i);
this->joints_[name]->collision_threshold =
request.upper_torque_thresholds_nominal.at(i);
}
std::move(request.lower_force_thresholds_nominal.begin(),
request.lower_force_thresholds_nominal.end(),
this->lower_force_thresholds_nominal_.begin());
std::move(request.upper_force_thresholds_nominal.begin(),
request.upper_force_thresholds_nominal.end(),
this->upper_force_thresholds_nominal_.begin());
response.success = true;
return true;
});
this->service_user_stop_ =
nh.advertiseService<std_srvs::SetBool::Request, std_srvs::SetBool::Response>(
"set_user_stop", [&](auto& request, auto& response) {
this->sm_.process_event(UserStop{static_cast<bool>(request.data)});
response.success = true;
return true;
});
this->service_controller_list_ = nh.serviceClient<controller_manager_msgs::ListControllers>(
"controller_manager/list_controllers");
this->service_controller_switch_ = nh.serviceClient<controller_manager_msgs::SwitchController>(
"controller_manager/switch_controller");
}
void FrankaHWSim::restartControllers() {
// Restart controllers by stopping and starting all running ones
auto name = this->service_controller_list_.getService();
if (not this->service_controller_list_.waitForExistence(ros::Duration(3))) {
throw std::runtime_error("Cannot find service '" + name +
"'. Is the controller_manager running?");
}
controller_manager_msgs::ListControllers list;
if (not this->service_controller_list_.call(list)) {
throw std::runtime_error("Service call '" + name + "' failed");
}
controller_manager_msgs::SwitchController swtch;
for (const auto& controller : list.response.controller) {
if (controller.state != "running") {
continue;
}
swtch.request.stop_controllers.push_back(controller.name);
swtch.request.start_controllers.push_back(controller.name);
}
swtch.request.start_asap = static_cast<decltype(swtch.request.start_asap)>(true);
swtch.request.strictness = controller_manager_msgs::SwitchControllerRequest::STRICT;
if (not this->service_controller_switch_.call(swtch) or
not static_cast<bool>(swtch.response.ok)) {
throw std::runtime_error("Service call '" + this->service_controller_switch_.getService() +
"' failed");
}
}
void FrankaHWSim::readSim(ros::Time time, ros::Duration period) {
for (const auto& pair : this->joints_) {
auto joint = pair.second;
joint->update(period);
}
this->updateRobotState(time);
}
double FrankaHWSim::positionControl(Joint& joint, double setpoint, const ros::Duration& period) {
double error;
const double kJointLowerLimit = joint.limits.min_position;
const double kJointUpperLimit = joint.limits.max_position;
switch (joint.type) {
case urdf::Joint::REVOLUTE:
angles::shortest_angular_distance_with_limits(joint.position, setpoint, kJointLowerLimit,
kJointUpperLimit, error);
break;
case urdf::Joint::PRISMATIC:
error =
boost::algorithm::clamp(setpoint - joint.position, kJointLowerLimit, kJointUpperLimit);
break;
default:
std::string error_message =
"Only revolute or prismatic joints are allowed for position control right now";
ROS_FATAL("%s", error_message.c_str());
throw std::invalid_argument(error_message);
}
return boost::algorithm::clamp(joint.position_controller.computeCommand(error, period),
-joint.limits.max_effort, joint.limits.max_effort);
}
double FrankaHWSim::velocityControl(Joint& joint, double setpoint, const ros::Duration& period) {
return boost::algorithm::clamp(
joint.velocity_controller.computeCommand(setpoint - joint.velocity, period),
-joint.limits.max_effort, joint.limits.max_effort);
}
void FrankaHWSim::writeSim(ros::Time /*time*/, ros::Duration period) {
auto g = this->model_->gravity(this->robot_state_, this->gravity_earth_);
for (auto& pair : this->joints_) {
auto joint = pair.second;
// Retrieve effort control command
double effort = 0;
if (not sm_.is(state<Move>)) {
effort = positionControl(*joint, joint->stop_position, period);
} else if (joint->control_method == POSITION) {
effort = positionControl(*joint, joint->desired_position, period);
} else if (joint->control_method == VELOCITY) {
velocityControl(*joint, joint->desired_velocity, period);
} else if (joint->control_method == EFFORT) {
// Feed-forward commands in effort control
effort = joint->command;
}
// Check if this joint is affected by gravity compensation
std::string prefix = this->arm_id_ + "_joint";
if (pair.first.rfind(prefix, 0) != std::string::npos) {
int i = std::stoi(pair.first.substr(prefix.size())) - 1;
joint->gravity = g.at(i);
}
effort += joint->gravity;
// Send control effort control command
if (not std::isfinite(effort)) {
ROS_WARN_STREAM_NAMED("franka_hw_sim",
"Command for " << joint->name << "is not finite, won't send to robot");
continue;
}
joint->handle->SetForce(0, effort);
}
}
void FrankaHWSim::eStopActive(bool /* active */) {}
bool FrankaHWSim::readParameters(const ros::NodeHandle& nh, const urdf::Model& urdf) {
try {
guessEndEffector(nh, urdf);
nh.param<double>("m_load", this->robot_state_.m_load, 0);
std::string I_load; // NOLINT [readability-identifier-naming]
nh.param<std::string>("I_load", I_load, "0 0 0 0 0 0 0 0 0");
this->robot_state_.I_load = readArray<9>(I_load, "I_load");
std::string F_x_Cload; // NOLINT [readability-identifier-naming]
nh.param<std::string>("F_x_Cload", F_x_Cload, "0 0 0");
this->robot_state_.F_x_Cload = readArray<3>(F_x_Cload, "F_x_Cload");
std::string NE_T_EE; // NOLINT [readability-identifier-naming]
nh.param<std::string>("NE_T_EE", NE_T_EE, "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1");
this->robot_state_.NE_T_EE = readArray<16>(NE_T_EE, "NE_T_EE");
std::string EE_T_K; // NOLINT [readability-identifier-naming]
nh.param<std::string>("EE_T_K", EE_T_K, "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1");
this->robot_state_.EE_T_K = readArray<16>(EE_T_K, "EE_T_K");
std::string gravity_vector;
if (nh.getParam("gravity_vector", gravity_vector)) {
this->gravity_earth_ = readArray<3>(gravity_vector, "gravity_vector");
}
// Only nominal cases supported for now
std::vector<double> lower_torque_thresholds = franka_hw::FrankaHW::getCollisionThresholds(
"lower_torque_thresholds_nominal", nh, {20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0});
std::vector<double> upper_torque_thresholds = franka_hw::FrankaHW::getCollisionThresholds(
"upper_torque_thresholds_nominal", nh, {20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0});
this->lower_force_thresholds_nominal_ = franka_hw::FrankaHW::getCollisionThresholds(
"lower_force_thresholds_nominal", nh, {20.0, 20.0, 20.0, 25.0, 25.0, 25.0});
this->upper_force_thresholds_nominal_ = franka_hw::FrankaHW::getCollisionThresholds(
"upper_force_thresholds_nominal", nh, {20.0, 20.0, 20.0, 25.0, 25.0, 25.0});
for (int i = 0; i < 7; i++) {
std::string name = this->arm_id_ + "_joint" + std::to_string(i + 1);
this->joints_[name]->contact_threshold = lower_torque_thresholds.at(i);
this->joints_[name]->collision_threshold = upper_torque_thresholds.at(i);
}
} catch (const std::invalid_argument& e) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", e.what());
return false;
}
updateRobotStateDynamics();
return true;
}
void FrankaHWSim::guessEndEffector(const ros::NodeHandle& nh, const urdf::Model& urdf) {
auto hand_link = this->arm_id_ + "_hand";
auto hand = urdf.getLink(hand_link);
if (hand != nullptr) {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
"Found link '" << hand_link
<< "' in URDF. Assuming it is defining the kinematics & "
"inertias of a Franka Hand Gripper.");
}
// By absolute default unless URDF or ROS params say otherwise, assume no end-effector.
double def_m_ee = 0;
std::string def_i_ee = "0.0 0 0 0 0.0 0 0 0 0.0";
std::string def_f_x_cee = "0 0 0";
std::string def_f_t_ne = "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1";
if (not nh.hasParam("F_T_NE") and hand != nullptr) {
// NOTE: We cannot interprete the Joint pose from the URDF directly, because
// its <arm_id>_link is mounted at the flange directly and not at NE
def_f_t_ne = "0.7071 -0.7071 0 0 0.7071 0.7071 0 0 0 0 1 0 0 0 0.1034 1";
}
std::string F_T_NE; // NOLINT [readability-identifier-naming]
nh.param<std::string>("F_T_NE", F_T_NE, def_f_t_ne);
this->robot_state_.F_T_NE = readArray<16>(F_T_NE, "F_T_NE");
if (not nh.hasParam("m_ee") and hand != nullptr) {
if (hand->inertial == nullptr) {
throw std::invalid_argument("Trying to use inertia of " + hand_link +
" but this link has no <inertial> tag defined in it.");
}
def_m_ee = hand->inertial->mass;
}
nh.param<double>("m_ee", this->robot_state_.m_ee, def_m_ee);
if (not nh.hasParam("I_ee") and hand != nullptr) {
if (hand->inertial == nullptr) {
throw std::invalid_argument("Trying to use inertia of " + hand_link +
" but this link has no <inertial> tag defined in it.");
}
// clang-format off
def_i_ee = std::to_string(hand->inertial->ixx) + " " + std::to_string(hand->inertial->ixy) + " " + std::to_string(hand->inertial->ixz) + " "
+ std::to_string(hand->inertial->ixy) + " " + std::to_string(hand->inertial->iyy) + " " + std::to_string(hand->inertial->iyz) + " "
+ std::to_string(hand->inertial->ixz) + " " + std::to_string(hand->inertial->iyz) + " " + std::to_string(hand->inertial->izz);
// clang-format on
}
std::string I_ee; // NOLINT [readability-identifier-naming]
nh.param<std::string>("I_ee", I_ee, def_i_ee);
this->robot_state_.I_ee = readArray<9>(I_ee, "I_ee");
if (not nh.hasParam("F_x_Cee") and hand != nullptr) {
if (hand->inertial == nullptr) {
throw std::invalid_argument("Trying to use inertia of " + hand_link +
" but this link has no <inertial> tag defined in it.");
}
def_f_x_cee = std::to_string(hand->inertial->origin.position.x) + " " +
std::to_string(hand->inertial->origin.position.y) + " " +
std::to_string(hand->inertial->origin.position.z);
}
std::string F_x_Cee; // NOLINT [readability-identifier-naming]
nh.param<std::string>("F_x_Cee", F_x_Cee, def_f_x_cee);
this->robot_state_.F_x_Cee = readArray<3>(F_x_Cee, "F_x_Cee");
}
void FrankaHWSim::updateRobotStateDynamics() {
this->robot_state_.m_total = this->robot_state_.m_ee + this->robot_state_.m_load;
Eigen::Map<Eigen::Matrix4d>(this->robot_state_.F_T_EE.data()) =
Eigen::Matrix4d(this->robot_state_.F_T_NE.data()) *
Eigen::Matrix4d(this->robot_state_.NE_T_EE.data());
Eigen::Map<Eigen::Matrix3d>(this->robot_state_.I_total.data()) =
shiftInertiaTensor(Eigen::Matrix3d(this->robot_state_.I_ee.data()), this->robot_state_.m_ee,
Eigen::Vector3d(this->robot_state_.F_x_Cload.data()));
}
void FrankaHWSim::updateRobotState(ros::Time time) {
// This is ensured, because a FrankaStateInterface checks for at least seven joints in the URDF
assert(this->joints_.size() >= 7);
auto mode = this->robot_state_.robot_mode;
for (int i = 0; i < 7; i++) {
std::string name = this->arm_id_ + "_joint" + std::to_string(i + 1);
const auto& joint = this->joints_.at(name);
this->robot_state_.q[i] = joint->position;
this->robot_state_.dq[i] = joint->velocity;
this->robot_state_.tau_J[i] = joint->effort;
this->robot_state_.dtau_J[i] = joint->jerk;
this->robot_state_.q_d[i] = joint->getDesiredPosition(mode);
this->robot_state_.dq_d[i] = joint->getDesiredVelocity(mode);
this->robot_state_.ddq_d[i] = joint->getDesiredAcceleration(mode);
this->robot_state_.tau_J_d[i] = joint->getDesiredTorque(mode);
// For now we assume no flexible joints
this->robot_state_.theta[i] = joint->position;
this->robot_state_.dtheta[i] = joint->velocity;
// first time initialization of the desired position
if (not this->robot_initialized_) {
joint->desired_position = joint->position;
joint->stop_position = joint->position;
}
if (this->robot_initialized_) {
double tau_ext = joint->effort - joint->command + joint->gravity;
// Exponential moving average filter from tau_ext -> tau_ext_hat_filtered
this->robot_state_.tau_ext_hat_filtered[i] =
this->tau_ext_lowpass_filter_ * tau_ext +
(1 - this->tau_ext_lowpass_filter_) * this->robot_state_.tau_ext_hat_filtered[i];
}
this->robot_state_.joint_contact[i] = static_cast<double>(joint->isInContact());
this->robot_state_.joint_collision[i] = static_cast<double>(joint->isInCollision());
}
// Calculate estimated wrenches in Task frame from external joint torques with jacobians
Eigen::Map<Eigen::Matrix<double, 7, 1>> tau_ext(this->robot_state_.tau_ext_hat_filtered.data());
Eigen::MatrixXd j0_transpose_pinv;
Eigen::MatrixXd jk_transpose_pinv;
Eigen::Matrix<double, 6, 7> j0(
this->model_->zeroJacobian(franka::Frame::kStiffness, this->robot_state_).data());
Eigen::Matrix<double, 6, 7> jk(
this->model_->bodyJacobian(franka::Frame::kStiffness, this->robot_state_).data());
franka_example_controllers::pseudoInverse(j0.transpose(), j0_transpose_pinv);
franka_example_controllers::pseudoInverse(jk.transpose(), jk_transpose_pinv);
Eigen::VectorXd f_ext_0 = j0_transpose_pinv * tau_ext;
Eigen::VectorXd f_ext_k = jk_transpose_pinv * tau_ext;
Eigen::VectorXd::Map(&this->robot_state_.O_F_ext_hat_K[0], 6) = f_ext_0;
Eigen::VectorXd::Map(&this->robot_state_.K_F_ext_hat_K[0], 6) = f_ext_k;
for (int i = 0; i < this->robot_state_.cartesian_contact.size(); i++) {
// Evaluate the cartesian contacts/collisions in K frame
double fi = std::abs(f_ext_k(i));
this->robot_state_.cartesian_contact[i] =
static_cast<double>(fi > this->lower_force_thresholds_nominal_.at(i));
this->robot_state_.cartesian_collision[i] =
static_cast<double>(fi > this->upper_force_thresholds_nominal_.at(i));
}
this->robot_state_.control_command_success_rate = 1.0;
this->robot_state_.time = franka::Duration(time.toNSec() / 1e6 /*ms*/);
this->robot_state_.O_T_EE = this->model_->pose(franka::Frame::kEndEffector, this->robot_state_);
#ifdef ENABLE_BASE_ACCELERATION
// This will always be {0,0,-9.81} on the real robot as it cannot be mounted differently for now
this->robot_state_.O_ddP_O = this->gravity_earth_;
#endif
std_msgs::Bool msg;
msg.data = static_cast<decltype(msg.data)>(true);
this->robot_initialized_ = true;
this->robot_initialized_pub_.publish(msg);
}
bool FrankaHWSim::prepareSwitch(
const std::list<hardware_interface::ControllerInfo>& start_list,
const std::list<hardware_interface::ControllerInfo>& /*stop_list*/) {
return std::all_of(start_list.cbegin(), start_list.cend(), [this](const auto& controller) {
return verifier_->isValidController(controller);
});
}
void FrankaHWSim::doSwitch(const std::list<hardware_interface::ControllerInfo>& start_list,
const std::list<hardware_interface::ControllerInfo>& stop_list) {
forControlledJoint(stop_list, [](franka_gazebo::Joint& joint, const ControlMethod& /*method*/) {
joint.control_method = boost::none;
joint.stop_position = joint.position;
joint.desired_position = joint.position;
joint.desired_velocity = 0;
});
forControlledJoint(start_list, [](franka_gazebo::Joint& joint, const ControlMethod& method) {
joint.control_method = method;
// sets the desired joint position once for the effort interface
joint.desired_position = joint.position;
joint.desired_velocity = 0;
});
this->sm_.process_event(SwitchControl());
}
void FrankaHWSim::forControlledJoint(
const std::list<hardware_interface::ControllerInfo>& controllers,
const std::function<void(franka_gazebo::Joint& joint, const ControlMethod&)>& f) {
for (const auto& controller : controllers) {
if (not verifier_->isClaimingArmController(controller)) {
continue;
}
for (const auto& resource : controller.claimed_resources) {
auto control_method = ControllerVerifier::determineControlMethod(resource.hardware_interface);
if (not control_method) {
continue;
}
for (const auto& joint_name : resource.resources) {
auto& joint = joints_.at(joint_name);
f(*joint, control_method.value());
}
}
}
}
} // namespace franka_gazebo
PLUGINLIB_EXPORT_CLASS(franka_gazebo::FrankaHWSim, gazebo_ros_control::RobotHWSim)
FIX: Allow finger joints to still be controlled while not in Move
#include <angles/angles.h>
#include <controller_manager_msgs/ListControllers.h>
#include <controller_manager_msgs/SwitchController.h>
#include <franka/duration.h>
#include <franka_example_controllers/pseudo_inversion.h>
#include <franka_gazebo/franka_hw_sim.h>
#include <franka_gazebo/model_kdl.h>
#include <franka_hw/franka_hw.h>
#include <franka_hw/services.h>
#include <franka_msgs/SetEEFrame.h>
#include <franka_msgs/SetForceTorqueCollisionBehavior.h>
#include <franka_msgs/SetKFrame.h>
#include <franka_msgs/SetLoad.h>
#include <gazebo_ros_control/robot_hw_sim.h>
#include <joint_limits_interface/joint_limits_urdf.h>
#include <std_msgs/Bool.h>
#include <std_srvs/SetBool.h>
#include <Eigen/Dense>
#include <boost/algorithm/clamp.hpp>
#include <boost/optional.hpp>
#include <iostream>
#include <sstream>
#include <string>
namespace franka_gazebo {
using actionlib::SimpleActionServer;
using boost::sml::state;
FrankaHWSim::FrankaHWSim() : sm_(this->robot_state_, this->joints_) {}
bool FrankaHWSim::initSim(const std::string& robot_namespace,
ros::NodeHandle model_nh,
gazebo::physics::ModelPtr parent,
const urdf::Model* const urdf,
std::vector<transmission_interface::TransmissionInfo> transmissions) {
model_nh.param<std::string>("arm_id", this->arm_id_, robot_namespace);
if (this->arm_id_ != robot_namespace) {
ROS_WARN_STREAM_NAMED(
"franka_hw_sim",
"Caution: Robot names differ! Read 'arm_id: "
<< this->arm_id_ << "' from parameter server but URDF defines '<robotNamespace>"
<< robot_namespace << "</robotNamespace>'. Will use '" << this->arm_id_ << "'!");
}
this->robot_ = parent;
this->robot_initialized_ = false;
this->robot_initialized_pub_ = model_nh.advertise<std_msgs::Bool>("initialized", 1);
std_msgs::Bool msg;
msg.data = static_cast<decltype(msg.data)>(false);
this->robot_initialized_pub_.publish(msg);
this->action_recovery_ = std::make_unique<SimpleActionServer<franka_msgs::ErrorRecoveryAction>>(
model_nh, "franka_control/error_recovery",
[&](const franka_msgs::ErrorRecoveryGoalConstPtr& goal) {
if (this->robot_state_.robot_mode == franka::RobotMode::kUserStopped) {
ROS_WARN_STREAM_NAMED("franka_hw_sim",
"Cannot recover errors since the user stop seems still pressed");
this->action_recovery_->setSucceeded();
return;
}
try {
restartControllers();
ROS_INFO_NAMED("franka_hw_sim", "Recovered from error");
this->sm_.process_event(ErrorRecovery());
this->action_recovery_->setSucceeded();
} catch (const std::runtime_error& e) {
ROS_WARN_STREAM_NAMED("franka_hw_sim", "Error recovery failed: " << e.what());
this->action_recovery_->setAborted();
}
},
false);
this->action_recovery_->start();
#if GAZEBO_MAJOR_VERSION >= 8
gazebo::physics::PhysicsEnginePtr physics = gazebo::physics::get_world()->Physics();
#else
gazebo::physics::PhysicsEnginePtr physics = gazebo::physics::get_world()->GetPhysicsEngine();
#endif
ROS_INFO_STREAM_NAMED("franka_hw_sim", "Using physics type " << physics->GetType());
// Retrieve initial gravity vector from Gazebo
// NOTE: Can be overwritten by the user via the 'gravity_vector' ROS parameter.
auto gravity = physics->World()->Gravity();
this->gravity_earth_ = {gravity.X(), gravity.Y(), gravity.Z()};
model_nh.param<double>("tau_ext_lowpass_filter", this->tau_ext_lowpass_filter_,
kDefaultTauExtLowpassFilter);
// Generate a list of franka_gazebo::Joint to store all relevant information
for (const auto& transmission : transmissions) {
if (transmission.type_ != "transmission_interface/SimpleTransmission") {
continue;
}
if (transmission.joints_.empty()) {
ROS_WARN_STREAM_NAMED("franka_hw_sim",
"Transmission " << transmission.name_ << " has no associated joints.");
return false;
}
if (transmission.joints_.size() > 1) {
ROS_WARN_STREAM_NAMED(
"franka_hw_sim",
"Transmission "
<< transmission.name_
<< " has more than one joint. Currently the franka robot hardware simulation "
<< " interface only supports one.");
return false;
}
// Fill a 'Joint' struct which holds all necessary data
auto joint = std::make_shared<franka_gazebo::Joint>();
joint->name = transmission.joints_[0].name_;
if (urdf == nullptr) {
ROS_ERROR_STREAM_NAMED(
"franka_hw_sim", "Could not find any URDF model. Was it loaded on the parameter server?");
return false;
}
auto urdf_joint = urdf->getJoint(joint->name);
if (not urdf_joint) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim",
"Could not get joint '" << joint->name << "' from URDF");
return false;
}
joint->type = urdf_joint->type;
joint_limits_interface::getJointLimits(urdf_joint, joint->limits);
joint->axis = Eigen::Vector3d(urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z);
// Get a handle to the underlying Gazebo Joint
gazebo::physics::JointPtr handle = parent->GetJoint(joint->name);
if (not handle) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", "This robot has a joint named '"
<< joint->name
<< "' which is not in the gazebo model.");
return false;
}
joint->handle = handle;
// set the control method for finger joints to effort
if (joint->name.find(arm_id_ + "_finger_joint") != std::string::npos) {
joint->control_method = EFFORT;
}
this->joints_.emplace(joint->name, joint);
}
// After the joint data containers have been fully initialized and their memory address don't
// change anymore, get the respective addresses to pass them to the handles
for (auto& pair : this->joints_) {
initJointStateHandle(pair.second);
}
// Register all supported command interfaces
for (const auto& transmission : transmissions) {
for (const auto& k_interface : transmission.joints_[0].hardware_interfaces_) {
auto joint = this->joints_[transmission.joints_[0].name_];
if (transmission.type_ == "transmission_interface/SimpleTransmission") {
ROS_INFO_STREAM_NAMED("franka_hw_sim", "Found transmission interface of joint '"
<< joint->name << "': " << k_interface);
if (k_interface == "hardware_interface/EffortJointInterface") {
initEffortCommandHandle(joint);
continue;
}
if (k_interface == "hardware_interface/PositionJointInterface") {
// Initiate position motion generator (PID controller)
joint->position_controller.initParam(robot_namespace +
"/motion_generators/position/gains/" + joint->name);
initPositionCommandHandle(joint);
continue;
}
if (k_interface == "hardware_interface/VelocityJointInterface") {
// Initiate velocity motion generator (PID controller)
joint->velocity_controller.initParam(robot_namespace +
"/motion_generators/velocity/gains/" + joint->name);
initVelocityCommandHandle(joint);
continue;
}
}
if (transmission.type_ == "franka_hw/FrankaStateInterface") {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
"Found transmission interface '" << transmission.type_ << "'");
try {
initFrankaStateHandle(this->arm_id_, *urdf, transmission);
continue;
} catch (const std::invalid_argument& e) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", e.what());
return false;
}
}
if (transmission.type_ == "franka_hw/FrankaModelInterface") {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
"Found transmission interface '" << transmission.type_ << "'");
double singularity_threshold;
model_nh.param<double>("singularity_warning_threshold", singularity_threshold, -1);
try {
initFrankaModelHandle(this->arm_id_, *urdf, transmission, singularity_threshold);
continue;
} catch (const std::invalid_argument& e) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", e.what());
return false;
}
}
ROS_WARN_STREAM_NAMED("franka_hw_sim", "Unsupported transmission interface of joint '"
<< joint->name << "': " << k_interface);
}
}
// After all handles have been assigned to interfaces, register them
assert(this->eji_.getNames().size() >= 7);
assert(this->pji_.getNames().size() == 7);
assert(this->vji_.getNames().size() == 7);
assert(this->jsi_.getNames().size() >= 7);
assert(this->fsi_.getNames().size() == 1);
assert(this->fmi_.getNames().size() == 1);
registerInterface(&this->eji_);
registerInterface(&this->pji_);
registerInterface(&this->vji_);
registerInterface(&this->jsi_);
registerInterface(&this->fsi_);
registerInterface(&this->fmi_);
// Initialize ROS Services
initServices(model_nh);
verifier_ = std::make_unique<ControllerVerifier>(joints_, arm_id_);
return readParameters(model_nh, *urdf);
}
void FrankaHWSim::initJointStateHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->jsi_.registerHandle(hardware_interface::JointStateHandle(joint->name, &joint->position,
&joint->velocity, &joint->effort));
}
void FrankaHWSim::initEffortCommandHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->eji_.registerHandle(
hardware_interface::JointHandle(this->jsi_.getHandle(joint->name), &joint->command));
}
void FrankaHWSim::initPositionCommandHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->pji_.registerHandle(
hardware_interface::JointHandle(this->jsi_.getHandle(joint->name), &joint->desired_position));
}
void FrankaHWSim::initVelocityCommandHandle(const std::shared_ptr<franka_gazebo::Joint>& joint) {
this->vji_.registerHandle(
hardware_interface::JointHandle(this->jsi_.getHandle(joint->name), &joint->desired_velocity));
}
void FrankaHWSim::initFrankaStateHandle(
const std::string& robot,
const urdf::Model& urdf,
const transmission_interface::TransmissionInfo& transmission) {
if (transmission.joints_.size() != 7) {
throw std::invalid_argument(
"Cannot create franka_hw/FrankaStateInterface for robot '" + robot + "_robot' because " +
std::to_string(transmission.joints_.size()) +
" joints were found beneath the <transmission> tag, but 7 are required.");
}
// Initialize robot_mode to "Idle". Once a controller is started, we will switch to "Move"
this->robot_state_.robot_mode = franka::RobotMode::kIdle;
// Check if all joints defined in the <transmission> actually exist in the URDF
for (const auto& joint : transmission.joints_) {
if (not urdf.getJoint(joint.name_)) {
throw std::invalid_argument("Cannot create franka_hw/FrankaStateInterface for robot '" +
robot + "_robot' because the specified joint '" + joint.name_ +
"' in the <transmission> tag cannot be found in the URDF");
}
ROS_DEBUG_STREAM_NAMED("franka_hw_sim",
"Found joint " << joint.name_ << " to belong to a Panda robot");
}
this->fsi_.registerHandle(franka_hw::FrankaStateHandle(robot + "_robot", this->robot_state_));
}
void FrankaHWSim::initFrankaModelHandle(
const std::string& robot,
const urdf::Model& urdf,
const transmission_interface::TransmissionInfo& transmission,
double singularity_threshold) {
if (transmission.joints_.size() != 2) {
throw std::invalid_argument(
"Cannot create franka_hw/FrankaModelInterface for robot '" + robot + "_model' because " +
std::to_string(transmission.joints_.size()) +
" joints were found beneath the <transmission> tag, but 2 are required.");
}
for (const auto& joint : transmission.joints_) {
if (not urdf.getJoint(joint.name_)) {
if (not urdf.getJoint(joint.name_)) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" +
robot + "_model' because the specified joint '" + joint.name_ +
"' in the <transmission> tag cannot be found in the URDF");
}
}
}
auto root =
std::find_if(transmission.joints_.begin(), transmission.joints_.end(),
[&](const transmission_interface::JointInfo& i) { return i.role_ == "root"; });
if (root == transmission.joints_.end()) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" + robot +
"_model' because no <joint> with <role>root</root> can be found "
"in the <transmission>");
}
auto tip =
std::find_if(transmission.joints_.begin(), transmission.joints_.end(),
[&](const transmission_interface::JointInfo& i) { return i.role_ == "tip"; });
if (tip == transmission.joints_.end()) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" + robot +
"_model' because no <joint> with <role>tip</role> can be found "
"in the <transmission>");
}
try {
auto root_link = urdf.getJoint(root->name_)->parent_link_name;
auto tip_link = urdf.getJoint(tip->name_)->child_link_name;
this->model_ =
std::make_unique<franka_gazebo::ModelKDL>(urdf, root_link, tip_link, singularity_threshold);
} catch (const std::invalid_argument& e) {
throw std::invalid_argument("Cannot create franka_hw/FrankaModelInterface for robot '" + robot +
"_model'. " + e.what());
}
this->fmi_.registerHandle(
franka_hw::FrankaModelHandle(robot + "_model", *this->model_, this->robot_state_));
}
void FrankaHWSim::initServices(ros::NodeHandle& nh) {
this->service_set_ee_ =
nh.advertiseService<franka_msgs::SetEEFrame::Request, franka_msgs::SetEEFrame::Response>(
"set_EE_frame", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
this->arm_id_ << ": Setting NE_T_EE transformation");
std::copy(request.NE_T_EE.cbegin(), request.NE_T_EE.cend(),
this->robot_state_.NE_T_EE.begin());
this->updateRobotStateDynamics();
response.success = true;
return true;
});
this->service_set_k_ = franka_hw::advertiseService<franka_msgs::SetKFrame>(
nh, "set_K_frame", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim", this->arm_id_ << ": Setting EE_T_K transformation");
std::copy(request.EE_T_K.cbegin(), request.EE_T_K.cend(),
this->robot_state_.EE_T_K.begin());
this->updateRobotStateDynamics();
response.success = true;
return true;
});
this->service_set_load_ = franka_hw::advertiseService<franka_msgs::SetLoad>(
nh, "set_load", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim", this->arm_id_ << ": Setting Load");
this->robot_state_.m_load = request.mass;
std::copy(request.F_x_center_load.cbegin(), request.F_x_center_load.cend(),
this->robot_state_.F_x_Cload.begin());
std::copy(request.load_inertia.cbegin(), request.load_inertia.cend(),
this->robot_state_.I_load.begin());
this->updateRobotStateDynamics();
response.success = true;
return true;
});
this->service_collision_behavior_ =
franka_hw::advertiseService<franka_msgs::SetForceTorqueCollisionBehavior>(
nh, "set_force_torque_collision_behavior", [&](auto& request, auto& response) {
ROS_INFO_STREAM_NAMED("franka_hw_sim", this->arm_id_ << ": Setting Collision Behavior");
for (int i = 0; i < 7; i++) {
std::string name = this->arm_id_ + "_joint" + std::to_string(i + 1);
this->joints_[name]->contact_threshold =
request.lower_torque_thresholds_nominal.at(i);
this->joints_[name]->collision_threshold =
request.upper_torque_thresholds_nominal.at(i);
}
std::move(request.lower_force_thresholds_nominal.begin(),
request.lower_force_thresholds_nominal.end(),
this->lower_force_thresholds_nominal_.begin());
std::move(request.upper_force_thresholds_nominal.begin(),
request.upper_force_thresholds_nominal.end(),
this->upper_force_thresholds_nominal_.begin());
response.success = true;
return true;
});
this->service_user_stop_ =
nh.advertiseService<std_srvs::SetBool::Request, std_srvs::SetBool::Response>(
"set_user_stop", [&](auto& request, auto& response) {
this->sm_.process_event(UserStop{static_cast<bool>(request.data)});
response.success = true;
return true;
});
this->service_controller_list_ = nh.serviceClient<controller_manager_msgs::ListControllers>(
"controller_manager/list_controllers");
this->service_controller_switch_ = nh.serviceClient<controller_manager_msgs::SwitchController>(
"controller_manager/switch_controller");
}
void FrankaHWSim::restartControllers() {
// Restart controllers by stopping and starting all running ones
auto name = this->service_controller_list_.getService();
if (not this->service_controller_list_.waitForExistence(ros::Duration(3))) {
throw std::runtime_error("Cannot find service '" + name +
"'. Is the controller_manager running?");
}
controller_manager_msgs::ListControllers list;
if (not this->service_controller_list_.call(list)) {
throw std::runtime_error("Service call '" + name + "' failed");
}
controller_manager_msgs::SwitchController swtch;
for (const auto& controller : list.response.controller) {
if (controller.state != "running") {
continue;
}
swtch.request.stop_controllers.push_back(controller.name);
swtch.request.start_controllers.push_back(controller.name);
}
swtch.request.start_asap = static_cast<decltype(swtch.request.start_asap)>(true);
swtch.request.strictness = controller_manager_msgs::SwitchControllerRequest::STRICT;
if (not this->service_controller_switch_.call(swtch) or
not static_cast<bool>(swtch.response.ok)) {
throw std::runtime_error("Service call '" + this->service_controller_switch_.getService() +
"' failed");
}
}
void FrankaHWSim::readSim(ros::Time time, ros::Duration period) {
for (const auto& pair : this->joints_) {
auto joint = pair.second;
joint->update(period);
}
this->updateRobotState(time);
}
double FrankaHWSim::positionControl(Joint& joint, double setpoint, const ros::Duration& period) {
double error;
const double kJointLowerLimit = joint.limits.min_position;
const double kJointUpperLimit = joint.limits.max_position;
switch (joint.type) {
case urdf::Joint::REVOLUTE:
angles::shortest_angular_distance_with_limits(joint.position, setpoint, kJointLowerLimit,
kJointUpperLimit, error);
break;
case urdf::Joint::PRISMATIC:
error =
boost::algorithm::clamp(setpoint - joint.position, kJointLowerLimit, kJointUpperLimit);
break;
default:
std::string error_message =
"Only revolute or prismatic joints are allowed for position control right now";
ROS_FATAL("%s", error_message.c_str());
throw std::invalid_argument(error_message);
}
return boost::algorithm::clamp(joint.position_controller.computeCommand(error, period),
-joint.limits.max_effort, joint.limits.max_effort);
}
double FrankaHWSim::velocityControl(Joint& joint, double setpoint, const ros::Duration& period) {
return boost::algorithm::clamp(
joint.velocity_controller.computeCommand(setpoint - joint.velocity, period),
-joint.limits.max_effort, joint.limits.max_effort);
}
void FrankaHWSim::writeSim(ros::Time /*time*/, ros::Duration period) {
auto g = this->model_->gravity(this->robot_state_, this->gravity_earth_);
for (auto& pair : this->joints_) {
auto joint = pair.second;
// Retrieve effort control command
double effort = 0;
// Finger joints must still be controllable from franka_gripper_sim controller
if (not sm_.is(state<Move>) and not contains(pair.first, "finger_joint")) {
effort = positionControl(*joint, joint->stop_position, period);
} else if (joint->control_method == POSITION) {
effort = positionControl(*joint, joint->desired_position, period);
} else if (joint->control_method == VELOCITY) {
velocityControl(*joint, joint->desired_velocity, period);
} else if (joint->control_method == EFFORT) {
// Feed-forward commands in effort control
effort = joint->command;
}
// Check if this joint is affected by gravity compensation
std::string prefix = this->arm_id_ + "_joint";
if (pair.first.rfind(prefix, 0) != std::string::npos) {
int i = std::stoi(pair.first.substr(prefix.size())) - 1;
joint->gravity = g.at(i);
}
effort += joint->gravity;
// Send control effort control command
if (not std::isfinite(effort)) {
ROS_WARN_STREAM_NAMED("franka_hw_sim",
"Command for " << joint->name << "is not finite, won't send to robot");
continue;
}
joint->handle->SetForce(0, effort);
}
}
void FrankaHWSim::eStopActive(bool /* active */) {}
bool FrankaHWSim::readParameters(const ros::NodeHandle& nh, const urdf::Model& urdf) {
try {
guessEndEffector(nh, urdf);
nh.param<double>("m_load", this->robot_state_.m_load, 0);
std::string I_load; // NOLINT [readability-identifier-naming]
nh.param<std::string>("I_load", I_load, "0 0 0 0 0 0 0 0 0");
this->robot_state_.I_load = readArray<9>(I_load, "I_load");
std::string F_x_Cload; // NOLINT [readability-identifier-naming]
nh.param<std::string>("F_x_Cload", F_x_Cload, "0 0 0");
this->robot_state_.F_x_Cload = readArray<3>(F_x_Cload, "F_x_Cload");
std::string NE_T_EE; // NOLINT [readability-identifier-naming]
nh.param<std::string>("NE_T_EE", NE_T_EE, "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1");
this->robot_state_.NE_T_EE = readArray<16>(NE_T_EE, "NE_T_EE");
std::string EE_T_K; // NOLINT [readability-identifier-naming]
nh.param<std::string>("EE_T_K", EE_T_K, "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1");
this->robot_state_.EE_T_K = readArray<16>(EE_T_K, "EE_T_K");
std::string gravity_vector;
if (nh.getParam("gravity_vector", gravity_vector)) {
this->gravity_earth_ = readArray<3>(gravity_vector, "gravity_vector");
}
// Only nominal cases supported for now
std::vector<double> lower_torque_thresholds = franka_hw::FrankaHW::getCollisionThresholds(
"lower_torque_thresholds_nominal", nh, {20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0});
std::vector<double> upper_torque_thresholds = franka_hw::FrankaHW::getCollisionThresholds(
"upper_torque_thresholds_nominal", nh, {20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0});
this->lower_force_thresholds_nominal_ = franka_hw::FrankaHW::getCollisionThresholds(
"lower_force_thresholds_nominal", nh, {20.0, 20.0, 20.0, 25.0, 25.0, 25.0});
this->upper_force_thresholds_nominal_ = franka_hw::FrankaHW::getCollisionThresholds(
"upper_force_thresholds_nominal", nh, {20.0, 20.0, 20.0, 25.0, 25.0, 25.0});
for (int i = 0; i < 7; i++) {
std::string name = this->arm_id_ + "_joint" + std::to_string(i + 1);
this->joints_[name]->contact_threshold = lower_torque_thresholds.at(i);
this->joints_[name]->collision_threshold = upper_torque_thresholds.at(i);
}
} catch (const std::invalid_argument& e) {
ROS_ERROR_STREAM_NAMED("franka_hw_sim", e.what());
return false;
}
updateRobotStateDynamics();
return true;
}
void FrankaHWSim::guessEndEffector(const ros::NodeHandle& nh, const urdf::Model& urdf) {
auto hand_link = this->arm_id_ + "_hand";
auto hand = urdf.getLink(hand_link);
if (hand != nullptr) {
ROS_INFO_STREAM_NAMED("franka_hw_sim",
"Found link '" << hand_link
<< "' in URDF. Assuming it is defining the kinematics & "
"inertias of a Franka Hand Gripper.");
}
// By absolute default unless URDF or ROS params say otherwise, assume no end-effector.
double def_m_ee = 0;
std::string def_i_ee = "0.0 0 0 0 0.0 0 0 0 0.0";
std::string def_f_x_cee = "0 0 0";
std::string def_f_t_ne = "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1";
if (not nh.hasParam("F_T_NE") and hand != nullptr) {
// NOTE: We cannot interprete the Joint pose from the URDF directly, because
// its <arm_id>_link is mounted at the flange directly and not at NE
def_f_t_ne = "0.7071 -0.7071 0 0 0.7071 0.7071 0 0 0 0 1 0 0 0 0.1034 1";
}
std::string F_T_NE; // NOLINT [readability-identifier-naming]
nh.param<std::string>("F_T_NE", F_T_NE, def_f_t_ne);
this->robot_state_.F_T_NE = readArray<16>(F_T_NE, "F_T_NE");
if (not nh.hasParam("m_ee") and hand != nullptr) {
if (hand->inertial == nullptr) {
throw std::invalid_argument("Trying to use inertia of " + hand_link +
" but this link has no <inertial> tag defined in it.");
}
def_m_ee = hand->inertial->mass;
}
nh.param<double>("m_ee", this->robot_state_.m_ee, def_m_ee);
if (not nh.hasParam("I_ee") and hand != nullptr) {
if (hand->inertial == nullptr) {
throw std::invalid_argument("Trying to use inertia of " + hand_link +
" but this link has no <inertial> tag defined in it.");
}
// clang-format off
def_i_ee = std::to_string(hand->inertial->ixx) + " " + std::to_string(hand->inertial->ixy) + " " + std::to_string(hand->inertial->ixz) + " "
+ std::to_string(hand->inertial->ixy) + " " + std::to_string(hand->inertial->iyy) + " " + std::to_string(hand->inertial->iyz) + " "
+ std::to_string(hand->inertial->ixz) + " " + std::to_string(hand->inertial->iyz) + " " + std::to_string(hand->inertial->izz);
// clang-format on
}
std::string I_ee; // NOLINT [readability-identifier-naming]
nh.param<std::string>("I_ee", I_ee, def_i_ee);
this->robot_state_.I_ee = readArray<9>(I_ee, "I_ee");
if (not nh.hasParam("F_x_Cee") and hand != nullptr) {
if (hand->inertial == nullptr) {
throw std::invalid_argument("Trying to use inertia of " + hand_link +
" but this link has no <inertial> tag defined in it.");
}
def_f_x_cee = std::to_string(hand->inertial->origin.position.x) + " " +
std::to_string(hand->inertial->origin.position.y) + " " +
std::to_string(hand->inertial->origin.position.z);
}
std::string F_x_Cee; // NOLINT [readability-identifier-naming]
nh.param<std::string>("F_x_Cee", F_x_Cee, def_f_x_cee);
this->robot_state_.F_x_Cee = readArray<3>(F_x_Cee, "F_x_Cee");
}
void FrankaHWSim::updateRobotStateDynamics() {
this->robot_state_.m_total = this->robot_state_.m_ee + this->robot_state_.m_load;
Eigen::Map<Eigen::Matrix4d>(this->robot_state_.F_T_EE.data()) =
Eigen::Matrix4d(this->robot_state_.F_T_NE.data()) *
Eigen::Matrix4d(this->robot_state_.NE_T_EE.data());
Eigen::Map<Eigen::Matrix3d>(this->robot_state_.I_total.data()) =
shiftInertiaTensor(Eigen::Matrix3d(this->robot_state_.I_ee.data()), this->robot_state_.m_ee,
Eigen::Vector3d(this->robot_state_.F_x_Cload.data()));
}
void FrankaHWSim::updateRobotState(ros::Time time) {
// This is ensured, because a FrankaStateInterface checks for at least seven joints in the URDF
assert(this->joints_.size() >= 7);
auto mode = this->robot_state_.robot_mode;
for (int i = 0; i < 7; i++) {
std::string name = this->arm_id_ + "_joint" + std::to_string(i + 1);
const auto& joint = this->joints_.at(name);
this->robot_state_.q[i] = joint->position;
this->robot_state_.dq[i] = joint->velocity;
this->robot_state_.tau_J[i] = joint->effort;
this->robot_state_.dtau_J[i] = joint->jerk;
this->robot_state_.q_d[i] = joint->getDesiredPosition(mode);
this->robot_state_.dq_d[i] = joint->getDesiredVelocity(mode);
this->robot_state_.ddq_d[i] = joint->getDesiredAcceleration(mode);
this->robot_state_.tau_J_d[i] = joint->getDesiredTorque(mode);
// For now we assume no flexible joints
this->robot_state_.theta[i] = joint->position;
this->robot_state_.dtheta[i] = joint->velocity;
// first time initialization of the desired position
if (not this->robot_initialized_) {
joint->desired_position = joint->position;
joint->stop_position = joint->position;
}
if (this->robot_initialized_) {
double tau_ext = joint->effort - joint->command + joint->gravity;
// Exponential moving average filter from tau_ext -> tau_ext_hat_filtered
this->robot_state_.tau_ext_hat_filtered[i] =
this->tau_ext_lowpass_filter_ * tau_ext +
(1 - this->tau_ext_lowpass_filter_) * this->robot_state_.tau_ext_hat_filtered[i];
}
this->robot_state_.joint_contact[i] = static_cast<double>(joint->isInContact());
this->robot_state_.joint_collision[i] = static_cast<double>(joint->isInCollision());
}
// Calculate estimated wrenches in Task frame from external joint torques with jacobians
Eigen::Map<Eigen::Matrix<double, 7, 1>> tau_ext(this->robot_state_.tau_ext_hat_filtered.data());
Eigen::MatrixXd j0_transpose_pinv;
Eigen::MatrixXd jk_transpose_pinv;
Eigen::Matrix<double, 6, 7> j0(
this->model_->zeroJacobian(franka::Frame::kStiffness, this->robot_state_).data());
Eigen::Matrix<double, 6, 7> jk(
this->model_->bodyJacobian(franka::Frame::kStiffness, this->robot_state_).data());
franka_example_controllers::pseudoInverse(j0.transpose(), j0_transpose_pinv);
franka_example_controllers::pseudoInverse(jk.transpose(), jk_transpose_pinv);
Eigen::VectorXd f_ext_0 = j0_transpose_pinv * tau_ext;
Eigen::VectorXd f_ext_k = jk_transpose_pinv * tau_ext;
Eigen::VectorXd::Map(&this->robot_state_.O_F_ext_hat_K[0], 6) = f_ext_0;
Eigen::VectorXd::Map(&this->robot_state_.K_F_ext_hat_K[0], 6) = f_ext_k;
for (int i = 0; i < this->robot_state_.cartesian_contact.size(); i++) {
// Evaluate the cartesian contacts/collisions in K frame
double fi = std::abs(f_ext_k(i));
this->robot_state_.cartesian_contact[i] =
static_cast<double>(fi > this->lower_force_thresholds_nominal_.at(i));
this->robot_state_.cartesian_collision[i] =
static_cast<double>(fi > this->upper_force_thresholds_nominal_.at(i));
}
this->robot_state_.control_command_success_rate = 1.0;
this->robot_state_.time = franka::Duration(time.toNSec() / 1e6 /*ms*/);
this->robot_state_.O_T_EE = this->model_->pose(franka::Frame::kEndEffector, this->robot_state_);
#ifdef ENABLE_BASE_ACCELERATION
// This will always be {0,0,-9.81} on the real robot as it cannot be mounted differently for now
this->robot_state_.O_ddP_O = this->gravity_earth_;
#endif
std_msgs::Bool msg;
msg.data = static_cast<decltype(msg.data)>(true);
this->robot_initialized_ = true;
this->robot_initialized_pub_.publish(msg);
}
bool FrankaHWSim::prepareSwitch(
const std::list<hardware_interface::ControllerInfo>& start_list,
const std::list<hardware_interface::ControllerInfo>& /*stop_list*/) {
return std::all_of(start_list.cbegin(), start_list.cend(), [this](const auto& controller) {
return verifier_->isValidController(controller);
});
}
void FrankaHWSim::doSwitch(const std::list<hardware_interface::ControllerInfo>& start_list,
const std::list<hardware_interface::ControllerInfo>& stop_list) {
forControlledJoint(stop_list, [](franka_gazebo::Joint& joint, const ControlMethod& /*method*/) {
joint.control_method = boost::none;
joint.stop_position = joint.position;
joint.desired_position = joint.position;
joint.desired_velocity = 0;
});
forControlledJoint(start_list, [](franka_gazebo::Joint& joint, const ControlMethod& method) {
joint.control_method = method;
// sets the desired joint position once for the effort interface
joint.desired_position = joint.position;
joint.desired_velocity = 0;
});
this->sm_.process_event(SwitchControl());
}
void FrankaHWSim::forControlledJoint(
const std::list<hardware_interface::ControllerInfo>& controllers,
const std::function<void(franka_gazebo::Joint& joint, const ControlMethod&)>& f) {
for (const auto& controller : controllers) {
if (not verifier_->isClaimingArmController(controller)) {
continue;
}
for (const auto& resource : controller.claimed_resources) {
auto control_method = ControllerVerifier::determineControlMethod(resource.hardware_interface);
if (not control_method) {
continue;
}
for (const auto& joint_name : resource.resources) {
auto& joint = joints_.at(joint_name);
f(*joint, control_method.value());
}
}
}
}
} // namespace franka_gazebo
PLUGINLIB_EXPORT_CLASS(franka_gazebo::FrankaHWSim, gazebo_ros_control::RobotHWSim)
|
/*-
* Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS 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 <assert.h>
#include <config.h>
#include <string.h>
#include <algorithm>
#include "IO.h"
#include "Camera.h"
#include "CameraException.h"
#if ENABLE_VIDEO
#include <video/VideoDecoder.h>
#endif
using namespace std;
namespace wcl
{
/**
* Helper function to sort the configuration list
*/
static bool configurationSort ( Camera::Configuration a, Camera::Configuration b)
{
if(((int)a.format) > (int)b.format)
return true;
if(((int)a.format) < (int)b.format)
return false;
// Format Equal
if(a.format == Camera::FORMAT7){
if ( ((int)a.format7.format) > ((int)b.format7.format))
return true;
if ( ((int)a.format7.format) < ((int)b.format7.format))
return false;
// Format Equal
if( a.format7.xMax > b.format7.xMax )
return true;
else
return false;
} else {
if ( a.width > b.width )
return true;
if( a.width < b.width )
return false;
// Width Equal
if ( a.height > b.height )
return true;
if( a.height < b.height )
return false;
// Height Equal
if( a.fps > b.fps )
return true;
// Equal or < fps
return false;
}
}
struct Camera::Priv
{
#if ENABLE_VIDEO
VideoDecoder *decoder;
#endif
};
Camera::CameraBuffer::CameraBuffer():
start(0)
{}
Camera::Camera() :
buffers(NULL),
bufferSize(0),
numBuffers(0),
areParametersSet(false),
currentFrame(NULL),
conversionBuffer(NULL),
internal(NULL)
{
}
Camera::~Camera()
{
this->destroyBuffers();
if(this->conversionBuffer != NULL){
delete (unsigned char *)this->conversionBuffer->start;
delete this->conversionBuffer;
}
if(this->internal){
#if ENABLE_VIDEO
delete this->internal->decoder;
#endif
delete this->internal;
}
}
void Camera::allocateBuffers(const size_t size, const unsigned count)
{
this->destroyBuffers();
this->buffers = new CameraBuffer[count];
for(unsigned i =0; i < count; i++)
this->buffers[i].length = size;
}
void Camera::destroyBuffers()
{
if( this->buffers )
delete [] this->buffers;
this->buffers = NULL;
this->numBuffers=0;
}
Camera::CameraParameters Camera::getParameters() const
{
return this->parameters;
}
int Camera::convertPixelYUYV422toRGB8(const int y, const int u, const int v )
{
unsigned int pixel32 = 0;
unsigned char *pixel = (unsigned char *)&pixel32;
int r, g, b;
r = y + (1.370705 * (v-128));
g = y - (0.698001 * (v-128)) - (0.337633 * (u-128));
b = y + (1.732446 * (u-128));
if(r > 255) r = 255;
if(g > 255) g = 255;
if(b > 255) b = 255;
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
pixel[0] = r * 220 / 256;
pixel[1] = g * 220 / 256;
pixel[2] = b * 220 / 256;
return pixel32;
}
void Camera::convertImageYUYV411toRGB8(const unsigned char *yuv, unsigned char *rgb,
const unsigned int width, const unsigned int height)
{
unsigned int in = 0;
unsigned int out = 0;
unsigned char pixel_24[3];
unsigned int pixel32;
int y1, y2, y3, y4, u, v;
for(in = 0; in < (6 * width * height / 4); in += 6)
{
u = yuv[in];
y1 = yuv[in+1];
y2 = yuv[in+2];
v = yuv[in+3];
y3 = yuv[in+4];
y4 = yuv[in+5];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y1, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y2, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y3, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y4, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
}
}
void Camera::convertImageYUYV422toRGB8(const unsigned char *yuv, unsigned char *rgb,
const unsigned int width, const unsigned int height)
{
unsigned int in = 0;
unsigned int out = 0;
unsigned int pixel_16;
unsigned char pixel_24[3];
unsigned int pixel32;
int y0, u, y1, v;
for(in = 0; in < width * height * 2; in += 4)
{
pixel_16 =
yuv[in + 3] << 24 |
yuv[in + 2] << 16 |
yuv[in + 1] << 8 |
yuv[in + 0];
y0 = (pixel_16 & 0x000000ff);
u = (pixel_16 & 0x0000ff00) >> 8;
y1 = (pixel_16 & 0x00ff0000) >> 16;
v = (pixel_16 & 0xff000000) >> 24;
pixel32 = Camera::convertPixelYUYV422toRGB8(y0, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
pixel32 = Camera::convertPixelYUYV422toRGB8(y1, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
}
}
void Camera::convertImageMONO8toRGB8( const unsigned char *mono, unsigned char *rgb,
const unsigned int width, const unsigned int height )
{
unsigned int in = 0;
unsigned int out = 0;
for(in = 0; in < width * height; in++ )
{
rgb[out+0]=mono[in];
rgb[out+1]=mono[in];
rgb[out+2]=mono[in];
out+=3;
}
}
void Camera::convertImageRGB8toMONO8(const unsigned char* rgb, unsigned char* mono, const unsigned width, const unsigned height)
{
unsigned int in = 0;
unsigned int out = 0;
for (out = 0; out < width*height; ++out)
{
mono[out] = (unsigned char) (rgb[in]*0.3 + rgb[in+1]*0.59 + rgb[in+2]*0.11);
in+=3;
}
}
void Camera::setConfiguration(const Configuration &c)
{
assert ( (c.format == FORMAT7 && c.format7.xMax > 0 && c.format7.yMax > 0 && c.format7.xOffset >= 0 && c.format7.yOffset >= 0 ) ||
( c.format != FORMAT7 && c.width > 0 && c.height > 0 && c.fps > 0));
this->activeConfiguration = c;
}
std::vector<Camera::Configuration> Camera::getSupportedConfigurations() const
{
return this->supportedConfigurations;
}
Camera::Configuration Camera::findConfiguration(Camera::Configuration partialConfig) const
{
for (std::vector<Configuration>::const_iterator it = supportedConfigurations.begin(); it < supportedConfigurations.end(); ++it)
{
// does this config match what we are looking for?
if( partialConfig.format == FORMAT7 ){
if(partialConfig.format7.format != ANY && (*it).format7.format != partialConfig.format7.format)
continue;
if (partialConfig.format7.xMax != 0 && (*it).format7.xMax > partialConfig.format7.xMax)
continue;
if (partialConfig.format7.yMax != 0 && (*it).format7.yMax > partialConfig.format7.yMax)
continue;
return *it;
} else {
if (partialConfig.format != ANY && (*it).format != partialConfig.format)
continue;
if (partialConfig.width != 0 && (*it).width != partialConfig.width)
continue;
if (partialConfig.height != 0 && (*it).height != partialConfig.height)
continue;
if (partialConfig.fps != 0 && (*it).fps != partialConfig.fps)
continue;
// matches everything we asked for!
return *it;
}
}
throw CameraException(CameraException::INVALIDCONFIGURATION);
}
/**
* Perform a software conversion of the frame to the requested format.
* The first call to this function is expensive as an internal buffer must be
* setup to support the conversion. Successive calls with the same format
* only incur the performance hit of the conversion. Changing image formats
* will also incurr an reallocation performance hit.
*
* @param f The format to convert the frame too
* @return A pointer to the converted frame
*/
const unsigned char* Camera::getFrame()
{
update();
return currentFrame;
}
const unsigned char *Camera::getFrame(const ImageFormat f )
{
update();
// Handle the same image format being requested
if( this->activeConfiguration.format == f )
return currentFrame;
unsigned width = this->activeConfiguration.width;
unsigned height = this->activeConfiguration.height;
this->setupConversionBuffer(this->getFormatBufferSize(f));
unsigned char *buffer=(unsigned char *)this->conversionBuffer->start;
switch( f ){
case RGB8:
{
switch( this->activeConfiguration.format){
case MONO8:
convertImageMONO8toRGB8(currentFrame, buffer, width, height);
return buffer;
case YUYV422:
convertImageYUYV422toRGB8( currentFrame, buffer, width, height);
return buffer;
case YUYV411:
convertImageYUYV411toRGB8( currentFrame, buffer, width, height);
return buffer;
#if ENABLE_VIDEO
case MJPEG:{
// Init the video decoder on the first MJPEG decoding frame
if( this->internal == NULL){
this->internal = new Priv;
this->internal->decoder = new VideoDecoder(width, height,CODEC_ID_MJPEG, false );
}
internal->decoder->nextFrame(currentFrame, this->getFormatBufferSize());
return internal->decoder->getFrame();
}
#endif
default:
;
}
goto NOTIMP;
}
case MJPEG:
case YUYV422:
case YUYV411:
case RGB16:
case RGB32:
case BGR8:
case MONO8:
{
switch( this->activeConfiguration.format ){
case RGB8:
convertImageRGB8toMONO8(currentFrame,buffer,width,height);
return buffer;
case YUYV422:
{
//create a temporary buffer
unsigned char *temp = new unsigned char[getFormatBufferSize(RGB8)];
convertImageYUYV422toRGB8(currentFrame, temp, width, height);
convertImageRGB8toMONO8(temp, buffer, width, height);
delete [] temp;
return buffer;
}
case MJPEG:
{
#if ENABLE_VIDEO
VideoDecoder dec(width, height,CODEC_ID_MJPEG, false );
dec.nextFrame(currentFrame, this->getFormatBufferSize());
convertImageRGB8toMONO8(dec.getFrame(), buffer, width, height);
return buffer;
#endif
}
default:
;
}
goto NOTIMP;
}
case MONO16:
default:
NOTIMP:
assert(0 && "Camera::getFrame(const ImageFormat) - Requested Conversion Not Implemented");
}
return NULL;
}
const unsigned char* Camera::getCurrentFrame() const
{
return currentFrame;
}
void Camera::getCurrentFrame(unsigned char* buffer, const ImageFormat& format) const
{
// Handle the case where this method is called before any other
// method that actually performs a capture. If the currentFrame
// is not set then most the conversions below will fail
if(this->currentFrame == NULL ){
buffer = NULL;
return;
}
// Handle the same image format being requested
if( this->activeConfiguration.format == format )
{
memcpy(buffer, currentFrame, getFormatBufferSize());
return;
}
unsigned width = this->activeConfiguration.width;
unsigned height = this->activeConfiguration.height;
unsigned char* temp;
switch( format ){
case RGB8:
{
switch( this->activeConfiguration.format){
case MONO8:
convertImageMONO8toRGB8(currentFrame, buffer, width, height);
return;
case YUYV422:
convertImageYUYV422toRGB8( currentFrame, buffer, width, height);
return;
case YUYV411:
convertImageYUYV411toRGB8( currentFrame, buffer, width, height);
return;
#if ENABLE_VIDEO
case MJPEG:{
// Init the video decoder on the first MJPEG decoding frame
VideoDecoder decoder(width, height,CODEC_ID_MJPEG, false );
decoder.nextFrame(currentFrame, this->getFormatBufferSize());
memcpy(buffer, decoder.getFrame(), getFormatBufferSize(format));
return;
}
#endif
default:
;
}
goto NOTIMP;
}
case MJPEG:
case YUYV422:
case YUYV411:
case RGB16:
case RGB32:
case BGR8:
case MONO8:
switch (this->activeConfiguration.format)
{
case RGB8:
convertImageRGB8toMONO8(currentFrame, buffer, width, height);
return;
case YUYV422:
//create a temporary buffer
temp = new unsigned char[getFormatBufferSize(RGB8)];
convertImageYUYV422toRGB8(currentFrame, temp, width, height);
convertImageRGB8toMONO8(temp, buffer, width, height);
delete [] temp;
return;
case MJPEG:
{
#if ENABLE_VIDEO
VideoDecoder dec(width, height,CODEC_ID_MJPEG, false );
dec.nextFrame(currentFrame, this->getFormatBufferSize());
convertImageRGB8toMONO8(dec.getFrame(), buffer, width, height);
return;
#endif
}
default:
;
}
goto NOTIMP;
break;
case MONO16:
default:
NOTIMP:
assert(0 && "Camera::getFrame(const ImageFormat) - Requested Conversion Not Implemented");
}
}
unsigned Camera::getFormatBytesPerPixel() const
{
return Camera::getFormatBytesPerPixel(this->activeConfiguration.format);
}
unsigned Camera::getFormatBytesPerPixel(const ImageFormat f ) const
{
switch( f ){
case RGB8:
return 3;
case RGB16:
return 6;
case RGB32:
return 12;
case BGR8:
return 3;
case MONO8:
return 1;
case MONO16:
return 2;
case YUYV422:
return 4;
case YUYV411:
return 4;
case MJPEG:
return 12;
case RAW8:
return 3;
case RAW16:
return 6;
default:
return 0;
}
}
unsigned Camera::getFormatBufferSize() const
{
return Camera::getFormatBufferSize( this->activeConfiguration.format);
}
unsigned Camera::getFormatBufferSize(const ImageFormat f ) const
{
return (this->getFormatBytesPerPixel(f) *
this->getActiveConfiguration().width *
this->activeConfiguration.height);
}
void Camera::setupConversionBuffer( const size_t buffersize )
{
if( this->conversionBuffer ){
if( this->conversionBuffer->length >= buffersize )
return;
delete this->conversionBuffer;
}
this->conversionBuffer = new CameraBuffer;
this->conversionBuffer->length = buffersize;
this->conversionBuffer->start = (void *)new unsigned char[buffersize];
}
bool Camera::hasParameters() const { return areParametersSet; }
void Camera::setParameters(const Camera::CameraParameters& p) {
areParametersSet = true;
this->parameters = p;
}
void Camera::printFormat7(const Format7 f,const bool inUse)
{
if(inUse)
wclclog << "FORMAT7 (" << this->imageFormatToString(f.format) << ") "
<< " Region: (" << f.xOffset << "," << f.yOffset << ")"
<< " -> (" << f.xMax << "," << f.yMax << ")";
else
wclclog << "FORMAT7 (" << this->imageFormatToString(f.format) << ") "
<< " Region Available: (" << f.xOffset << "," << f.yOffset << ")"
<< " -> (" << f.xMax << "," << f.yMax << ")"
<< " OffsetStepSize: (" << f.xOffsetStepSize << "," << f.yOffsetStepSize << ")"
<< " ExtentStepSize: (" << f.xStepSize << "," << f.yStepSize << ")";
}
void Camera::printDetails(bool state)
{
Configuration a = this->getActiveConfiguration();
wclclog << "Camera ID:" << this->id << " (" << this->getTypeIdentifier() << ") |";
if( a.format == FORMAT7)
this->printFormat7(a.format7,true);
else
wclclog<< this->imageFormatToString(a.format) << ":" << a.width << "x" << a.height << "@" << a.fps;
wclclog << endl;
if ( state ){
sort(this->supportedConfigurations.begin(),
this->supportedConfigurations.end(), configurationSort);
wclcout << "Features/Modes" << endl;
for(std::vector<Configuration>::iterator it =
supportedConfigurations.begin(); it !=
supportedConfigurations.end(); ++it ){
Configuration c = *it;
if(c.format == FORMAT7 ){
wclclog << "\t";
this->printFormat7(c.format7,false);
wclclog << endl;
} else {
if( it == supportedConfigurations.begin()){
wclclog << "\t" << this->imageFormatToString(c.format) << " " << c.width << "x" << c.height << " @" << c.fps;
}
else {
--it;
Configuration prev = *it;
++it;
if( c.format == prev.format && c.width == prev.width && c.height == prev.height )
wclclog << "," << c.fps;
else {
wclclog << endl;
wclclog << "\t" << this->imageFormatToString(c.format) << " "
<< c.width << "x" << c.height << " @" << c.fps;
}
}
}
}
wclclog << endl;
}
}
const char *Camera::imageFormatToString(const ImageFormat f )
{
switch(f)
{
case MJPEG: return "MJPEG";
case YUYV411: return "YUYV411";
case YUYV422: return "YUYV422";
case YUYV444: return "YUYV444";
case RGB8: return "RGB8";
case RGB16: return "RGB16";
case RGB32: return "RGB32";
case BGR8: return "BGR8";
case MONO8: return "MONO8";
case MONO16: return "MONO16";
case RAW8: return "RAW8";
case RAW16: return "RAW16";
case FORMAT7: return "FORMAT7";
case ANY:
default:
return "UNKNOWN:";
};
}
}
camera: With format 7 frame rate can't be specified hence we don't check for it
/*-
* Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS 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 <assert.h>
#include <config.h>
#include <string.h>
#include <algorithm>
#include "IO.h"
#include "Camera.h"
#include "CameraException.h"
#if ENABLE_VIDEO
#include <video/VideoDecoder.h>
#endif
using namespace std;
namespace wcl
{
/**
* Helper function to sort the configuration list
*/
static bool configurationSort ( Camera::Configuration a, Camera::Configuration b)
{
if(((int)a.format) > (int)b.format)
return true;
if(((int)a.format) < (int)b.format)
return false;
// Format Equal
if(a.format == Camera::FORMAT7){
if ( ((int)a.format7.format) > ((int)b.format7.format))
return true;
if ( ((int)a.format7.format) < ((int)b.format7.format))
return false;
// Format Equal
if( a.format7.xMax > b.format7.xMax )
return true;
else
return false;
} else {
if ( a.width > b.width )
return true;
if( a.width < b.width )
return false;
// Width Equal
if ( a.height > b.height )
return true;
if( a.height < b.height )
return false;
// Height Equal
if( a.fps > b.fps )
return true;
// Equal or < fps
return false;
}
}
struct Camera::Priv
{
#if ENABLE_VIDEO
VideoDecoder *decoder;
#endif
};
Camera::CameraBuffer::CameraBuffer():
start(0)
{}
Camera::Camera() :
buffers(NULL),
bufferSize(0),
numBuffers(0),
areParametersSet(false),
currentFrame(NULL),
conversionBuffer(NULL),
internal(NULL)
{
}
Camera::~Camera()
{
this->destroyBuffers();
if(this->conversionBuffer != NULL){
delete (unsigned char *)this->conversionBuffer->start;
delete this->conversionBuffer;
}
if(this->internal){
#if ENABLE_VIDEO
delete this->internal->decoder;
#endif
delete this->internal;
}
}
void Camera::allocateBuffers(const size_t size, const unsigned count)
{
this->destroyBuffers();
this->buffers = new CameraBuffer[count];
for(unsigned i =0; i < count; i++)
this->buffers[i].length = size;
}
void Camera::destroyBuffers()
{
if( this->buffers )
delete [] this->buffers;
this->buffers = NULL;
this->numBuffers=0;
}
Camera::CameraParameters Camera::getParameters() const
{
return this->parameters;
}
int Camera::convertPixelYUYV422toRGB8(const int y, const int u, const int v )
{
unsigned int pixel32 = 0;
unsigned char *pixel = (unsigned char *)&pixel32;
int r, g, b;
r = y + (1.370705 * (v-128));
g = y - (0.698001 * (v-128)) - (0.337633 * (u-128));
b = y + (1.732446 * (u-128));
if(r > 255) r = 255;
if(g > 255) g = 255;
if(b > 255) b = 255;
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
pixel[0] = r * 220 / 256;
pixel[1] = g * 220 / 256;
pixel[2] = b * 220 / 256;
return pixel32;
}
void Camera::convertImageYUYV411toRGB8(const unsigned char *yuv, unsigned char *rgb,
const unsigned int width, const unsigned int height)
{
unsigned int in = 0;
unsigned int out = 0;
unsigned char pixel_24[3];
unsigned int pixel32;
int y1, y2, y3, y4, u, v;
for(in = 0; in < (6 * width * height / 4); in += 6)
{
u = yuv[in];
y1 = yuv[in+1];
y2 = yuv[in+2];
v = yuv[in+3];
y3 = yuv[in+4];
y4 = yuv[in+5];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y1, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y2, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y3, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
//Convert formats and push into chars.
pixel32 = Camera::convertPixelYUYV422toRGB8(y4, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
//Push out.
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
}
}
void Camera::convertImageYUYV422toRGB8(const unsigned char *yuv, unsigned char *rgb,
const unsigned int width, const unsigned int height)
{
unsigned int in = 0;
unsigned int out = 0;
unsigned int pixel_16;
unsigned char pixel_24[3];
unsigned int pixel32;
int y0, u, y1, v;
for(in = 0; in < width * height * 2; in += 4)
{
pixel_16 =
yuv[in + 3] << 24 |
yuv[in + 2] << 16 |
yuv[in + 1] << 8 |
yuv[in + 0];
y0 = (pixel_16 & 0x000000ff);
u = (pixel_16 & 0x0000ff00) >> 8;
y1 = (pixel_16 & 0x00ff0000) >> 16;
v = (pixel_16 & 0xff000000) >> 24;
pixel32 = Camera::convertPixelYUYV422toRGB8(y0, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
pixel32 = Camera::convertPixelYUYV422toRGB8(y1, u, v);
pixel_24[0] = (pixel32 & 0x000000ff);
pixel_24[1] = (pixel32 & 0x0000ff00) >> 8;
pixel_24[2] = (pixel32 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
}
}
void Camera::convertImageMONO8toRGB8( const unsigned char *mono, unsigned char *rgb,
const unsigned int width, const unsigned int height )
{
unsigned int in = 0;
unsigned int out = 0;
for(in = 0; in < width * height; in++ )
{
rgb[out+0]=mono[in];
rgb[out+1]=mono[in];
rgb[out+2]=mono[in];
out+=3;
}
}
void Camera::convertImageRGB8toMONO8(const unsigned char* rgb, unsigned char* mono, const unsigned width, const unsigned height)
{
unsigned int in = 0;
unsigned int out = 0;
for (out = 0; out < width*height; ++out)
{
mono[out] = (unsigned char) (rgb[in]*0.3 + rgb[in+1]*0.59 + rgb[in+2]*0.11);
in+=3;
}
}
void Camera::setConfiguration(const Configuration &c)
{
assert ( (c.format == FORMAT7 && c.format7.xMax > 0 && c.format7.yMax > 0 && c.format7.xOffset >= 0 && c.format7.yOffset >= 0 ) ||
( c.format != FORMAT7 && c.width > 0 && c.height > 0));
this->activeConfiguration = c;
}
std::vector<Camera::Configuration> Camera::getSupportedConfigurations() const
{
return this->supportedConfigurations;
}
Camera::Configuration Camera::findConfiguration(Camera::Configuration partialConfig) const
{
for (std::vector<Configuration>::const_iterator it = supportedConfigurations.begin(); it < supportedConfigurations.end(); ++it)
{
// does this config match what we are looking for?
if( partialConfig.format == FORMAT7 ){
if(partialConfig.format7.format != ANY && (*it).format7.format != partialConfig.format7.format)
continue;
if (partialConfig.format7.xMax != 0 && (*it).format7.xMax > partialConfig.format7.xMax)
continue;
if (partialConfig.format7.yMax != 0 && (*it).format7.yMax > partialConfig.format7.yMax)
continue;
return *it;
} else {
if (partialConfig.format != ANY && (*it).format != partialConfig.format)
continue;
if (partialConfig.width != 0 && (*it).width != partialConfig.width)
continue;
if (partialConfig.height != 0 && (*it).height != partialConfig.height)
continue;
if (partialConfig.fps != 0 && (*it).fps != partialConfig.fps)
continue;
// matches everything we asked for!
return *it;
}
}
throw CameraException(CameraException::INVALIDCONFIGURATION);
}
/**
* Perform a software conversion of the frame to the requested format.
* The first call to this function is expensive as an internal buffer must be
* setup to support the conversion. Successive calls with the same format
* only incur the performance hit of the conversion. Changing image formats
* will also incurr an reallocation performance hit.
*
* @param f The format to convert the frame too
* @return A pointer to the converted frame
*/
const unsigned char* Camera::getFrame()
{
update();
return currentFrame;
}
const unsigned char *Camera::getFrame(const ImageFormat f )
{
update();
// Handle the same image format being requested
if( this->activeConfiguration.format == f )
return currentFrame;
unsigned width = this->activeConfiguration.width;
unsigned height = this->activeConfiguration.height;
this->setupConversionBuffer(this->getFormatBufferSize(f));
unsigned char *buffer=(unsigned char *)this->conversionBuffer->start;
switch( f ){
case RGB8:
{
switch( this->activeConfiguration.format){
case MONO8:
convertImageMONO8toRGB8(currentFrame, buffer, width, height);
return buffer;
case YUYV422:
convertImageYUYV422toRGB8( currentFrame, buffer, width, height);
return buffer;
case YUYV411:
convertImageYUYV411toRGB8( currentFrame, buffer, width, height);
return buffer;
#if ENABLE_VIDEO
case MJPEG:{
// Init the video decoder on the first MJPEG decoding frame
if( this->internal == NULL){
this->internal = new Priv;
this->internal->decoder = new VideoDecoder(width, height,CODEC_ID_MJPEG, false );
}
internal->decoder->nextFrame(currentFrame, this->getFormatBufferSize());
return internal->decoder->getFrame();
}
#endif
default:
;
}
goto NOTIMP;
}
case MJPEG:
case YUYV422:
case YUYV411:
case RGB16:
case RGB32:
case BGR8:
case MONO8:
{
switch( this->activeConfiguration.format ){
case RGB8:
convertImageRGB8toMONO8(currentFrame,buffer,width,height);
return buffer;
case YUYV422:
{
//create a temporary buffer
unsigned char *temp = new unsigned char[getFormatBufferSize(RGB8)];
convertImageYUYV422toRGB8(currentFrame, temp, width, height);
convertImageRGB8toMONO8(temp, buffer, width, height);
delete [] temp;
return buffer;
}
case MJPEG:
{
#if ENABLE_VIDEO
VideoDecoder dec(width, height,CODEC_ID_MJPEG, false );
dec.nextFrame(currentFrame, this->getFormatBufferSize());
convertImageRGB8toMONO8(dec.getFrame(), buffer, width, height);
return buffer;
#endif
}
default:
;
}
goto NOTIMP;
}
case MONO16:
default:
NOTIMP:
assert(0 && "Camera::getFrame(const ImageFormat) - Requested Conversion Not Implemented");
}
return NULL;
}
const unsigned char* Camera::getCurrentFrame() const
{
return currentFrame;
}
void Camera::getCurrentFrame(unsigned char* buffer, const ImageFormat& format) const
{
// Handle the case where this method is called before any other
// method that actually performs a capture. If the currentFrame
// is not set then most the conversions below will fail
if(this->currentFrame == NULL ){
buffer = NULL;
return;
}
// Handle the same image format being requested
if( this->activeConfiguration.format == format )
{
memcpy(buffer, currentFrame, getFormatBufferSize());
return;
}
unsigned width = this->activeConfiguration.width;
unsigned height = this->activeConfiguration.height;
unsigned char* temp;
switch( format ){
case RGB8:
{
switch( this->activeConfiguration.format){
case MONO8:
convertImageMONO8toRGB8(currentFrame, buffer, width, height);
return;
case YUYV422:
convertImageYUYV422toRGB8( currentFrame, buffer, width, height);
return;
case YUYV411:
convertImageYUYV411toRGB8( currentFrame, buffer, width, height);
return;
#if ENABLE_VIDEO
case MJPEG:{
// Init the video decoder on the first MJPEG decoding frame
VideoDecoder decoder(width, height,CODEC_ID_MJPEG, false );
decoder.nextFrame(currentFrame, this->getFormatBufferSize());
memcpy(buffer, decoder.getFrame(), getFormatBufferSize(format));
return;
}
#endif
default:
;
}
goto NOTIMP;
}
case MJPEG:
case YUYV422:
case YUYV411:
case RGB16:
case RGB32:
case BGR8:
case MONO8:
switch (this->activeConfiguration.format)
{
case RGB8:
convertImageRGB8toMONO8(currentFrame, buffer, width, height);
return;
case YUYV422:
//create a temporary buffer
temp = new unsigned char[getFormatBufferSize(RGB8)];
convertImageYUYV422toRGB8(currentFrame, temp, width, height);
convertImageRGB8toMONO8(temp, buffer, width, height);
delete [] temp;
return;
case MJPEG:
{
#if ENABLE_VIDEO
VideoDecoder dec(width, height,CODEC_ID_MJPEG, false );
dec.nextFrame(currentFrame, this->getFormatBufferSize());
convertImageRGB8toMONO8(dec.getFrame(), buffer, width, height);
return;
#endif
}
default:
;
}
goto NOTIMP;
break;
case MONO16:
default:
NOTIMP:
assert(0 && "Camera::getFrame(const ImageFormat) - Requested Conversion Not Implemented");
}
}
unsigned Camera::getFormatBytesPerPixel() const
{
return Camera::getFormatBytesPerPixel(this->activeConfiguration.format);
}
unsigned Camera::getFormatBytesPerPixel(const ImageFormat f ) const
{
switch( f ){
case RGB8:
return 3;
case RGB16:
return 6;
case RGB32:
return 12;
case BGR8:
return 3;
case MONO8:
return 1;
case MONO16:
return 2;
case YUYV422:
return 4;
case YUYV411:
return 4;
case MJPEG:
return 12;
case RAW8:
return 3;
case RAW16:
return 6;
default:
return 0;
}
}
unsigned Camera::getFormatBufferSize() const
{
return Camera::getFormatBufferSize( this->activeConfiguration.format);
}
unsigned Camera::getFormatBufferSize(const ImageFormat f ) const
{
return (this->getFormatBytesPerPixel(f) *
this->getActiveConfiguration().width *
this->activeConfiguration.height);
}
void Camera::setupConversionBuffer( const size_t buffersize )
{
if( this->conversionBuffer ){
if( this->conversionBuffer->length >= buffersize )
return;
delete this->conversionBuffer;
}
this->conversionBuffer = new CameraBuffer;
this->conversionBuffer->length = buffersize;
this->conversionBuffer->start = (void *)new unsigned char[buffersize];
}
bool Camera::hasParameters() const { return areParametersSet; }
void Camera::setParameters(const Camera::CameraParameters& p) {
areParametersSet = true;
this->parameters = p;
}
void Camera::printFormat7(const Format7 f,const bool inUse)
{
if(inUse)
wclclog << "FORMAT7 (" << this->imageFormatToString(f.format) << ") "
<< " Region: (" << f.xOffset << "," << f.yOffset << ")"
<< " -> (" << f.xMax << "," << f.yMax << ")";
else
wclclog << "FORMAT7 (" << this->imageFormatToString(f.format) << ") "
<< " Region Available: (" << f.xOffset << "," << f.yOffset << ")"
<< " -> (" << f.xMax << "," << f.yMax << ")"
<< " OffsetStepSize: (" << f.xOffsetStepSize << "," << f.yOffsetStepSize << ")"
<< " ExtentStepSize: (" << f.xStepSize << "," << f.yStepSize << ")";
}
void Camera::printDetails(bool state)
{
Configuration a = this->getActiveConfiguration();
wclclog << "Camera ID:" << this->id << " (" << this->getTypeIdentifier() << ") |";
if( a.format == FORMAT7)
this->printFormat7(a.format7,true);
else
wclclog<< this->imageFormatToString(a.format) << ":" << a.width << "x" << a.height << "@" << a.fps;
wclclog << endl;
if ( state ){
sort(this->supportedConfigurations.begin(),
this->supportedConfigurations.end(), configurationSort);
wclcout << "Features/Modes" << endl;
for(std::vector<Configuration>::iterator it =
supportedConfigurations.begin(); it !=
supportedConfigurations.end(); ++it ){
Configuration c = *it;
if(c.format == FORMAT7 ){
wclclog << "\t";
this->printFormat7(c.format7,false);
wclclog << endl;
} else {
if( it == supportedConfigurations.begin()){
wclclog << "\t" << this->imageFormatToString(c.format) << " " << c.width << "x" << c.height << " @" << c.fps;
}
else {
--it;
Configuration prev = *it;
++it;
if( c.format == prev.format && c.width == prev.width && c.height == prev.height )
wclclog << "," << c.fps;
else {
wclclog << endl;
wclclog << "\t" << this->imageFormatToString(c.format) << " "
<< c.width << "x" << c.height << " @" << c.fps;
}
}
}
}
wclclog << endl;
}
}
const char *Camera::imageFormatToString(const ImageFormat f )
{
switch(f)
{
case MJPEG: return "MJPEG";
case YUYV411: return "YUYV411";
case YUYV422: return "YUYV422";
case YUYV444: return "YUYV444";
case RGB8: return "RGB8";
case RGB16: return "RGB16";
case RGB32: return "RGB32";
case BGR8: return "BGR8";
case MONO8: return "MONO8";
case MONO16: return "MONO16";
case RAW8: return "RAW8";
case RAW16: return "RAW16";
case FORMAT7: return "FORMAT7";
case ANY:
default:
return "UNKNOWN:";
};
}
}
|
/*************************************************************************
*
* $RCSfile: SharedConnection.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: oj $ $Date: 2002-08-12 09:21:58 $
*
* 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 DBA_CORE_SHARED_CONNECTION_HXX
#define DBA_CORE_SHARED_CONNECTION_HXX
#ifndef _CONNECTIVITY_CONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif
#ifndef _CPPUHELPER_COMPONENT_HXX_
#include <cppuhelper/component.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMMANDPREPARATION_HPP_
#include <com/sun/star/sdb/XCommandPreparation.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
namespace dbaccess
{
//=======================================================================================
//= OSharedConnection: This class implements a simple forwarding of connection calls.
//= All methods will be forwarded with exception of the set methods, which are not allowed
//= to be called on shared connections. Instances of this class will be created when the
//= datasource is asked for not isolated connection.
//=======================================================================================
typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection
> OSharedConnection_BASE;
typedef ::connectivity::OConnectionWrapper OSharedConnection_BASE2;
class OSharedConnection : public ::comphelper::OBaseMutex
, public OSharedConnection_BASE
, public OSharedConnection_BASE2
{
protected:
virtual void SAL_CALL disposing(void)
{
OSharedConnection_BASE::disposing();
}
public:
OSharedConnection(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _rxProxyConnection)
: OSharedConnection_BASE(m_aMutex)
{
setDelegation(_rxProxyConnection,m_refCount);
}
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw() { OSharedConnection_BASE::acquire(); }
virtual void SAL_CALL release() throw() { OSharedConnection_BASE::release(); }
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException)
{
return ::comphelper::concatSequences(
OSharedConnection_BASE::getTypes(),
OSharedConnection_BASE2::getTypes()
);
}
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Any aReturn = OSharedConnection_BASE::queryInterface(_rType);
if ( !aReturn.hasValue() )
aReturn = OSharedConnection_BASE2::queryInterface(_rType);
return aReturn;
}
// --------------------------------------------------------------------------------
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
{
::osl::MutexGuard aGuard( m_aMutex );
::connectivity::checkDisposed(rBHelper.bDisposed);
}
dispose();
}
// XConnection
virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
IMPLEMENT_GET_IMPLEMENTATION_ID( OSharedConnection );
//........................................................................
} // namespace dbaccess
//........................................................................
#endif // DBA_CORE_SHARED_CONNECTION_HXX
INTEGRATION: CWS ooo20031110 (1.2.148); FILE MERGED
2003/11/07 10:50:34 waratah 1.2.148.1: #i21906# bracket an undefined macro so that non permissive build will compile
/*************************************************************************
*
* $RCSfile: SharedConnection.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-12-01 18:01:20 $
*
* 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 DBA_CORE_SHARED_CONNECTION_HXX
#define DBA_CORE_SHARED_CONNECTION_HXX
#ifndef _CONNECTIVITY_CONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif
#ifndef _CPPUHELPER_COMPONENT_HXX_
#include <cppuhelper/component.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMMANDPREPARATION_HPP_
#include <com/sun/star/sdb/XCommandPreparation.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
namespace dbaccess
{
//=======================================================================================
//= OSharedConnection: This class implements a simple forwarding of connection calls.
//= All methods will be forwarded with exception of the set methods, which are not allowed
//= to be called on shared connections. Instances of this class will be created when the
//= datasource is asked for not isolated connection.
//=======================================================================================
typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection
> OSharedConnection_BASE;
typedef ::connectivity::OConnectionWrapper OSharedConnection_BASE2;
class OSharedConnection : public ::comphelper::OBaseMutex
, public OSharedConnection_BASE
, public OSharedConnection_BASE2
{
protected:
virtual void SAL_CALL disposing(void)
{
OSharedConnection_BASE::disposing();
}
public:
OSharedConnection(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _rxProxyConnection)
: OSharedConnection_BASE(m_aMutex)
{
setDelegation(_rxProxyConnection,m_refCount);
}
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw() { OSharedConnection_BASE::acquire(); }
virtual void SAL_CALL release() throw() { OSharedConnection_BASE::release(); }
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException)
{
return ::comphelper::concatSequences(
OSharedConnection_BASE::getTypes(),
OSharedConnection_BASE2::getTypes()
);
}
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Any aReturn = OSharedConnection_BASE::queryInterface(_rType);
if ( !aReturn.hasValue() )
aReturn = OSharedConnection_BASE2::queryInterface(_rType);
return aReturn;
}
// --------------------------------------------------------------------------------
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
{
::osl::MutexGuard aGuard( m_aMutex );
::connectivity::checkDisposed(rBHelper.bDisposed);
}
dispose();
}
// XConnection
virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
}
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
#ifdef IMPLEMENT_GET_IMPLEMENTATION_ID
IMPLEMENT_GET_IMPLEMENTATION_ID( OSharedConnection );
#endif
//........................................................................
} // namespace dbaccess
//........................................................................
#endif // DBA_CORE_SHARED_CONNECTION_HXX
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: databasedocument.cxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: obo $ $Date: 2005-12-21 13:34:54 $
*
* 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 _DBA_COREDATAACCESS_DATASOURCE_HXX_
#include "datasource.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_DATABASEDOCUMENT_HXX_
#include "databasedocument.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#include <comphelper/documentconstants.hxx>
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_ERRORCODEIOEXCEPTION_HPP_
#include <com/sun/star/task/ErrorCodeIOException.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_DATABASECONTEXT_HXX_
#include "databasecontext.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _ERRCODE_HXX
#include <tools/errcode.hxx>
#endif
#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#include <comphelper/mediadescriptor.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONSTORAGE_HPP_
#include <com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTIONBROADCASTER_HPP_
#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEMBEDPERSIST_HPP_
#include <com/sun/star/embed/XEmbedPersist.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_
#include <com/sun/star/embed/EntryInitModes.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_
#include <com/sun/star/view/XSelectionSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif
namespace css = ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::view;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml::sax;
using namespace ::cppu;
using namespace ::osl;
namespace css = ::com::sun::star;
//........................................................................
namespace dbaccess
{
//........................................................................
//============================================================
//= ODatabaseContext
//============================================================
DBG_NAME(ODatabaseDocument)
//--------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_ODatabaseDocument()
{
static OMultiInstanceAutoRegistration< ODatabaseDocument > aAutoRegistration;
}
//--------------------------------------------------------------------------
Reference< XInterface > ODatabaseDocument_CreateInstance(const Reference< XMultiServiceFactory >& _rxFactory)
{
ODatabaseContext* pContext = NULL;
try
{
Reference<XUnoTunnel> xUnoTunnel(_rxFactory->createInstance(SERVICE_SDB_DATABASECONTEXT),UNO_QUERY);
if ( xUnoTunnel.is() )
pContext = reinterpret_cast<ODatabaseContext*>(xUnoTunnel->getSomething(ODatabaseContext::getUnoTunnelImplementationId()));
}
catch(Exception)
{
}
::rtl::Reference<ODatabaseModelImpl> pImpl(new ODatabaseModelImpl(_rxFactory));
pImpl->m_pDBContext = pContext;
Reference< XModel > xModel( pImpl->createNewModel_deliverOwnership() );
return xModel.get();
}
//--------------------------------------------------------------------------
ODatabaseDocument::ODatabaseDocument(const ::rtl::Reference<ODatabaseModelImpl>& _pImpl )
:ModelDependentComponent( _pImpl )
,ODatabaseDocument_OfficeDocument( getMutex() )
,m_aModifyListeners( getMutex() )
,m_aCloseListener( getMutex() )
,m_aDocEventListeners( getMutex() )
{
DBG_CTOR(ODatabaseDocument,NULL);
// adjust our readonly flag
try
{
m_xDocEventBroadcaster.set(m_pImpl->m_xServiceFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.GlobalEventBroadcaster"))),
UNO_QUERY);
}
catch(Exception)
{
OSL_ENSURE(0,"Could not create GlobalEventBroadcaster!");
}
Reference<XChild> xChild(m_pImpl->m_xForms.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
xChild.set(m_pImpl->m_xReports.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
xChild.set(m_pImpl->m_xTableDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
xChild.set(m_pImpl->m_xCommandDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
}
//--------------------------------------------------------------------------
ODatabaseDocument::~ODatabaseDocument()
{
DBG_DTOR(ODatabaseDocument,NULL);
if ( !ODatabaseDocument_OfficeDocument::rBHelper.bInDispose && !ODatabaseDocument_OfficeDocument::rBHelper.bDisposed )
{
acquire();
dispose();
}
}
// -----------------------------------------------------------------------------
// local functions
// -----------------------------------------------------------------------------
void lcl_stripLoadArguments( ::comphelper::MediaDescriptor& _rDescriptor, Sequence< PropertyValue >& _rArgs )
{
_rDescriptor.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StatusIndicator" ) ) );
_rDescriptor.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InteractionHandler" ) ) );
_rDescriptor.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Model" ) ) );
_rDescriptor >> _rArgs;
}
// -----------------------------------------------------------------------------
void lcl_extractAndStartStatusIndicator( const ::comphelper::MediaDescriptor& _rDescriptor, Reference< XStatusIndicator >& _rxStatusIndicator,
Sequence< Any >& _rCallArgs )
{
try
{
_rxStatusIndicator = _rDescriptor.getUnpackedValueOrDefault( _rDescriptor.PROP_STATUSINDICATOR(), _rxStatusIndicator );
if ( _rxStatusIndicator.is() )
{
_rxStatusIndicator->start( ::rtl::OUString(), (sal_Int32)1000000 );
sal_Int32 nLength = _rCallArgs.getLength();
_rCallArgs.realloc( nLength + 1 );
_rCallArgs[ nLength ] <<= _rxStatusIndicator;
}
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "lcl_extractAndStartStatusIndicator: caught an exception!" );
}
}
// -----------------------------------------------------------------------------
// XModel
// ATTENTION: The Application controller attaches the same resource to force a reload.
sal_Bool SAL_CALL ODatabaseDocument::attachResource( const ::rtl::OUString& _rURL, const Sequence< PropertyValue >& _aArguments ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
try
{
m_pImpl->clearConnections();
m_pImpl->disposeStorages();
if ( m_pImpl->m_bOwnStorage )
::comphelper::disposeComponent(m_pImpl->m_xStorage);
Reference< XNameAccess > xContainer = m_pImpl->m_xForms;
::comphelper::disposeComponent(xContainer);
xContainer = m_pImpl->m_xReports;
::comphelper::disposeComponent(xContainer);
xContainer = m_pImpl->m_xTableDefinitions;
::comphelper::disposeComponent(xContainer);
xContainer = m_pImpl->m_xCommandDefinitions;
::comphelper::disposeComponent(xContainer);
m_pImpl->m_aContainer.clear();
m_pImpl->lateInit();
}
catch(const Exception&)
{
m_pImpl->m_xStorage = NULL;
}
m_pImpl->m_bDocumentReadOnly = sal_False;
::comphelper::MediaDescriptor aDescriptor( _aArguments );
lcl_stripLoadArguments( aDescriptor, m_pImpl->m_aArgs );
m_pImpl->m_sFileURL = _rURL;
m_pImpl->m_sRealFileURL = aDescriptor.getUnpackedValueOrDefault(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SalvagedFile" ) ), _rURL );
if ( !m_pImpl->m_sRealFileURL.getLength() )
m_pImpl->m_sRealFileURL = m_pImpl->m_sFileURL;
if ( !m_pImpl->m_sName.getLength() )
m_pImpl->m_sName = m_pImpl->m_sRealFileURL;
m_pImpl->getStorage();
try
{
Sequence<Any> aFilterArgs;
Reference<XStatusIndicator> xStatusIndicator;
lcl_extractAndStartStatusIndicator( aDescriptor, xStatusIndicator, aFilterArgs );
Reference<XImporter> xImporter(
m_pImpl->m_xServiceFactory->createInstanceWithArguments(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.sdb.DBFilter" ) ),
aFilterArgs
),
UNO_QUERY
);
if ( xImporter.is() )
{
Reference<XComponent> xComponent(*this,UNO_QUERY);
xImporter->setTargetDocument(xComponent);
Reference<XFilter> xFilter(xImporter,UNO_QUERY);
xFilter->filter(_aArguments);
if ( xStatusIndicator.is() )
xStatusIndicator->end();
}
else
return sal_False;
}
catch(const RuntimeException& e)
{
throw e;
}
catch(const Exception&)
{
return sal_False;
}
if ( m_pImpl->m_pDBContext )
{
m_pImpl->m_pDBContext->registerPrivate(m_pImpl->m_sRealFileURL,m_pImpl);
m_pImpl->setModified(sal_False);
}
return sal_True;
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODatabaseDocument::getURL( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_sRealFileURL;
}
// -----------------------------------------------------------------------------
Sequence< PropertyValue > SAL_CALL ODatabaseDocument::getArgs( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_aArgs;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::connectController( const Reference< XController >& _xController ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
m_pImpl->m_aControllers.push_back(_xController);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::disconnectController( const Reference< XController >& _xController ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
m_pImpl->m_aControllers.erase(::std::find(m_pImpl->m_aControllers.begin(),m_pImpl->m_aControllers.end(),_xController));
if ( m_pImpl->m_xCurrentController == _xController )
m_pImpl->m_xCurrentController = NULL;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::lockControllers( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
++m_pImpl->m_nControllerLockCount;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::unlockControllers( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
--m_pImpl->m_nControllerLockCount;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL ODatabaseDocument::hasControllersLocked( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_nControllerLockCount != 0;
}
// -----------------------------------------------------------------------------
Reference< XController > SAL_CALL ODatabaseDocument::getCurrentController() throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_xCurrentController.is() ? m_pImpl->m_xCurrentController : ( m_pImpl->m_aControllers.empty() ? Reference< XController >() : *m_pImpl->m_aControllers.begin() );
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::setCurrentController( const Reference< XController >& _xController ) throw (NoSuchElementException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
m_pImpl->m_xCurrentController = _xController;
}
// -----------------------------------------------------------------------------
Reference< XInterface > SAL_CALL ODatabaseDocument::getCurrentSelection( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XInterface > xRet;
Reference< XSelectionSupplier > xDocView( getCurrentController(), UNO_QUERY );
if ( xDocView.is() )
xRet.set(xDocView->getSelection(),UNO_QUERY);
return xRet;
}
// -----------------------------------------------------------------------------
// XStorable
sal_Bool SAL_CALL ODatabaseDocument::hasLocation( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_sRealFileURL.getLength() != 0;
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODatabaseDocument::getLocation( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_sRealFileURL;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL ODatabaseDocument::isReadonly( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_bDocumentReadOnly;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::store( ) throw (IOException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
if ( m_pImpl->m_sFileURL == m_pImpl->m_sRealFileURL )
store( m_pImpl->m_sFileURL, m_pImpl->m_aArgs );
else
storeAsURL( m_pImpl->m_sRealFileURL, m_pImpl->m_aArgs );
impl_notifyEvent( "OnSaveDone", aGuard );
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::store(const ::rtl::OUString& _rURL
,const Sequence< PropertyValue >& _rArguments)
{
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
if ( m_pImpl->m_bDocumentReadOnly )
throw IOException();
m_bCommitMasterStorage = sal_False;
m_pImpl->commitStorages();
m_bCommitMasterStorage = sal_True;
writeStorage(_rURL,_rArguments,m_pImpl->getStorage());
m_pImpl->commitRootStorage();
setModified(sal_False);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::storeAsURL( const ::rtl::OUString& _rURL, const Sequence< PropertyValue >& _rArguments ) throw (IOException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XSingleServiceFactory > xStorageFactory( m_pImpl->createStorageFactory() );
if ( !xStorageFactory.is() )
throw RuntimeException();
// don't use _rURL - we might be recovering/salvaging a file currently ...
// #i45314# / 2005-03-21 / frank.schoenheit@sun.com
::comphelper::MediaDescriptor aDescriptor( _rArguments );
sal_Bool bLocationChanged = ( _rURL != m_pImpl->m_sFileURL );
if ( bLocationChanged )
{
Sequence<Any> aParam(2);
aParam[0] <<= _rURL;
aParam[1] <<= ElementModes::READWRITE | ElementModes::TRUNCATE;
Reference<XStorage> xStorage;
try
{
xStorage.set(xStorageFactory->createInstanceWithArguments( aParam ),UNO_QUERY);
}
catch(Exception&)
{
}
if ( !xStorage.is() )
throw IOException();
if ( m_pImpl->isEmbeddedDatabase() )
m_pImpl->clearConnections();
m_pImpl->commitEmbeddedStorage();
Reference<XStorage> xMyStorage = m_pImpl->getStorage();
if ( xMyStorage.is() )
{
m_pImpl->commitStorages();
xMyStorage->copyToStorage( xStorage );
}
m_pImpl->disposeStorages();
m_pImpl->m_xStorage = xStorage;
if ( m_pImpl->m_bOwnStorage )
::comphelper::disposeComponent(xMyStorage);
else
m_pImpl->m_bOwnStorage = sal_True;
m_pImpl->m_bDocumentReadOnly = sal_False;
if ( _rURL != m_pImpl->m_sRealFileURL )
{
if ( m_pImpl->m_pDBContext )
{
if ( m_pImpl->m_sRealFileURL.getLength() )
m_pImpl->m_pDBContext->nameChangePrivate(m_pImpl->m_sRealFileURL,_rURL);
else
m_pImpl->m_pDBContext->registerPrivate(_rURL,m_pImpl);
}
INetURLObject aURL( _rURL );
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
m_pImpl->m_sName = _rURL;
}
m_pImpl->m_sRealFileURL = m_pImpl->m_sFileURL = _rURL;
}
lcl_stripLoadArguments( aDescriptor, m_pImpl->m_aArgs );
store(m_pImpl->m_sFileURL,_rArguments);
impl_notifyEvent( "OnSaveAsDone", aGuard );
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::storeToURL( const ::rtl::OUString& _rURL, const Sequence< PropertyValue >& _rArguments ) throw (IOException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XSingleServiceFactory > xStorageFactory( m_pImpl->createStorageFactory() );
Sequence<Any> aParam(2);
aParam[0] <<= _rURL;
aParam[1] <<= ElementModes::READWRITE | ElementModes::TRUNCATE;
Reference<XStorage> xStorage;
if ( xStorageFactory.is() )
xStorage = xStorage.query( xStorageFactory->createInstanceWithArguments( aParam ) );
OSL_ENSURE( xStorage.is(), "ODatabaseDocument::storeToURL: no storage factory!" );
if ( !xStorage.is() )
{
IOException aError;
aError.Message = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Could not create a target storage." ) );
aError.Context = *this;
throw IOException( aError );
}
Reference<XStorage> xMyStorage = m_pImpl->getStorage();
OSL_ENSURE( xMyStorage.is(), "ODatabaseDocument::storeToURL: no own storage?" );
if ( !xMyStorage.is() )
{
IOException aError;
aError.Message = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Internal error: no source storage available." ) );
aError.Context = *this;
throw IOException( aError );
}
m_pImpl->commitEmbeddedStorage();
xMyStorage->copyToStorage( xStorage );
writeStorage(_rURL,_rArguments,xStorage);
try
{
Reference<XTransactedObject> xTransact(xStorage,UNO_QUERY);
if ( xTransact.is() )
xTransact->commit();
}
catch(Exception)
{
OSL_ENSURE(0,"Exception Caught: Could not store database!");
throw IOException();
}
}
// -----------------------------------------------------------------------------
// XModifyBroadcaster
void SAL_CALL ODatabaseDocument::addModifyListener( const Reference< XModifyListener >& _xListener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aModifyListeners.addInterface(_xListener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeModifyListener( const Reference< XModifyListener >& _xListener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aModifyListeners.removeInterface(_xListener);
}
// -----------------------------------------------------------------------------
// XModifiable
sal_Bool SAL_CALL ODatabaseDocument::isModified( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_bModified;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::setModified( sal_Bool _bModified ) throw (PropertyVetoException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
if ( m_pImpl->m_bModified == _bModified )
return;
m_pImpl->m_bModified = _bModified;
lang::EventObject aEvt( *this );
aGuard.clear();
m_aModifyListeners.notifyEach( &XModifyListener::modified, aEvt );
aGuard.reset();
impl_notifyEvent( "OnModifyChanged", aGuard );
}
// ::com::sun::star::document::XEventBroadcaster
void SAL_CALL ODatabaseDocument::addEventListener(const css::uno::Reference< css::document::XEventListener >& _xListener ) throw (css::uno::RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aDocEventListeners.addInterface(_xListener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeEventListener( const css::uno::Reference< css::document::XEventListener >& _xListener ) throw (css::uno::RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aDocEventListeners.removeInterface(_xListener);
}
// -----------------------------------------------------------------------------
// ::com::sun::star::document::XEventListener
void SAL_CALL ODatabaseDocument::notifyEvent( const css::document::EventObject& aEvent ) throw (css::uno::RuntimeException)
{
ModelMethodGuard aGuard( *this );
// used only to forward external events (e.g. for doc creation) from the frame loader
// to the global event broadcaster and all other interested doc event listener.
impl_notifyEvent( aEvent.EventName, aGuard );
}
// -----------------------------------------------------------------------------
// ::com::sun::star::view::XPrintable
Sequence< PropertyValue > SAL_CALL ODatabaseDocument::getPrinter( ) throw (RuntimeException)
{
return Sequence< PropertyValue >();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::setPrinter( const Sequence< PropertyValue >& aPrinter ) throw (IllegalArgumentException, RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::print( const Sequence< PropertyValue >& xOptions ) throw (IllegalArgumentException, RuntimeException)
{
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::impl_closeControllerFrames( sal_Bool _bDeliverOwnership )
{
::std::vector< Reference< XController> > aCopy = m_pImpl->m_aControllers;
::std::vector< Reference< XController> >::iterator aIter = aCopy.begin();
::std::vector< Reference< XController> >::iterator aEnd = aCopy.end();
for ( ;aIter != aEnd ; ++aIter )
{
if ( aIter->is() )
{
try
{
Reference< XCloseable> xFrame( (*aIter)->getFrame(), UNO_QUERY );
if ( xFrame.is() )
xFrame->close( _bDeliverOwnership );
}
catch( const CloseVetoException& ) { throw; }
catch( const Exception& )
{
OSL_ENSURE( sal_False, "ODatabaseDocument::impl_closeControllerFrames: caught an unexpected exception!" );
}
}
}
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::close( sal_Bool _bDeliverOwnership ) throw (::com::sun::star::util::CloseVetoException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
lang::EventObject aEvent( *this );
{
aGuard.clear();
m_aCloseListener.forEach< XCloseListener >(
boost::bind( &XCloseListener::queryClosing, _1, boost::cref( aEvent ), boost::cref( _bDeliverOwnership ) ) );
aGuard.reset();
}
DBG_ASSERT( m_pImpl->m_aControllers.empty(), "ODatabaseDocument::close: aren't controllers expected to veto the closing?" );
impl_closeControllerFrames( _bDeliverOwnership );
{
aGuard.clear();
m_aCloseListener.notifyEach( &XCloseListener::notifyClosing, aEvent );
aGuard.reset();
}
dispose();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::addCloseListener( const Reference< ::com::sun::star::util::XCloseListener >& Listener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aCloseListener.addInterface(Listener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeCloseListener( const Reference< ::com::sun::star::util::XCloseListener >& Listener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aCloseListener.removeInterface(Listener);
}
// -----------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL ODatabaseDocument::getFormDocuments( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XNameAccess > xContainer = m_pImpl->m_xForms;
if ( !xContainer.is() )
{
if ( !m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM].get() )
{
::rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM("forms"));
m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM] = TContentPtr(new ODefinitionContainer_Impl);
m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM]->m_pDataSource = m_pImpl.get();
m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM]->m_aProps.aTitle = sName;
}
xContainer = new ODocumentContainer(m_pImpl->m_xServiceFactory,*this,m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM],sal_True);
m_pImpl->m_xForms = xContainer;
}
return xContainer;
}
// -----------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL ODatabaseDocument::getReportDocuments( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XNameAccess > xContainer = m_pImpl->m_xReports;
if ( !xContainer.is() )
{
if ( !m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT].get() )
{
m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT] = TContentPtr(new ODefinitionContainer_Impl);
::rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM("reports"));
m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT]->m_pDataSource = m_pImpl.get();
m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT]->m_aProps.aTitle = sName;
}
xContainer = new ODocumentContainer(m_pImpl->m_xServiceFactory,*this,m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT],sal_False);
m_pImpl->m_xReports = xContainer;
}
return xContainer;
}
// -----------------------------------------------------------------------------
sal_Bool ODatabaseDocument::WriteThroughComponent(
const Reference<XComponent> & xComponent,
const sal_Char* pStreamName,
const sal_Char* pServiceName,
const Sequence<Any> & rArguments,
const Sequence<PropertyValue> & rMediaDesc,
sal_Bool bPlainStream
,const Reference<XStorage>& _xStorageToSaveTo)
{
OSL_ENSURE( NULL != pStreamName, "Need stream name!" );
OSL_ENSURE( NULL != pServiceName, "Need service name!" );
Reference<XStorage> xMyStorage = _xStorageToSaveTo;
// open stream
::rtl::OUString sStreamName = ::rtl::OUString::createFromAscii( pStreamName );
Reference<XStream> xStream = xMyStorage->openStreamElement( sStreamName,ElementModes::READWRITE | ElementModes::TRUNCATE );
if ( !xStream.is() )
return sal_False;
Reference<XOutputStream> xOutputStream = xStream->getOutputStream();
OSL_ENSURE(xOutputStream.is(), "Can't create output stream in package!");
if ( ! xOutputStream.is() )
return sal_False;
Reference<XPropertySet> xStreamProp(xOutputStream,UNO_QUERY);
OSL_ENSURE(xStreamProp.is(),"No valid preoperty set for the output stream!");
Reference<XSeekable> xSeek(xStreamProp,UNO_QUERY);
if ( xSeek.is() )
{
OSL_TRACE("Length of stream %i",(int)xSeek->getPosition());
xSeek->seek(0);
}
String aPropName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM("MediaType") ) );
::rtl::OUString aMime( RTL_CONSTASCII_USTRINGPARAM("text/xml") );
Any aAny;
aAny <<= aMime;
xStreamProp->setPropertyValue( aPropName, aAny );
if( bPlainStream )
{
::rtl::OUString aPropName( RTL_CONSTASCII_USTRINGPARAM("Compressed") );
sal_Bool bFalse = sal_False;
aAny.setValue( &bFalse, ::getBooleanCppuType() );
xStreamProp->setPropertyValue( aPropName, aAny );
}
else
{
::rtl::OUString aPropName( RTL_CONSTASCII_USTRINGPARAM("Encrypted") );
sal_Bool bTrue = sal_True;
aAny.setValue( &bTrue, ::getBooleanCppuType() );
xStreamProp->setPropertyValue( aPropName, aAny );
}
// set buffer and create outputstream
// write the stuff
sal_Bool bRet = WriteThroughComponent(
xOutputStream, xComponent,
pServiceName, rArguments, rMediaDesc );
// finally, commit stream.
return bRet;
}
sal_Bool ODatabaseDocument::WriteThroughComponent(
const Reference<XOutputStream> & xOutputStream,
const Reference<XComponent> & xComponent,
const sal_Char* pServiceName,
const Sequence<Any> & rArguments,
const Sequence<PropertyValue> & rMediaDesc)
{
OSL_ENSURE( xOutputStream.is(), "I really need an output stream!" );
OSL_ENSURE( xComponent.is(), "Need component!" );
OSL_ENSURE( NULL != pServiceName, "Need component name!" );
// get component
Reference< XActiveDataSource > xSaxWriter(
m_pImpl->m_xServiceFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer"))),
UNO_QUERY );
OSL_ENSURE( xSaxWriter.is(), "can't instantiate XML com.sun.star.xml.sax.Writer" );
if(!xSaxWriter.is())
return sal_False;
// connect XML writer to output stream
xSaxWriter->setOutputStream( xOutputStream );
// prepare arguments (prepend doc handler to given arguments)
Reference<XDocumentHandler> xDocHandler( xSaxWriter,UNO_QUERY);
Sequence<Any> aArgs( 1 + rArguments.getLength() );
aArgs[0] <<= xDocHandler;
for(sal_Int32 i = 0; i < rArguments.getLength(); i++)
aArgs[i+1] = rArguments[i];
// get filter component
Reference< XExporter > xExporter(
m_pImpl->m_xServiceFactory->createInstanceWithArguments(
::rtl::OUString::createFromAscii(pServiceName), aArgs), UNO_QUERY);
OSL_ENSURE( xExporter.is(),
"can't instantiate export filter component" );
if( !xExporter.is() )
return sal_False;
// connect model and filter
xExporter->setSourceDocument( xComponent );
// filter!
Reference<XFilter> xFilter( xExporter, UNO_QUERY );
return xFilter->filter( rMediaDesc );
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::writeStorage(const ::rtl::OUString& _rURL
,const Sequence< PropertyValue >& _rArguments
,const Reference<XStorage>& _xStorageToSaveTo)
{
// create XStatusIndicator
Reference<XStatusIndicator> xStatusIndicator;
Sequence< Any > aDelegatorArguments;
::comphelper::MediaDescriptor aDescriptor( _rArguments );
lcl_extractAndStartStatusIndicator( aDescriptor, xStatusIndicator, aDelegatorArguments );
// properties
Sequence < PropertyValue > aProps( _rURL.getLength() ? 1 : 0 );
if( _rURL.getLength() )
{
PropertyValue *pProps = aProps.getArray();
pProps->Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("FileName") );
(pProps++)->Value <<= _rURL;
}
// export sub streams for package, else full stream into a file
sal_Bool bWarn = sal_False, bErr = sal_False;
String sWarnFile, sErrFile;
Reference<XPropertySet> xProp(_xStorageToSaveTo,UNO_QUERY);
if ( xProp.is() )
{
static const ::rtl::OUString sPropName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MediaType"));
Any aAny;
aAny <<= MIMETYPE_OASIS_OPENDOCUMENT_DATABASE;
xProp->setPropertyValue( sPropName, aAny );
}
Reference<XComponent> xCom(static_cast<OWeakObject*>(this),UNO_QUERY);
if( !bErr )
{
if( !WriteThroughComponent(
xCom, "settings.xml",
"com.sun.star.comp.sdb.XMLSettingsExporter",
aDelegatorArguments, aProps, sal_True,_xStorageToSaveTo ) )
{
if( !bWarn )
{
bWarn = sal_True;
sWarnFile = String( RTL_CONSTASCII_STRINGPARAM("settings.xml"),
RTL_TEXTENCODING_ASCII_US );
}
}
}
if ( !bErr )
{
if( !WriteThroughComponent(
xCom, "content.xml",
"com.sun.star.comp.sdb.DBExportFilter",
aDelegatorArguments, aProps, sal_True,_xStorageToSaveTo ) )
{
bErr = sal_True;
sErrFile = String( RTL_CONSTASCII_STRINGPARAM("content.xml"),
RTL_TEXTENCODING_ASCII_US );
}
}
if ( xStatusIndicator.is() )
xStatusIndicator->end();
}
// -----------------------------------------------------------------------------
Reference< ::com::sun::star::ui::XUIConfigurationManager > SAL_CALL ODatabaseDocument::getUIConfigurationManager( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
if ( !m_xUIConfigurationManager.is() )
{
m_xUIConfigurationManager = Reference< ::com::sun::star::ui::XUIConfigurationManager >(
m_pImpl->m_xServiceFactory->createInstance(
::rtl::OUString::createFromAscii( "com.sun.star.ui.UIConfigurationManager" )),
UNO_QUERY );
Reference< ::com::sun::star::ui::XUIConfigurationStorage > xUIConfigStorage( m_xUIConfigurationManager, UNO_QUERY );
if ( xUIConfigStorage.is() )
{
rtl::OUString aUIConfigFolderName( RTL_CONSTASCII_USTRINGPARAM( "Configurations2" ));
Reference< XStorage > xConfigStorage;
// First try to open with READWRITE and then READ
xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, ElementModes::READWRITE );
if ( xConfigStorage.is() )
{
rtl::OUString aMediaTypeProp( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ));
rtl::OUString aUIConfigMediaType( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.sun.xml.ui.configuration" ));
rtl::OUString aMediaType;
Reference< XPropertySet > xPropSet( xConfigStorage, UNO_QUERY );
Any a = xPropSet->getPropertyValue( aMediaTypeProp );
if ( !( a >>= aMediaType ) || ( aMediaType.getLength() == 0 ))
{
a <<= aUIConfigMediaType;
xPropSet->setPropertyValue( aMediaTypeProp, a );
}
}
else
xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, ElementModes::READ );
// initialize ui configuration manager with document substorage
xUIConfigStorage->setStorage( xConfigStorage );
}
}
return m_xUIConfigurationManager;
}
// -----------------------------------------------------------------------------
Reference< XStorage > SAL_CALL ODatabaseDocument::getDocumentSubStorage( const ::rtl::OUString& aStorageName, sal_Int32 nMode ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
Reference< XDocumentSubStorageSupplier > xStorageAccess( m_pImpl->getDocumentSubStorageSupplier() );
return xStorageAccess->getDocumentSubStorage( aStorageName, nMode );
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL ODatabaseDocument::getDocumentSubStoragesNames( ) throw (::com::sun::star::io::IOException, RuntimeException)
{
Reference< XDocumentSubStorageSupplier > xStorageAccess( m_pImpl->getDocumentSubStorageSupplier() );
return xStorageAccess->getDocumentSubStoragesNames();
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::impl_notifyEvent( const ::rtl::OUString& _sEventName, ::osl::ClearableMutexGuard& _rGuard )
{
try
{
css::document::EventObject aEvt(*this, _sEventName);
Reference< XEventListener > xDocEventBroadcaster;
/// TODO: this code has to be deleted after AS' cws will be integrated
try
{
xDocEventBroadcaster = xDocEventBroadcaster.query( m_pImpl->m_xServiceFactory->createInstance(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.GlobalEventBroadcaster" ) ) ) );
}
catch(Exception)
{
OSL_ENSURE(0,"Could not create GlobalEventBroadcaster!");
}
_rGuard.clear();
if ( xDocEventBroadcaster.is() )
xDocEventBroadcaster->notifyEvent(aEvt);
m_aDocEventListeners.notifyEach( &css::document::XEventListener::notifyEvent, aEvt );
}
catch(Exception&)
{
}
}
//------------------------------------------------------------------------------
void ODatabaseDocument::disposing()
{
if ( !m_pImpl.is() )
{
// this means that we're already disposed
DBG_ASSERT( ODatabaseDocument_OfficeDocument::rBHelper.bDisposed, "ODatabaseDocument::disposing: no impl anymore, but not yet disposed!" );
return;
}
DBG_ASSERT( m_pImpl->m_aControllers.empty(), "ODatabaseDocument::disposing: there still are controllers!" );
// normally, nobody should explicitly dispose, but only XCloseable::close the document. And controllers
// are expected to veto the closing, so when we're here, there shouldn't be any controllers anymore.
m_pImpl->m_aControllers.clear();
Reference< XModel > xHoldAlive( this );
{
{
::osl::ClearableMutexGuard aGuard( getMutex() );
impl_notifyEvent( "OnUnload", aGuard );
}
css::lang::EventObject aDisposeEvent(static_cast<XWeak*>(this));
m_aModifyListeners.disposeAndClear( aDisposeEvent );
m_aCloseListener.disposeAndClear( aDisposeEvent );
m_aDocEventListeners.disposeAndClear( aDisposeEvent );
m_xDocEventBroadcaster = NULL;
m_xUIConfigurationManager = NULL;
Reference<XChild> xChild(m_pImpl->m_xForms.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
xChild.set(m_pImpl->m_xReports.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
xChild.set(m_pImpl->m_xTableDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
xChild.set(m_pImpl->m_xCommandDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
m_pImpl->modelIsDisposing( ODatabaseModelImpl::ResetModelAccess() );
}
m_pImpl.clear();
}
// -----------------------------------------------------------------------------
// XComponent
void SAL_CALL ODatabaseDocument::dispose( ) throw (RuntimeException)
{
::cppu::WeakComponentImplHelperBase::dispose();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::addEventListener( const Reference< css::lang::XEventListener >& _xListener ) throw (RuntimeException)
{
::cppu::WeakComponentImplHelperBase::addEventListener(_xListener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeEventListener( const Reference< css::lang::XEventListener >& _xListener ) throw (RuntimeException)
{
::cppu::WeakComponentImplHelperBase::removeEventListener(_xListener);
}
// XServiceInfo
//------------------------------------------------------------------------------
rtl::OUString ODatabaseDocument::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------------------
rtl::OUString ODatabaseDocument::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii("com.sun.star.comp.dba.ODatabaseDocument");
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > ODatabaseDocument::getSupportedServiceNames( ) throw (RuntimeException)
{
return getSupportedServiceNames_Static();
}
//------------------------------------------------------------------------------
Reference< XInterface > ODatabaseDocument::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
return ODatabaseDocument_CreateInstance(_rxFactory);
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > ODatabaseDocument::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aSNS( 2 );
aSNS[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.OfficeDatabaseDocument"));
aSNS[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.OfficeDocument"));
return aSNS;
}
//------------------------------------------------------------------------------
sal_Bool ODatabaseDocument::supportsService( const ::rtl::OUString& _rServiceName ) throw (RuntimeException)
{
return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0;
}
// -----------------------------------------------------------------------------
Reference< XDataSource > SAL_CALL ODatabaseDocument::getDataSource() throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->getDataSource();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::disposing( const ::com::sun::star::lang::EventObject& Source ) throw(RuntimeException)
{
if ( m_pImpl.is() )
m_pImpl->disposing(Source);
}
//------------------------------------------------------------------
Reference< XInterface > ODatabaseDocument::getThis()
{
return *this;
}
//------------------------------------------------------------------
//........................................................................
} // namespace dbaccess
//........................................................................
INTEGRATION: CWS dba202c (1.22.50); FILE MERGED
2005/12/05 12:16:58 oj 1.22.50.1: #128008 # check storage, wehn null throw IOException
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: databasedocument.cxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: kz $ $Date: 2006-01-03 16:14:40 $
*
* 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 _DBA_COREDATAACCESS_DATASOURCE_HXX_
#include "datasource.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_DATABASEDOCUMENT_HXX_
#include "databasedocument.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#include <comphelper/documentconstants.hxx>
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_ERRORCODEIOEXCEPTION_HPP_
#include <com/sun/star/task/ErrorCodeIOException.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_DATABASECONTEXT_HXX_
#include "databasecontext.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _ERRCODE_HXX
#include <tools/errcode.hxx>
#endif
#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#include <comphelper/mediadescriptor.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONSTORAGE_HPP_
#include <com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTIONBROADCASTER_HPP_
#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEMBEDPERSIST_HPP_
#include <com/sun/star/embed/XEmbedPersist.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_
#include <com/sun/star/embed/EntryInitModes.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_
#include <com/sun/star/view/XSelectionSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif
namespace css = ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::view;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml::sax;
using namespace ::cppu;
using namespace ::osl;
namespace css = ::com::sun::star;
//........................................................................
namespace dbaccess
{
//........................................................................
//============================================================
//= ODatabaseContext
//============================================================
DBG_NAME(ODatabaseDocument)
//--------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_ODatabaseDocument()
{
static OMultiInstanceAutoRegistration< ODatabaseDocument > aAutoRegistration;
}
//--------------------------------------------------------------------------
Reference< XInterface > ODatabaseDocument_CreateInstance(const Reference< XMultiServiceFactory >& _rxFactory)
{
ODatabaseContext* pContext = NULL;
try
{
Reference<XUnoTunnel> xUnoTunnel(_rxFactory->createInstance(SERVICE_SDB_DATABASECONTEXT),UNO_QUERY);
if ( xUnoTunnel.is() )
pContext = reinterpret_cast<ODatabaseContext*>(xUnoTunnel->getSomething(ODatabaseContext::getUnoTunnelImplementationId()));
}
catch(Exception)
{
}
::rtl::Reference<ODatabaseModelImpl> pImpl(new ODatabaseModelImpl(_rxFactory));
pImpl->m_pDBContext = pContext;
Reference< XModel > xModel( pImpl->createNewModel_deliverOwnership() );
return xModel.get();
}
//--------------------------------------------------------------------------
ODatabaseDocument::ODatabaseDocument(const ::rtl::Reference<ODatabaseModelImpl>& _pImpl )
:ModelDependentComponent( _pImpl )
,ODatabaseDocument_OfficeDocument( getMutex() )
,m_aModifyListeners( getMutex() )
,m_aCloseListener( getMutex() )
,m_aDocEventListeners( getMutex() )
{
DBG_CTOR(ODatabaseDocument,NULL);
// adjust our readonly flag
try
{
m_xDocEventBroadcaster.set(m_pImpl->m_xServiceFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.GlobalEventBroadcaster"))),
UNO_QUERY);
}
catch(Exception)
{
OSL_ENSURE(0,"Could not create GlobalEventBroadcaster!");
}
Reference<XChild> xChild(m_pImpl->m_xForms.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
xChild.set(m_pImpl->m_xReports.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
xChild.set(m_pImpl->m_xTableDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
xChild.set(m_pImpl->m_xCommandDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(static_cast<OWeakObject*>(this));
}
//--------------------------------------------------------------------------
ODatabaseDocument::~ODatabaseDocument()
{
DBG_DTOR(ODatabaseDocument,NULL);
if ( !ODatabaseDocument_OfficeDocument::rBHelper.bInDispose && !ODatabaseDocument_OfficeDocument::rBHelper.bDisposed )
{
acquire();
dispose();
}
}
// -----------------------------------------------------------------------------
// local functions
// -----------------------------------------------------------------------------
void lcl_stripLoadArguments( ::comphelper::MediaDescriptor& _rDescriptor, Sequence< PropertyValue >& _rArgs )
{
_rDescriptor.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StatusIndicator" ) ) );
_rDescriptor.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InteractionHandler" ) ) );
_rDescriptor.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Model" ) ) );
_rDescriptor >> _rArgs;
}
// -----------------------------------------------------------------------------
void lcl_extractAndStartStatusIndicator( const ::comphelper::MediaDescriptor& _rDescriptor, Reference< XStatusIndicator >& _rxStatusIndicator,
Sequence< Any >& _rCallArgs )
{
try
{
_rxStatusIndicator = _rDescriptor.getUnpackedValueOrDefault( _rDescriptor.PROP_STATUSINDICATOR(), _rxStatusIndicator );
if ( _rxStatusIndicator.is() )
{
_rxStatusIndicator->start( ::rtl::OUString(), (sal_Int32)1000000 );
sal_Int32 nLength = _rCallArgs.getLength();
_rCallArgs.realloc( nLength + 1 );
_rCallArgs[ nLength ] <<= _rxStatusIndicator;
}
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "lcl_extractAndStartStatusIndicator: caught an exception!" );
}
}
// -----------------------------------------------------------------------------
// XModel
// ATTENTION: The Application controller attaches the same resource to force a reload.
sal_Bool SAL_CALL ODatabaseDocument::attachResource( const ::rtl::OUString& _rURL, const Sequence< PropertyValue >& _aArguments ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
try
{
m_pImpl->clearConnections();
m_pImpl->disposeStorages();
if ( m_pImpl->m_bOwnStorage )
::comphelper::disposeComponent(m_pImpl->m_xStorage);
Reference< XNameAccess > xContainer = m_pImpl->m_xForms;
::comphelper::disposeComponent(xContainer);
xContainer = m_pImpl->m_xReports;
::comphelper::disposeComponent(xContainer);
xContainer = m_pImpl->m_xTableDefinitions;
::comphelper::disposeComponent(xContainer);
xContainer = m_pImpl->m_xCommandDefinitions;
::comphelper::disposeComponent(xContainer);
m_pImpl->m_aContainer.clear();
m_pImpl->lateInit();
}
catch(const Exception&)
{
m_pImpl->m_xStorage = NULL;
}
m_pImpl->m_bDocumentReadOnly = sal_False;
::comphelper::MediaDescriptor aDescriptor( _aArguments );
lcl_stripLoadArguments( aDescriptor, m_pImpl->m_aArgs );
m_pImpl->m_sFileURL = _rURL;
m_pImpl->m_sRealFileURL = aDescriptor.getUnpackedValueOrDefault(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SalvagedFile" ) ), _rURL );
if ( !m_pImpl->m_sRealFileURL.getLength() )
m_pImpl->m_sRealFileURL = m_pImpl->m_sFileURL;
if ( !m_pImpl->m_sName.getLength() )
m_pImpl->m_sName = m_pImpl->m_sRealFileURL;
m_pImpl->getStorage();
try
{
Sequence<Any> aFilterArgs;
Reference<XStatusIndicator> xStatusIndicator;
lcl_extractAndStartStatusIndicator( aDescriptor, xStatusIndicator, aFilterArgs );
Reference<XImporter> xImporter(
m_pImpl->m_xServiceFactory->createInstanceWithArguments(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.sdb.DBFilter" ) ),
aFilterArgs
),
UNO_QUERY
);
if ( xImporter.is() )
{
Reference<XComponent> xComponent(*this,UNO_QUERY);
xImporter->setTargetDocument(xComponent);
Reference<XFilter> xFilter(xImporter,UNO_QUERY);
xFilter->filter(_aArguments);
if ( xStatusIndicator.is() )
xStatusIndicator->end();
}
else
return sal_False;
}
catch(const RuntimeException& e)
{
throw e;
}
catch(const Exception&)
{
return sal_False;
}
if ( m_pImpl->m_pDBContext )
{
m_pImpl->m_pDBContext->registerPrivate(m_pImpl->m_sRealFileURL,m_pImpl);
m_pImpl->setModified(sal_False);
}
return sal_True;
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODatabaseDocument::getURL( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_sRealFileURL;
}
// -----------------------------------------------------------------------------
Sequence< PropertyValue > SAL_CALL ODatabaseDocument::getArgs( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_aArgs;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::connectController( const Reference< XController >& _xController ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
m_pImpl->m_aControllers.push_back(_xController);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::disconnectController( const Reference< XController >& _xController ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
m_pImpl->m_aControllers.erase(::std::find(m_pImpl->m_aControllers.begin(),m_pImpl->m_aControllers.end(),_xController));
if ( m_pImpl->m_xCurrentController == _xController )
m_pImpl->m_xCurrentController = NULL;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::lockControllers( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
++m_pImpl->m_nControllerLockCount;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::unlockControllers( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
--m_pImpl->m_nControllerLockCount;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL ODatabaseDocument::hasControllersLocked( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_nControllerLockCount != 0;
}
// -----------------------------------------------------------------------------
Reference< XController > SAL_CALL ODatabaseDocument::getCurrentController() throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_xCurrentController.is() ? m_pImpl->m_xCurrentController : ( m_pImpl->m_aControllers.empty() ? Reference< XController >() : *m_pImpl->m_aControllers.begin() );
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::setCurrentController( const Reference< XController >& _xController ) throw (NoSuchElementException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
m_pImpl->m_xCurrentController = _xController;
}
// -----------------------------------------------------------------------------
Reference< XInterface > SAL_CALL ODatabaseDocument::getCurrentSelection( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XInterface > xRet;
Reference< XSelectionSupplier > xDocView( getCurrentController(), UNO_QUERY );
if ( xDocView.is() )
xRet.set(xDocView->getSelection(),UNO_QUERY);
return xRet;
}
// -----------------------------------------------------------------------------
// XStorable
sal_Bool SAL_CALL ODatabaseDocument::hasLocation( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_sRealFileURL.getLength() != 0;
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODatabaseDocument::getLocation( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_sRealFileURL;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL ODatabaseDocument::isReadonly( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_bDocumentReadOnly;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::store( ) throw (IOException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
if ( m_pImpl->m_sFileURL == m_pImpl->m_sRealFileURL )
store( m_pImpl->m_sFileURL, m_pImpl->m_aArgs );
else
storeAsURL( m_pImpl->m_sRealFileURL, m_pImpl->m_aArgs );
impl_notifyEvent( "OnSaveDone", aGuard );
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::store(const ::rtl::OUString& _rURL
,const Sequence< PropertyValue >& _rArguments)
{
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
if ( m_pImpl->m_bDocumentReadOnly )
throw IOException();
m_bCommitMasterStorage = sal_False;
m_pImpl->commitStorages();
m_bCommitMasterStorage = sal_True;
Reference<XStorage> xMyStorage = m_pImpl->getStorage();
OSL_ENSURE( xMyStorage.is(), "ODatabaseDocument::storeToURL: no own storage?" );
if ( !xMyStorage.is() )
{
IOException aError;
aError.Message = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Internal error: no source storage available." ) );
aError.Context = *this;
throw IOException( aError );
}
writeStorage(_rURL,_rArguments,xMyStorage);
m_pImpl->commitRootStorage();
setModified(sal_False);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::storeAsURL( const ::rtl::OUString& _rURL, const Sequence< PropertyValue >& _rArguments ) throw (IOException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XSingleServiceFactory > xStorageFactory( m_pImpl->createStorageFactory() );
if ( !xStorageFactory.is() )
throw RuntimeException();
// don't use _rURL - we might be recovering/salvaging a file currently ...
// #i45314# / 2005-03-21 / frank.schoenheit@sun.com
::comphelper::MediaDescriptor aDescriptor( _rArguments );
sal_Bool bLocationChanged = ( _rURL != m_pImpl->m_sFileURL );
if ( bLocationChanged )
{
Sequence<Any> aParam(2);
aParam[0] <<= _rURL;
aParam[1] <<= ElementModes::READWRITE | ElementModes::TRUNCATE;
Reference<XStorage> xStorage;
try
{
xStorage.set(xStorageFactory->createInstanceWithArguments( aParam ),UNO_QUERY);
}
catch(Exception&)
{
}
if ( !xStorage.is() )
throw IOException();
if ( m_pImpl->isEmbeddedDatabase() )
m_pImpl->clearConnections();
m_pImpl->commitEmbeddedStorage();
Reference<XStorage> xMyStorage = m_pImpl->getStorage();
if ( xMyStorage.is() )
{
m_pImpl->commitStorages();
xMyStorage->copyToStorage( xStorage );
}
m_pImpl->disposeStorages();
m_pImpl->m_xStorage = xStorage;
if ( m_pImpl->m_bOwnStorage )
::comphelper::disposeComponent(xMyStorage);
else
m_pImpl->m_bOwnStorage = sal_True;
m_pImpl->m_bDocumentReadOnly = sal_False;
if ( _rURL != m_pImpl->m_sRealFileURL )
{
if ( m_pImpl->m_pDBContext )
{
if ( m_pImpl->m_sRealFileURL.getLength() )
m_pImpl->m_pDBContext->nameChangePrivate(m_pImpl->m_sRealFileURL,_rURL);
else
m_pImpl->m_pDBContext->registerPrivate(_rURL,m_pImpl);
}
INetURLObject aURL( _rURL );
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
m_pImpl->m_sName = _rURL;
}
m_pImpl->m_sRealFileURL = m_pImpl->m_sFileURL = _rURL;
}
lcl_stripLoadArguments( aDescriptor, m_pImpl->m_aArgs );
store(m_pImpl->m_sFileURL,_rArguments);
impl_notifyEvent( "OnSaveAsDone", aGuard );
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::storeToURL( const ::rtl::OUString& _rURL, const Sequence< PropertyValue >& _rArguments ) throw (IOException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XSingleServiceFactory > xStorageFactory( m_pImpl->createStorageFactory() );
Sequence<Any> aParam(2);
aParam[0] <<= _rURL;
aParam[1] <<= ElementModes::READWRITE | ElementModes::TRUNCATE;
Reference<XStorage> xStorage;
if ( xStorageFactory.is() )
xStorage = xStorage.query( xStorageFactory->createInstanceWithArguments( aParam ) );
OSL_ENSURE( xStorage.is(), "ODatabaseDocument::storeToURL: no storage factory!" );
if ( !xStorage.is() )
{
IOException aError;
aError.Message = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Could not create a target storage." ) );
aError.Context = *this;
throw IOException( aError );
}
Reference<XStorage> xMyStorage = m_pImpl->getStorage();
OSL_ENSURE( xMyStorage.is(), "ODatabaseDocument::storeToURL: no own storage?" );
if ( !xMyStorage.is() )
{
IOException aError;
aError.Message = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Internal error: no source storage available." ) );
aError.Context = *this;
throw IOException( aError );
}
m_pImpl->commitEmbeddedStorage();
xMyStorage->copyToStorage( xStorage );
writeStorage(_rURL,_rArguments,xStorage);
try
{
Reference<XTransactedObject> xTransact(xStorage,UNO_QUERY);
if ( xTransact.is() )
xTransact->commit();
}
catch(Exception)
{
OSL_ENSURE(0,"Exception Caught: Could not store database!");
throw IOException();
}
}
// -----------------------------------------------------------------------------
// XModifyBroadcaster
void SAL_CALL ODatabaseDocument::addModifyListener( const Reference< XModifyListener >& _xListener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aModifyListeners.addInterface(_xListener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeModifyListener( const Reference< XModifyListener >& _xListener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aModifyListeners.removeInterface(_xListener);
}
// -----------------------------------------------------------------------------
// XModifiable
sal_Bool SAL_CALL ODatabaseDocument::isModified( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->m_bModified;
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::setModified( sal_Bool _bModified ) throw (PropertyVetoException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
if ( m_pImpl->m_bModified == _bModified )
return;
m_pImpl->m_bModified = _bModified;
lang::EventObject aEvt( *this );
aGuard.clear();
m_aModifyListeners.notifyEach( &XModifyListener::modified, aEvt );
aGuard.reset();
impl_notifyEvent( "OnModifyChanged", aGuard );
}
// ::com::sun::star::document::XEventBroadcaster
void SAL_CALL ODatabaseDocument::addEventListener(const css::uno::Reference< css::document::XEventListener >& _xListener ) throw (css::uno::RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aDocEventListeners.addInterface(_xListener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeEventListener( const css::uno::Reference< css::document::XEventListener >& _xListener ) throw (css::uno::RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aDocEventListeners.removeInterface(_xListener);
}
// -----------------------------------------------------------------------------
// ::com::sun::star::document::XEventListener
void SAL_CALL ODatabaseDocument::notifyEvent( const css::document::EventObject& aEvent ) throw (css::uno::RuntimeException)
{
ModelMethodGuard aGuard( *this );
// used only to forward external events (e.g. for doc creation) from the frame loader
// to the global event broadcaster and all other interested doc event listener.
impl_notifyEvent( aEvent.EventName, aGuard );
}
// -----------------------------------------------------------------------------
// ::com::sun::star::view::XPrintable
Sequence< PropertyValue > SAL_CALL ODatabaseDocument::getPrinter( ) throw (RuntimeException)
{
return Sequence< PropertyValue >();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::setPrinter( const Sequence< PropertyValue >& aPrinter ) throw (IllegalArgumentException, RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::print( const Sequence< PropertyValue >& xOptions ) throw (IllegalArgumentException, RuntimeException)
{
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::impl_closeControllerFrames( sal_Bool _bDeliverOwnership )
{
::std::vector< Reference< XController> > aCopy = m_pImpl->m_aControllers;
::std::vector< Reference< XController> >::iterator aIter = aCopy.begin();
::std::vector< Reference< XController> >::iterator aEnd = aCopy.end();
for ( ;aIter != aEnd ; ++aIter )
{
if ( aIter->is() )
{
try
{
Reference< XCloseable> xFrame( (*aIter)->getFrame(), UNO_QUERY );
if ( xFrame.is() )
xFrame->close( _bDeliverOwnership );
}
catch( const CloseVetoException& ) { throw; }
catch( const Exception& )
{
OSL_ENSURE( sal_False, "ODatabaseDocument::impl_closeControllerFrames: caught an unexpected exception!" );
}
}
}
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::close( sal_Bool _bDeliverOwnership ) throw (::com::sun::star::util::CloseVetoException, RuntimeException)
{
ModelMethodGuard aGuard( *this );
lang::EventObject aEvent( *this );
{
aGuard.clear();
m_aCloseListener.forEach< XCloseListener >(
boost::bind( &XCloseListener::queryClosing, _1, boost::cref( aEvent ), boost::cref( _bDeliverOwnership ) ) );
aGuard.reset();
}
DBG_ASSERT( m_pImpl->m_aControllers.empty(), "ODatabaseDocument::close: aren't controllers expected to veto the closing?" );
impl_closeControllerFrames( _bDeliverOwnership );
{
aGuard.clear();
m_aCloseListener.notifyEach( &XCloseListener::notifyClosing, aEvent );
aGuard.reset();
}
dispose();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::addCloseListener( const Reference< ::com::sun::star::util::XCloseListener >& Listener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aCloseListener.addInterface(Listener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeCloseListener( const Reference< ::com::sun::star::util::XCloseListener >& Listener ) throw (RuntimeException)
{
::connectivity::checkDisposed(ODatabaseDocument_OfficeDocument::rBHelper.bDisposed);
m_aCloseListener.removeInterface(Listener);
}
// -----------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL ODatabaseDocument::getFormDocuments( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XNameAccess > xContainer = m_pImpl->m_xForms;
if ( !xContainer.is() )
{
if ( !m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM].get() )
{
::rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM("forms"));
m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM] = TContentPtr(new ODefinitionContainer_Impl);
m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM]->m_pDataSource = m_pImpl.get();
m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM]->m_aProps.aTitle = sName;
}
xContainer = new ODocumentContainer(m_pImpl->m_xServiceFactory,*this,m_pImpl->m_aContainer[ODatabaseModelImpl::E_FORM],sal_True);
m_pImpl->m_xForms = xContainer;
}
return xContainer;
}
// -----------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL ODatabaseDocument::getReportDocuments( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
Reference< XNameAccess > xContainer = m_pImpl->m_xReports;
if ( !xContainer.is() )
{
if ( !m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT].get() )
{
m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT] = TContentPtr(new ODefinitionContainer_Impl);
::rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM("reports"));
m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT]->m_pDataSource = m_pImpl.get();
m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT]->m_aProps.aTitle = sName;
}
xContainer = new ODocumentContainer(m_pImpl->m_xServiceFactory,*this,m_pImpl->m_aContainer[ODatabaseModelImpl::E_REPORT],sal_False);
m_pImpl->m_xReports = xContainer;
}
return xContainer;
}
// -----------------------------------------------------------------------------
sal_Bool ODatabaseDocument::WriteThroughComponent(
const Reference<XComponent> & xComponent,
const sal_Char* pStreamName,
const sal_Char* pServiceName,
const Sequence<Any> & rArguments,
const Sequence<PropertyValue> & rMediaDesc,
sal_Bool bPlainStream
,const Reference<XStorage>& _xStorageToSaveTo)
{
OSL_ENSURE( NULL != pStreamName, "Need stream name!" );
OSL_ENSURE( NULL != pServiceName, "Need service name!" );
Reference<XStorage> xMyStorage = _xStorageToSaveTo;
// open stream
::rtl::OUString sStreamName = ::rtl::OUString::createFromAscii( pStreamName );
Reference<XStream> xStream = xMyStorage->openStreamElement( sStreamName,ElementModes::READWRITE | ElementModes::TRUNCATE );
if ( !xStream.is() )
return sal_False;
Reference<XOutputStream> xOutputStream = xStream->getOutputStream();
OSL_ENSURE(xOutputStream.is(), "Can't create output stream in package!");
if ( ! xOutputStream.is() )
return sal_False;
Reference<XPropertySet> xStreamProp(xOutputStream,UNO_QUERY);
OSL_ENSURE(xStreamProp.is(),"No valid preoperty set for the output stream!");
Reference<XSeekable> xSeek(xStreamProp,UNO_QUERY);
if ( xSeek.is() )
{
OSL_TRACE("Length of stream %i",(int)xSeek->getPosition());
xSeek->seek(0);
}
String aPropName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM("MediaType") ) );
::rtl::OUString aMime( RTL_CONSTASCII_USTRINGPARAM("text/xml") );
Any aAny;
aAny <<= aMime;
xStreamProp->setPropertyValue( aPropName, aAny );
if( bPlainStream )
{
::rtl::OUString aPropName( RTL_CONSTASCII_USTRINGPARAM("Compressed") );
sal_Bool bFalse = sal_False;
aAny.setValue( &bFalse, ::getBooleanCppuType() );
xStreamProp->setPropertyValue( aPropName, aAny );
}
else
{
::rtl::OUString aPropName( RTL_CONSTASCII_USTRINGPARAM("Encrypted") );
sal_Bool bTrue = sal_True;
aAny.setValue( &bTrue, ::getBooleanCppuType() );
xStreamProp->setPropertyValue( aPropName, aAny );
}
// set buffer and create outputstream
// write the stuff
sal_Bool bRet = WriteThroughComponent(
xOutputStream, xComponent,
pServiceName, rArguments, rMediaDesc );
// finally, commit stream.
return bRet;
}
sal_Bool ODatabaseDocument::WriteThroughComponent(
const Reference<XOutputStream> & xOutputStream,
const Reference<XComponent> & xComponent,
const sal_Char* pServiceName,
const Sequence<Any> & rArguments,
const Sequence<PropertyValue> & rMediaDesc)
{
OSL_ENSURE( xOutputStream.is(), "I really need an output stream!" );
OSL_ENSURE( xComponent.is(), "Need component!" );
OSL_ENSURE( NULL != pServiceName, "Need component name!" );
// get component
Reference< XActiveDataSource > xSaxWriter(
m_pImpl->m_xServiceFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer"))),
UNO_QUERY );
OSL_ENSURE( xSaxWriter.is(), "can't instantiate XML com.sun.star.xml.sax.Writer" );
if(!xSaxWriter.is())
return sal_False;
// connect XML writer to output stream
xSaxWriter->setOutputStream( xOutputStream );
// prepare arguments (prepend doc handler to given arguments)
Reference<XDocumentHandler> xDocHandler( xSaxWriter,UNO_QUERY);
Sequence<Any> aArgs( 1 + rArguments.getLength() );
aArgs[0] <<= xDocHandler;
for(sal_Int32 i = 0; i < rArguments.getLength(); i++)
aArgs[i+1] = rArguments[i];
// get filter component
Reference< XExporter > xExporter(
m_pImpl->m_xServiceFactory->createInstanceWithArguments(
::rtl::OUString::createFromAscii(pServiceName), aArgs), UNO_QUERY);
OSL_ENSURE( xExporter.is(),
"can't instantiate export filter component" );
if( !xExporter.is() )
return sal_False;
// connect model and filter
xExporter->setSourceDocument( xComponent );
// filter!
Reference<XFilter> xFilter( xExporter, UNO_QUERY );
return xFilter->filter( rMediaDesc );
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::writeStorage(const ::rtl::OUString& _rURL
,const Sequence< PropertyValue >& _rArguments
,const Reference<XStorage>& _xStorageToSaveTo)
{
// create XStatusIndicator
Reference<XStatusIndicator> xStatusIndicator;
Sequence< Any > aDelegatorArguments;
::comphelper::MediaDescriptor aDescriptor( _rArguments );
lcl_extractAndStartStatusIndicator( aDescriptor, xStatusIndicator, aDelegatorArguments );
// properties
Sequence < PropertyValue > aProps( _rURL.getLength() ? 1 : 0 );
if( _rURL.getLength() )
{
PropertyValue *pProps = aProps.getArray();
pProps->Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("FileName") );
(pProps++)->Value <<= _rURL;
}
// export sub streams for package, else full stream into a file
sal_Bool bWarn = sal_False, bErr = sal_False;
String sWarnFile, sErrFile;
Reference<XPropertySet> xProp(_xStorageToSaveTo,UNO_QUERY);
if ( xProp.is() )
{
static const ::rtl::OUString sPropName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MediaType"));
Any aAny;
aAny <<= MIMETYPE_OASIS_OPENDOCUMENT_DATABASE;
xProp->setPropertyValue( sPropName, aAny );
}
Reference<XComponent> xCom(static_cast<OWeakObject*>(this),UNO_QUERY);
if( !bErr )
{
if( !WriteThroughComponent(
xCom, "settings.xml",
"com.sun.star.comp.sdb.XMLSettingsExporter",
aDelegatorArguments, aProps, sal_True,_xStorageToSaveTo ) )
{
if( !bWarn )
{
bWarn = sal_True;
sWarnFile = String( RTL_CONSTASCII_STRINGPARAM("settings.xml"),
RTL_TEXTENCODING_ASCII_US );
}
}
}
if ( !bErr )
{
if( !WriteThroughComponent(
xCom, "content.xml",
"com.sun.star.comp.sdb.DBExportFilter",
aDelegatorArguments, aProps, sal_True,_xStorageToSaveTo ) )
{
bErr = sal_True;
sErrFile = String( RTL_CONSTASCII_STRINGPARAM("content.xml"),
RTL_TEXTENCODING_ASCII_US );
}
}
if ( xStatusIndicator.is() )
xStatusIndicator->end();
}
// -----------------------------------------------------------------------------
Reference< ::com::sun::star::ui::XUIConfigurationManager > SAL_CALL ODatabaseDocument::getUIConfigurationManager( ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
if ( !m_xUIConfigurationManager.is() )
{
m_xUIConfigurationManager = Reference< ::com::sun::star::ui::XUIConfigurationManager >(
m_pImpl->m_xServiceFactory->createInstance(
::rtl::OUString::createFromAscii( "com.sun.star.ui.UIConfigurationManager" )),
UNO_QUERY );
Reference< ::com::sun::star::ui::XUIConfigurationStorage > xUIConfigStorage( m_xUIConfigurationManager, UNO_QUERY );
if ( xUIConfigStorage.is() )
{
rtl::OUString aUIConfigFolderName( RTL_CONSTASCII_USTRINGPARAM( "Configurations2" ));
Reference< XStorage > xConfigStorage;
// First try to open with READWRITE and then READ
xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, ElementModes::READWRITE );
if ( xConfigStorage.is() )
{
rtl::OUString aMediaTypeProp( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ));
rtl::OUString aUIConfigMediaType( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.sun.xml.ui.configuration" ));
rtl::OUString aMediaType;
Reference< XPropertySet > xPropSet( xConfigStorage, UNO_QUERY );
Any a = xPropSet->getPropertyValue( aMediaTypeProp );
if ( !( a >>= aMediaType ) || ( aMediaType.getLength() == 0 ))
{
a <<= aUIConfigMediaType;
xPropSet->setPropertyValue( aMediaTypeProp, a );
}
}
else
xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, ElementModes::READ );
// initialize ui configuration manager with document substorage
xUIConfigStorage->setStorage( xConfigStorage );
}
}
return m_xUIConfigurationManager;
}
// -----------------------------------------------------------------------------
Reference< XStorage > SAL_CALL ODatabaseDocument::getDocumentSubStorage( const ::rtl::OUString& aStorageName, sal_Int32 nMode ) throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
Reference< XDocumentSubStorageSupplier > xStorageAccess( m_pImpl->getDocumentSubStorageSupplier() );
return xStorageAccess->getDocumentSubStorage( aStorageName, nMode );
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL ODatabaseDocument::getDocumentSubStoragesNames( ) throw (::com::sun::star::io::IOException, RuntimeException)
{
Reference< XDocumentSubStorageSupplier > xStorageAccess( m_pImpl->getDocumentSubStorageSupplier() );
return xStorageAccess->getDocumentSubStoragesNames();
}
// -----------------------------------------------------------------------------
void ODatabaseDocument::impl_notifyEvent( const ::rtl::OUString& _sEventName, ::osl::ClearableMutexGuard& _rGuard )
{
try
{
css::document::EventObject aEvt(*this, _sEventName);
Reference< XEventListener > xDocEventBroadcaster;
/// TODO: this code has to be deleted after AS' cws will be integrated
try
{
xDocEventBroadcaster = xDocEventBroadcaster.query( m_pImpl->m_xServiceFactory->createInstance(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.GlobalEventBroadcaster" ) ) ) );
}
catch(Exception)
{
OSL_ENSURE(0,"Could not create GlobalEventBroadcaster!");
}
_rGuard.clear();
if ( xDocEventBroadcaster.is() )
xDocEventBroadcaster->notifyEvent(aEvt);
m_aDocEventListeners.notifyEach( &css::document::XEventListener::notifyEvent, aEvt );
}
catch(Exception&)
{
}
}
//------------------------------------------------------------------------------
void ODatabaseDocument::disposing()
{
if ( !m_pImpl.is() )
{
// this means that we're already disposed
DBG_ASSERT( ODatabaseDocument_OfficeDocument::rBHelper.bDisposed, "ODatabaseDocument::disposing: no impl anymore, but not yet disposed!" );
return;
}
DBG_ASSERT( m_pImpl->m_aControllers.empty(), "ODatabaseDocument::disposing: there still are controllers!" );
// normally, nobody should explicitly dispose, but only XCloseable::close the document. And controllers
// are expected to veto the closing, so when we're here, there shouldn't be any controllers anymore.
m_pImpl->m_aControllers.clear();
Reference< XModel > xHoldAlive( this );
{
{
::osl::ClearableMutexGuard aGuard( getMutex() );
impl_notifyEvent( "OnUnload", aGuard );
}
css::lang::EventObject aDisposeEvent(static_cast<XWeak*>(this));
m_aModifyListeners.disposeAndClear( aDisposeEvent );
m_aCloseListener.disposeAndClear( aDisposeEvent );
m_aDocEventListeners.disposeAndClear( aDisposeEvent );
m_xDocEventBroadcaster = NULL;
m_xUIConfigurationManager = NULL;
Reference<XChild> xChild(m_pImpl->m_xForms.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
xChild.set(m_pImpl->m_xReports.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
xChild.set(m_pImpl->m_xTableDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
xChild.set(m_pImpl->m_xCommandDefinitions.get(),UNO_QUERY);
if ( xChild.is() )
xChild->setParent(NULL);
m_pImpl->modelIsDisposing( ODatabaseModelImpl::ResetModelAccess() );
}
m_pImpl.clear();
}
// -----------------------------------------------------------------------------
// XComponent
void SAL_CALL ODatabaseDocument::dispose( ) throw (RuntimeException)
{
::cppu::WeakComponentImplHelperBase::dispose();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::addEventListener( const Reference< css::lang::XEventListener >& _xListener ) throw (RuntimeException)
{
::cppu::WeakComponentImplHelperBase::addEventListener(_xListener);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::removeEventListener( const Reference< css::lang::XEventListener >& _xListener ) throw (RuntimeException)
{
::cppu::WeakComponentImplHelperBase::removeEventListener(_xListener);
}
// XServiceInfo
//------------------------------------------------------------------------------
rtl::OUString ODatabaseDocument::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------------------
rtl::OUString ODatabaseDocument::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii("com.sun.star.comp.dba.ODatabaseDocument");
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > ODatabaseDocument::getSupportedServiceNames( ) throw (RuntimeException)
{
return getSupportedServiceNames_Static();
}
//------------------------------------------------------------------------------
Reference< XInterface > ODatabaseDocument::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
return ODatabaseDocument_CreateInstance(_rxFactory);
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > ODatabaseDocument::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aSNS( 2 );
aSNS[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.OfficeDatabaseDocument"));
aSNS[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.OfficeDocument"));
return aSNS;
}
//------------------------------------------------------------------------------
sal_Bool ODatabaseDocument::supportsService( const ::rtl::OUString& _rServiceName ) throw (RuntimeException)
{
return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0;
}
// -----------------------------------------------------------------------------
Reference< XDataSource > SAL_CALL ODatabaseDocument::getDataSource() throw (RuntimeException)
{
ModelMethodGuard aGuard( *this );
OSL_ENSURE(m_pImpl.is(),"Impl is NULL");
return m_pImpl->getDataSource();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseDocument::disposing( const ::com::sun::star::lang::EventObject& Source ) throw(RuntimeException)
{
if ( m_pImpl.is() )
m_pImpl->disposing(Source);
}
//------------------------------------------------------------------
Reference< XInterface > ODatabaseDocument::getThis()
{
return *this;
}
//------------------------------------------------------------------
//........................................................................
} // namespace dbaccess
//........................................................................
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\BatchEncoder.h"
#include "..\utilities\Utilities.h"
#include "..\utilities\UnicodeUtf8.h"
#include "..\utilities\Utf8String.h"
#include "..\dialogs\BatchEncoderDlg.h"
#include "WorkThread.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
DWORD WINAPI ReadThread(LPVOID lpParam)
{
// NOTE: 4096 bytes is default buffer for pipes (on XP SP2)
PREAD_DATA pReadData = (PREAD_DATA)lpParam;
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesRead = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
bool bRunning = true;
pReadData->bError = false;
pReadData->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pReadData->szFileName,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pReadData->bError = true;
pReadData->bFinished = true;
return(1);
}
nFileSize = GetFileSize64(hFile);
if (nFileSize == 0)
{
pReadData->bError = true;
pReadData->bFinished = true;
::CloseHandle(hFile);
return(1);
}
// read/write loop
do
{
// read data from source file
bRes = ::ReadFile(hFile, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// NOTE: Sleep(0) solves problem writing to pipe error (MPPDEC)
::Sleep(0);
// write data to write pipe
bRes = ::WriteFile(pReadData->hPipe, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesRead += dwReadBytes;
nProgress = (int)((nTotalBytesRead * 100) / nFileSize);
bRunning = pReadData->pDlg->WorkerCallback(nProgress, false);
if (bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
// check if all data was processed
if (nTotalBytesRead != nFileSize)
{
pReadData->bError = true;
pReadData->bFinished = true;
return(1);
}
pReadData->bError = false;
pReadData->bFinished = true;
return(0);
}
DWORD WINAPI WriteThread(LPVOID lpParam)
{
// NOTE: 4096 bytes is default buffer for pipes (on XP SP2)
PREAD_DATA pReadData = (PREAD_DATA)lpParam;
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesWrite = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
pReadData->bError = false;
pReadData->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pReadData->szFileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pReadData->bError = true;
pReadData->bFinished = true;
return(1);
}
// read/write loop
do
{
// read data from source pipe
bRes = ::ReadFile(pReadData->hPipe, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// write data to file
bRes = ::WriteFile(hFile, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesWrite += dwReadBytes;
// handle user Stop
if (pReadData->pDlg->bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
pReadData->bError = false;
pReadData->bFinished = true;
return(0);
}
bool ConvertFile(CBatchEncoderDlg *pDlg,
CString szInputFile,
CString szOutputFile,
TCHAR *szCommandLine,
int nIndex,
bool bDecode,
int nTool,
bool bUseReadPipes,
bool bUseWritePipes)
{
// TODO:
// if there is no input pipes and output pipes are enabled
// we can not get progress status for out ProgressBars
// so for encoder/decoder mode treat this as an error
// and for trans-coding thread this as decoder to encoder piping
// TODO: handle bUseWritePipes flag mostly like bUseReadPipes
// NOTE: bUseReadPipes
// if true use pipes to read source file and send the data to console stdin
// if false create full command-line and read from stdout/stderr conversion progress
// log console text output
bool bLogConsoleOutput = false;
CMenu *mainMenu = pDlg->GetMenu();
UINT nState = mainMenu->GetMenuState(ID_OPTIONS_LOGCONSOLEOUTPUT, MF_BYCOMMAND);
if (nState & MF_CHECKED)
bLogConsoleOutput = true;
// set the correct security attributes
SECURITY_ATTRIBUTES secattr;
ZeroMemory(&secattr, sizeof(secattr));
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = TRUE;
HANDLE rOutErrPipe = INVALID_HANDLE_VALUE;
HANDLE wOutErrPipe = INVALID_HANDLE_VALUE;
HANDLE rInPipe = INVALID_HANDLE_VALUE;
HANDLE wInPipe = INVALID_HANDLE_VALUE;
HANDLE rOutPipe = INVALID_HANDLE_VALUE;
HANDLE wOutPipe = INVALID_HANDLE_VALUE;
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
// create pipes for stdout and stderr
BOOL bRet = FALSE;
bRet = ::CreatePipe(&rOutErrPipe, &wOutErrPipe, &secattr, 0);
if (bRet == FALSE)
{
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
else
{
if (bUseReadPipes == true)
{
// create pipes for stdin
BOOL bRet = FALSE;
bRet = ::CreatePipe(&rInPipe, &wInPipe, &secattr, 0);
if (bRet == FALSE)
{
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
if (bUseWritePipes == true)
{
// create pipes for stdout
BOOL bRet = FALSE;
bRet = ::CreatePipe(&rOutPipe, &wOutPipe, &secattr, 0);
if (bRet == FALSE)
{
if (bUseReadPipes == true)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
}
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
}
// this pipes are not inherited by child process
// Windows XP or later
if (true)
{
if (bUseReadPipes == true)
{
BOOL bRet = FALSE;
bRet = ::SetHandleInformation(wInPipe, HANDLE_FLAG_INHERIT, 0);
if (bRet == FALSE)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
if (bUseWritePipes == true)
{
BOOL bRet = FALSE;
bRet = ::SetHandleInformation(rOutPipe, HANDLE_FLAG_INHERIT, 0);
if (bRet == FALSE)
{
if (bUseWritePipes == true)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
}
::CloseHandle(rOutPipe);
::CloseHandle(wOutPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
}
// NOTE: DuplicateHandle prevents child process to close pipe
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
// this could be useful when reading from stderr
if (::DuplicateHandle(::GetCurrentProcess(),
rOutErrPipe,
::GetCurrentProcess(),
&rOutErrPipe,
0,
TRUE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == FALSE)
{
::CloseHandle(rOutErrPipe);
::CloseHandle(wOutErrPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
STARTUPINFO sInfo;
ZeroMemory(&sInfo, sizeof(sInfo));
PROCESS_INFORMATION pInfo;
ZeroMemory(&pInfo, sizeof(pInfo));
sInfo.cb = sizeof(sInfo);
sInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
// TODO:
// when read pipes are disabled and write pipes enabled
// we maybe can get stderr progress from console
// this was tested not tested with command-line tools
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
sInfo.hStdInput = NULL;
sInfo.hStdOutput = wOutErrPipe;
sInfo.hStdError = wOutErrPipe;
}
else
{
if ((bUseReadPipes == true) && (bUseWritePipes == false))
{
sInfo.hStdInput = rInPipe;
sInfo.hStdOutput = NULL;
sInfo.hStdError = NULL;
}
else if ((bUseReadPipes == false) && (bUseWritePipes == true))
{
sInfo.hStdInput = NULL;
sInfo.hStdOutput = wOutPipe;
sInfo.hStdError = NULL;
}
else if ((bUseReadPipes == true) && (bUseWritePipes == true))
{
sInfo.hStdInput = rInPipe;
sInfo.hStdOutput = wOutPipe;
sInfo.hStdError = NULL;
}
}
int nProgress = 0;
CTimeCount countTime;
// init conversion time counter
countTime.InitCounter();
// and start it right now
countTime.StartCounter();
if (pDlg->m_Config.m_Options.bForceConsoleWindow == true)
{
// in this mode all encoders/decoders are forced
// to run in native system console windows
// all pipes and progress options are omitted
int nRet;
_flushall();
nRet = ::_tsystem(NULL);
if ((nRet == 0) && (errno == ENOENT))
{
// the command interpreter is not found
nProgress = -1;
}
else
{
// remove path to tool and leave only raw tool name
// note that this is complicated method and in future
// we need to simplify creation of command-line for system
// or use CreateProcess here instead of using _tsystem
CString szSysCommandLine = szCommandLine;
CString szToolName;
CString szToolPath;
CString szReplace;
int nStart = szSysCommandLine.Find('"', 0);
int nEnd = szSysCommandLine.Find('"', nStart + 1);
szToolPath = szSysCommandLine;
szToolPath.Truncate(nEnd);
szReplace = szToolPath + _T("\"");
szToolPath.TrimLeft(_T("\""));
szToolName = ::GetFileName(szToolPath);
szToolPath = szToolPath.TrimRight(szToolName);
szToolName.Replace(_T("\""), _T(""));
szSysCommandLine.Replace(szReplace, szToolName);
// set tool name to current dir because using only tool .exe name
::SetCurrentDirectory(szToolPath);
// use system(...) stdlib.h/process.h function
_flushall();
nRet = ::_tsystem(szSysCommandLine); // szCommandLine
if (nRet == -1)
{
nProgress = -1;
}
else
{
nProgress = 100;
}
}
}
else
{
// NOTE: lpCurrentDirectory param may be useful when app is loading some dll's
BOOL bRet = FALSE;
bRet = ::CreateProcess(0,
szCommandLine,
0,
0,
TRUE,
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW /* | CREATE_SUSPENDED */,
0,
0,
&sInfo,
&pInfo);
if (bRet == FALSE)
{
countTime.StopCounter();
::CloseHandle(rOutErrPipe);
::CloseHandle(wOutErrPipe);
if (bUseReadPipes == true)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
}
if (bUseWritePipes == true)
{
::CloseHandle(rOutPipe);
::CloseHandle(wOutPipe);
}
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
// close unused pipes handles
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
::CloseHandle(wOutErrPipe);
}
else
{
if (bUseReadPipes == true)
::CloseHandle(rInPipe);
if (bUseWritePipes == true)
::CloseHandle(wOutPipe);
}
bool bWriteSuccess = false;
READ_DATA rd;
READ_DATA wd;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
if (bUseReadPipes == true)
{
// NOTE: get pipe buffer size
// DWORD dwOutBufferSize, dwInBufferSize, dwMaxInstances;
// ::GetNamedPipeInfo(wInPipe, NULL, &dwOutBufferSize, &dwInBufferSize, &dwMaxInstances);
rd.bError = false;
rd.bFinished = false;
rd.pDlg = pDlg;
rd.szFileName = szInputFile;
rd.hPipe = wInPipe;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL,
0,
ReadThread,
(LPVOID)&rd,
/* CREATE_SUSPENDED */ 0,
&dwReadThreadID);
if (hReadThread == NULL)
{
countTime.StopCounter();
::CloseHandle(wInPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
// ::ResumeThread(pInfo.hThread);
// ::ResumeThread(hReadThread);
if (bUseWritePipes == false)
{
::WaitForSingleObject(hReadThread, INFINITE);
::CloseHandle(wInPipe);
// check for result from read thread
if ((rd.bError == false) && (rd.bFinished == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
}
// NOTE:
// write pipes may cause serious problems
// because seeking on written file is impossible
// this means that file headers can not be written
// NOTE: write pipes are designed for trans-coding only
if (bUseWritePipes == true)
{
// NOTE: get pipe buffer size
// DWORD dwOutBufferSize, dwInBufferSize, dwMaxInstances;
// ::GetNamedPipeInfo(rInPipe, NULL, &dwOutBufferSize, &dwInBufferSize, &dwMaxInstances);
wd.bError = false;
wd.bFinished = false;
wd.pDlg = pDlg;
wd.szFileName = szOutputFile;
wd.hPipe = rOutPipe;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL,
0,
WriteThread,
(LPVOID)&wd,
/* CREATE_SUSPENDED */ 0,
&dwWriteThreadID);
if (hWriteThread == NULL)
{
countTime.StopCounter();
::CloseHandle(rOutPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
// ::ResumeThread(pInfo.hThread);
// ::ResumeThread(hWriteThread);
::WaitForSingleObject(hWriteThread, INFINITE);
::CloseHandle(rOutPipe);
// check for result from read thread
if ((wd.bError == false) && (wd.bFinished == true))
{
bWriteSuccess = true;
if (bUseReadPipes == false)
nProgress = 100;
}
else
{
bWriteSuccess = false;
if (bUseReadPipes == false)
nProgress = -1;
}
// close read thread handle
::CloseHandle(hWriteThread);
}
if ((bUseReadPipes == true) && (bUseWritePipes == true))
{
::WaitForSingleObject(hReadThread, INFINITE);
::CloseHandle(wInPipe);
// check for result from read thread
if ((rd.bError == false) && (rd.bFinished == true) && (bWriteSuccess == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
// ::ResumeThread(pInfo.hThread);
// NOTE:
// is there a need to check console output code-page
// all apps should be using system code-page
// or they are using UNICODE output?
char szReadBuff[512];
char szLineBuff[512];
DWORD dwReadBytes = 0L;
BOOL bRes = FALSE;
bool bLineStart;
bool bLineEnd;
bool bRunning = true;
int nLineLen = 0;
// init buffers
ZeroMemory(szReadBuff, sizeof(szReadBuff));
ZeroMemory(szLineBuff, sizeof(szLineBuff));
// NOTE: what we get first start of line or end of line?
bLineStart = false;
bLineEnd = false;
// create logfile
CFile fp;
bool bHaveLogFile = false;
if (bLogConsoleOutput == true)
{
::UpdatePath();
if (fp.Open(pDlg->m_Config.m_Options.szLogFileName, CFile::modeWrite | CFile::modeNoTruncate | CFile::modeCreate) == TRUE)
{
bHaveLogFile = true;
if (fp.GetLength() == (ULONGLONG)0)
{
const unsigned char szHeaderUnicode[2] = { 0xFFU, 0xFEU };
const unsigned char szHeaderUtf8[3] = { 0xEFU, 0xBBU, 0xBFU };
switch (pDlg->m_Config.m_Options.nLogEncoding)
{
case 1: // UNICODE
fp.Write(szHeaderUnicode, 2);
fp.Flush();
break;
case 2: // UTF-8
fp.Write(szHeaderUtf8, 3);
fp.Flush();
break;
};
}
fp.SeekToEnd();
}
}
// NOTE: preload all progress dll's before conversion process
// load progress function
typedef int(*lpfnGetProgress)(char *szLineBuff, int nLineLen);
lpfnGetProgress pProgressProc;
HMODULE hDll = ::LoadLibrary(pDlg->m_Config.m_Formats[nTool].szFunction);
if (hDll != NULL)
{
// NOTE: the GetProcAddress function has only ANSI version
pProgressProc = (lpfnGetProgress) ::GetProcAddress(hDll, "GetProgress");
if (pProgressProc == NULL)
return false; // ERROR
// TODO: when failed to load dll we need to do more clean-up
}
// main loop
do
{
ZeroMemory(szReadBuff, sizeof(szReadBuff));
// check if there is something to read, only for debug
// DWORD dwAvailable;
// ::PeekNamedPipe(rOutErrPipe, NULL, 0, NULL, &dwAvailable, NULL);
bRes = ::ReadFile(rOutErrPipe, szReadBuff, 100, &dwReadBytes, 0);
if (bRes == FALSE || dwReadBytes == 0)
break;
// terminate readed data by '\0'
szReadBuff[dwReadBytes] = '\0';
for (int i = 0; i < (int)dwReadBytes; i++)
{
// NOTE: processed escape chars ( \r \n \t \b )
if (szReadBuff[i] == '\r') // '\r'
{
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (szReadBuff[i] == '\n') // '\n'
{
// do nothing
}
else if (szReadBuff[i] == '\t') // '\t'
{
// do nothing
}
else if (szReadBuff[i] == '\b') // '\b'
{
// do nothing in most situations
// NOTE: special case for wavpack and wvunpack
if (((bDecode == false) && (nTool == 9)) || // WAVPACK
((bDecode == true) && (nTool == 26))) // WVUNPACK
{
// NOTE: same code as if(szReadBuff[i] == '\r')
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
}
else if (bLineEnd == false)
{
bLineStart = true; // for sure we have start
nLineLen++;
szLineBuff[nLineLen - 1] = szReadBuff[i];
}
// now we have correct full line of text
if ((bLineEnd == true) && (bLineStart == false))
{
// don't include empty lines
if (strlen(szLineBuff) > 0)
{
if (bDecode == false)
{
int nRet = (pProgressProc)(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
}
else
{
int nRet = (pProgressProc)(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
}
// log all console output for error checking
if (bLogConsoleOutput == true)
{
if ((bHaveLogFile == true)
&& (fp.m_hFile != NULL)
&& (strlen(szLineBuff) > (size_t)0))
{
switch (pDlg->m_Config.m_Options.nLogEncoding)
{
case 0: // ANSI, default string is ANSI
{
fp.Write(szLineBuff, (UINT)strlen(szLineBuff));
fp.Write("\r\n", 2);
fp.Flush();
}
break;
case 1: // UNICODE
{
wchar_t *pszBuffUnicode;
UnicodeEncode(szLineBuff, &pszBuffUnicode);
fp.Write(pszBuffUnicode, (UINT)wcslen(pszBuffUnicode) * 2);
fp.Write(L"\r\n", 4);
fp.Flush();
free(pszBuffUnicode);
}
break;
case 2: // UTF-8
{
char *pszBuffUtf8;
Utf8Encode(szLineBuff, &pszBuffUtf8);
fp.Write(pszBuffUtf8, (UINT)strlen(pszBuffUtf8));
fp.Write("\r\n", 2);
fp.Flush();
free(pszBuffUtf8);
}
break;
default:
break;
};
}
}
ZeroMemory(szLineBuff, sizeof(szLineBuff));
bRunning = pDlg->WorkerCallback(nProgress, false);
if (bRunning == false)
break;
}
// reset line counter
nLineLen = 0;
// now find next start
bLineStart = true;
bLineEnd = false;
}
}
if (bRunning == false)
break;
} while (bRes);
// free memory by unloading unused dll
if (hDll != NULL)
::FreeLibrary(hDll);
// close logfile
if ((bLogConsoleOutput == true) && (bHaveLogFile = true))
{
fp.Close();
bHaveLogFile = false;
}
::CloseHandle(rOutErrPipe);
}
}
// finished, stop conversion time counter
countTime.StopCounter();
if (pDlg->m_Config.m_Options.bForceConsoleWindow == false)
{
// terminate console process if there was error
HANDLE hProc;
hProc = ::OpenProcess(PROCESS_ALL_ACCESS, TRUE, pInfo.dwProcessId); // PROCESS_TERMINATE
if (hProc != NULL)
{
if (nProgress == 100)
{
// when properly finishing we need to wait
// for process to terminate = 5 seconds max
// here we are doing this right and clean
DWORD dwRet = ::WaitForSingleObject(hProc, 2000);
switch (dwRet)
{
case WAIT_FAILED:
// failed, probably process has finished, but error could be to
::TerminateProcess(hProc, 0);
break;
case WAIT_ABANDONED:
// skip, only for mutex objects
break;
case WAIT_OBJECT_0:
// skip, object is signaled, process has terminated
break;
case WAIT_TIMEOUT:
// time-out interval elapsed
// object's state is non-signaled
// used when user had pressed stop button
::TerminateProcess(hProc, 0);
break;
};
}
else
{
// don't wait for process to terminate because
// this code is only executed when user pressed Stop
::TerminateProcess(hProc, 0);
// wait for process to terminate = 5 seconds max
// this is because process must release file handles
// and we need to delete it if there was an error
::WaitForSingleObject(hProc, 5000);
}
// release process handle
::CloseHandle(hProc);
}
::CloseHandle(pInfo.hProcess);
::CloseHandle(pInfo.hThread);
}
pDlg->WorkerCallback(nProgress, true, false, countTime.GetTime(), nIndex);
if (nProgress == 100)
return true;
else
return false;
}
DWORD WINAPI WorkThread(LPVOID lpParam)
{
// NOTE:
// input and output filenames are UNICODE but
// we can convert it to OS current code-page using CharToOem
// this should work if UNICODE chars are in code-page of OS
::UpdatePath();
// get handle of main dialog
CBatchEncoderDlg *pDlg = (CBatchEncoderDlg *)lpParam;
if (pDlg == NULL)
return (DWORD)(-1);
TCHAR szCommandLine[(64 * 1024)];
ZeroMemory(szCommandLine, sizeof(szCommandLine));
// check for delete flag
bool bDeleteAfterconversion = false;
if (pDlg->GetMenu()->GetMenuState(ID_OPTIONS_DELETESOURCEFILEWHENDONE, MF_BYCOMMAND) == MF_CHECKED)
bDeleteAfterconversion = true;
else
bDeleteAfterconversion = false;
// check for output path
CString szOutPath;
bool bOutPath;
pDlg->m_EdtOutPath.GetWindowText(szOutPath);
if (pDlg->m_ChkOutPath.GetCheck() == BST_CHECKED)
bOutPath = true;
else
bOutPath = false;
// get number of files in ListView
int nFiles = pDlg->m_LstInputItems.GetItemCount();
// get number of checked files in ListView
int nTotalFiles = 0;
int nProcessedFiles = 0;
int nDoneWithoutError = 0;
int nErrors = 0;
for (int i = 0; i < nFiles; i++)
{
if (pDlg->m_LstInputItems.GetCheck(i) == TRUE)
nTotalFiles++;
}
CTimeCount countTime;
countTime.InitCounter();
countTime.StartCounter();
// process all checked files
for (int i = 0; i < nFiles; i++)
{
// get next file name and check if we need to encode/decode/trans-code
if (pDlg->m_LstInputItems.GetCheck(i) == TRUE)
{
// update status-bar conversion status
nProcessedFiles++;
nErrors = (nProcessedFiles - 1) - nDoneWithoutError;
CString szText;
szText.Format(_T("Processing item %d of %d (%d Done, %d %s)"),
nProcessedFiles,
nTotalFiles,
nDoneWithoutError,
nErrors,
((nErrors == 0) || (nErrors > 1)) ? _T("Errors") : _T("Error"));
VERIFY(pDlg->m_StatusBar.SetText(szText, 1, 0));
// reset progress bar on start of next file
pDlg->m_FileProgress.SetPos(0);
// scroll list to ensure the item is visible
pDlg->m_LstInputItems.EnsureVisible(i, FALSE);
// TODO: when trans-coding on decode pass sum the decode+encode passes as one
// in the total progress-bar calculations
// processing modes:
// 0 - encoding - input is WAV file and we only have to encode
// 1 - decoding - we only have to decode input file to WAV
// 2 - trans-coding - we need to decode input file to encoder stdin stream
int nProcessingMode = -1;
// get input file format
int nIntputFormat = pDlg->m_Config.m_Items.GetItemInFormat(i);
// get output file format
int nOutputFormat = pDlg->m_Config.m_Items.GetItemOutFormat(i);
// get output preset for selected format
int nPreset = pDlg->m_Config.m_Items.GetItemOutPreset(i);
// get full file path
CString szInputFile = pDlg->m_Config.m_Items.GetItemFilePath(i);
// output path is same as input file path
if (bOutPath == false)
{
szOutPath = szInputFile;
CString szToRemove = pDlg->m_Config.m_Items.GetFileName(szInputFile);
int nNewLenght = szOutPath.GetLength() - szToRemove.GetLength();
szOutPath.Truncate(nNewLenght);
}
// setup decoder steps:
// 1. set encoder exe path
// 2. set encoder options string
CString szDecoderExePath;
CString szDecoderOptions;
szDecoderExePath = pDlg->GetDecoderExe(nIntputFormat);
szDecoderOptions = pDlg->GetDecoderOpt(nIntputFormat, -1);
// get only output filename
CString szName = pDlg->m_Config.m_Items.GetItemFileName(i);
// setup encoder steps:
// 1. add extension to output filename
// 2. set encoder exe path
// 3. set encoder options string
CString szEncoderExePath;
CString szEncoderOptions;
szEncoderExePath = pDlg->GetEncoderExe(nOutputFormat);
szEncoderOptions = pDlg->GetEncoderOpt(nOutputFormat, nPreset);
szName = szName + _T(".") + pDlg->m_Config.m_Items.GetItemOutExt(i).MakeLower();
// set full path for output file
CString szOutputFile;
if (szOutPath.GetLength() >= 1)
{
if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/')
szOutputFile = szOutPath + szName;
else
szOutputFile = szOutPath + _T("\\") + szName;
}
else
{
szOutputFile = szName;
}
// set proper processing mode
nProcessingMode = 1;
if (nIntputFormat == 0)
nProcessingMode = 0;
if (nProcessingMode == 1)
nProcessingMode = 2;
// [1] Input is WAV, [Output is WAV], No Resampling = Copy Input File (using SSRC without options)
// [2] Input is WAV, [Output is WAV], Resampling = Encode Input File (using SSRC)
// [3] Input need decoding, [Output is WAV], No Resampling = Decode Input File (using Decoder)
// [4] Input need decoding, [Output is WAV], Resampling = Decode and Encode (using Decoder and SSRC)
if (nOutputFormat == 0)
{
bool bNeedResampling = (szEncoderOptions.GetLength() > 0) ? true : false;
// case 1
if ((nIntputFormat == 0) && (bNeedResampling == false))
nProcessingMode = 0;
// case 2
if ((nIntputFormat == 0) && (bNeedResampling == true))
nProcessingMode = 0;
// case 3
if ((nIntputFormat > 0) && (bNeedResampling == false))
nProcessingMode = 1;
// case 4
if ((nIntputFormat > 0) && (bNeedResampling == true))
nProcessingMode = 2;
}
// build proper command-line depending on processing mode:
CString csExecute;
bool bDecode = false;
int nTool = -1;
bool bUseInPipesEnc = false;
bool bUseOutPipesEnc = false;
bool bUseInPipesDec = false;
bool bUseOutPipesDec = false;
CString szOrgInputFile = szInputFile;
CString szOrgOutputFile = szOutputFile;
// decode
if ((nProcessingMode == 1) || (nProcessingMode == 2))
{
if (pDlg->m_Config.m_Options.bForceConsoleWindow == false)
{
// configure decoder input and output pipes
bUseInPipesDec = pDlg->m_Config.m_Formats[(NUM_OUTPUT_EXT + nIntputFormat - 1)].bInput;
bUseOutPipesDec = pDlg->m_Config.m_Formats[(NUM_OUTPUT_EXT + nIntputFormat - 1)].bOutput;
}
// input file is stdin
if (bUseInPipesDec == true)
szInputFile = _T("-");
// output file is stdout
if (bUseOutPipesDec == true)
szOutputFile = _T("-");
// TODO:
// bUseOutPipes == true then handle szOutputFile same as input file
if (nProcessingMode == 2)
szOutputFile = szOutputFile + _T(".wav");
// TODO: validate the command-line template
// build full command line for decoder (DECODER-EXE + OPTIONS + INFILE + OUTFILE)
// this is basic model, some of encoder may have different command-line structure
csExecute = pDlg->m_Config.m_Formats[(NUM_OUTPUT_EXT + nIntputFormat - 1)].szTemplate;
csExecute.Replace(_T("$EXE"), _T("\"$EXE\""));
csExecute.Replace(_T("$EXE"), szDecoderExePath);
csExecute.Replace(_T("$OPTIONS"), szDecoderOptions);
csExecute.Replace(_T("$INFILE"), _T("\"$INFILE\""));
csExecute.Replace(_T("$INFILE"), szInputFile);
csExecute.Replace(_T("$OUTFILE"), _T("\"$OUTFILE\""));
csExecute.Replace(_T("$OUTFILE"), szOutputFile);
bDecode = true;
nTool = (NUM_OUTPUT_EXT + nIntputFormat - 1);
lstrcpy(szCommandLine, csExecute.GetBuffer(csExecute.GetLength()));
pDlg->m_LstInputItems.SetItemText(i, 5, _T("--:--"));
pDlg->m_LstInputItems.SetItemText(i, 6, _T("Decoding..."));
// TODO: when decoding in nProcessingMode == 2 don't show time stats
if (::ConvertFile(pDlg,
szOrgInputFile,
szOrgOutputFile,
szCommandLine,
i,
bDecode,
nTool,
bUseInPipesDec,
bUseOutPipesDec) == true)
{
if (nProcessingMode == 1)
nDoneWithoutError++;
if (bDeleteAfterconversion == true)
::DeleteFile(szOrgInputFile);
if (nProcessingMode == 1)
pDlg->m_LstInputItems.SetCheck(i, FALSE);
}
else
{
// delete output file on error
if (pDlg->m_Config.m_Options.bDeleteOnError == true)
::DeleteFile(szOutputFile);
if (pDlg->bRunning == false)
break;
// stop conversion process on error
if (pDlg->m_Config.m_Options.bStopOnErrors == true)
break;
// in processing mode 2 we are skipping to next file
// no encoding is done when decoding failed
continue;
}
}
if (pDlg->bRunning == false)
break;
if (pDlg->m_Config.m_Options.bForceConsoleWindow == false)
{
// configure encoder input and output pipes
bUseInPipesEnc = pDlg->m_Config.m_Formats[nOutputFormat].bInput;
bUseOutPipesEnc = pDlg->m_Config.m_Formats[nOutputFormat].bOutput;
}
if (nProcessingMode == 0)
{
// input file is stdin
if (bUseInPipesEnc == true)
szInputFile = _T("-");
// output file is stdout
if (bUseOutPipesEnc == true)
szOutputFile = _T("-");
}
if (nProcessingMode == 2)
{
// input filename is decoded output filename
szInputFile = szOutputFile;
szOrgInputFile = szOutputFile;
// restore output filename
szOutputFile = szOrgOutputFile;
// input file is stdin
if (bUseInPipesEnc == true)
szInputFile = _T("-");
// output file is stdout
if (bUseOutPipesEnc == true)
szOutputFile = _T("-");
}
// encode
if ((nProcessingMode == 0) || (nProcessingMode == 2))
{
// TODO: validate the command-line template
// build full command line for encoder (ENCODER-EXE + OPTIONS + INFILE + OUTFILE)
// this is basic model, some of encoder may have different command-line structure
csExecute = pDlg->m_Config.m_Formats[nOutputFormat].szTemplate;
csExecute.Replace(_T("$EXE"), _T("\"$EXE\""));
csExecute.Replace(_T("$EXE"), szEncoderExePath);
csExecute.Replace(_T("$OPTIONS"), szEncoderOptions);
csExecute.Replace(_T("$INFILE"), _T("\"$INFILE\""));
csExecute.Replace(_T("$INFILE"), szInputFile);
csExecute.Replace(_T("$OUTFILE"), _T("\"$OUTFILE\""));
csExecute.Replace(_T("$OUTFILE"), szOutputFile);
bDecode = false;
nTool = nOutputFormat;
lstrcpy(szCommandLine, csExecute.GetBuffer(csExecute.GetLength()));
pDlg->m_LstInputItems.SetItemText(i, 5, _T("--:--"));
pDlg->m_LstInputItems.SetItemText(i, 6, _T("Encoding..."));
if (::ConvertFile(pDlg,
szOrgInputFile,
szOrgOutputFile,
szCommandLine,
i,
bDecode,
nTool,
bUseInPipesEnc,
bUseOutPipesEnc) == true)
{
nDoneWithoutError++;
if (bDeleteAfterconversion == true)
::DeleteFile(szOrgInputFile);
pDlg->m_LstInputItems.SetCheck(i, FALSE);
}
else
{
// delete output file on error
if (pDlg->m_Config.m_Options.bDeleteOnError == true)
::DeleteFile(szOutputFile);
// stop conversion process on error
if (pDlg->m_Config.m_Options.bStopOnErrors == true)
break;
}
// delete temporary file
if (nProcessingMode == 2)
::DeleteFile(szOrgInputFile);
}
if (pDlg->bRunning == false)
break;
}
}
countTime.StopCounter();
// show total time
if (nProcessedFiles > 0)
{
CString szText;
szText.Format(_T("Done in %s"), ::FormatTime(countTime.GetTime(), 3));
pDlg->m_StatusBar.SetText(szText, 1, 0);
}
else
{
pDlg->m_StatusBar.SetText(_T(""), 1, 0);
}
// restore user interface to default state
if (pDlg->m_Config.m_Options.bShowTrayIcon == true)
pDlg->EnableTrayIcon(true, true);
pDlg->m_BtnConvert.SetWindowText(_T("Conve&rt"));
pDlg->GetMenu()->ModifyMenu(ID_ACTION_CONVERT, MF_BYCOMMAND, ID_ACTION_CONVERT, _T("Conve&rt\tF9"));
pDlg->m_FileProgress.SetPos(0);
pDlg->bRunning = false;
pDlg->EnableUserInterface(TRUE);
// now we shutdown the system
if (pDlg->GetMenu()->GetMenuState(ID_OPTIONS_SHUTDOWN_WHEN_FINISHED, MF_BYCOMMAND) == MF_CHECKED)
{
// NOTE: before shutdown we are doing OnClose() stuff
// save current configuration to file
if (pDlg->GetMenu()->GetMenuState(ID_OPTIONS_DO_NOT_SAVE, MF_BYCOMMAND) != MF_CHECKED)
pDlg->SaveConfigFile(pDlg->szMainConfigFile);
// disable tray icon
pDlg->EnableTrayIcon(false);
::DoTheShutdown();
}
// close this worker thread handle
return ::CloseHandle(pDlg->hThread);
}
Update WorkThread.cpp
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\BatchEncoder.h"
#include "..\utilities\Utilities.h"
#include "..\utilities\UnicodeUtf8.h"
#include "..\utilities\Utf8String.h"
#include "..\dialogs\BatchEncoderDlg.h"
#include "WorkThread.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
DWORD WINAPI ReadThread(LPVOID lpParam)
{
PREAD_DATA pReadData = (PREAD_DATA)lpParam;
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesRead = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
bool bRunning = true;
pReadData->bError = false;
pReadData->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pReadData->szFileName,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pReadData->bError = true;
pReadData->bFinished = true;
return(1);
}
nFileSize = GetFileSize64(hFile);
if (nFileSize == 0)
{
pReadData->bError = true;
pReadData->bFinished = true;
::CloseHandle(hFile);
return(1);
}
// read/write loop
do
{
// read data from source file
bRes = ::ReadFile(hFile, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// NOTE: Sleep(0) solves problem writing to pipe error (MPPDEC)
::Sleep(0);
// write data to write pipe
bRes = ::WriteFile(pReadData->hPipe, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesRead += dwReadBytes;
nProgress = (int)((nTotalBytesRead * 100) / nFileSize);
bRunning = pReadData->pDlg->WorkerCallback(nProgress, false);
if (bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
// check if all data was processed
if (nTotalBytesRead != nFileSize)
{
pReadData->bError = true;
pReadData->bFinished = true;
return(1);
}
pReadData->bError = false;
pReadData->bFinished = true;
return(0);
}
DWORD WINAPI WriteThread(LPVOID lpParam)
{
PREAD_DATA pReadData = (PREAD_DATA)lpParam;
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesWrite = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
pReadData->bError = false;
pReadData->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pReadData->szFileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pReadData->bError = true;
pReadData->bFinished = true;
return(1);
}
// read/write loop
do
{
// read data from source pipe
bRes = ::ReadFile(pReadData->hPipe, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// write data to file
bRes = ::WriteFile(hFile, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesWrite += dwReadBytes;
// handle user Stop
if (pReadData->pDlg->bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
pReadData->bError = false;
pReadData->bFinished = true;
return(0);
}
bool ConvertFile(CBatchEncoderDlg *pDlg,
CString szInputFile,
CString szOutputFile,
TCHAR *szCommandLine,
int nIndex,
bool bDecode,
int nTool,
bool bUseReadPipes,
bool bUseWritePipes)
{
// TODO:
// if there is no input pipe and output pipe enabled
// we can not get progress status for the ProgressBars
// so for encoder/decoder mode treat this as an error
// and for trans-coding treat this as decoder to encoder piping
// TODO: handle bUseWritePipes flag like bUseReadPipes
// NOTE: bUseReadPipes
// if true use pipes to read source file and send the data to console stdin
// if false create full command-line and read from stdout/stderr conversion progress
// log console text output
bool bLogConsoleOutput = pDlg->GetMenu()->GetMenuState(ID_OPTIONS_LOGCONSOLEOUTPUT, MF_BYCOMMAND) & MF_CHECKED;
// set the correct security attributes
SECURITY_ATTRIBUTES secattr;
ZeroMemory(&secattr, sizeof(secattr));
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = TRUE;
HANDLE rOutErrPipe = INVALID_HANDLE_VALUE;
HANDLE wOutErrPipe = INVALID_HANDLE_VALUE;
HANDLE rInPipe = INVALID_HANDLE_VALUE;
HANDLE wInPipe = INVALID_HANDLE_VALUE;
HANDLE rOutPipe = INVALID_HANDLE_VALUE;
HANDLE wOutPipe = INVALID_HANDLE_VALUE;
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
// create pipes for stdout and stderr
BOOL bRet = FALSE;
bRet = ::CreatePipe(&rOutErrPipe, &wOutErrPipe, &secattr, 0);
if (bRet == FALSE)
{
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
else
{
if (bUseReadPipes == true)
{
// create pipes for stdin
BOOL bRet = FALSE;
bRet = ::CreatePipe(&rInPipe, &wInPipe, &secattr, 0);
if (bRet == FALSE)
{
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
if (bUseWritePipes == true)
{
// create pipes for stdout
BOOL bRet = FALSE;
bRet = ::CreatePipe(&rOutPipe, &wOutPipe, &secattr, 0);
if (bRet == FALSE)
{
if (bUseReadPipes == true)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
}
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
}
// this pipes are not inherited by child process
// Windows XP or later
if (true)
{
if (bUseReadPipes == true)
{
BOOL bRet = FALSE;
bRet = ::SetHandleInformation(wInPipe, HANDLE_FLAG_INHERIT, 0);
if (bRet == FALSE)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
if (bUseWritePipes == true)
{
BOOL bRet = FALSE;
bRet = ::SetHandleInformation(rOutPipe, HANDLE_FLAG_INHERIT, 0);
if (bRet == FALSE)
{
if (bUseWritePipes == true)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
}
::CloseHandle(rOutPipe);
::CloseHandle(wOutPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
}
// NOTE: DuplicateHandle prevents child process to close pipe
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
// NOTE: this could be used when reading from stderr
if (::DuplicateHandle(::GetCurrentProcess(),
rOutErrPipe,
::GetCurrentProcess(),
&rOutErrPipe,
0,
TRUE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == FALSE)
{
::CloseHandle(rOutErrPipe);
::CloseHandle(wOutErrPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
}
STARTUPINFO sInfo;
ZeroMemory(&sInfo, sizeof(sInfo));
PROCESS_INFORMATION pInfo;
ZeroMemory(&pInfo, sizeof(pInfo));
sInfo.cb = sizeof(sInfo);
sInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
// TODO:
// when read pipes are disabled and write pipes enabled
// we can try to get stderr progress from console
// this was tested not tested with command-line tools
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
sInfo.hStdInput = NULL;
sInfo.hStdOutput = wOutErrPipe;
sInfo.hStdError = wOutErrPipe;
}
else
{
if ((bUseReadPipes == true) && (bUseWritePipes == false))
{
sInfo.hStdInput = rInPipe;
sInfo.hStdOutput = NULL;
sInfo.hStdError = NULL;
}
else if ((bUseReadPipes == false) && (bUseWritePipes == true))
{
sInfo.hStdInput = NULL;
sInfo.hStdOutput = wOutPipe;
sInfo.hStdError = NULL;
}
else if ((bUseReadPipes == true) && (bUseWritePipes == true))
{
sInfo.hStdInput = rInPipe;
sInfo.hStdOutput = wOutPipe;
sInfo.hStdError = NULL;
}
}
int nProgress = 0;
CTimeCount countTime;
// init and start conversion time counter
countTime.InitCounter();
countTime.StartCounter();
if (pDlg->m_Config.m_Options.bForceConsoleWindow == true)
{
// in this mode all encoders/decoders are forced
// to run in native system console window
// all pipes and progress options are omitted
int nRet;
_flushall();
nRet = ::_tsystem(NULL);
if ((nRet == 0) && (errno == ENOENT))
{
// the command interpreter is not found
nProgress = -1;
}
else
{
// remove path to tool and leave only raw tool name
// note that this is complicated method and in future
// we need to simplify creation of command-line for system
// or use CreateProcess here instead of using _tsystem
CString szSysCommandLine = szCommandLine;
CString szToolName;
CString szToolPath;
CString szReplace;
int nStart = szSysCommandLine.Find('"', 0);
int nEnd = szSysCommandLine.Find('"', nStart + 1);
szToolPath = szSysCommandLine;
szToolPath.Truncate(nEnd);
szReplace = szToolPath + _T("\"");
szToolPath.TrimLeft(_T("\""));
szToolName = ::GetFileName(szToolPath);
szToolPath = szToolPath.TrimRight(szToolName);
szToolName.Replace(_T("\""), _T(""));
szSysCommandLine.Replace(szReplace, szToolName);
// set tool name to current dir because using only tool .exe name
::SetCurrentDirectory(szToolPath);
// use system(...) stdlib.h/process.h function
_flushall();
nRet = ::_tsystem(szSysCommandLine); // szCommandLine
if (nRet == -1)
nProgress = -1;
else
nProgress = 100;
}
}
else
{
// NOTE: lpCurrentDirectory param may be useful when app is loading some dll's
BOOL bRet = FALSE;
bRet = ::CreateProcess(0,
szCommandLine,
0,
0,
TRUE,
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW /* | CREATE_SUSPENDED */,
0,
0,
&sInfo,
&pInfo);
if (bRet == FALSE)
{
countTime.StopCounter();
::CloseHandle(rOutErrPipe);
::CloseHandle(wOutErrPipe);
if (bUseReadPipes == true)
{
::CloseHandle(rInPipe);
::CloseHandle(wInPipe);
}
if (bUseWritePipes == true)
{
::CloseHandle(rOutPipe);
::CloseHandle(wOutPipe);
}
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
// close unused pipes handles
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
::CloseHandle(wOutErrPipe);
}
else
{
if (bUseReadPipes == true)
::CloseHandle(rInPipe);
if (bUseWritePipes == true)
::CloseHandle(wOutPipe);
}
bool bWriteSuccess = false;
READ_DATA rd;
READ_DATA wd;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
if (bUseReadPipes == true)
{
// NOTE: get pipe buffer size
// DWORD dwOutBufferSize, dwInBufferSize, dwMaxInstances;
// ::GetNamedPipeInfo(wInPipe, NULL, &dwOutBufferSize, &dwInBufferSize, &dwMaxInstances);
rd.bError = false;
rd.bFinished = false;
rd.pDlg = pDlg;
rd.szFileName = szInputFile;
rd.hPipe = wInPipe;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL,
0,
ReadThread,
(LPVOID)&rd,
/* CREATE_SUSPENDED */ 0,
&dwReadThreadID);
if (hReadThread == NULL)
{
countTime.StopCounter();
::CloseHandle(wInPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
// ::ResumeThread(pInfo.hThread);
// ::ResumeThread(hReadThread);
if (bUseWritePipes == false)
{
::WaitForSingleObject(hReadThread, INFINITE);
::CloseHandle(wInPipe);
// check for result from read thread
if ((rd.bError == false) && (rd.bFinished == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
}
// NOTE:
// write pipes may cause serious problems
// because seeking on written file is impossible
// this means that file headers can not be written
// NOTE: write pipes are designed for trans-coding only
if (bUseWritePipes == true)
{
// NOTE: get pipe buffer size
// DWORD dwOutBufferSize, dwInBufferSize, dwMaxInstances;
// ::GetNamedPipeInfo(rInPipe, NULL, &dwOutBufferSize, &dwInBufferSize, &dwMaxInstances);
wd.bError = false;
wd.bFinished = false;
wd.pDlg = pDlg;
wd.szFileName = szOutputFile;
wd.hPipe = rOutPipe;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL,
0,
WriteThread,
(LPVOID)&wd,
/* CREATE_SUSPENDED */ 0,
&dwWriteThreadID);
if (hWriteThread == NULL)
{
countTime.StopCounter();
::CloseHandle(rOutPipe);
pDlg->WorkerCallback(-1, true, true, 0.0, nIndex);
return false;
}
// ::ResumeThread(pInfo.hThread);
// ::ResumeThread(hWriteThread);
::WaitForSingleObject(hWriteThread, INFINITE);
::CloseHandle(rOutPipe);
// check for result from read thread
if ((wd.bError == false) && (wd.bFinished == true))
{
bWriteSuccess = true;
if (bUseReadPipes == false)
nProgress = 100;
}
else
{
bWriteSuccess = false;
if (bUseReadPipes == false)
nProgress = -1;
}
// close read thread handle
::CloseHandle(hWriteThread);
}
if ((bUseReadPipes == true) && (bUseWritePipes == true))
{
::WaitForSingleObject(hReadThread, INFINITE);
::CloseHandle(wInPipe);
// check for result from read thread
if ((rd.bError == false) && (rd.bFinished == true) && (bWriteSuccess == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
if ((bUseReadPipes == false) && (bUseWritePipes == false))
{
// ::ResumeThread(pInfo.hThread);
// NOTE:
// dow we need to check console output code-page?
// all apps should be using system code-page or they are using UNICODE output?
char szReadBuff[512];
char szLineBuff[512];
DWORD dwReadBytes = 0L;
BOOL bRes = FALSE;
bool bLineStart;
bool bLineEnd;
bool bRunning = true;
int nLineLen = 0;
// init buffers
ZeroMemory(szReadBuff, sizeof(szReadBuff));
ZeroMemory(szLineBuff, sizeof(szLineBuff));
// NOTE: what we get is first start of line or end of line?
bLineStart = false;
bLineEnd = false;
// create logfile
CFile fp;
bool bHaveLogFile = false;
if (bLogConsoleOutput == true)
{
::UpdatePath();
if (fp.Open(pDlg->m_Config.m_Options.szLogFileName, CFile::modeWrite | CFile::modeNoTruncate | CFile::modeCreate) == TRUE)
{
bHaveLogFile = true;
if (fp.GetLength() == (ULONGLONG)0)
{
const unsigned char szHeaderUnicode[2] = { 0xFFU, 0xFEU };
const unsigned char szHeaderUtf8[3] = { 0xEFU, 0xBBU, 0xBFU };
switch (pDlg->m_Config.m_Options.nLogEncoding)
{
case 1: // UNICODE
fp.Write(szHeaderUnicode, 2);
fp.Flush();
break;
case 2: // UTF-8
fp.Write(szHeaderUtf8, 3);
fp.Flush();
break;
};
}
fp.SeekToEnd();
}
}
// NOTE: preload all progress dll's before conversion process
// load progress function
typedef int(*lpfnGetProgress)(char *szLineBuff, int nLineLen);
lpfnGetProgress pProgressProc;
HMODULE hDll = ::LoadLibrary(pDlg->m_Config.m_Formats[nTool].szFunction);
if (hDll != NULL)
{
// NOTE: the GetProcAddress function has only ANSI version
pProgressProc = (lpfnGetProgress) ::GetProcAddress(hDll, "GetProgress");
if (pProgressProc == NULL)
return false; // ERROR
// TODO: when failed to load dll we need to do more clean-up
}
// main loop
do
{
ZeroMemory(szReadBuff, sizeof(szReadBuff));
// check if there is something to read, only for debug
// DWORD dwAvailable;
// ::PeekNamedPipe(rOutErrPipe, NULL, 0, NULL, &dwAvailable, NULL);
bRes = ::ReadFile(rOutErrPipe, szReadBuff, 100, &dwReadBytes, 0);
if (bRes == FALSE || dwReadBytes == 0)
break;
// terminate readed data by '\0'
szReadBuff[dwReadBytes] = '\0';
for (int i = 0; i < (int)dwReadBytes; i++)
{
// NOTE: processed escape chars ( \r \n \t \b )
if (szReadBuff[i] == '\r') // '\r'
{
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (szReadBuff[i] == '\n') // '\n'
{
// do nothing
}
else if (szReadBuff[i] == '\t') // '\t'
{
// do nothing
}
else if (szReadBuff[i] == '\b') // '\b'
{
// do nothing in most situations
// NOTE: special case for wavpack and wvunpack
if (((bDecode == false) && (nTool == 9)) || // WAVPACK
((bDecode == true) && (nTool == 26))) // WVUNPACK
{
// NOTE: same code as if(szReadBuff[i] == '\r')
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
}
else if (bLineEnd == false)
{
bLineStart = true; // we have start
nLineLen++;
szLineBuff[nLineLen - 1] = szReadBuff[i];
}
// now we have correct full line of text
if ((bLineEnd == true) && (bLineStart == false))
{
// don't include empty lines
if (strlen(szLineBuff) > 0)
{
if (bDecode == false)
{
int nRet = (pProgressProc)(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
}
else
{
int nRet = (pProgressProc)(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
}
// log all console output for error checking
if (bLogConsoleOutput == true)
{
if ((bHaveLogFile == true)
&& (fp.m_hFile != NULL)
&& (strlen(szLineBuff) > (size_t)0))
{
switch (pDlg->m_Config.m_Options.nLogEncoding)
{
case 0: // ANSI, default string is ANSI
{
fp.Write(szLineBuff, (UINT)strlen(szLineBuff));
fp.Write("\r\n", 2);
fp.Flush();
}
break;
case 1: // UNICODE
{
wchar_t *pszBuffUnicode;
UnicodeEncode(szLineBuff, &pszBuffUnicode);
fp.Write(pszBuffUnicode, (UINT)wcslen(pszBuffUnicode) * 2);
fp.Write(L"\r\n", 4);
fp.Flush();
free(pszBuffUnicode);
}
break;
case 2: // UTF-8
{
char *pszBuffUtf8;
Utf8Encode(szLineBuff, &pszBuffUtf8);
fp.Write(pszBuffUtf8, (UINT)strlen(pszBuffUtf8));
fp.Write("\r\n", 2);
fp.Flush();
free(pszBuffUtf8);
}
break;
default:
break;
};
}
}
ZeroMemory(szLineBuff, sizeof(szLineBuff));
bRunning = pDlg->WorkerCallback(nProgress, false);
if (bRunning == false)
break;
}
// reset line counter
nLineLen = 0;
// now find next start
bLineStart = true;
bLineEnd = false;
}
}
if (bRunning == false)
break;
} while (bRes);
// free memory by unloading unused dll
if (hDll != NULL)
::FreeLibrary(hDll);
// close logfile
if ((bLogConsoleOutput == true) && (bHaveLogFile = true))
{
fp.Close();
bHaveLogFile = false;
}
::CloseHandle(rOutErrPipe);
}
}
// finished, stop conversion time counter
countTime.StopCounter();
if (pDlg->m_Config.m_Options.bForceConsoleWindow == false)
{
// terminate console process if there was error
HANDLE hProc;
hProc = ::OpenProcess(PROCESS_ALL_ACCESS, TRUE, pInfo.dwProcessId); // PROCESS_TERMINATE
if (hProc != NULL)
{
if (nProgress == 100)
{
// when properly finishing we need to wait
// for process to terminate = 5 seconds max
DWORD dwRet = ::WaitForSingleObject(hProc, 2000);
switch (dwRet)
{
case WAIT_FAILED:
// failed, probably process has finished, but error could be to
::TerminateProcess(hProc, 0);
break;
case WAIT_ABANDONED:
// skip, only for mutex objects
break;
case WAIT_OBJECT_0:
// skip, object is signaled, process has terminated
break;
case WAIT_TIMEOUT:
// time-out interval elapsed
// object's state is non-signaled
// used when user had pressed stop button
::TerminateProcess(hProc, 0);
break;
};
}
else
{
// don't wait for process to terminate because
// this code is only executed when user pressed Stop
::TerminateProcess(hProc, 0);
// wait for process to terminate = 5 seconds max
// this is because process must release file handles
// and we need to delete it if there was an error
::WaitForSingleObject(hProc, 5000);
}
// release process handle
::CloseHandle(hProc);
}
::CloseHandle(pInfo.hProcess);
::CloseHandle(pInfo.hThread);
}
pDlg->WorkerCallback(nProgress, true, false, countTime.GetTime(), nIndex);
if (nProgress == 100)
return true;
else
return false;
}
DWORD WINAPI WorkThread(LPVOID lpParam)
{
// NOTE:
// input and output filenames are UNICODE but
// we can convert it to OS current code-page using CharToOem
// this should work if UNICODE chars are in code-page of OS
::UpdatePath();
// get handle of main dialog
CBatchEncoderDlg *pDlg = (CBatchEncoderDlg *)lpParam;
if (pDlg == NULL)
return (DWORD)(-1);
TCHAR szCommandLine[(64 * 1024)];
ZeroMemory(szCommandLine, sizeof(szCommandLine));
// check for delete flag
bool bDeleteAfterconversion = pDlg->GetMenu()->GetMenuState(ID_OPTIONS_DELETESOURCEFILEWHENDONE, MF_BYCOMMAND) == MF_CHECKED;
// check for output path
CString szOutPath;
pDlg->m_EdtOutPath.GetWindowText(szOutPath);
bool bOutPath = pDlg->m_ChkOutPath.GetCheck() == BST_CHECKED;
// get number of files in ListView
int nFiles = pDlg->m_LstInputItems.GetItemCount();
// get number of checked files in ListView
int nTotalFiles = 0;
int nProcessedFiles = 0;
int nDoneWithoutError = 0;
int nErrors = 0;
for (int i = 0; i < nFiles; i++)
{
if (pDlg->m_LstInputItems.GetCheck(i) == TRUE)
nTotalFiles++;
}
CTimeCount countTime;
countTime.InitCounter();
countTime.StartCounter();
// process all checked files
for (int i = 0; i < nFiles; i++)
{
// get next file name and check if we need to encode/decode/trans-code
if (pDlg->m_LstInputItems.GetCheck(i) == TRUE)
{
// update status-bar conversion status
nProcessedFiles++;
nErrors = (nProcessedFiles - 1) - nDoneWithoutError;
CString szText;
szText.Format(_T("Processing item %d of %d (%d Done, %d %s)"),
nProcessedFiles,
nTotalFiles,
nDoneWithoutError,
nErrors,
((nErrors == 0) || (nErrors > 1)) ? _T("Errors") : _T("Error"));
VERIFY(pDlg->m_StatusBar.SetText(szText, 1, 0));
// reset progress bar on start of next file
pDlg->m_FileProgress.SetPos(0);
// scroll list to ensure the item is visible
pDlg->m_LstInputItems.EnsureVisible(i, FALSE);
// TODO:
// when trans-coding on decode pass sum the decode+encode passes as one
// in the total progress-bar calculations
// processing modes:
// 0. encoding - input is WAV file and we only have to encode
// 1. decoding - we only have to decode input file to WAV
// 2. trans-coding - we need to decode input file to encoder stdin stream
int nProcessingMode = -1;
// get input file format
int nIntputFormat = pDlg->m_Config.m_Items.GetItemInFormat(i);
// get output file format
int nOutputFormat = pDlg->m_Config.m_Items.GetItemOutFormat(i);
// get output preset for selected format
int nPreset = pDlg->m_Config.m_Items.GetItemOutPreset(i);
// get full file path
CString szInputFile = pDlg->m_Config.m_Items.GetItemFilePath(i);
// output path is same as input file path
if (bOutPath == false)
{
szOutPath = szInputFile;
CString szToRemove = pDlg->m_Config.m_Items.GetFileName(szInputFile);
int nNewLenght = szOutPath.GetLength() - szToRemove.GetLength();
szOutPath.Truncate(nNewLenght);
}
// setup decoder steps:
// 1. set encoder exe path
// 2. set encoder options string
CString szDecoderExePath;
CString szDecoderOptions;
szDecoderExePath = pDlg->GetDecoderExe(nIntputFormat);
szDecoderOptions = pDlg->GetDecoderOpt(nIntputFormat, -1);
// get only output filename
CString szName = pDlg->m_Config.m_Items.GetItemFileName(i);
// setup encoder steps:
// 1. add extension to output filename
// 2. set encoder exe path
// 3. set encoder options string
CString szEncoderExePath;
CString szEncoderOptions;
szEncoderExePath = pDlg->GetEncoderExe(nOutputFormat);
szEncoderOptions = pDlg->GetEncoderOpt(nOutputFormat, nPreset);
szName = szName + _T(".") + pDlg->m_Config.m_Items.GetItemOutExt(i).MakeLower();
// set full path for output file
CString szOutputFile;
if (szOutPath.GetLength() >= 1)
{
if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/')
szOutputFile = szOutPath + szName;
else
szOutputFile = szOutPath + _T("\\") + szName;
}
else
{
szOutputFile = szName;
}
// set proper processing mode
nProcessingMode = 1;
if (nIntputFormat == 0)
nProcessingMode = 0;
if (nProcessingMode == 1)
nProcessingMode = 2;
// 1. Input is WAV, [Output is WAV], No Resampling = Copy Input File (using SSRC without options)
// 2. Input is WAV, [Output is WAV], Resampling = Encode Input File (using SSRC)
// 3. Input need decoding, [Output is WAV], No Resampling = Decode Input File (using Decoder)
// 4. Input need decoding, [Output is WAV], Resampling = Decode and Encode (using Decoder and SSRC)
if (nOutputFormat == 0)
{
bool bNeedResampling = (szEncoderOptions.GetLength() > 0) ? true : false;
// case 1
if ((nIntputFormat == 0) && (bNeedResampling == false))
nProcessingMode = 0;
// case 2
if ((nIntputFormat == 0) && (bNeedResampling == true))
nProcessingMode = 0;
// case 3
if ((nIntputFormat > 0) && (bNeedResampling == false))
nProcessingMode = 1;
// case 4
if ((nIntputFormat > 0) && (bNeedResampling == true))
nProcessingMode = 2;
}
// build proper command-line depending on processing mode:
CString csExecute;
bool bDecode = false;
int nTool = -1;
bool bUseInPipesEnc = false;
bool bUseOutPipesEnc = false;
bool bUseInPipesDec = false;
bool bUseOutPipesDec = false;
CString szOrgInputFile = szInputFile;
CString szOrgOutputFile = szOutputFile;
// decode
if ((nProcessingMode == 1) || (nProcessingMode == 2))
{
if (pDlg->m_Config.m_Options.bForceConsoleWindow == false)
{
// configure decoder input and output pipes
bUseInPipesDec = pDlg->m_Config.m_Formats[(NUM_OUTPUT_EXT + nIntputFormat - 1)].bInput;
bUseOutPipesDec = pDlg->m_Config.m_Formats[(NUM_OUTPUT_EXT + nIntputFormat - 1)].bOutput;
}
// input file is stdin
if (bUseInPipesDec == true)
szInputFile = _T("-");
// output file is stdout
if (bUseOutPipesDec == true)
szOutputFile = _T("-");
// TODO:
// bUseOutPipes == true than handle szOutputFile same as input file
if (nProcessingMode == 2)
szOutputFile = szOutputFile + _T(".wav");
// TODO: validate the command-line template
// build full command line for decoder (DECODER-EXE + OPTIONS + INFILE + OUTFILE)
// this is basic model, some of encoder may have different command-line structure
csExecute = pDlg->m_Config.m_Formats[(NUM_OUTPUT_EXT + nIntputFormat - 1)].szTemplate;
csExecute.Replace(_T("$EXE"), _T("\"$EXE\""));
csExecute.Replace(_T("$EXE"), szDecoderExePath);
csExecute.Replace(_T("$OPTIONS"), szDecoderOptions);
csExecute.Replace(_T("$INFILE"), _T("\"$INFILE\""));
csExecute.Replace(_T("$INFILE"), szInputFile);
csExecute.Replace(_T("$OUTFILE"), _T("\"$OUTFILE\""));
csExecute.Replace(_T("$OUTFILE"), szOutputFile);
bDecode = true;
nTool = (NUM_OUTPUT_EXT + nIntputFormat - 1);
lstrcpy(szCommandLine, csExecute.GetBuffer(csExecute.GetLength()));
pDlg->m_LstInputItems.SetItemText(i, 5, _T("--:--"));
pDlg->m_LstInputItems.SetItemText(i, 6, _T("Decoding..."));
// TODO: when decoding in nProcessingMode == 2 don't show time stats
if (::ConvertFile(pDlg,
szOrgInputFile,
szOrgOutputFile,
szCommandLine,
i,
bDecode,
nTool,
bUseInPipesDec,
bUseOutPipesDec) == true)
{
if (nProcessingMode == 1)
nDoneWithoutError++;
if (bDeleteAfterconversion == true)
::DeleteFile(szOrgInputFile);
if (nProcessingMode == 1)
pDlg->m_LstInputItems.SetCheck(i, FALSE);
}
else
{
// delete output file on error
if (pDlg->m_Config.m_Options.bDeleteOnError == true)
::DeleteFile(szOutputFile);
if (pDlg->bRunning == false)
break;
// stop conversion process on error
if (pDlg->m_Config.m_Options.bStopOnErrors == true)
break;
// in processing mode 2 we are skipping to next file
// no encoding is done when decoding failed
continue;
}
}
if (pDlg->bRunning == false)
break;
if (pDlg->m_Config.m_Options.bForceConsoleWindow == false)
{
// configure encoder input and output pipes
bUseInPipesEnc = pDlg->m_Config.m_Formats[nOutputFormat].bInput;
bUseOutPipesEnc = pDlg->m_Config.m_Formats[nOutputFormat].bOutput;
}
if (nProcessingMode == 0)
{
// input file is stdin
if (bUseInPipesEnc == true)
szInputFile = _T("-");
// output file is stdout
if (bUseOutPipesEnc == true)
szOutputFile = _T("-");
}
if (nProcessingMode == 2)
{
// input filename is decoded output filename
szInputFile = szOutputFile;
szOrgInputFile = szOutputFile;
// restore output filename
szOutputFile = szOrgOutputFile;
// input file is stdin
if (bUseInPipesEnc == true)
szInputFile = _T("-");
// output file is stdout
if (bUseOutPipesEnc == true)
szOutputFile = _T("-");
}
// encode
if ((nProcessingMode == 0) || (nProcessingMode == 2))
{
// TODO: validate the command-line template
// build full command line for encoder (ENCODER-EXE + OPTIONS + INFILE + OUTFILE)
// this is basic model, some of encoder may have different command-line structure
csExecute = pDlg->m_Config.m_Formats[nOutputFormat].szTemplate;
csExecute.Replace(_T("$EXE"), _T("\"$EXE\""));
csExecute.Replace(_T("$EXE"), szEncoderExePath);
csExecute.Replace(_T("$OPTIONS"), szEncoderOptions);
csExecute.Replace(_T("$INFILE"), _T("\"$INFILE\""));
csExecute.Replace(_T("$INFILE"), szInputFile);
csExecute.Replace(_T("$OUTFILE"), _T("\"$OUTFILE\""));
csExecute.Replace(_T("$OUTFILE"), szOutputFile);
bDecode = false;
nTool = nOutputFormat;
lstrcpy(szCommandLine, csExecute.GetBuffer(csExecute.GetLength()));
pDlg->m_LstInputItems.SetItemText(i, 5, _T("--:--"));
pDlg->m_LstInputItems.SetItemText(i, 6, _T("Encoding..."));
if (::ConvertFile(pDlg,
szOrgInputFile,
szOrgOutputFile,
szCommandLine,
i,
bDecode,
nTool,
bUseInPipesEnc,
bUseOutPipesEnc) == true)
{
nDoneWithoutError++;
if (bDeleteAfterconversion == true)
::DeleteFile(szOrgInputFile);
pDlg->m_LstInputItems.SetCheck(i, FALSE);
}
else
{
// delete output file on error
if (pDlg->m_Config.m_Options.bDeleteOnError == true)
::DeleteFile(szOutputFile);
// stop conversion process on error
if (pDlg->m_Config.m_Options.bStopOnErrors == true)
break;
}
// delete temporary file
if (nProcessingMode == 2)
::DeleteFile(szOrgInputFile);
}
if (pDlg->bRunning == false)
break;
}
}
countTime.StopCounter();
// show total time
if (nProcessedFiles > 0)
{
CString szText;
szText.Format(_T("Done in %s"), ::FormatTime(countTime.GetTime(), 3));
pDlg->m_StatusBar.SetText(szText, 1, 0);
}
else
{
pDlg->m_StatusBar.SetText(_T(""), 1, 0);
}
// restore user interface to default state
if (pDlg->m_Config.m_Options.bShowTrayIcon == true)
pDlg->EnableTrayIcon(true, true);
pDlg->m_BtnConvert.SetWindowText(_T("Conve&rt"));
pDlg->GetMenu()->ModifyMenu(ID_ACTION_CONVERT, MF_BYCOMMAND, ID_ACTION_CONVERT, _T("Conve&rt\tF9"));
pDlg->m_FileProgress.SetPos(0);
pDlg->bRunning = false;
pDlg->EnableUserInterface(TRUE);
// now we shutdown the system
if (pDlg->GetMenu()->GetMenuState(ID_OPTIONS_SHUTDOWN_WHEN_FINISHED, MF_BYCOMMAND) == MF_CHECKED)
{
// NOTE: before shutdown we are doing OnClose() stuff
// save current configuration to file
if (pDlg->GetMenu()->GetMenuState(ID_OPTIONS_DO_NOT_SAVE, MF_BYCOMMAND) != MF_CHECKED)
pDlg->SaveConfigFile(pDlg->szMainConfigFile);
// disable tray icon
pDlg->EnableTrayIcon(false);
::DoTheShutdown();
}
// close this worker thread handle
return ::CloseHandle(pDlg->hThread);
}
|
// codegen
#include <nan.h>
using Nan::ObjectWrap;
using namespace v8;
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include "types.h"
#include "function_builder.h"
#include "codegen.h"
// definitions from http://www.llvm.org/docs/doxygen/html/DerivedTypes_8h_source.html#l00046
#define MIN_INT_BITS 1
#define MAX_INT_BITS (1<<23)-1
// function type helper
#define EXTRACT_FUNCTION_PARAMS(first) \
TypeHandle *returns; \
std::vector<TypeHandle *> takes; \
\
if (info.Length() == first) \
{ \
returns = new VoidTypeHandle(); \
} \
else \
{ \
Local<Object> handle = info[first]->ToObject(); \
\
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle); \
returns = wrapper->Type; \
} \
\
for (unsigned i = first + 1, e = info.Length(); i < e; i += 1) \
{ \
Local<Object> handle = info[i]->ToObject(); \
\
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle); \
takes.push_back(wrapper->Type); \
}
class TypeWrapper : public Nan::ObjectWrap
{
TypeWrapper(TypeHandle *t)
: Type(t) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate type directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
TypeHandle *t = static_cast<TypeHandle *>(handle->Value());
TypeWrapper *instance = new TypeWrapper(t);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(ToString)
{
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
std::string name = wrapper->Type->toString();
info.GetReturnValue().Set(Nan::New(name).ToLocalChecked());
}
public:
static Handle<Value> wrapType(TypeHandle *type)
{
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[1] = { Nan::New<External>((void *)type) };
Local<Function> cons = Nan::New(constructor());
return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
TypeHandle *Type;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init) {
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(TypeWrapper::New);
tmpl->SetClassName(Nan::New("Type").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tmpl, "toString", TypeWrapper::ToString);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("TypeWrapper").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
static NAN_METHOD(GetVoidTy)
{
info.GetReturnValue().Set(wrapType(new VoidTypeHandle()));
}
static NAN_METHOD(GetIntTy)
{
if (info.Length() == 0 || !info[0]->IsNumber()) {
return Nan::ThrowError("Must provide integer bit width");
}
Local<Number> bitWidth = info[0].As<Number>();
double requestedBits = bitWidth->Value();
if (requestedBits < MIN_INT_BITS) {
return Nan::ThrowError("Integer bit width below the minimum");
}
if (requestedBits > MAX_INT_BITS) {
return Nan::ThrowError("Integer bit width above the maximum");
}
unsigned bits = (unsigned)requestedBits;
if (bits != requestedBits) {
return Nan::ThrowError("Integer bit width not valid");
}
info.GetReturnValue().Set(wrapType(new IntTypeHandle(bits)));
}
static NAN_METHOD(GetPointerTy)
{
TypeHandle *pointee;
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide pointee type");
}
Local<Object> handle = info[0]->ToObject();
/* TODO
if (!Nan::HasInstance(prototype, handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
*/
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
pointee = wrapper->Type;
info.GetReturnValue().Set(wrapType(new PointerTypeHandle(pointee)));
}
static NAN_METHOD(GetArrayTy)
{
unsigned size;
TypeHandle *element;
if (info.Length() == 0 || !info[0]->IsNumber())
{
return Nan::ThrowError("Must provide array size");
}
Local<Number> sizeNumber = info[0].As<Number>();
double sizeDouble = sizeNumber->Value();
size = (unsigned)sizeDouble;
if (info.Length() == 1)
{
return Nan::ThrowError("Must provide array element type");
}
Local<Object> handle = info[1]->ToObject();
/* TODO
if (!Nan::HasInstance(prototype, handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
*/
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
element = wrapper->Type;
info.GetReturnValue().Set(wrapType(new ArrayTypeHandle(size, element)));
}
static NAN_METHOD(GetFunctionTy)
{
EXTRACT_FUNCTION_PARAMS(0)
info.GetReturnValue().Set(wrapType(new FunctionTypeHandle(returns, takes)));
}
};
class ValueWrapper : public Nan::ObjectWrap
{
ValueWrapper(ValueHandle *v)
: Val(v) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate value directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
ValueHandle *v = static_cast<ValueHandle *>(handle->Value());
ValueWrapper *instance = new ValueWrapper(v);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_GETTER(GetType)
{
ValueWrapper *wrapper = Nan::ObjectWrap::Unwrap<ValueWrapper>(info.This());
info.GetReturnValue().Set(TypeWrapper::wrapType(wrapper->Val->Type));
}
public:
static Handle<Value> wrapValue(ValueHandle *value)
{
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { Nan::New<External>((void *)value) };
Local<Function> cons = Nan::New(constructor());
return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
ValueHandle *Val;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init)
{
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(ValueWrapper::New);
tmpl->SetClassName(Nan::New("Value").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("type").ToLocalChecked(), GetType);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("ValueWrapper").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
};
class FunctionBuilderWrapper : public Nan::ObjectWrap
{
explicit FunctionBuilderWrapper(FunctionBuilder *builder)
: Builder(builder) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate type directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
FunctionBuilder *fb = static_cast<FunctionBuilder *>(handle->Value());
FunctionBuilderWrapper *instance = new FunctionBuilderWrapper(fb);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_GETTER(GetName)
{
FunctionBuilderWrapper *wrapper = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
info.GetReturnValue().Set(Nan::New(wrapper->Builder->Name).ToLocalChecked());
}
static NAN_GETTER(GetType)
{
FunctionBuilderWrapper *wrapper = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
info.GetReturnValue().Set(TypeWrapper::wrapType(wrapper->Builder->Type));
}
static NAN_METHOD(Return)
{
FunctionBuilderWrapper *wrapper = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
if (info.Length() == 0)
{
wrapper->Builder->Return();
}
else if (info[0]->IsNumber())
{
Local<Number> num = info[0].As<Number>();
double numVal = num->Value();
wrapper->Builder->Return((int)numVal);
}
else
{
return Nan::ThrowError("Return value not supported");
}
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(LoadConstant)
{
FunctionBuilderWrapper *self = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide constant value");
}
Local<Object> handle = info[0]->ToObject();
/* TODO
if (!Nan::HasInstance(ValueWrapper::prototype, handle))
{
return Nan::ThrowError("Must provide constant value");
}
*/
ValueWrapper *wrapper = Nan::ObjectWrap::Unwrap<ValueWrapper>(handle);
ValueHandle *result = self->Builder->LoadConstant(wrapper->Val);
info.GetReturnValue().Set(ValueWrapper::wrapValue(result));
}
static NAN_METHOD(CallFunction)
{
FunctionBuilderWrapper *self = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide function value");
}
Local<Object> handle = info[0]->ToObject();
/* TODO
if (!Nan::HasInstance(ValueWrapper::prototype, handle))
{
return Nan::ThrowError("Must provide function value");
}
*/
ValueWrapper *wrapper = Nan::ObjectWrap::Unwrap<ValueWrapper>(handle);
ValueHandle *callee = wrapper->Val;
std::vector<ValueHandle *> argVals;
for (unsigned i = 1, e = info.Length(); i < e; i += 1)
{
Local<Object> handle = info[i]->ToObject();
/* TODO
if (!Nan::HasInstance(ValueWrapper::prototype, handle))
{
return Nan::ThrowError("Argument must be a value");
}
*/
ValueWrapper *arg = Nan::ObjectWrap::Unwrap<ValueWrapper>(handle);
argVals.push_back(arg->Val);
}
ValueHandle *result = self->Builder->CallFunction(callee, argVals);
info.GetReturnValue().Set(ValueWrapper::wrapValue(result));
}
public:
FunctionBuilder *Builder;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init)
{
Nan::HandleScope scope;
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(FunctionBuilderWrapper::New);
tmpl->SetClassName(Nan::New("FunctionBuilder").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("name").ToLocalChecked(), GetName);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("type").ToLocalChecked(), GetType);
Nan::SetPrototypeMethod(tmpl, "return", Return);
Nan::SetPrototypeMethod(tmpl, "loadConstant", LoadConstant);
Nan::SetPrototypeMethod(tmpl, "callFunction", CallFunction);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("FunctionBuilder").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
};
class CodeUnitWrapper : public Nan::ObjectWrap
{
explicit CodeUnitWrapper(CodeUnit *unit)
: Unit(unit) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall())
{
const int argc = 1;
Local<Value> argv[argc] = { info[0] };
Local<Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
else
{
if (!info[0]->IsString())
{
return Nan::ThrowError("Must provide file name.");
}
Local<String> filename = info[0].As<String>();
String::Utf8Value encoded(filename);
CodeUnit *unit = new CodeUnit(*encoded);
CodeUnitWrapper *wrapper = new CodeUnitWrapper(unit);
wrapper->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
}
void dumpModule()
{
Unit->dumpModule();
}
static NAN_METHOD(Dump)
{
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
self->dumpModule();
return;
}
static NAN_METHOD(WriteToFile)
{
if (info.Length() == 0 || !info[0]->IsString())
{
return Nan::ThrowError("Must provide file name");
}
Local<String> raw = info[0].As<String>();
String::Utf8Value filename(raw);
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (!self->Unit->WriteToFile(*filename))
{
return Nan::ThrowError("Unable to write file");
}
return;
}
static NAN_METHOD(MakeFunction)
{
Nan::EscapableHandleScope scope;
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (info.Length() == 0 || !info[0]->IsString())
{
return Nan::ThrowError("Must provide function name");
}
Local<String> fnname = info[0].As<String>();
String::Utf8Value encoded(fnname);
EXTRACT_FUNCTION_PARAMS(1)
FunctionBuilder *builder = self->Unit->MakeFunction(*encoded, new FunctionTypeHandle(returns, takes));
if (!builder)
{
return Nan::ThrowError("Unable to create function (is name unique?)");
}
const unsigned argc = 1;
Handle<Value> argv[argc] = { Nan::New<External>((void *)builder) };
Local<Function> cons = Nan::New(FunctionBuilderWrapper::constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
static NAN_METHOD(DeclareFunction)
{
Nan::EscapableHandleScope scope;
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (info.Length() == 0 || !info[0]->IsString())
{
return Nan::ThrowError("Must provide function name");
}
Local<String> fnname = info[0].As<String>();
String::Utf8Value encoded(fnname);
EXTRACT_FUNCTION_PARAMS(1)
FunctionValueHandle *fn = self->Unit->DeclareFunction(*encoded, new FunctionTypeHandle(returns, takes));
if (!fn)
{
return Nan::ThrowError("Unable to create function (is name unique?)");
}
info.GetReturnValue().Set(ValueWrapper::wrapValue(fn));
}
static NAN_METHOD(Constant)
{
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide constant value");
}
if (info[0]->IsString())
{
Local<String> str = info[0].As<String>();
String::Utf8Value encoded(str);
ConstantValueHandle *handle = self->Unit->ConstantString(*encoded);
info.GetReturnValue().Set(ValueWrapper::wrapValue(handle));
}
else
{
return Nan::ThrowError("Constant type yet supported");
}
}
public:
CodeUnit *Unit;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init)
{
Nan::HandleScope scope;
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(CodeUnitWrapper::New);
tmpl->SetClassName(Nan::New("CodeUnit").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tmpl, "dump", Dump);
Nan::SetPrototypeMethod(tmpl, "writeBitcodeToFile", WriteToFile);
Nan::SetPrototypeMethod(tmpl, "makeFunction", MakeFunction);
Nan::SetPrototypeMethod(tmpl, "declareFunction", DeclareFunction);
Nan::SetPrototypeMethod(tmpl, "constant", Constant);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("CodeUnit").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
};
static NAN_MODULE_INIT(Init)
{
TypeWrapper::Init(target);
ValueWrapper::Init(target);
CodeUnitWrapper::Init(target);
FunctionBuilderWrapper::Init(target);
Local<FunctionTemplate> getVoidTy = Nan::New<FunctionTemplate>(TypeWrapper::GetVoidTy);
Nan::Set(target, Nan::New("getVoidTy").ToLocalChecked(), Nan::GetFunction(getVoidTy).ToLocalChecked());
Local<FunctionTemplate> getFunctionTy = Nan::New<FunctionTemplate>(TypeWrapper::GetFunctionTy);
Nan::Set(target, Nan::New("getFunctionTy").ToLocalChecked(), Nan::GetFunction(getFunctionTy).ToLocalChecked());
Local<FunctionTemplate> getIntTy = Nan::New<FunctionTemplate>(TypeWrapper::GetIntTy);
Nan::Set(target, Nan::New("getIntTy").ToLocalChecked(), Nan::GetFunction(getIntTy).ToLocalChecked());
Local<FunctionTemplate> getPointerTy = Nan::New<FunctionTemplate>(TypeWrapper::GetPointerTy);
Nan::Set(target, Nan::New("getPointerTy").ToLocalChecked(), Nan::GetFunction(getPointerTy).ToLocalChecked());
Local<FunctionTemplate> getArrayTy = Nan::New<FunctionTemplate>(TypeWrapper::GetArrayTy);
Nan::Set(target, Nan::New("getArrayTy").ToLocalChecked(), Nan::GetFunction(getArrayTy).ToLocalChecked());
Local<Function> codeUnit = Nan::New(CodeUnitWrapper::constructor());
Nan::Set(target, Nan::New("CodeUnit").ToLocalChecked(), codeUnit);
}
NODE_MODULE(codegen, Init)
fix value wrapper type checks
// codegen
#include <nan.h>
using Nan::ObjectWrap;
using namespace v8;
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include "types.h"
#include "function_builder.h"
#include "codegen.h"
// definitions from http://www.llvm.org/docs/doxygen/html/DerivedTypes_8h_source.html#l00046
#define MIN_INT_BITS 1
#define MAX_INT_BITS (1<<23)-1
// function type helper
#define EXTRACT_FUNCTION_PARAMS(first) \
TypeHandle *returns; \
std::vector<TypeHandle *> takes; \
\
if (info.Length() == first) \
{ \
returns = new VoidTypeHandle(); \
} \
else \
{ \
Local<Object> handle = info[first]->ToObject(); \
\
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle); \
returns = wrapper->Type; \
} \
\
for (unsigned i = first + 1, e = info.Length(); i < e; i += 1) \
{ \
Local<Object> handle = info[i]->ToObject(); \
\
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle); \
takes.push_back(wrapper->Type); \
}
class TypeWrapper : public Nan::ObjectWrap
{
TypeWrapper(TypeHandle *t)
: Type(t) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate type directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
TypeHandle *t = static_cast<TypeHandle *>(handle->Value());
TypeWrapper *instance = new TypeWrapper(t);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(ToString)
{
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
std::string name = wrapper->Type->toString();
info.GetReturnValue().Set(Nan::New(name).ToLocalChecked());
}
public:
static Handle<Value> wrapType(TypeHandle *type)
{
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[1] = { Nan::New<External>((void *)type) };
Local<Function> cons = Nan::New(constructor());
return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
TypeHandle *Type;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init) {
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(TypeWrapper::New);
tmpl->SetClassName(Nan::New("Type").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tmpl, "toString", TypeWrapper::ToString);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("TypeWrapper").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
static NAN_METHOD(GetVoidTy)
{
info.GetReturnValue().Set(wrapType(new VoidTypeHandle()));
}
static NAN_METHOD(GetIntTy)
{
if (info.Length() == 0 || !info[0]->IsNumber()) {
return Nan::ThrowError("Must provide integer bit width");
}
Local<Number> bitWidth = info[0].As<Number>();
double requestedBits = bitWidth->Value();
if (requestedBits < MIN_INT_BITS) {
return Nan::ThrowError("Integer bit width below the minimum");
}
if (requestedBits > MAX_INT_BITS) {
return Nan::ThrowError("Integer bit width above the maximum");
}
unsigned bits = (unsigned)requestedBits;
if (bits != requestedBits) {
return Nan::ThrowError("Integer bit width not valid");
}
info.GetReturnValue().Set(wrapType(new IntTypeHandle(bits)));
}
static NAN_METHOD(GetPointerTy)
{
TypeHandle *pointee;
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide pointee type");
}
Local<Object> handle = info[0]->ToObject();
/* TODO
if (!Nan::HasInstance(prototype, handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
*/
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
pointee = wrapper->Type;
info.GetReturnValue().Set(wrapType(new PointerTypeHandle(pointee)));
}
static NAN_METHOD(GetArrayTy)
{
unsigned size;
TypeHandle *element;
if (info.Length() == 0 || !info[0]->IsNumber())
{
return Nan::ThrowError("Must provide array size");
}
Local<Number> sizeNumber = info[0].As<Number>();
double sizeDouble = sizeNumber->Value();
size = (unsigned)sizeDouble;
if (info.Length() == 1)
{
return Nan::ThrowError("Must provide array element type");
}
Local<Object> handle = info[1]->ToObject();
/* TODO
if (!Nan::HasInstance(prototype, handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
*/
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
element = wrapper->Type;
info.GetReturnValue().Set(wrapType(new ArrayTypeHandle(size, element)));
}
static NAN_METHOD(GetFunctionTy)
{
EXTRACT_FUNCTION_PARAMS(0)
info.GetReturnValue().Set(wrapType(new FunctionTypeHandle(returns, takes)));
}
};
class ValueWrapper : public Nan::ObjectWrap
{
ValueWrapper(ValueHandle *v)
: Val(v) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate value directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
ValueHandle *v = static_cast<ValueHandle *>(handle->Value());
ValueWrapper *instance = new ValueWrapper(v);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_GETTER(GetType)
{
ValueWrapper *wrapper = Nan::ObjectWrap::Unwrap<ValueWrapper>(info.This());
info.GetReturnValue().Set(TypeWrapper::wrapType(wrapper->Val->Type));
}
public:
static Handle<Value> wrapValue(ValueHandle *value)
{
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { Nan::New<External>((void *)value) };
Local<Function> cons = Nan::New(constructor());
return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
ValueHandle *Val;
static Nan::Persistent<FunctionTemplate> prototype;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init)
{
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(ValueWrapper::New);
tmpl->SetClassName(Nan::New("Value").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("type").ToLocalChecked(), GetType);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("ValueWrapper").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
prototype.Reset(tmpl);
}
};
Nan::Persistent<FunctionTemplate> ValueWrapper::prototype;
class FunctionBuilderWrapper : public Nan::ObjectWrap
{
explicit FunctionBuilderWrapper(FunctionBuilder *builder)
: Builder(builder) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate type directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
FunctionBuilder *fb = static_cast<FunctionBuilder *>(handle->Value());
FunctionBuilderWrapper *instance = new FunctionBuilderWrapper(fb);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_GETTER(GetName)
{
FunctionBuilderWrapper *wrapper = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
info.GetReturnValue().Set(Nan::New(wrapper->Builder->Name).ToLocalChecked());
}
static NAN_GETTER(GetType)
{
FunctionBuilderWrapper *wrapper = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
info.GetReturnValue().Set(TypeWrapper::wrapType(wrapper->Builder->Type));
}
static NAN_METHOD(Return)
{
FunctionBuilderWrapper *wrapper = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
if (info.Length() == 0)
{
wrapper->Builder->Return();
}
else if (info[0]->IsNumber())
{
Local<Number> num = info[0].As<Number>();
double numVal = num->Value();
wrapper->Builder->Return((int)numVal);
}
else
{
return Nan::ThrowError("Return value not supported");
}
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(LoadConstant)
{
FunctionBuilderWrapper *self = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide constant value");
}
Local<Object> handle = info[0]->ToObject();
if (!Nan::New(ValueWrapper::prototype)->HasInstance(handle))
{
return Nan::ThrowError("Must provide constant value");
}
ValueWrapper *wrapper = Nan::ObjectWrap::Unwrap<ValueWrapper>(handle);
ValueHandle *result = self->Builder->LoadConstant(wrapper->Val);
info.GetReturnValue().Set(ValueWrapper::wrapValue(result));
}
static NAN_METHOD(CallFunction)
{
FunctionBuilderWrapper *self = Nan::ObjectWrap::Unwrap<FunctionBuilderWrapper>(info.This());
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide function value");
}
Local<Object> handle = info[0]->ToObject();
if (!Nan::New(ValueWrapper::prototype)->HasInstance(handle))
{
return Nan::ThrowError("Must provide function value");
}
ValueWrapper *wrapper = Nan::ObjectWrap::Unwrap<ValueWrapper>(handle);
ValueHandle *callee = wrapper->Val;
std::vector<ValueHandle *> argVals;
for (unsigned i = 1, e = info.Length(); i < e; i += 1)
{
Local<Object> handle = info[i]->ToObject();
if (!Nan::New(ValueWrapper::prototype)->HasInstance(handle))
{
return Nan::ThrowError("Argument must be a value");
}
ValueWrapper *arg = Nan::ObjectWrap::Unwrap<ValueWrapper>(handle);
argVals.push_back(arg->Val);
}
ValueHandle *result = self->Builder->CallFunction(callee, argVals);
info.GetReturnValue().Set(ValueWrapper::wrapValue(result));
}
public:
FunctionBuilder *Builder;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init)
{
Nan::HandleScope scope;
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(FunctionBuilderWrapper::New);
tmpl->SetClassName(Nan::New("FunctionBuilder").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("name").ToLocalChecked(), GetName);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("type").ToLocalChecked(), GetType);
Nan::SetPrototypeMethod(tmpl, "return", Return);
Nan::SetPrototypeMethod(tmpl, "loadConstant", LoadConstant);
Nan::SetPrototypeMethod(tmpl, "callFunction", CallFunction);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("FunctionBuilder").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
};
class CodeUnitWrapper : public Nan::ObjectWrap
{
explicit CodeUnitWrapper(CodeUnit *unit)
: Unit(unit) {}
static NAN_METHOD(New)
{
if (!info.IsConstructCall())
{
const int argc = 1;
Local<Value> argv[argc] = { info[0] };
Local<Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
else
{
if (!info[0]->IsString())
{
return Nan::ThrowError("Must provide file name.");
}
Local<String> filename = info[0].As<String>();
String::Utf8Value encoded(filename);
CodeUnit *unit = new CodeUnit(*encoded);
CodeUnitWrapper *wrapper = new CodeUnitWrapper(unit);
wrapper->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
}
void dumpModule()
{
Unit->dumpModule();
}
static NAN_METHOD(Dump)
{
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
self->dumpModule();
return;
}
static NAN_METHOD(WriteToFile)
{
if (info.Length() == 0 || !info[0]->IsString())
{
return Nan::ThrowError("Must provide file name");
}
Local<String> raw = info[0].As<String>();
String::Utf8Value filename(raw);
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (!self->Unit->WriteToFile(*filename))
{
return Nan::ThrowError("Unable to write file");
}
return;
}
static NAN_METHOD(MakeFunction)
{
Nan::EscapableHandleScope scope;
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (info.Length() == 0 || !info[0]->IsString())
{
return Nan::ThrowError("Must provide function name");
}
Local<String> fnname = info[0].As<String>();
String::Utf8Value encoded(fnname);
EXTRACT_FUNCTION_PARAMS(1)
FunctionBuilder *builder = self->Unit->MakeFunction(*encoded, new FunctionTypeHandle(returns, takes));
if (!builder)
{
return Nan::ThrowError("Unable to create function (is name unique?)");
}
const unsigned argc = 1;
Handle<Value> argv[argc] = { Nan::New<External>((void *)builder) };
Local<Function> cons = Nan::New(FunctionBuilderWrapper::constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
static NAN_METHOD(DeclareFunction)
{
Nan::EscapableHandleScope scope;
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (info.Length() == 0 || !info[0]->IsString())
{
return Nan::ThrowError("Must provide function name");
}
Local<String> fnname = info[0].As<String>();
String::Utf8Value encoded(fnname);
EXTRACT_FUNCTION_PARAMS(1)
FunctionValueHandle *fn = self->Unit->DeclareFunction(*encoded, new FunctionTypeHandle(returns, takes));
if (!fn)
{
return Nan::ThrowError("Unable to create function (is name unique?)");
}
info.GetReturnValue().Set(ValueWrapper::wrapValue(fn));
}
static NAN_METHOD(Constant)
{
CodeUnitWrapper *self = Nan::ObjectWrap::Unwrap<CodeUnitWrapper>(info.This());
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide constant value");
}
if (info[0]->IsString())
{
Local<String> str = info[0].As<String>();
String::Utf8Value encoded(str);
ConstantValueHandle *handle = self->Unit->ConstantString(*encoded);
info.GetReturnValue().Set(ValueWrapper::wrapValue(handle));
}
else
{
return Nan::ThrowError("Constant type yet supported");
}
}
public:
CodeUnit *Unit;
static inline Nan::Persistent<Function>& constructor() {
static Nan::Persistent<Function> my_constructor;
return my_constructor;
}
static NAN_MODULE_INIT(Init)
{
Nan::HandleScope scope;
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(CodeUnitWrapper::New);
tmpl->SetClassName(Nan::New("CodeUnit").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tmpl, "dump", Dump);
Nan::SetPrototypeMethod(tmpl, "writeBitcodeToFile", WriteToFile);
Nan::SetPrototypeMethod(tmpl, "makeFunction", MakeFunction);
Nan::SetPrototypeMethod(tmpl, "declareFunction", DeclareFunction);
Nan::SetPrototypeMethod(tmpl, "constant", Constant);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("CodeUnit").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
}
};
static NAN_MODULE_INIT(Init)
{
TypeWrapper::Init(target);
ValueWrapper::Init(target);
CodeUnitWrapper::Init(target);
FunctionBuilderWrapper::Init(target);
Local<FunctionTemplate> getVoidTy = Nan::New<FunctionTemplate>(TypeWrapper::GetVoidTy);
Nan::Set(target, Nan::New("getVoidTy").ToLocalChecked(), Nan::GetFunction(getVoidTy).ToLocalChecked());
Local<FunctionTemplate> getFunctionTy = Nan::New<FunctionTemplate>(TypeWrapper::GetFunctionTy);
Nan::Set(target, Nan::New("getFunctionTy").ToLocalChecked(), Nan::GetFunction(getFunctionTy).ToLocalChecked());
Local<FunctionTemplate> getIntTy = Nan::New<FunctionTemplate>(TypeWrapper::GetIntTy);
Nan::Set(target, Nan::New("getIntTy").ToLocalChecked(), Nan::GetFunction(getIntTy).ToLocalChecked());
Local<FunctionTemplate> getPointerTy = Nan::New<FunctionTemplate>(TypeWrapper::GetPointerTy);
Nan::Set(target, Nan::New("getPointerTy").ToLocalChecked(), Nan::GetFunction(getPointerTy).ToLocalChecked());
Local<FunctionTemplate> getArrayTy = Nan::New<FunctionTemplate>(TypeWrapper::GetArrayTy);
Nan::Set(target, Nan::New("getArrayTy").ToLocalChecked(), Nan::GetFunction(getArrayTy).ToLocalChecked());
Local<Function> codeUnit = Nan::New(CodeUnitWrapper::constructor());
Nan::Set(target, Nan::New("CodeUnit").ToLocalChecked(), codeUnit);
}
NODE_MODULE(codegen, Init)
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\MainApp.h"
#include "..\Strings.h"
#include "..\utilities\TimeCount.h"
#include "..\utilities\Utilities.h"
#include "LuaProgess.h"
#include "WorkThread.h"
bool ProgresssLoop(CFileContext* pContext, CProcessContext &processContext, CPipe &Stderr, int &nProgress)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
const int nBuffSize = 4096;
char szReadBuff[nBuffSize];
char szLineBuff[nBuffSize];
DWORD dwReadBytes = 0L;
BOOL bRes = FALSE;
bool bLineStart = false;
bool bLineEnd = false;
bool bRunning = true;
int nLineLen = 0;
int nPreviousProgress = 0;
::SetCurrentDirectory(::GetExeFilePath());
// load progress function
CLuaProgess luaProgress;
if (luaProgress.Open(CT2CA(pContext->pFormat->szFunction)) == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00110001, pszProgresssLoop[0]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
if (luaProgress.HaveGetProgress() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00110002, pszProgresssLoop[1]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
// initialize buffers
ZeroMemory(szReadBuff, sizeof(szReadBuff));
ZeroMemory(szLineBuff, sizeof(szLineBuff));
do
{
ZeroMemory(szReadBuff, sizeof(szReadBuff));
bRes = ::ReadFile(Stderr.hRead, szReadBuff, 100, &dwReadBytes, 0);
if (bRes == FALSE || dwReadBytes == 0)
break;
// terminate read data by '\0'
szReadBuff[dwReadBytes] = '\0';
for (int i = 0; i < (int)dwReadBytes; i++)
{
// processed escape chars ( \r \n \t \b )
if (szReadBuff[i] == '\r') // '\r'
{
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (szReadBuff[i] == '\n') // '\n'
{
// do nothing
}
else if (szReadBuff[i] == '\t') // '\t'
{
// do nothing
}
else if (szReadBuff[i] == '\b') // '\b'
{
// do nothing (most of the tools)
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (bLineEnd == false)
{
bLineStart = true; // we have start
nLineLen++;
if (nLineLen > nBuffSize)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00110003, pszProgresssLoop[2]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
szLineBuff[nLineLen - 1] = szReadBuff[i];
}
// now we have correct full line of text
if ((bLineEnd == true) && (bLineStart == false))
{
// don't include empty lines
if (strlen(szLineBuff) > 0)
{
//OutputDebugStringA(szLineBuff); OutputDebugStringA("\n");
int nRet = (int)luaProgress.GetProgress(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
//CString szRet; szRet.Format(_T("%d#n"), nRet); OutputDebugString(szRet);
ZeroMemory(szLineBuff, sizeof(szLineBuff));
if (nProgress != nPreviousProgress)
{
bRunning = pWorkerContext->Callback(pContext->nItemId, nProgress, false);
nPreviousProgress = nProgress;
}
if ((pContext->pWorkerContext->bRunning == false) || (bRunning == false))
break;
}
// reset line counter
nLineLen = 0;
// find next start
bLineStart = true;
bLineEnd = false;
}
}
if (bRunning == false)
break;
} while (bRes);
luaProgress.Close();
return true;
}
bool ConvertFileUsingConsole(CFileContext* pContext)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
if ((pContext->bUseReadPipes == true) || (pContext->bUseWritePipes == true))
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120001, pszConvertConsole[0]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
CPipe Stderr(TRUE);
int nProgress = 0;
CTimeCount timer;
// create pipes for stderr
if (Stderr.Create() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120002, pszConvertConsole[1]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// duplicate stderr read pipe handle to prevent child process from closing the pipe
if (Stderr.DuplicateRead() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120003, pszConvertConsole[2]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// connect pipes to process
processContext.ConnectStdInput(NULL);
processContext.ConnectStdOutput(Stderr.hWrite);
processContext.ConnectStdError(Stderr.hWrite);
timer.Start();
if (processContext.Start(pContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
Stderr.CloseRead();
Stderr.CloseWrite();
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00120004, pszConvertConsole[3]), ::GetLastError());
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handle
Stderr.CloseWrite();
// console progress loop
if (ProgresssLoop(pContext, processContext, Stderr, nProgress) == false)
{
timer.Stop();
Stderr.CloseRead();
processContext.Stop(false);
return false;
}
timer.Stop();
Stderr.CloseRead();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120005, pszConvertConsole[4]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), pWorkerContext->GetString(0x00120006, pszConvertConsole[5]));
pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ReadLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesRead = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
int nPreviousProgress = -1;
bool bRunning = true;
pContext->bError = false;
pContext->bFinished = false;
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
::CloseHandle(pContext->hPipe);
return false;
}
nFileSize = ::GetFileSize64(hFile);
if (nFileSize == 0)
{
pContext->bError = true;
pContext->bFinished = true;
::CloseHandle(hFile);
::CloseHandle(pContext->hPipe);
return false;
}
do
{
bRes = ::ReadFile(hFile, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
::Sleep(0);
bRes = ::WriteFile(pContext->hPipe, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
nTotalBytesRead += dwReadBytes;
nProgress = (int)((nTotalBytesRead * 100) / nFileSize);
if (nProgress != nPreviousProgress)
{
bRunning = pContext->pWorkerContext->Callback(pContext->nIndex, nProgress, false);
nPreviousProgress = nProgress;
}
if ((pContext->pWorkerContext->bRunning == false) || (bRunning == false))
break;
} while (bRes != FALSE);
::CloseHandle(hFile);
::CloseHandle(pContext->hPipe);
if (nTotalBytesRead != nFileSize)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
pContext->bError = false;
pContext->bFinished = true;
return true;
}
bool WriteLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesWrite = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
pContext->bError = false;
pContext->bFinished = false;
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
do
{
::Sleep(0);
bRes = ::ReadFile(pContext->hPipe, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
bRes = ::WriteFile(hFile, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
nTotalBytesWrite += dwReadBytes;
if (pContext->pWorkerContext->bRunning == false)
break;
} while (bRes != FALSE);
::CloseHandle(hFile);
pContext->bError = false;
pContext->bFinished = true;
return true;
}
DWORD WINAPI ReadThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (ReadLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WriteThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (WriteLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
bool ConvertFileUsingPipes(CFileContext* pContext)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == false))
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130001, pszConvertPipes[0]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
CPipe Stdin(TRUE);
CPipe Stdout(TRUE);
CPipeContext readContext;
CPipeContext writeContext;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
int nProgress = 0;
CTimeCount timer;
if (pContext->bUseReadPipes == true)
{
// create pipes for stdin
if (Stdin.Create() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130002, pszConvertPipes[1]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdin write pipe inherit flag
if (Stdin.InheritWrite() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130003, pszConvertPipes[2]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
if (pContext->bUseWritePipes == true)
{
// create pipes for stdout
if (Stdout.Create() == false)
{
if (pContext->bUseReadPipes == true)
{
Stdin.CloseRead();
Stdin.CloseWrite();
}
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130004, pszConvertPipes[3]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdout read pipe inherit flag
if (Stdout.InheritRead() == false)
{
if (pContext->bUseReadPipes == true)
{
Stdin.CloseRead();
Stdin.CloseWrite();
}
Stdout.CloseRead();
Stdout.CloseWrite();
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130005, pszConvertPipes[4]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
// connect pipes to process
if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == false))
{
processContext.ConnectStdInput(Stdin.hRead);
processContext.ConnectStdOutput(GetStdHandle(STD_OUTPUT_HANDLE));
processContext.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
}
else if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(GetStdHandle(STD_INPUT_HANDLE));
processContext.ConnectStdOutput(Stdout.hWrite);
processContext.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
}
else if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(Stdin.hRead);
processContext.ConnectStdOutput(Stdout.hWrite);
processContext.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
}
timer.Start();
if (processContext.Start(pContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
if (pContext->bUseReadPipes == true)
{
Stdin.CloseRead();
Stdin.CloseWrite();
}
if (pContext->bUseWritePipes == true)
{
Stdout.CloseRead();
Stdout.CloseWrite();
}
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00130006, pszConvertPipes[5]), ::GetLastError());
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handles
if (pContext->bUseReadPipes == true)
Stdin.CloseRead();
if (pContext->bUseWritePipes == true)
Stdout.CloseWrite();
// create read thread
if (pContext->bUseReadPipes == true)
{
readContext.bError = false;
readContext.bFinished = false;
readContext.pWorkerContext = pWorkerContext;
readContext.szFileName = pContext->szInputFile;
readContext.hPipe = Stdin.hWrite;
readContext.nIndex = pContext->nItemId;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL, 0, ReadThread, (LPVOID)&readContext, 0, &dwReadThreadID);
if (hReadThread == NULL)
{
timer.Stop();
Stdin.CloseWrite();
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130007, pszConvertPipes[6]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// wait for read thread to finish
if (pContext->bUseWritePipes == false)
{
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//Stdin.CloseWrite();
// close read thread handle
::CloseHandle(hReadThread);
// wait for process to finish
::WaitForSingleObject(processContext.pInfo.hProcess, INFINITE);
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
}
}
// create write thread
if (pContext->bUseWritePipes == true)
{
writeContext.bError = false;
writeContext.bFinished = false;
writeContext.pWorkerContext = pWorkerContext;
writeContext.szFileName = pContext->szOutputFile;
writeContext.hPipe = Stdout.hRead;
writeContext.nIndex = pContext->nItemId;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL, 0, WriteThread, (LPVOID)&writeContext, 0, &dwWriteThreadID);
if (hWriteThread == NULL)
{
timer.Stop();
Stdout.CloseRead();
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130008, pszConvertPipes[7]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
if (pContext->bUseReadPipes == true)
{
// wait for read thread to finish
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//Stdin.CloseWrite();
// close read thread handle
::CloseHandle(hReadThread);
// close read thread handle
Stdout.CloseRead();
// wait for process to finish
::WaitForSingleObject(processContext.pInfo.hProcess, INFINITE);
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
// close read thread handle
::CloseHandle(hWriteThread);
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true)
&& (writeContext.bError == false) && (writeContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
}
else
{
// wait for process to finish
::WaitForSingleObject(processContext.pInfo.hProcess, INFINITE);
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
Stdout.CloseRead();
// close read thread handle
::CloseHandle(hWriteThread);
// check for result from write thread
if ((writeContext.bError == false) && (writeContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
}
}
timer.Stop();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130009, pszConvertPipes[8]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), pWorkerContext->GetString(0x0013000B, pszConvertPipes[10]));
pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ConvertFileUsingOnlyPipes(CFileContext* pDecoderContext, CFileContext* pEncoderContext)
{
CWorkerContext *pWorkerContext = pDecoderContext->pWorkerContext;
CProcessContext processContextDecoder;
CProcessContext processContextEncoder;
CPipe Stdin(TRUE);
CPipe Stdout(TRUE);
CPipe Bridge(TRUE);
CPipeContext readContext;
CPipeContext writeContext;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
int nProgress = 0;
CTimeCount timer;
// create pipes for stdin
if (Stdin.Create() == false)
{
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130002, pszConvertPipes[1]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// set stdin write pipe inherit flag
if (Stdin.InheritWrite() == false)
{
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130003, pszConvertPipes[2]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create pipes for stdout
if (Stdout.Create() == false)
{
Stdin.CloseRead();
Stdin.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130004, pszConvertPipes[3]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// set stdout read pipe inherit flag
if (Stdout.InheritRead() == false)
{
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130005, pszConvertPipes[4]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create pipes for processes bridge
if (Bridge.Create() == false)
{
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x0013000A, pszConvertPipes[9]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// connect pipes to decoder process
processContextDecoder.ConnectStdInput(Stdin.hRead);
processContextDecoder.ConnectStdOutput(Bridge.hWrite);
processContextDecoder.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
// connect pipes to encoder process
processContextEncoder.ConnectStdInput(Bridge.hRead);
processContextEncoder.ConnectStdOutput(Stdout.hWrite);
processContextEncoder.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
timer.Start();
// create decoder process
if (processContextDecoder.Start(pDecoderContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
Bridge.CloseRead();
Bridge.CloseWrite();
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00130006, pszConvertPipes[5]), ::GetLastError());
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create encoder process
if (processContextEncoder.Start(pEncoderContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
processContextDecoder.Stop(false);
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
Bridge.CloseRead();
Bridge.CloseWrite();
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00130006, pszConvertPipes[5]), ::GetLastError());
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handles
Stdin.CloseRead();
Stdout.CloseWrite();
Bridge.CloseWrite();
Bridge.CloseRead();
// create read thread
readContext.bError = false;
readContext.bFinished = false;
readContext.pWorkerContext = pWorkerContext;
readContext.szFileName = pDecoderContext->szInputFile;
readContext.hPipe = Stdin.hWrite;
readContext.nIndex = pDecoderContext->nItemId;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL, 0, ReadThread, (LPVOID)&readContext, 0, &dwReadThreadID);
if (hReadThread == NULL)
{
timer.Stop();
Stdin.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130007, pszConvertPipes[6]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create write thread
writeContext.bError = false;
writeContext.bFinished = false;
writeContext.pWorkerContext = pWorkerContext;
writeContext.szFileName = pEncoderContext->szOutputFile;
writeContext.hPipe = Stdout.hRead;
writeContext.nIndex = pEncoderContext->nItemId;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL, 0, WriteThread, (LPVOID)&writeContext, 0, &dwWriteThreadID);
if (hWriteThread == NULL)
{
timer.Stop();
Stdout.CloseRead();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130008, pszConvertPipes[7]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// wait for read thread to finish after write thread finished
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//Stdin.CloseWrite();
// close read thread handle
::CloseHandle(hReadThread);
Stdout.CloseRead();
// wait for encoder process to finish
::WaitForSingleObject(processContextEncoder.pInfo.hProcess, INFINITE);
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
// close read thread handle
::CloseHandle(hWriteThread);
// check for result from read and write thread
if ((readContext.bError == false) && (readContext.bFinished == true)
&& (writeContext.bError == false) && (writeContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
timer.Stop();
processContextDecoder.Stop(nProgress == 100);
processContextEncoder.Stop(nProgress == 100);
if (nProgress != 100)
{
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130009, pszConvertPipes[8]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
else
{
pWorkerContext->Status(pDecoderContext->nItemId, timer.Format(timer.ElapsedTime(), 1), pWorkerContext->GetString(0x0013000B, pszConvertPipes[10]));
pWorkerContext->Callback(pDecoderContext->nItemId, 100, true, false);
return true;
}
}
bool ConvertItem(CItemContext* pContext)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
CFormat *pEncFormat = NULL;
CFormat *pDecFormat = NULL;
CString szEncInputFile;
CString szEncOutputFile;
CString szDecInputFile;
CString szDecOutputFile;
CString szOutPath;
if (pWorkerContext->pConfig->m_Options.bOutputPathChecked == true)
szOutPath = pWorkerContext->pConfig->m_Options.szOutputPath;
else
szOutPath = ::GetFilePath(pContext->item->szPath);
// prepare encoder
szEncInputFile = pContext->item->szPath;
if (::FileExists(szEncInputFile) == false)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140001, pszConvertItem[0]));
return false;
}
int nEncoder = pWorkerContext->pConfig->m_Formats.GetFormatById(pContext->item->szFormatId);
if (nEncoder == -1)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140002, pszConvertItem[1]));
return false;
}
pEncFormat = &pWorkerContext->pConfig->m_Formats.GetData(nEncoder);
if (pContext->item->nPreset >= pEncFormat->m_Presets.GetSize())
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140003, pszConvertItem[2]));
return false;
}
bool bIsValidEncoderInput = pEncFormat->IsValidInputExtension(::GetFileExtension(szEncInputFile));
szEncOutputFile = pContext->item->szName + _T(".") + CString(pEncFormat->szOutputExtension).MakeLower();
if (szOutPath.GetLength() >= 1)
{
if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/')
szEncOutputFile = szOutPath + szEncOutputFile;
else
szEncOutputFile = szOutPath + _T("\\") + szEncOutputFile;
}
// prepare decoder
if (bIsValidEncoderInput == false)
{
int nDecoder = pWorkerContext->pConfig->m_Formats.GetDecoderByExtensionAndFormat(pContext->item->szExtension, pEncFormat);
if (nDecoder == -1)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140004, pszConvertItem[3]));
return false;
}
pDecFormat = &pWorkerContext->pConfig->m_Formats.GetData(nDecoder);
if (pDecFormat->nDefaultPreset >= pDecFormat->m_Presets.GetSize())
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140005, pszConvertItem[4]));
return false;
}
bool bIsValidDecoderOutput = pEncFormat->IsValidInputExtension(pDecFormat->szOutputExtension);
if (bIsValidDecoderOutput == false)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140006, pszConvertItem[5]));
return false;
}
szDecInputFile = szEncInputFile;
szDecOutputFile = szEncOutputFile + _T(".") + CString(pDecFormat->szOutputExtension).MakeLower();
}
CFileContext decoderContext;
if (bIsValidEncoderInput == false)
{
decoderContext.Init(
pWorkerContext,
pDecFormat,
pDecFormat->nDefaultPreset,
pContext->item->nId,
szDecInputFile,
szDecOutputFile,
pDecFormat->bPipeInput,
pDecFormat->bPipeOutput);
}
CFileContext encoderContext;
encoderContext.Init(
pWorkerContext,
pEncFormat,
pContext->item->nPreset,
pContext->item->nId,
bIsValidEncoderInput == true ? szEncInputFile : szDecOutputFile,
szEncOutputFile,
pEncFormat->bPipeInput,
pEncFormat->bPipeOutput);
if (bIsValidEncoderInput == false
&& decoderContext.bUseReadPipes == true
&& decoderContext.bUseWritePipes == true
&& encoderContext.bUseReadPipes == true
&& encoderContext.bUseWritePipes == true)
{
// trans-code
try
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000C, pszConvertItem[11]));
bool bResult = ConvertFileUsingOnlyPipes(&decoderContext, &encoderContext);
if (bResult == true)
{
if (::FileExists(szEncOutputFile) == false)
{
if (bIsValidEncoderInput == false)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncInputFile);
}
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000D, pszConvertItem[12]));
return false;
}
if (pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true)
::DeleteFile(szEncInputFile);
return true;
}
else
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
return false;
}
}
catch (...)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000E, pszConvertItem[13]));
pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
else
{
// decode
if (bIsValidEncoderInput == false)
{
try
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140007, pszConvertItem[6]));
bool bResult = false;
if ((decoderContext.bUseReadPipes == false) && (decoderContext.bUseWritePipes == false))
bResult = ConvertFileUsingConsole(&decoderContext);
else
bResult = ConvertFileUsingPipes(&decoderContext);
if (bResult == false)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szDecOutputFile);
return false;
}
if (::FileExists(szDecOutputFile) == false)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140008, pszConvertItem[7]));
return false;
}
}
catch (...)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140009, pszConvertItem[8]));
pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
if (pWorkerContext->bRunning == false)
return false;
// encode
try
{
if (pEncFormat->nType == 0)
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000A, pszConvertItem[9]));
else if (pEncFormat->nType == 1)
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000B, pszConvertItem[10]));
bool bResult = false;
if ((encoderContext.bUseReadPipes == false) && (encoderContext.bUseWritePipes == false))
bResult = ConvertFileUsingConsole(&encoderContext);
else
bResult = ConvertFileUsingPipes(&encoderContext);
if (bResult == true)
{
if (::FileExists(szEncOutputFile) == false)
{
if (bIsValidEncoderInput == false)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncInputFile);
}
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000D, pszConvertItem[12]));
return false;
}
if (bIsValidEncoderInput == false)
::DeleteFile(szDecOutputFile);
if (pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true)
::DeleteFile(szEncInputFile);
return true;
}
else
{
if (bIsValidEncoderInput == false)
::DeleteFile(szDecOutputFile);
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
return false;
}
}
catch (...)
{
if (bIsValidEncoderInput == false)
::DeleteFile(szDecOutputFile);
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000E, pszConvertItem[13]));
pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
return false;
}
bool ConvertLoop(CWorkerContext* pWorkerContext)
{
while (TRUE)
{
try
{
CItemContext* pContext = NULL;
DWORD dwWaitResult = ::WaitForSingleObject(pWorkerContext->hMutex, INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
{
if (!pWorkerContext->pQueue->IsEmpty())
{
pContext = (CItemContext*)pWorkerContext->pQueue->RemoveHead();
}
if (!::ReleaseMutex(pWorkerContext->hMutex))
return false;
}
break;
case WAIT_ABANDONED:
return false;
}
if (pContext != NULL)
{
if (pContext->pWorkerContext->bRunning == false)
return false;
pContext->pWorkerContext->Next(pContext->item->nId);
if (ConvertItem(pContext) == true)
{
pContext->pWorkerContext->nDoneWithoutError++;
}
else
{
if (pContext->pWorkerContext->pConfig->m_Options.bStopOnErrors == true)
return false;
}
if (pContext->pWorkerContext->bRunning == false)
return false;
}
else
{
return true;
}
}
catch (...)
{
return false;
}
}
return true;
}
DWORD WINAPI ConvertThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext != NULL)
{
if (ConvertLoop(pWorkerContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WorkThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext == NULL)
return (DWORD)(-1);
int nItems = pWorkerContext->pConfig->m_Items.GetSize();
CItemContext *pItemsContext = new CItemContext[nItems];
pWorkerContext->nTotalFiles = 0;
pWorkerContext->nProcessedFiles = 0;
pWorkerContext->nDoneWithoutError = 0;
pWorkerContext->nErrors = 0;
pWorkerContext->pQueue = new CObList(nItems);
pWorkerContext->nProgess = new int[nItems];
pWorkerContext->nPreviousProgess = new int[nItems];
pWorkerContext->nLastItemId = -1;
for (int i = 0; i < nItems; i++)
{
CItem& item = pWorkerContext->pConfig->m_Items.GetData(i);
if (item.bChecked == true)
{
pWorkerContext->nTotalFiles++;
pWorkerContext->nProgess[i] = 0;
pWorkerContext->nPreviousProgess[i] = 0;
pItemsContext[i].pWorkerContext = pWorkerContext;
pItemsContext[i].item = &item;
pWorkerContext->pQueue->AddTail(&pItemsContext[i]);
}
else
{
pWorkerContext->nProgess[i] = 100;
pWorkerContext->nPreviousProgess[i] = 100;
}
}
pWorkerContext->nThreadCount = pWorkerContext->pConfig->m_Options.nThreadCount;
if (pWorkerContext->nThreadCount < 1)
{
// auto-detect number of available threads
LogicalProcessorInformation info;
if (GetLogicalProcessorInformation(&info) == 0)
pWorkerContext->nThreadCount = info.processorCoreCount;
else
pWorkerContext->nThreadCount = 1;
}
pWorkerContext->hMutex = ::CreateMutex(NULL, FALSE, NULL);
pWorkerContext->hConvertThread = new HANDLE[pWorkerContext->nThreadCount];
pWorkerContext->dwConvertThreadID = new DWORD[pWorkerContext->nThreadCount];
pWorkerContext->Init();
// single-threaded
if (pWorkerContext->nThreadCount == 1)
{
ConvertLoop(pWorkerContext);
}
// multi-threaded
if (pWorkerContext->nThreadCount > 1)
{
// create worker threads
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
{
pWorkerContext->dwConvertThreadID[i] = i;
pWorkerContext->hConvertThread[i] = ::CreateThread(NULL, 0, ConvertThread, pWorkerContext, CREATE_SUSPENDED, &pWorkerContext->dwConvertThreadID[i]);
if (pWorkerContext->hConvertThread[i] == NULL)
break;
::ResumeThread(pWorkerContext->hConvertThread[i]);
}
// wait for all workers to finish
::WaitForMultipleObjects(pWorkerContext->nThreadCount, pWorkerContext->hConvertThread, TRUE, INFINITE);
// close convert thread handles
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
::CloseHandle(pWorkerContext->hConvertThread[i]);
}
delete pWorkerContext->hConvertThread;
delete pWorkerContext->dwConvertThreadID;
delete pWorkerContext->pQueue;
delete pWorkerContext->nProgess;
delete pWorkerContext->nPreviousProgess;
delete[] pItemsContext;
::CloseHandle(pWorkerContext->hMutex);
pWorkerContext->Done();
pWorkerContext->bDone = true;
return ::CloseHandle(pWorkerContext->hThread);
}
Added else statement
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\MainApp.h"
#include "..\Strings.h"
#include "..\utilities\TimeCount.h"
#include "..\utilities\Utilities.h"
#include "LuaProgess.h"
#include "WorkThread.h"
bool ProgresssLoop(CFileContext* pContext, CProcessContext &processContext, CPipe &Stderr, int &nProgress)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
const int nBuffSize = 4096;
char szReadBuff[nBuffSize];
char szLineBuff[nBuffSize];
DWORD dwReadBytes = 0L;
BOOL bRes = FALSE;
bool bLineStart = false;
bool bLineEnd = false;
bool bRunning = true;
int nLineLen = 0;
int nPreviousProgress = 0;
::SetCurrentDirectory(::GetExeFilePath());
// load progress function
CLuaProgess luaProgress;
if (luaProgress.Open(CT2CA(pContext->pFormat->szFunction)) == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00110001, pszProgresssLoop[0]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
if (luaProgress.HaveGetProgress() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00110002, pszProgresssLoop[1]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
// initialize buffers
ZeroMemory(szReadBuff, sizeof(szReadBuff));
ZeroMemory(szLineBuff, sizeof(szLineBuff));
do
{
ZeroMemory(szReadBuff, sizeof(szReadBuff));
bRes = ::ReadFile(Stderr.hRead, szReadBuff, 100, &dwReadBytes, 0);
if (bRes == FALSE || dwReadBytes == 0)
break;
// terminate read data by '\0'
szReadBuff[dwReadBytes] = '\0';
for (int i = 0; i < (int)dwReadBytes; i++)
{
// processed escape chars ( \r \n \t \b )
if (szReadBuff[i] == '\r') // '\r'
{
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (szReadBuff[i] == '\n') // '\n'
{
// do nothing
}
else if (szReadBuff[i] == '\t') // '\t'
{
// do nothing
}
else if (szReadBuff[i] == '\b') // '\b'
{
// do nothing (most of the tools)
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (bLineEnd == false)
{
bLineStart = true; // we have start
nLineLen++;
if (nLineLen > nBuffSize)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00110003, pszProgresssLoop[2]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
szLineBuff[nLineLen - 1] = szReadBuff[i];
}
// now we have correct full line of text
if ((bLineEnd == true) && (bLineStart == false))
{
// don't include empty lines
if (strlen(szLineBuff) > 0)
{
//OutputDebugStringA(szLineBuff); OutputDebugStringA("\n");
int nRet = (int)luaProgress.GetProgress(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
//CString szRet; szRet.Format(_T("%d#n"), nRet); OutputDebugString(szRet);
ZeroMemory(szLineBuff, sizeof(szLineBuff));
if (nProgress != nPreviousProgress)
{
bRunning = pWorkerContext->Callback(pContext->nItemId, nProgress, false);
nPreviousProgress = nProgress;
}
if ((pContext->pWorkerContext->bRunning == false) || (bRunning == false))
break;
}
// reset line counter
nLineLen = 0;
// find next start
bLineStart = true;
bLineEnd = false;
}
}
if (bRunning == false)
break;
} while (bRes);
luaProgress.Close();
return true;
}
bool ConvertFileUsingConsole(CFileContext* pContext)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
if ((pContext->bUseReadPipes == true) || (pContext->bUseWritePipes == true))
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120001, pszConvertConsole[0]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
CPipe Stderr(TRUE);
int nProgress = 0;
CTimeCount timer;
// create pipes for stderr
if (Stderr.Create() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120002, pszConvertConsole[1]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// duplicate stderr read pipe handle to prevent child process from closing the pipe
if (Stderr.DuplicateRead() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120003, pszConvertConsole[2]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// connect pipes to process
processContext.ConnectStdInput(NULL);
processContext.ConnectStdOutput(Stderr.hWrite);
processContext.ConnectStdError(Stderr.hWrite);
timer.Start();
if (processContext.Start(pContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
Stderr.CloseRead();
Stderr.CloseWrite();
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00120004, pszConvertConsole[3]), ::GetLastError());
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handle
Stderr.CloseWrite();
// console progress loop
if (ProgresssLoop(pContext, processContext, Stderr, nProgress) == false)
{
timer.Stop();
Stderr.CloseRead();
processContext.Stop(false);
return false;
}
timer.Stop();
Stderr.CloseRead();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00120005, pszConvertConsole[4]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), pWorkerContext->GetString(0x00120006, pszConvertConsole[5]));
pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ReadLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesRead = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
int nPreviousProgress = -1;
bool bRunning = true;
pContext->bError = false;
pContext->bFinished = false;
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
::CloseHandle(pContext->hPipe);
return false;
}
nFileSize = ::GetFileSize64(hFile);
if (nFileSize == 0)
{
pContext->bError = true;
pContext->bFinished = true;
::CloseHandle(hFile);
::CloseHandle(pContext->hPipe);
return false;
}
do
{
bRes = ::ReadFile(hFile, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
::Sleep(0);
bRes = ::WriteFile(pContext->hPipe, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
nTotalBytesRead += dwReadBytes;
nProgress = (int)((nTotalBytesRead * 100) / nFileSize);
if (nProgress != nPreviousProgress)
{
bRunning = pContext->pWorkerContext->Callback(pContext->nIndex, nProgress, false);
nPreviousProgress = nProgress;
}
if ((pContext->pWorkerContext->bRunning == false) || (bRunning == false))
break;
} while (bRes != FALSE);
::CloseHandle(hFile);
::CloseHandle(pContext->hPipe);
if (nTotalBytesRead != nFileSize)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
else
{
pContext->bError = false;
pContext->bFinished = true;
return true;
}
}
bool WriteLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesWrite = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
pContext->bError = false;
pContext->bFinished = false;
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
do
{
::Sleep(0);
bRes = ::ReadFile(pContext->hPipe, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
bRes = ::WriteFile(hFile, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
nTotalBytesWrite += dwReadBytes;
if (pContext->pWorkerContext->bRunning == false)
break;
} while (bRes != FALSE);
::CloseHandle(hFile);
pContext->bError = false;
pContext->bFinished = true;
return true;
}
DWORD WINAPI ReadThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (ReadLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WriteThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (WriteLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
bool ConvertFileUsingPipes(CFileContext* pContext)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == false))
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130001, pszConvertPipes[0]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
CPipe Stdin(TRUE);
CPipe Stdout(TRUE);
CPipeContext readContext;
CPipeContext writeContext;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
int nProgress = 0;
CTimeCount timer;
if (pContext->bUseReadPipes == true)
{
// create pipes for stdin
if (Stdin.Create() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130002, pszConvertPipes[1]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdin write pipe inherit flag
if (Stdin.InheritWrite() == false)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130003, pszConvertPipes[2]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
if (pContext->bUseWritePipes == true)
{
// create pipes for stdout
if (Stdout.Create() == false)
{
if (pContext->bUseReadPipes == true)
{
Stdin.CloseRead();
Stdin.CloseWrite();
}
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130004, pszConvertPipes[3]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdout read pipe inherit flag
if (Stdout.InheritRead() == false)
{
if (pContext->bUseReadPipes == true)
{
Stdin.CloseRead();
Stdin.CloseWrite();
}
Stdout.CloseRead();
Stdout.CloseWrite();
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130005, pszConvertPipes[4]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
// connect pipes to process
if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == false))
{
processContext.ConnectStdInput(Stdin.hRead);
processContext.ConnectStdOutput(GetStdHandle(STD_OUTPUT_HANDLE));
processContext.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
}
else if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(GetStdHandle(STD_INPUT_HANDLE));
processContext.ConnectStdOutput(Stdout.hWrite);
processContext.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
}
else if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(Stdin.hRead);
processContext.ConnectStdOutput(Stdout.hWrite);
processContext.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
}
timer.Start();
if (processContext.Start(pContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
if (pContext->bUseReadPipes == true)
{
Stdin.CloseRead();
Stdin.CloseWrite();
}
if (pContext->bUseWritePipes == true)
{
Stdout.CloseRead();
Stdout.CloseWrite();
}
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00130006, pszConvertPipes[5]), ::GetLastError());
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handles
if (pContext->bUseReadPipes == true)
Stdin.CloseRead();
if (pContext->bUseWritePipes == true)
Stdout.CloseWrite();
// create read thread
if (pContext->bUseReadPipes == true)
{
readContext.bError = false;
readContext.bFinished = false;
readContext.pWorkerContext = pWorkerContext;
readContext.szFileName = pContext->szInputFile;
readContext.hPipe = Stdin.hWrite;
readContext.nIndex = pContext->nItemId;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL, 0, ReadThread, (LPVOID)&readContext, 0, &dwReadThreadID);
if (hReadThread == NULL)
{
timer.Stop();
Stdin.CloseWrite();
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130007, pszConvertPipes[6]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// wait for read thread to finish
if (pContext->bUseWritePipes == false)
{
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//Stdin.CloseWrite();
// close read thread handle
::CloseHandle(hReadThread);
// wait for process to finish
::WaitForSingleObject(processContext.pInfo.hProcess, INFINITE);
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
}
}
// create write thread
if (pContext->bUseWritePipes == true)
{
writeContext.bError = false;
writeContext.bFinished = false;
writeContext.pWorkerContext = pWorkerContext;
writeContext.szFileName = pContext->szOutputFile;
writeContext.hPipe = Stdout.hRead;
writeContext.nIndex = pContext->nItemId;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL, 0, WriteThread, (LPVOID)&writeContext, 0, &dwWriteThreadID);
if (hWriteThread == NULL)
{
timer.Stop();
Stdout.CloseRead();
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130008, pszConvertPipes[7]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
if (pContext->bUseReadPipes == true)
{
// wait for read thread to finish
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//Stdin.CloseWrite();
// close read thread handle
::CloseHandle(hReadThread);
// close read thread handle
Stdout.CloseRead();
// wait for process to finish
::WaitForSingleObject(processContext.pInfo.hProcess, INFINITE);
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
// close read thread handle
::CloseHandle(hWriteThread);
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true)
&& (writeContext.bError == false) && (writeContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
}
else
{
// wait for process to finish
::WaitForSingleObject(processContext.pInfo.hProcess, INFINITE);
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
Stdout.CloseRead();
// close read thread handle
::CloseHandle(hWriteThread);
// check for result from write thread
if ((writeContext.bError == false) && (writeContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
}
}
timer.Stop();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pWorkerContext->Status(pContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130009, pszConvertPipes[8]));
pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), pWorkerContext->GetString(0x0013000B, pszConvertPipes[10]));
pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ConvertFileUsingOnlyPipes(CFileContext* pDecoderContext, CFileContext* pEncoderContext)
{
CWorkerContext *pWorkerContext = pDecoderContext->pWorkerContext;
CProcessContext processContextDecoder;
CProcessContext processContextEncoder;
CPipe Stdin(TRUE);
CPipe Stdout(TRUE);
CPipe Bridge(TRUE);
CPipeContext readContext;
CPipeContext writeContext;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
int nProgress = 0;
CTimeCount timer;
// create pipes for stdin
if (Stdin.Create() == false)
{
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130002, pszConvertPipes[1]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// set stdin write pipe inherit flag
if (Stdin.InheritWrite() == false)
{
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130003, pszConvertPipes[2]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create pipes for stdout
if (Stdout.Create() == false)
{
Stdin.CloseRead();
Stdin.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130004, pszConvertPipes[3]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// set stdout read pipe inherit flag
if (Stdout.InheritRead() == false)
{
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130005, pszConvertPipes[4]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create pipes for processes bridge
if (Bridge.Create() == false)
{
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x0013000A, pszConvertPipes[9]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// connect pipes to decoder process
processContextDecoder.ConnectStdInput(Stdin.hRead);
processContextDecoder.ConnectStdOutput(Bridge.hWrite);
processContextDecoder.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
// connect pipes to encoder process
processContextEncoder.ConnectStdInput(Bridge.hRead);
processContextEncoder.ConnectStdOutput(Stdout.hWrite);
processContextEncoder.ConnectStdError(GetStdHandle(STD_ERROR_HANDLE));
timer.Start();
// create decoder process
if (processContextDecoder.Start(pDecoderContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
Bridge.CloseRead();
Bridge.CloseWrite();
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00130006, pszConvertPipes[5]), ::GetLastError());
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create encoder process
if (processContextEncoder.Start(pEncoderContext->pszCommandLine, pWorkerContext->pConfig->m_Options.bHideConsoleWindow) == false)
{
timer.Stop();
processContextDecoder.Stop(false);
Stdin.CloseRead();
Stdin.CloseWrite();
Stdout.CloseRead();
Stdout.CloseWrite();
Bridge.CloseRead();
Bridge.CloseWrite();
CString szStatus;
szStatus.Format(pWorkerContext->GetString(0x00130006, pszConvertPipes[5]), ::GetLastError());
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, szStatus);
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handles
Stdin.CloseRead();
Stdout.CloseWrite();
Bridge.CloseWrite();
Bridge.CloseRead();
// create read thread
readContext.bError = false;
readContext.bFinished = false;
readContext.pWorkerContext = pWorkerContext;
readContext.szFileName = pDecoderContext->szInputFile;
readContext.hPipe = Stdin.hWrite;
readContext.nIndex = pDecoderContext->nItemId;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL, 0, ReadThread, (LPVOID)&readContext, 0, &dwReadThreadID);
if (hReadThread == NULL)
{
timer.Stop();
Stdin.CloseWrite();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130007, pszConvertPipes[6]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// create write thread
writeContext.bError = false;
writeContext.bFinished = false;
writeContext.pWorkerContext = pWorkerContext;
writeContext.szFileName = pEncoderContext->szOutputFile;
writeContext.hPipe = Stdout.hRead;
writeContext.nIndex = pEncoderContext->nItemId;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL, 0, WriteThread, (LPVOID)&writeContext, 0, &dwWriteThreadID);
if (hWriteThread == NULL)
{
timer.Stop();
Stdout.CloseRead();
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130008, pszConvertPipes[7]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
// wait for read thread to finish after write thread finished
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//Stdin.CloseWrite();
// close read thread handle
::CloseHandle(hReadThread);
Stdout.CloseRead();
// wait for encoder process to finish
::WaitForSingleObject(processContextEncoder.pInfo.hProcess, INFINITE);
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
// close read thread handle
::CloseHandle(hWriteThread);
// check for result from read and write thread
if ((readContext.bError == false) && (readContext.bFinished == true)
&& (writeContext.bError == false) && (writeContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
timer.Stop();
processContextDecoder.Stop(nProgress == 100);
processContextEncoder.Stop(nProgress == 100);
if (nProgress != 100)
{
pWorkerContext->Status(pDecoderContext->nItemId, pszDefaulTime, pWorkerContext->GetString(0x00130009, pszConvertPipes[8]));
pWorkerContext->Callback(pDecoderContext->nItemId, -1, true, true);
return false;
}
else
{
pWorkerContext->Status(pDecoderContext->nItemId, timer.Format(timer.ElapsedTime(), 1), pWorkerContext->GetString(0x0013000B, pszConvertPipes[10]));
pWorkerContext->Callback(pDecoderContext->nItemId, 100, true, false);
return true;
}
}
bool ConvertItem(CItemContext* pContext)
{
CWorkerContext *pWorkerContext = pContext->pWorkerContext;
CFormat *pEncFormat = NULL;
CFormat *pDecFormat = NULL;
CString szEncInputFile;
CString szEncOutputFile;
CString szDecInputFile;
CString szDecOutputFile;
CString szOutPath;
if (pWorkerContext->pConfig->m_Options.bOutputPathChecked == true)
szOutPath = pWorkerContext->pConfig->m_Options.szOutputPath;
else
szOutPath = ::GetFilePath(pContext->item->szPath);
// prepare encoder
szEncInputFile = pContext->item->szPath;
if (::FileExists(szEncInputFile) == false)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140001, pszConvertItem[0]));
return false;
}
int nEncoder = pWorkerContext->pConfig->m_Formats.GetFormatById(pContext->item->szFormatId);
if (nEncoder == -1)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140002, pszConvertItem[1]));
return false;
}
pEncFormat = &pWorkerContext->pConfig->m_Formats.GetData(nEncoder);
if (pContext->item->nPreset >= pEncFormat->m_Presets.GetSize())
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140003, pszConvertItem[2]));
return false;
}
bool bIsValidEncoderInput = pEncFormat->IsValidInputExtension(::GetFileExtension(szEncInputFile));
szEncOutputFile = pContext->item->szName + _T(".") + CString(pEncFormat->szOutputExtension).MakeLower();
if (szOutPath.GetLength() >= 1)
{
if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/')
szEncOutputFile = szOutPath + szEncOutputFile;
else
szEncOutputFile = szOutPath + _T("\\") + szEncOutputFile;
}
// prepare decoder
if (bIsValidEncoderInput == false)
{
int nDecoder = pWorkerContext->pConfig->m_Formats.GetDecoderByExtensionAndFormat(pContext->item->szExtension, pEncFormat);
if (nDecoder == -1)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140004, pszConvertItem[3]));
return false;
}
pDecFormat = &pWorkerContext->pConfig->m_Formats.GetData(nDecoder);
if (pDecFormat->nDefaultPreset >= pDecFormat->m_Presets.GetSize())
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140005, pszConvertItem[4]));
return false;
}
bool bIsValidDecoderOutput = pEncFormat->IsValidInputExtension(pDecFormat->szOutputExtension);
if (bIsValidDecoderOutput == false)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140006, pszConvertItem[5]));
return false;
}
szDecInputFile = szEncInputFile;
szDecOutputFile = szEncOutputFile + _T(".") + CString(pDecFormat->szOutputExtension).MakeLower();
}
CFileContext decoderContext;
if (bIsValidEncoderInput == false)
{
decoderContext.Init(
pWorkerContext,
pDecFormat,
pDecFormat->nDefaultPreset,
pContext->item->nId,
szDecInputFile,
szDecOutputFile,
pDecFormat->bPipeInput,
pDecFormat->bPipeOutput);
}
CFileContext encoderContext;
encoderContext.Init(
pWorkerContext,
pEncFormat,
pContext->item->nPreset,
pContext->item->nId,
bIsValidEncoderInput == true ? szEncInputFile : szDecOutputFile,
szEncOutputFile,
pEncFormat->bPipeInput,
pEncFormat->bPipeOutput);
if (bIsValidEncoderInput == false
&& decoderContext.bUseReadPipes == true
&& decoderContext.bUseWritePipes == true
&& encoderContext.bUseReadPipes == true
&& encoderContext.bUseWritePipes == true)
{
// trans-code
try
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000C, pszConvertItem[11]));
bool bResult = ConvertFileUsingOnlyPipes(&decoderContext, &encoderContext);
if (bResult == true)
{
if (::FileExists(szEncOutputFile) == false)
{
if (bIsValidEncoderInput == false)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncInputFile);
}
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000D, pszConvertItem[12]));
return false;
}
if (pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true)
::DeleteFile(szEncInputFile);
return true;
}
else
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
return false;
}
}
catch (...)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000E, pszConvertItem[13]));
pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
else
{
// decode
if (bIsValidEncoderInput == false)
{
try
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140007, pszConvertItem[6]));
bool bResult = false;
if ((decoderContext.bUseReadPipes == false) && (decoderContext.bUseWritePipes == false))
bResult = ConvertFileUsingConsole(&decoderContext);
else
bResult = ConvertFileUsingPipes(&decoderContext);
if (bResult == false)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szDecOutputFile);
return false;
}
if (::FileExists(szDecOutputFile) == false)
{
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140008, pszConvertItem[7]));
return false;
}
}
catch (...)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x00140009, pszConvertItem[8]));
pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
if (pWorkerContext->bRunning == false)
return false;
// encode
try
{
if (pEncFormat->nType == 0)
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000A, pszConvertItem[9]));
else if (pEncFormat->nType == 1)
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000B, pszConvertItem[10]));
bool bResult = false;
if ((encoderContext.bUseReadPipes == false) && (encoderContext.bUseWritePipes == false))
bResult = ConvertFileUsingConsole(&encoderContext);
else
bResult = ConvertFileUsingPipes(&encoderContext);
if (bResult == true)
{
if (::FileExists(szEncOutputFile) == false)
{
if (bIsValidEncoderInput == false)
{
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncInputFile);
}
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000D, pszConvertItem[12]));
return false;
}
if (bIsValidEncoderInput == false)
::DeleteFile(szDecOutputFile);
if (pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true)
::DeleteFile(szEncInputFile);
return true;
}
else
{
if (bIsValidEncoderInput == false)
::DeleteFile(szDecOutputFile);
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
return false;
}
}
catch (...)
{
if (bIsValidEncoderInput == false)
::DeleteFile(szDecOutputFile);
if (pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szEncOutputFile);
pWorkerContext->Status(pContext->item->nId, pszDefaulTime, pWorkerContext->GetString(0x0014000E, pszConvertItem[13]));
pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
return false;
}
bool ConvertLoop(CWorkerContext* pWorkerContext)
{
while (TRUE)
{
try
{
CItemContext* pContext = NULL;
DWORD dwWaitResult = ::WaitForSingleObject(pWorkerContext->hMutex, INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
{
if (!pWorkerContext->pQueue->IsEmpty())
{
pContext = (CItemContext*)pWorkerContext->pQueue->RemoveHead();
}
if (!::ReleaseMutex(pWorkerContext->hMutex))
return false;
}
break;
case WAIT_ABANDONED:
return false;
}
if (pContext != NULL)
{
if (pContext->pWorkerContext->bRunning == false)
return false;
pContext->pWorkerContext->Next(pContext->item->nId);
if (ConvertItem(pContext) == true)
{
pContext->pWorkerContext->nDoneWithoutError++;
}
else
{
if (pContext->pWorkerContext->pConfig->m_Options.bStopOnErrors == true)
return false;
}
if (pContext->pWorkerContext->bRunning == false)
return false;
}
else
{
return true;
}
}
catch (...)
{
return false;
}
}
return true;
}
DWORD WINAPI ConvertThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext != NULL)
{
if (ConvertLoop(pWorkerContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WorkThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext == NULL)
return (DWORD)(-1);
int nItems = pWorkerContext->pConfig->m_Items.GetSize();
CItemContext *pItemsContext = new CItemContext[nItems];
pWorkerContext->nTotalFiles = 0;
pWorkerContext->nProcessedFiles = 0;
pWorkerContext->nDoneWithoutError = 0;
pWorkerContext->nErrors = 0;
pWorkerContext->pQueue = new CObList(nItems);
pWorkerContext->nProgess = new int[nItems];
pWorkerContext->nPreviousProgess = new int[nItems];
pWorkerContext->nLastItemId = -1;
for (int i = 0; i < nItems; i++)
{
CItem& item = pWorkerContext->pConfig->m_Items.GetData(i);
if (item.bChecked == true)
{
pWorkerContext->nTotalFiles++;
pWorkerContext->nProgess[i] = 0;
pWorkerContext->nPreviousProgess[i] = 0;
pItemsContext[i].pWorkerContext = pWorkerContext;
pItemsContext[i].item = &item;
pWorkerContext->pQueue->AddTail(&pItemsContext[i]);
}
else
{
pWorkerContext->nProgess[i] = 100;
pWorkerContext->nPreviousProgess[i] = 100;
}
}
pWorkerContext->nThreadCount = pWorkerContext->pConfig->m_Options.nThreadCount;
if (pWorkerContext->nThreadCount < 1)
{
// auto-detect number of available threads
LogicalProcessorInformation info;
if (GetLogicalProcessorInformation(&info) == 0)
pWorkerContext->nThreadCount = info.processorCoreCount;
else
pWorkerContext->nThreadCount = 1;
}
pWorkerContext->hMutex = ::CreateMutex(NULL, FALSE, NULL);
pWorkerContext->hConvertThread = new HANDLE[pWorkerContext->nThreadCount];
pWorkerContext->dwConvertThreadID = new DWORD[pWorkerContext->nThreadCount];
pWorkerContext->Init();
// single-threaded
if (pWorkerContext->nThreadCount == 1)
{
ConvertLoop(pWorkerContext);
}
// multi-threaded
if (pWorkerContext->nThreadCount > 1)
{
// create worker threads
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
{
pWorkerContext->dwConvertThreadID[i] = i;
pWorkerContext->hConvertThread[i] = ::CreateThread(NULL, 0, ConvertThread, pWorkerContext, CREATE_SUSPENDED, &pWorkerContext->dwConvertThreadID[i]);
if (pWorkerContext->hConvertThread[i] == NULL)
break;
::ResumeThread(pWorkerContext->hConvertThread[i]);
}
// wait for all workers to finish
::WaitForMultipleObjects(pWorkerContext->nThreadCount, pWorkerContext->hConvertThread, TRUE, INFINITE);
// close convert thread handles
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
::CloseHandle(pWorkerContext->hConvertThread[i]);
}
delete pWorkerContext->hConvertThread;
delete pWorkerContext->dwConvertThreadID;
delete pWorkerContext->pQueue;
delete pWorkerContext->nProgess;
delete pWorkerContext->nPreviousProgess;
delete[] pItemsContext;
::CloseHandle(pWorkerContext->hMutex);
pWorkerContext->Done();
pWorkerContext->bDone = true;
return ::CloseHandle(pWorkerContext->hThread);
}
|
#ifndef _app_hpp_INCLUDED
#define _app_hpp_INCLUDED
namespace CaDiCaL {
class Solver;
class File;
// A wrapper app which makes up the CaDiCaL stand alone solver. It in
// essence only consists of the 'App::main' function. So this class
// contains code, which is not required if only the library interface in
// 'Solver' is used. It further uses static data structures in order to
// have a signal handler catch signals. It should not be used in a
// multithreaded application. If you want to use multiple instances of the
// solver use the 'Solver' interface directly.
class App {
// Global solver.
static Solver * solver;
// Printing.
static void usage ();
static void witness ();
static void banner ();
// Option handling.
static bool set (const char*);
public:
static int main (int arg, char ** argv);
};
};
#endif
issue
#ifndef _app_hpp_INCLUDED
#define _app_hpp_INCLUDED
namespace CaDiCaL {
class Solver;
class File;
// A wrapper app which makes up the CaDiCaL stand alone solver. It in
// essence only consists of the 'App::main' function. So this class
// contains code, which is not required if only the library interface in
// 'Solver' is used. It further uses static data structures in order to
// have a signal handler catch signals. It is thus not reentrant and should
// not be used in a multithreaded application. If you want to use multiple
// instances of the solver use the 'Solver' interface directly.
class App {
// Global solver.
static Solver * solver;
// Printing.
static void usage ();
static void witness ();
static void banner ();
// Option handling.
static bool set (const char*);
public:
static int main (int arg, char ** argv);
};
};
#endif
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\BatchEncoder.h"
#include "..\utilities\TimeCount.h"
#include "..\utilities\UnicodeUtf8.h"
#include "..\utilities\Utf8String.h"
#include "..\utilities\Utilities.h"
#include "..\Configuration.h"
#include "WorkerContext.h"
#include "PipeContext.h"
#include "FileContext.h"
#include "ItemContext.h"
#include "ProcessContext.h"
#include "WorkThread.h"
bool ProgresssLoop(CFileContext* pContext, CProcessContext &processContext, int &nProgress)
{
const int nBuffSize = 4096;
char szReadBuff[nBuffSize];
char szLineBuff[nBuffSize];
DWORD dwReadBytes = 0L;
BOOL bRes = FALSE;
bool bLineStart = false;
bool bLineEnd = false;
bool bRunning = true;
int nLineLen = 0;
int nPreviousProgress = 0;
// load progress function
HMODULE hDll = ::LoadLibrary(pContext->szFunction);
if (hDll == NULL)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not load GetProgress function library dll."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
GetProgress *pGetProgress = (GetProgress*) ::GetProcAddress(hDll, "GetProgress");
if (pGetProgress == NULL)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not get GetProgress function address."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
// initialize buffers
ZeroMemory(szReadBuff, sizeof(szReadBuff));
ZeroMemory(szLineBuff, sizeof(szLineBuff));
do
{
ZeroMemory(szReadBuff, sizeof(szReadBuff));
bRes = ::ReadFile(processContext.hReadPipeStderr, szReadBuff, 100, &dwReadBytes, 0);
if (bRes == FALSE || dwReadBytes == 0)
break;
// terminate read data by '\0'
szReadBuff[dwReadBytes] = '\0';
for (int i = 0; i < (int)dwReadBytes; i++)
{
// processed escape chars ( \r \n \t \b )
if (szReadBuff[i] == '\r') // '\r'
{
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (szReadBuff[i] == '\n') // '\n'
{
// do nothing
}
else if (szReadBuff[i] == '\t') // '\t'
{
// do nothing
}
else if (szReadBuff[i] == '\b') // '\b'
{
// do nothing (most of the tools)
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (bLineEnd == false)
{
bLineStart = true; // we have start
nLineLen++;
if (nLineLen > nBuffSize)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: console line is too large for read buffer."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
szLineBuff[nLineLen - 1] = szReadBuff[i];
}
// now we have correct full line of text
if ((bLineEnd == true) && (bLineStart == false))
{
// don't include empty lines
if (strlen(szLineBuff) > 0)
{
int nRet = (pGetProgress)(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
ZeroMemory(szLineBuff, sizeof(szLineBuff));
if (nProgress != nPreviousProgress)
{
bRunning = pContext->pWorkerContext->Callback(pContext->nItemId, nProgress, false);
nPreviousProgress = nProgress;
}
if (bRunning == false)
break;
}
// reset line counter
nLineLen = 0;
// find next start
bLineStart = true;
bLineEnd = false;
}
}
if (bRunning == false)
break;
} while (bRes);
if (hDll != NULL)
::FreeLibrary(hDll);
return true;
}
bool ConvertFileUsingConsole(CFileContext* pContext)
{
if ((pContext->bUseReadPipes == true) || (pContext->bUseWritePipes == true))
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: invalid format pipe configuration."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
int nProgress = 0;
CTimeCount timer;
// create pipes for stderr
if (processContext.CreateStderrPipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create pipes for stderr."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// duplicate stderr read pipe handle to prevent child process from closing the pipe
if (processContext.DuplicateStderrReadPipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not duplicate stderr pipe to prevent child process from closing the pipe."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// connect pipes to process
processContext.ConnectStdInput(NULL);
processContext.ConnectStdOutput(processContext.hWritePipeStderr);
processContext.ConnectStdError(processContext.hWritePipeStderr);
timer.Start();
if (processContext.Start(pContext->szCommandLine) == false)
{
timer.Stop();
processContext.CloseStderrReadPipe();
processContext.CloseStderrWritePipe();
CString szStatus;
szStatus.Format(_T("Error: can not create command-line process (%d)."), ::GetLastError());
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), szStatus);
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handle
processContext.CloseStderrWritePipe();
// console progresss loop
if (ProgresssLoop(pContext, processContext, nProgress) == false)
{
timer.Stop();
processContext.CloseStderrReadPipe();
processContext.Stop(false);
return false;
}
timer.Stop();
processContext.CloseStderrReadPipe();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: progress did not reach 100%."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pContext->pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), _T("Done"));
pContext->pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ReadLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesRead = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
int nPreviousProgress = -1;
bool bRunning = true;
pContext->bError = false;
pContext->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
nFileSize = ::GetFileSize64(hFile);
if (nFileSize == 0)
{
pContext->bError = true;
pContext->bFinished = true;
::CloseHandle(hFile);
return false;
}
// read/write loop
do
{
// read data from source file
bRes = ::ReadFile(hFile, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// NOTE: Sleep(0) solves problem writing to pipe errors
::Sleep(0);
// write data to write pipe
bRes = ::WriteFile(pContext->hPipe, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesRead += dwReadBytes;
nProgress = (int)((nTotalBytesRead * 100) / nFileSize);
if (nProgress != nPreviousProgress)
{
bRunning = pContext->pWorkerContext->Callback(pContext->nIndex, nProgress, false);
nPreviousProgress = nProgress;
}
if (bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
// close write pipe to allow write thread terminate reading
::CloseHandle(pContext->hPipe);
// check if all data was processed
if (nTotalBytesRead != nFileSize)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
pContext->bError = false;
pContext->bFinished = true;
return true;
}
bool WriteLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesWrite = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
pContext->bError = false;
pContext->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
// read/write loop
do
{
// read data from source pipe
bRes = ::ReadFile(pContext->hPipe, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// write data to file
bRes = ::WriteFile(hFile, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesWrite += dwReadBytes;
// handle user Stop
if (pContext->pWorkerContext->bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
pContext->bError = false;
pContext->bFinished = true;
return true;
}
DWORD WINAPI ReadThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (ReadLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WriteThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (WriteLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
bool ConvertFileUsingPipes(CFileContext* pContext)
{
if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == false))
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: invalid format pipe configuration."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
CPipeContext readContext;
CPipeContext writeContext;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
bool bWriteThreadResult = false;
int nProgress = 0;
CTimeCount timer;
if (pContext->bUseReadPipes == true)
{
// create pipes for stdin
if (processContext.CreateStdinPipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create pipes for stdin."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdin write pipe inherit flag
if (processContext.InheritStdinWritePipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not set stdin pipe inherit flag."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
if (pContext->bUseWritePipes == true)
{
// create pipes for stdout
if (processContext.CreateStdoutPipe() == false)
{
if (pContext->bUseReadPipes == true)
{
processContext.CloseStdinReadPipe();
processContext.CloseStdinWritePipe();
}
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create pipes for stdout."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdout read pipe inherit flag
if (processContext.InheritStdoutReadPipe() == false)
{
if (pContext->bUseReadPipes == true)
{
processContext.CloseStdinReadPipe();
processContext.CloseStdinWritePipe();
}
processContext.CloseStdoutReadPipe();
processContext.CloseStdoutWritePipe();
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not set stdout pipe inherit flag."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
// connect pipes to process
if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == false))
{
processContext.ConnectStdInput(processContext.hReadPipeStdin);
processContext.ConnectStdOutput(NULL);
processContext.ConnectStdError(NULL);
}
else if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(NULL);
processContext.ConnectStdOutput(processContext.hWritePipeStdout);
processContext.ConnectStdError(NULL);
}
else if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(processContext.hReadPipeStdin);
processContext.ConnectStdOutput(processContext.hWritePipeStdout);
processContext.ConnectStdError(NULL);
}
timer.Start();
if (processContext.Start(pContext->szCommandLine) == false)
{
timer.Stop();
if (pContext->bUseReadPipes == true)
{
processContext.CloseStdinReadPipe();
processContext.CloseStdinWritePipe();
}
if (pContext->bUseWritePipes == true)
{
processContext.CloseStdoutReadPipe();
processContext.CloseStdoutWritePipe();
}
CString szStatus;
szStatus.Format(_T("Error: can not create command-line process (%d)."), ::GetLastError());
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), szStatus);
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handles
if (pContext->bUseReadPipes == true)
processContext.CloseStdinReadPipe();
if (pContext->bUseWritePipes == true)
processContext.CloseStdoutWritePipe();
// create read thread
if (pContext->bUseReadPipes == true)
{
readContext.bError = false;
readContext.bFinished = false;
readContext.pWorkerContext = pContext->pWorkerContext;
readContext.szFileName = pContext->szInputFile;
readContext.hPipe = processContext.hWritePipeStdin;
readContext.nIndex = pContext->nItemId;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL, 0, ReadThread, (LPVOID)&readContext, 0, &dwReadThreadID);
if (hReadThread == NULL)
{
timer.Stop();
processContext.CloseStdinWritePipe();
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create read thread."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// wait for read thread to finish
if (pContext->bUseWritePipes == false)
{
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//processContext.CloseStdinWritePipe();
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
}
// create write thread
if (pContext->bUseWritePipes == true)
{
writeContext.bError = false;
writeContext.bFinished = false;
writeContext.pWorkerContext = pContext->pWorkerContext;
writeContext.szFileName = pContext->szOutputFile;
writeContext.hPipe = processContext.hReadPipeStdout;
writeContext.nIndex = pContext->nItemId;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL, 0, WriteThread, (LPVOID)&writeContext, 0, &dwWriteThreadID);
if (hWriteThread == NULL)
{
timer.Stop();
processContext.CloseStdoutReadPipe();
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create write thread."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
processContext.CloseStdoutReadPipe();
// check for result from read thread
if ((writeContext.bError == false) && (writeContext.bFinished == true))
{
bWriteThreadResult = true;
if (pContext->bUseReadPipes == false)
nProgress = 100;
}
else
{
bWriteThreadResult = false;
if (pContext->bUseReadPipes == false)
nProgress = -1;
}
// close read thread handle
::CloseHandle(hWriteThread);
}
// wait for read thread to finish after write thread finished
if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == true))
{
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//processContext.CloseStdinWritePipe();
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true) && (bWriteThreadResult == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
timer.Stop();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: progress did not reach 100%."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pContext->pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), _T("Done"));
pContext->pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ConvertFile(CFileContext* pContext)
{
if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == false))
return ConvertFileUsingConsole(pContext);
else
return ConvertFileUsingPipes(pContext);
}
enum Mode { None = -1, Encode = 0, Transcode = 1 };
bool FileExists(CString szPath)
{
WIN32_FIND_DATA w32FileData;
ZeroMemory(&w32FileData, sizeof(WIN32_FIND_DATA));
HANDLE hFind = ::FindFirstFile(szPath, &w32FileData);
bool bInvalidHandle = hFind == INVALID_HANDLE_VALUE;
::FindClose(hFind);
return bInvalidHandle == false;
}
bool ConvertItem(CItemContext* pContext)
{
// input file
CString szInputFile = pContext->item->szPath;
// validate input file
if (FileExists(szInputFile) == false)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find input file."));
return false;
}
// output path
CString szOutPath;
if (pContext->pWorkerContext->pConfig->m_Options.bOutputPathChecked == true)
{
szOutPath = pContext->pWorkerContext->pConfig->m_Options.szOutputPath;
}
else
{
CString szInputFileName = ::GetFileName(szInputFile);
szOutPath = szInputFile;
szOutPath.Truncate(szOutPath.GetLength() - szInputFileName.GetLength());
}
// find encoder
int nEncoder = pContext->pWorkerContext->pConfig->m_Formats.GetFormatById(pContext->item->szFormatId);
if (nEncoder == -1)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid encoder by id."));
return false;
}
CFormat& encoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nEncoder);
// validate encoder preset
if (pContext->item->nPreset >= encoderFormat.m_Presets.GetSize())
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoder format preset."));
return false;
}
// validate input extension
CString szInputFileExt = ::GetFileExtension(szInputFile).MakeUpper();
bool bIsValidEncoderInput = encoderFormat.IsValidInputExtension(szInputFileExt);
// processing mode
Mode nProcessingMode = Mode::None;
if (bIsValidEncoderInput)
nProcessingMode = Mode::Encode;
else
nProcessingMode = Mode::Transcode;
// output path
CString szEncoderExtension = encoderFormat.szOutputExtension;
CString szName = pContext->item->szName + _T(".") + szEncoderExtension.MakeLower();
CString szOutputFile;
if (szOutPath.GetLength() >= 1)
{
if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/')
szOutputFile = szOutPath + szName;
else
szOutputFile = szOutPath + _T("\\") + szName;
}
else
{
szOutputFile = szName;
}
CString szOrgInputFile = szInputFile;
CString szOrgOutputFile = szOutputFile;
if (nProcessingMode == Mode::Transcode)
{
// find decoder
int nDecoder = pContext->pWorkerContext->pConfig->m_Formats.GetDecoderByExtension(pContext->item->szExtension);
if (nDecoder == -1)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid decoder by extension."));
return false;
}
CFormat& decoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nDecoder);
// validate decoder preset
if (decoderFormat.nDefaultPreset >= decoderFormat.m_Presets.GetSize())
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoder format preset."));
return false;
}
// validate decoder output extension
bIsValidEncoderInput = encoderFormat.IsValidInputExtension(decoderFormat.szOutputExtension);
if (bIsValidEncoderInput == false)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: decoder output not supported by encoder."));
return false;
}
CString szDecoderExtension = decoderFormat.szOutputExtension;
szOutputFile = szOutputFile + +_T(".") + szDecoderExtension.MakeLower();
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Decoding..."));
try
{
CFileContext context(pContext->pWorkerContext, decoderFormat, decoderFormat.nDefaultPreset, pContext->item->nId, szInputFile, szOutputFile);
if (::ConvertFile(&context) == false)
{
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
return false;
}
// validate decoded file
if (FileExists(szOutputFile) == false)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoded file."));
return false;
}
}
catch (...)
{
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file."));
pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
if (pContext->pWorkerContext->bRunning == false)
return false;
if (nProcessingMode == Mode::Transcode)
{
// decoder output file as encoder input file
szInputFile = szOutputFile;
// original encoder output file
szOutputFile = szOrgOutputFile;
}
if ((nProcessingMode == Mode::Encode) || (nProcessingMode == Mode::Transcode))
{
if (encoderFormat.nType == 0)
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Encoding..."));
else if (encoderFormat.nType == 1)
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Decoding..."));
else
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Processing..."));
try
{
CFileContext context(pContext->pWorkerContext, encoderFormat, pContext->item->nPreset, pContext->item->nId, szInputFile, szOutputFile);
if (::ConvertFile(&context) == true)
{
// validate encoded file
if (FileExists(szOutputFile) == false)
{
if (nProcessingMode == Mode::Transcode)
{
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szInputFile);
}
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoded file."));
return false;
}
if (nProcessingMode == Mode::Transcode)
::DeleteFile(szInputFile);
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true)
::DeleteFile(szOrgInputFile);
return true;
}
else
{
if (nProcessingMode == Mode::Transcode)
::DeleteFile(szInputFile);
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
return false;
}
}
catch (...)
{
if (nProcessingMode == Mode::Transcode)
::DeleteFile(szInputFile);
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file."));
pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
return false;
}
bool ConvertLoop(CWorkerContext* pWorkerContext)
{
while (!pWorkerContext->pQueue->IsEmpty())
{
try
{
CItemContext* pContext = NULL;
DWORD dwWaitResult = ::WaitForSingleObject(pWorkerContext->hMutex, INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
{
pContext = (CItemContext*)pWorkerContext->pQueue->RemoveHead();
if (!::ReleaseMutex(pWorkerContext->hMutex))
return false;
}
break;
case WAIT_ABANDONED:
return false;
}
if (pContext != NULL)
{
pContext->pWorkerContext->Next(pContext->item->nId);
if (ConvertItem(pContext) == true)
{
pContext->pWorkerContext->nDoneWithoutError++;
}
else
{
if (pContext->pWorkerContext->pConfig->m_Options.bStopOnErrors == true)
return false;
}
if (pContext->pWorkerContext->bRunning == false)
return false;
}
}
catch (...)
{
return false;
}
}
return true;
}
DWORD WINAPI ConvertThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext != NULL)
{
if (ConvertLoop(pWorkerContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WorkThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext == NULL)
return (DWORD)(-1);
int nItems = pWorkerContext->pConfig->m_Items.GetSize();
CItemContext *pItemsContext = new CItemContext[nItems];
pWorkerContext->nThreadCount = pWorkerContext->pConfig->m_Options.nThreadCount;
if (pWorkerContext->nThreadCount < 1)
{
// auto-detect number of available threads
LogicalProcessorInformation info;
if (GetLogicalProcessorInformation(&info) == 0)
pWorkerContext->nThreadCount = info.processorCoreCount;
else
pWorkerContext->nThreadCount = 1;
}
pWorkerContext->hMutex = ::CreateMutex(NULL, FALSE, NULL);
pWorkerContext->nTotalFiles = 0;
pWorkerContext->nProcessedFiles = 0;
pWorkerContext->nDoneWithoutError = 0;
pWorkerContext->nErrors = 0;
pWorkerContext->hConvertThread = new HANDLE[pWorkerContext->nThreadCount];
pWorkerContext->dwConvertThreadID = new DWORD[pWorkerContext->nThreadCount];
pWorkerContext->pQueue = new CObList();
pWorkerContext->nProgess = new int[nItems];
pWorkerContext->nPreviousProgess = new int[nItems];
pWorkerContext->nLastItemId = -1;
for (int i = 0; i < nItems; i++)
{
CItem& item = pWorkerContext->pConfig->m_Items.GetData(i);
if (item.bChecked == true)
{
pWorkerContext->nTotalFiles++;
pWorkerContext->nProgess[i] = 0;
pWorkerContext->nPreviousProgess[i] = 0;
pItemsContext[i].pWorkerContext = pWorkerContext;
pItemsContext[i].item = &item;
pWorkerContext->pQueue->AddTail(&pItemsContext[i]);
}
else
{
pWorkerContext->nProgess[i] = 100;
pWorkerContext->nPreviousProgess[i] = 100;
}
}
pWorkerContext->Init();
// single-threaded
if (pWorkerContext->nThreadCount == 1)
{
ConvertLoop(pWorkerContext);
}
// multi-threaded
if (pWorkerContext->nThreadCount > 1)
{
// create worker threads
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
{
pWorkerContext->dwConvertThreadID[i] = i;
pWorkerContext->hConvertThread[i] = ::CreateThread(NULL, 0, ConvertThread, pWorkerContext, CREATE_SUSPENDED, &pWorkerContext->dwConvertThreadID[i]);
if (pWorkerContext->hConvertThread[i] == NULL)
break;
::ResumeThread(pWorkerContext->hConvertThread[i]);
}
// wait for all workers to finish
::WaitForMultipleObjects(pWorkerContext->nThreadCount, pWorkerContext->hConvertThread, TRUE, INFINITE);
// close convert thread handles
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
::CloseHandle(pWorkerContext->hConvertThread[i]);
}
delete pWorkerContext->hConvertThread;
delete pWorkerContext->dwConvertThreadID;
delete pWorkerContext->pQueue;
delete pWorkerContext->nProgess;
delete pWorkerContext->nPreviousProgess;
delete[] pItemsContext;
::CloseHandle(pWorkerContext->hMutex);
pWorkerContext->Done();
pWorkerContext->bDone = true;
return ::CloseHandle(pWorkerContext->hThread);
}
Removed unused includes
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\BatchEncoder.h"
#include "..\utilities\TimeCount.h"
#include "..\utilities\Utilities.h"
#include "..\Configuration.h"
#include "WorkerContext.h"
#include "PipeContext.h"
#include "FileContext.h"
#include "ItemContext.h"
#include "ProcessContext.h"
#include "WorkThread.h"
bool ProgresssLoop(CFileContext* pContext, CProcessContext &processContext, int &nProgress)
{
const int nBuffSize = 4096;
char szReadBuff[nBuffSize];
char szLineBuff[nBuffSize];
DWORD dwReadBytes = 0L;
BOOL bRes = FALSE;
bool bLineStart = false;
bool bLineEnd = false;
bool bRunning = true;
int nLineLen = 0;
int nPreviousProgress = 0;
// load progress function
HMODULE hDll = ::LoadLibrary(pContext->szFunction);
if (hDll == NULL)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not load GetProgress function library dll."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
GetProgress *pGetProgress = (GetProgress*) ::GetProcAddress(hDll, "GetProgress");
if (pGetProgress == NULL)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not get GetProgress function address."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false; // ERROR
}
// initialize buffers
ZeroMemory(szReadBuff, sizeof(szReadBuff));
ZeroMemory(szLineBuff, sizeof(szLineBuff));
do
{
ZeroMemory(szReadBuff, sizeof(szReadBuff));
bRes = ::ReadFile(processContext.hReadPipeStderr, szReadBuff, 100, &dwReadBytes, 0);
if (bRes == FALSE || dwReadBytes == 0)
break;
// terminate read data by '\0'
szReadBuff[dwReadBytes] = '\0';
for (int i = 0; i < (int)dwReadBytes; i++)
{
// processed escape chars ( \r \n \t \b )
if (szReadBuff[i] == '\r') // '\r'
{
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (szReadBuff[i] == '\n') // '\n'
{
// do nothing
}
else if (szReadBuff[i] == '\t') // '\t'
{
// do nothing
}
else if (szReadBuff[i] == '\b') // '\b'
{
// do nothing (most of the tools)
if ((bLineStart == true) && (bLineEnd == false))
{
bLineEnd = true;
bLineStart = false;
szLineBuff[nLineLen] = '\0';
}
}
else if (bLineEnd == false)
{
bLineStart = true; // we have start
nLineLen++;
if (nLineLen > nBuffSize)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: console line is too large for read buffer."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
szLineBuff[nLineLen - 1] = szReadBuff[i];
}
// now we have correct full line of text
if ((bLineEnd == true) && (bLineStart == false))
{
// don't include empty lines
if (strlen(szLineBuff) > 0)
{
int nRet = (pGetProgress)(szLineBuff, nLineLen);
if (nRet != -1)
nProgress = nRet;
ZeroMemory(szLineBuff, sizeof(szLineBuff));
if (nProgress != nPreviousProgress)
{
bRunning = pContext->pWorkerContext->Callback(pContext->nItemId, nProgress, false);
nPreviousProgress = nProgress;
}
if (bRunning == false)
break;
}
// reset line counter
nLineLen = 0;
// find next start
bLineStart = true;
bLineEnd = false;
}
}
if (bRunning == false)
break;
} while (bRes);
if (hDll != NULL)
::FreeLibrary(hDll);
return true;
}
bool ConvertFileUsingConsole(CFileContext* pContext)
{
if ((pContext->bUseReadPipes == true) || (pContext->bUseWritePipes == true))
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: invalid format pipe configuration."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
int nProgress = 0;
CTimeCount timer;
// create pipes for stderr
if (processContext.CreateStderrPipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create pipes for stderr."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// duplicate stderr read pipe handle to prevent child process from closing the pipe
if (processContext.DuplicateStderrReadPipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not duplicate stderr pipe to prevent child process from closing the pipe."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// connect pipes to process
processContext.ConnectStdInput(NULL);
processContext.ConnectStdOutput(processContext.hWritePipeStderr);
processContext.ConnectStdError(processContext.hWritePipeStderr);
timer.Start();
if (processContext.Start(pContext->szCommandLine) == false)
{
timer.Stop();
processContext.CloseStderrReadPipe();
processContext.CloseStderrWritePipe();
CString szStatus;
szStatus.Format(_T("Error: can not create command-line process (%d)."), ::GetLastError());
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), szStatus);
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handle
processContext.CloseStderrWritePipe();
// console progresss loop
if (ProgresssLoop(pContext, processContext, nProgress) == false)
{
timer.Stop();
processContext.CloseStderrReadPipe();
processContext.Stop(false);
return false;
}
timer.Stop();
processContext.CloseStderrReadPipe();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: progress did not reach 100%."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pContext->pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), _T("Done"));
pContext->pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ReadLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesRead = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
int nPreviousProgress = -1;
bool bRunning = true;
pContext->bError = false;
pContext->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
nFileSize = ::GetFileSize64(hFile);
if (nFileSize == 0)
{
pContext->bError = true;
pContext->bFinished = true;
::CloseHandle(hFile);
return false;
}
// read/write loop
do
{
// read data from source file
bRes = ::ReadFile(hFile, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// NOTE: Sleep(0) solves problem writing to pipe errors
::Sleep(0);
// write data to write pipe
bRes = ::WriteFile(pContext->hPipe, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesRead += dwReadBytes;
nProgress = (int)((nTotalBytesRead * 100) / nFileSize);
if (nProgress != nPreviousProgress)
{
bRunning = pContext->pWorkerContext->Callback(pContext->nIndex, nProgress, false);
nPreviousProgress = nProgress;
}
if (bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
// close write pipe to allow write thread terminate reading
::CloseHandle(pContext->hPipe);
// check if all data was processed
if (nTotalBytesRead != nFileSize)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
pContext->bError = false;
pContext->bFinished = true;
return true;
}
bool WriteLoop(CPipeContext* pContext)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BYTE pReadBuff[4096];
BOOL bRes = FALSE;
DWORD dwReadBytes = 0;
DWORD dwWriteBytes = 0;
ULONGLONG nTotalBytesWrite = 0;
ULONGLONG nFileSize = 0;
int nProgress = -1;
pContext->bError = false;
pContext->bFinished = false;
// open existing source file with read-only flag
hFile = ::CreateFile(pContext->szFileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
pContext->bError = true;
pContext->bFinished = true;
return false;
}
// read/write loop
do
{
// read data from source pipe
bRes = ::ReadFile(pContext->hPipe, pReadBuff, 4096, &dwReadBytes, 0);
if ((bRes == FALSE) || (dwReadBytes == 0))
break;
// write data to file
bRes = ::WriteFile(hFile, pReadBuff, dwReadBytes, &dwWriteBytes, 0);
if ((bRes == FALSE) || (dwWriteBytes == 0) || (dwReadBytes != dwWriteBytes))
break;
// count read/write bytes
nTotalBytesWrite += dwReadBytes;
// handle user Stop
if (pContext->pWorkerContext->bRunning == false)
break;
} while (bRes != FALSE);
// clean up memory
::CloseHandle(hFile);
pContext->bError = false;
pContext->bFinished = true;
return true;
}
DWORD WINAPI ReadThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (ReadLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WriteThread(LPVOID lpParam)
{
CPipeContext* pContext = (CPipeContext*)lpParam;
if (pContext != NULL)
{
if (WriteLoop(pContext) == true)
return TRUE;
}
return FALSE;
}
bool ConvertFileUsingPipes(CFileContext* pContext)
{
if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == false))
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: invalid format pipe configuration."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
CProcessContext processContext;
CPipeContext readContext;
CPipeContext writeContext;
DWORD dwReadThreadID = 0L;
DWORD dwWriteThreadID = 0L;
HANDLE hReadThread = NULL;
HANDLE hWriteThread = NULL;
bool bWriteThreadResult = false;
int nProgress = 0;
CTimeCount timer;
if (pContext->bUseReadPipes == true)
{
// create pipes for stdin
if (processContext.CreateStdinPipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create pipes for stdin."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdin write pipe inherit flag
if (processContext.InheritStdinWritePipe() == false)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not set stdin pipe inherit flag."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
if (pContext->bUseWritePipes == true)
{
// create pipes for stdout
if (processContext.CreateStdoutPipe() == false)
{
if (pContext->bUseReadPipes == true)
{
processContext.CloseStdinReadPipe();
processContext.CloseStdinWritePipe();
}
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create pipes for stdout."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// set stdout read pipe inherit flag
if (processContext.InheritStdoutReadPipe() == false)
{
if (pContext->bUseReadPipes == true)
{
processContext.CloseStdinReadPipe();
processContext.CloseStdinWritePipe();
}
processContext.CloseStdoutReadPipe();
processContext.CloseStdoutWritePipe();
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not set stdout pipe inherit flag."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
}
// connect pipes to process
if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == false))
{
processContext.ConnectStdInput(processContext.hReadPipeStdin);
processContext.ConnectStdOutput(NULL);
processContext.ConnectStdError(NULL);
}
else if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(NULL);
processContext.ConnectStdOutput(processContext.hWritePipeStdout);
processContext.ConnectStdError(NULL);
}
else if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == true))
{
processContext.ConnectStdInput(processContext.hReadPipeStdin);
processContext.ConnectStdOutput(processContext.hWritePipeStdout);
processContext.ConnectStdError(NULL);
}
timer.Start();
if (processContext.Start(pContext->szCommandLine) == false)
{
timer.Stop();
if (pContext->bUseReadPipes == true)
{
processContext.CloseStdinReadPipe();
processContext.CloseStdinWritePipe();
}
if (pContext->bUseWritePipes == true)
{
processContext.CloseStdoutReadPipe();
processContext.CloseStdoutWritePipe();
}
CString szStatus;
szStatus.Format(_T("Error: can not create command-line process (%d)."), ::GetLastError());
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), szStatus);
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// close unused pipe handles
if (pContext->bUseReadPipes == true)
processContext.CloseStdinReadPipe();
if (pContext->bUseWritePipes == true)
processContext.CloseStdoutWritePipe();
// create read thread
if (pContext->bUseReadPipes == true)
{
readContext.bError = false;
readContext.bFinished = false;
readContext.pWorkerContext = pContext->pWorkerContext;
readContext.szFileName = pContext->szInputFile;
readContext.hPipe = processContext.hWritePipeStdin;
readContext.nIndex = pContext->nItemId;
dwReadThreadID = 0L;
hReadThread = ::CreateThread(NULL, 0, ReadThread, (LPVOID)&readContext, 0, &dwReadThreadID);
if (hReadThread == NULL)
{
timer.Stop();
processContext.CloseStdinWritePipe();
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create read thread."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// wait for read thread to finish
if (pContext->bUseWritePipes == false)
{
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//processContext.CloseStdinWritePipe();
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
}
// create write thread
if (pContext->bUseWritePipes == true)
{
writeContext.bError = false;
writeContext.bFinished = false;
writeContext.pWorkerContext = pContext->pWorkerContext;
writeContext.szFileName = pContext->szOutputFile;
writeContext.hPipe = processContext.hReadPipeStdout;
writeContext.nIndex = pContext->nItemId;
dwWriteThreadID = 0L;
hWriteThread = ::CreateThread(NULL, 0, WriteThread, (LPVOID)&writeContext, 0, &dwWriteThreadID);
if (hWriteThread == NULL)
{
timer.Stop();
processContext.CloseStdoutReadPipe();
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: can not create write thread."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
// wait for write thread to finish
::WaitForSingleObject(hWriteThread, INFINITE);
processContext.CloseStdoutReadPipe();
// check for result from read thread
if ((writeContext.bError == false) && (writeContext.bFinished == true))
{
bWriteThreadResult = true;
if (pContext->bUseReadPipes == false)
nProgress = 100;
}
else
{
bWriteThreadResult = false;
if (pContext->bUseReadPipes == false)
nProgress = -1;
}
// close read thread handle
::CloseHandle(hWriteThread);
}
// wait for read thread to finish after write thread finished
if ((pContext->bUseReadPipes == true) && (pContext->bUseWritePipes == true))
{
::WaitForSingleObject(hReadThread, INFINITE);
// NOTE: Handle is closed in ReadThread.
//processContext.CloseStdinWritePipe();
// check for result from read thread
if ((readContext.bError == false) && (readContext.bFinished == true) && (bWriteThreadResult == true))
nProgress = 100;
else
nProgress = -1;
// close read thread handle
::CloseHandle(hReadThread);
}
timer.Stop();
processContext.Stop(nProgress == 100);
if (nProgress != 100)
{
pContext->pWorkerContext->Status(pContext->nItemId, _T("--:--"), _T("Error: progress did not reach 100%."));
pContext->pWorkerContext->Callback(pContext->nItemId, -1, true, true);
return false;
}
else
{
pContext->pWorkerContext->Status(pContext->nItemId, timer.Format(timer.ElapsedTime(), 1), _T("Done"));
pContext->pWorkerContext->Callback(pContext->nItemId, 100, true, false);
return true;
}
}
bool ConvertFile(CFileContext* pContext)
{
if ((pContext->bUseReadPipes == false) && (pContext->bUseWritePipes == false))
return ConvertFileUsingConsole(pContext);
else
return ConvertFileUsingPipes(pContext);
}
enum Mode { None = -1, Encode = 0, Transcode = 1 };
bool FileExists(CString szPath)
{
WIN32_FIND_DATA w32FileData;
ZeroMemory(&w32FileData, sizeof(WIN32_FIND_DATA));
HANDLE hFind = ::FindFirstFile(szPath, &w32FileData);
bool bInvalidHandle = hFind == INVALID_HANDLE_VALUE;
::FindClose(hFind);
return bInvalidHandle == false;
}
bool ConvertItem(CItemContext* pContext)
{
// input file
CString szInputFile = pContext->item->szPath;
// validate input file
if (FileExists(szInputFile) == false)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find input file."));
return false;
}
// output path
CString szOutPath;
if (pContext->pWorkerContext->pConfig->m_Options.bOutputPathChecked == true)
{
szOutPath = pContext->pWorkerContext->pConfig->m_Options.szOutputPath;
}
else
{
CString szInputFileName = ::GetFileName(szInputFile);
szOutPath = szInputFile;
szOutPath.Truncate(szOutPath.GetLength() - szInputFileName.GetLength());
}
// find encoder
int nEncoder = pContext->pWorkerContext->pConfig->m_Formats.GetFormatById(pContext->item->szFormatId);
if (nEncoder == -1)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid encoder by id."));
return false;
}
CFormat& encoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nEncoder);
// validate encoder preset
if (pContext->item->nPreset >= encoderFormat.m_Presets.GetSize())
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoder format preset."));
return false;
}
// validate input extension
CString szInputFileExt = ::GetFileExtension(szInputFile).MakeUpper();
bool bIsValidEncoderInput = encoderFormat.IsValidInputExtension(szInputFileExt);
// processing mode
Mode nProcessingMode = Mode::None;
if (bIsValidEncoderInput)
nProcessingMode = Mode::Encode;
else
nProcessingMode = Mode::Transcode;
// output path
CString szEncoderExtension = encoderFormat.szOutputExtension;
CString szName = pContext->item->szName + _T(".") + szEncoderExtension.MakeLower();
CString szOutputFile;
if (szOutPath.GetLength() >= 1)
{
if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/')
szOutputFile = szOutPath + szName;
else
szOutputFile = szOutPath + _T("\\") + szName;
}
else
{
szOutputFile = szName;
}
CString szOrgInputFile = szInputFile;
CString szOrgOutputFile = szOutputFile;
if (nProcessingMode == Mode::Transcode)
{
// find decoder
int nDecoder = pContext->pWorkerContext->pConfig->m_Formats.GetDecoderByExtension(pContext->item->szExtension);
if (nDecoder == -1)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid decoder by extension."));
return false;
}
CFormat& decoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nDecoder);
// validate decoder preset
if (decoderFormat.nDefaultPreset >= decoderFormat.m_Presets.GetSize())
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoder format preset."));
return false;
}
// validate decoder output extension
bIsValidEncoderInput = encoderFormat.IsValidInputExtension(decoderFormat.szOutputExtension);
if (bIsValidEncoderInput == false)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: decoder output not supported by encoder."));
return false;
}
CString szDecoderExtension = decoderFormat.szOutputExtension;
szOutputFile = szOutputFile + +_T(".") + szDecoderExtension.MakeLower();
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Decoding..."));
try
{
CFileContext context(pContext->pWorkerContext, decoderFormat, decoderFormat.nDefaultPreset, pContext->item->nId, szInputFile, szOutputFile);
if (::ConvertFile(&context) == false)
{
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
return false;
}
// validate decoded file
if (FileExists(szOutputFile) == false)
{
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoded file."));
return false;
}
}
catch (...)
{
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file."));
pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
if (pContext->pWorkerContext->bRunning == false)
return false;
if (nProcessingMode == Mode::Transcode)
{
// decoder output file as encoder input file
szInputFile = szOutputFile;
// original encoder output file
szOutputFile = szOrgOutputFile;
}
if ((nProcessingMode == Mode::Encode) || (nProcessingMode == Mode::Transcode))
{
if (encoderFormat.nType == 0)
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Encoding..."));
else if (encoderFormat.nType == 1)
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Decoding..."));
else
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Processing..."));
try
{
CFileContext context(pContext->pWorkerContext, encoderFormat, pContext->item->nPreset, pContext->item->nId, szInputFile, szOutputFile);
if (::ConvertFile(&context) == true)
{
// validate encoded file
if (FileExists(szOutputFile) == false)
{
if (nProcessingMode == Mode::Transcode)
{
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szInputFile);
}
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoded file."));
return false;
}
if (nProcessingMode == Mode::Transcode)
::DeleteFile(szInputFile);
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true)
::DeleteFile(szOrgInputFile);
return true;
}
else
{
if (nProcessingMode == Mode::Transcode)
::DeleteFile(szInputFile);
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
return false;
}
}
catch (...)
{
if (nProcessingMode == Mode::Transcode)
::DeleteFile(szInputFile);
if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true)
::DeleteFile(szOutputFile);
pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file."));
pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true);
}
}
return false;
}
bool ConvertLoop(CWorkerContext* pWorkerContext)
{
while (!pWorkerContext->pQueue->IsEmpty())
{
try
{
CItemContext* pContext = NULL;
DWORD dwWaitResult = ::WaitForSingleObject(pWorkerContext->hMutex, INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
{
pContext = (CItemContext*)pWorkerContext->pQueue->RemoveHead();
if (!::ReleaseMutex(pWorkerContext->hMutex))
return false;
}
break;
case WAIT_ABANDONED:
return false;
}
if (pContext != NULL)
{
pContext->pWorkerContext->Next(pContext->item->nId);
if (ConvertItem(pContext) == true)
{
pContext->pWorkerContext->nDoneWithoutError++;
}
else
{
if (pContext->pWorkerContext->pConfig->m_Options.bStopOnErrors == true)
return false;
}
if (pContext->pWorkerContext->bRunning == false)
return false;
}
}
catch (...)
{
return false;
}
}
return true;
}
DWORD WINAPI ConvertThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext != NULL)
{
if (ConvertLoop(pWorkerContext) == true)
return TRUE;
}
return FALSE;
}
DWORD WINAPI WorkThread(LPVOID lpParam)
{
CWorkerContext* pWorkerContext = (CWorkerContext*)lpParam;
if (pWorkerContext == NULL)
return (DWORD)(-1);
int nItems = pWorkerContext->pConfig->m_Items.GetSize();
CItemContext *pItemsContext = new CItemContext[nItems];
pWorkerContext->nThreadCount = pWorkerContext->pConfig->m_Options.nThreadCount;
if (pWorkerContext->nThreadCount < 1)
{
// auto-detect number of available threads
LogicalProcessorInformation info;
if (GetLogicalProcessorInformation(&info) == 0)
pWorkerContext->nThreadCount = info.processorCoreCount;
else
pWorkerContext->nThreadCount = 1;
}
pWorkerContext->hMutex = ::CreateMutex(NULL, FALSE, NULL);
pWorkerContext->nTotalFiles = 0;
pWorkerContext->nProcessedFiles = 0;
pWorkerContext->nDoneWithoutError = 0;
pWorkerContext->nErrors = 0;
pWorkerContext->hConvertThread = new HANDLE[pWorkerContext->nThreadCount];
pWorkerContext->dwConvertThreadID = new DWORD[pWorkerContext->nThreadCount];
pWorkerContext->pQueue = new CObList();
pWorkerContext->nProgess = new int[nItems];
pWorkerContext->nPreviousProgess = new int[nItems];
pWorkerContext->nLastItemId = -1;
for (int i = 0; i < nItems; i++)
{
CItem& item = pWorkerContext->pConfig->m_Items.GetData(i);
if (item.bChecked == true)
{
pWorkerContext->nTotalFiles++;
pWorkerContext->nProgess[i] = 0;
pWorkerContext->nPreviousProgess[i] = 0;
pItemsContext[i].pWorkerContext = pWorkerContext;
pItemsContext[i].item = &item;
pWorkerContext->pQueue->AddTail(&pItemsContext[i]);
}
else
{
pWorkerContext->nProgess[i] = 100;
pWorkerContext->nPreviousProgess[i] = 100;
}
}
pWorkerContext->Init();
// single-threaded
if (pWorkerContext->nThreadCount == 1)
{
ConvertLoop(pWorkerContext);
}
// multi-threaded
if (pWorkerContext->nThreadCount > 1)
{
// create worker threads
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
{
pWorkerContext->dwConvertThreadID[i] = i;
pWorkerContext->hConvertThread[i] = ::CreateThread(NULL, 0, ConvertThread, pWorkerContext, CREATE_SUSPENDED, &pWorkerContext->dwConvertThreadID[i]);
if (pWorkerContext->hConvertThread[i] == NULL)
break;
::ResumeThread(pWorkerContext->hConvertThread[i]);
}
// wait for all workers to finish
::WaitForMultipleObjects(pWorkerContext->nThreadCount, pWorkerContext->hConvertThread, TRUE, INFINITE);
// close convert thread handles
for (int i = 0; i < pWorkerContext->nThreadCount; i++)
::CloseHandle(pWorkerContext->hConvertThread[i]);
}
delete pWorkerContext->hConvertThread;
delete pWorkerContext->dwConvertThreadID;
delete pWorkerContext->pQueue;
delete pWorkerContext->nProgess;
delete pWorkerContext->nPreviousProgess;
delete[] pItemsContext;
::CloseHandle(pWorkerContext->hMutex);
pWorkerContext->Done();
pWorkerContext->bDone = true;
return ::CloseHandle(pWorkerContext->hThread);
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basicmigration.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:40:29 $
*
* 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 _DESKTOP_BASICMIGRATION_HXX_
#include "basicmigration.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UTL_BOOTSTRAP_HXX
#include <unotools/bootstrap.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
//.........................................................................
namespace migration
{
//.........................................................................
static ::rtl::OUString sSourceUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/basic" ) );
static ::rtl::OUString sTargetUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/__basic_70" ) );
// =============================================================================
// component operations
// =============================================================================
::rtl::OUString BasicMigration_getImplementationName()
{
static ::rtl::OUString* pImplName = 0;
if ( !pImplName )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pImplName )
{
static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Basic" ) );
pImplName = &aImplName;
}
}
return *pImplName;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration_getSupportedServiceNames()
{
static Sequence< ::rtl::OUString >* pNames = 0;
if ( !pNames )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pNames )
{
static Sequence< ::rtl::OUString > aNames(1);
aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Basic" ) );
pNames = &aNames;
}
}
return *pNames;
}
// =============================================================================
// BasicMigration
// =============================================================================
BasicMigration::BasicMigration()
{
}
// -----------------------------------------------------------------------------
BasicMigration::~BasicMigration()
{
}
// -----------------------------------------------------------------------------
TStringVectorPtr BasicMigration::getFiles( const ::rtl::OUString& rBaseURL ) const
{
TStringVectorPtr aResult( new TStringVector );
::osl::Directory aDir( rBaseURL);
if ( aDir.open() == ::osl::FileBase::E_None )
{
// iterate over directory content
TStringVector aSubDirs;
::osl::DirectoryItem aItem;
while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None )
{
::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL );
if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None )
{
if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory )
aSubDirs.push_back( aFileStatus.getFileURL() );
else
aResult->push_back( aFileStatus.getFileURL() );
}
}
// iterate recursive over subfolders
TStringVector::const_iterator aI = aSubDirs.begin();
while ( aI != aSubDirs.end() )
{
TStringVectorPtr aSubResult = getFiles( *aI );
aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() );
++aI;
}
}
return aResult;
}
// -----------------------------------------------------------------------------
::osl::FileBase::RC BasicMigration::checkAndCreateDirectory( INetURLObject& rDirURL )
{
::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
if ( aResult == ::osl::FileBase::E_NOENT )
{
INetURLObject aBaseURL( rDirURL );
aBaseURL.removeSegment();
checkAndCreateDirectory( aBaseURL );
return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
}
else
{
return aResult;
}
}
// -----------------------------------------------------------------------------
void BasicMigration::copyFiles()
{
::rtl::OUString sTargetDir;
::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir );
if ( aStatus == ::utl::Bootstrap::PATH_EXISTS )
{
sTargetDir += sTargetUserBasic;
TStringVectorPtr aFileList = getFiles( m_sSourceDir );
TStringVector::const_iterator aI = aFileList->begin();
while ( aI != aFileList->end() )
{
::rtl::OUString sLocalName = aI->copy( m_sSourceDir.getLength() );
::rtl::OUString sTargetName = sTargetDir + sLocalName;
INetURLObject aURL( sTargetName );
aURL.removeSegment();
checkAndCreateDirectory( aURL );
::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName );
if ( aResult != ::osl::FileBase::E_None )
{
::rtl::OString aMsg( "BasicMigration::copyFiles: cannot copy " );
aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to "
+ ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 );
OSL_ENSURE( sal_False, aMsg.getStr() );
}
++aI;
}
}
else
{
OSL_ENSURE( sal_False, "BasicMigration::copyFiles: no user installation!" );
}
}
// -----------------------------------------------------------------------------
// XServiceInfo
// -----------------------------------------------------------------------------
::rtl::OUString BasicMigration::getImplementationName() throw (RuntimeException)
{
return BasicMigration_getImplementationName();
}
// -----------------------------------------------------------------------------
sal_Bool BasicMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
const ::rtl::OUString* pNames = aNames.getConstArray();
const ::rtl::OUString* pEnd = pNames + aNames.getLength();
for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
;
return pNames != pEnd;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration::getSupportedServiceNames() throw (RuntimeException)
{
return BasicMigration_getSupportedServiceNames();
}
// -----------------------------------------------------------------------------
// XInitialization
// -----------------------------------------------------------------------------
void BasicMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
const Any* pIter = aArguments.getConstArray();
const Any* pEnd = pIter + aArguments.getLength();
for ( ; pIter != pEnd ; ++pIter )
{
beans::NamedValue aValue;
*pIter >>= aValue;
if ( aValue.Name.equalsAscii( "UserData" ) )
{
sal_Bool bSuccess = aValue.Value >>= m_sSourceDir;
OSL_ENSURE( bSuccess == sal_True, "BasicMigration::initialize: argument UserData has wrong type!" );
m_sSourceDir += sSourceUserBasic;
break;
}
}
}
// -----------------------------------------------------------------------------
// XJob
// -----------------------------------------------------------------------------
Any BasicMigration::execute( const Sequence< beans::NamedValue >& Arguments )
throw (lang::IllegalArgumentException, Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
copyFiles();
return Any();
}
// =============================================================================
// component operations
// =============================================================================
Reference< XInterface > SAL_CALL BasicMigration_create(
Reference< XComponentContext > const & xContext )
SAL_THROW( () )
{
return static_cast< lang::XTypeProvider * >( new BasicMigration() );
}
// -----------------------------------------------------------------------------
//.........................................................................
} // namespace migration
//.........................................................................
INTEGRATION: CWS pchfix02 (1.4.222); FILE MERGED
2006/09/01 17:25:16 kaib 1.4.222.1: #i68856# Added header markers and pch files
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basicmigration.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 09:46:25 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#ifndef _DESKTOP_BASICMIGRATION_HXX_
#include "basicmigration.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UTL_BOOTSTRAP_HXX
#include <unotools/bootstrap.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
//.........................................................................
namespace migration
{
//.........................................................................
static ::rtl::OUString sSourceUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/basic" ) );
static ::rtl::OUString sTargetUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/__basic_70" ) );
// =============================================================================
// component operations
// =============================================================================
::rtl::OUString BasicMigration_getImplementationName()
{
static ::rtl::OUString* pImplName = 0;
if ( !pImplName )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pImplName )
{
static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Basic" ) );
pImplName = &aImplName;
}
}
return *pImplName;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration_getSupportedServiceNames()
{
static Sequence< ::rtl::OUString >* pNames = 0;
if ( !pNames )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pNames )
{
static Sequence< ::rtl::OUString > aNames(1);
aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Basic" ) );
pNames = &aNames;
}
}
return *pNames;
}
// =============================================================================
// BasicMigration
// =============================================================================
BasicMigration::BasicMigration()
{
}
// -----------------------------------------------------------------------------
BasicMigration::~BasicMigration()
{
}
// -----------------------------------------------------------------------------
TStringVectorPtr BasicMigration::getFiles( const ::rtl::OUString& rBaseURL ) const
{
TStringVectorPtr aResult( new TStringVector );
::osl::Directory aDir( rBaseURL);
if ( aDir.open() == ::osl::FileBase::E_None )
{
// iterate over directory content
TStringVector aSubDirs;
::osl::DirectoryItem aItem;
while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None )
{
::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL );
if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None )
{
if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory )
aSubDirs.push_back( aFileStatus.getFileURL() );
else
aResult->push_back( aFileStatus.getFileURL() );
}
}
// iterate recursive over subfolders
TStringVector::const_iterator aI = aSubDirs.begin();
while ( aI != aSubDirs.end() )
{
TStringVectorPtr aSubResult = getFiles( *aI );
aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() );
++aI;
}
}
return aResult;
}
// -----------------------------------------------------------------------------
::osl::FileBase::RC BasicMigration::checkAndCreateDirectory( INetURLObject& rDirURL )
{
::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
if ( aResult == ::osl::FileBase::E_NOENT )
{
INetURLObject aBaseURL( rDirURL );
aBaseURL.removeSegment();
checkAndCreateDirectory( aBaseURL );
return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
}
else
{
return aResult;
}
}
// -----------------------------------------------------------------------------
void BasicMigration::copyFiles()
{
::rtl::OUString sTargetDir;
::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir );
if ( aStatus == ::utl::Bootstrap::PATH_EXISTS )
{
sTargetDir += sTargetUserBasic;
TStringVectorPtr aFileList = getFiles( m_sSourceDir );
TStringVector::const_iterator aI = aFileList->begin();
while ( aI != aFileList->end() )
{
::rtl::OUString sLocalName = aI->copy( m_sSourceDir.getLength() );
::rtl::OUString sTargetName = sTargetDir + sLocalName;
INetURLObject aURL( sTargetName );
aURL.removeSegment();
checkAndCreateDirectory( aURL );
::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName );
if ( aResult != ::osl::FileBase::E_None )
{
::rtl::OString aMsg( "BasicMigration::copyFiles: cannot copy " );
aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to "
+ ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 );
OSL_ENSURE( sal_False, aMsg.getStr() );
}
++aI;
}
}
else
{
OSL_ENSURE( sal_False, "BasicMigration::copyFiles: no user installation!" );
}
}
// -----------------------------------------------------------------------------
// XServiceInfo
// -----------------------------------------------------------------------------
::rtl::OUString BasicMigration::getImplementationName() throw (RuntimeException)
{
return BasicMigration_getImplementationName();
}
// -----------------------------------------------------------------------------
sal_Bool BasicMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
const ::rtl::OUString* pNames = aNames.getConstArray();
const ::rtl::OUString* pEnd = pNames + aNames.getLength();
for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
;
return pNames != pEnd;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration::getSupportedServiceNames() throw (RuntimeException)
{
return BasicMigration_getSupportedServiceNames();
}
// -----------------------------------------------------------------------------
// XInitialization
// -----------------------------------------------------------------------------
void BasicMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
const Any* pIter = aArguments.getConstArray();
const Any* pEnd = pIter + aArguments.getLength();
for ( ; pIter != pEnd ; ++pIter )
{
beans::NamedValue aValue;
*pIter >>= aValue;
if ( aValue.Name.equalsAscii( "UserData" ) )
{
sal_Bool bSuccess = aValue.Value >>= m_sSourceDir;
OSL_ENSURE( bSuccess == sal_True, "BasicMigration::initialize: argument UserData has wrong type!" );
m_sSourceDir += sSourceUserBasic;
break;
}
}
}
// -----------------------------------------------------------------------------
// XJob
// -----------------------------------------------------------------------------
Any BasicMigration::execute( const Sequence< beans::NamedValue >& Arguments )
throw (lang::IllegalArgumentException, Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
copyFiles();
return Any();
}
// =============================================================================
// component operations
// =============================================================================
Reference< XInterface > SAL_CALL BasicMigration_create(
Reference< XComponentContext > const & xContext )
SAL_THROW( () )
{
return static_cast< lang::XTypeProvider * >( new BasicMigration() );
}
// -----------------------------------------------------------------------------
//.........................................................................
} // namespace migration
//.........................................................................
|
// Copyright 2011 the V8 project authors. 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 Google Inc. 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 COPYRIGHT
// OWNER OR CONTRIBUTORS 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 "v8.h"
#if defined(V8_TARGET_ARCH_X64)
#include "ic-inl.h"
#include "codegen.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
static void ProbeTable(Isolate* isolate,
MacroAssembler* masm,
Code::Flags flags,
StubCache::Table table,
Register name,
Register offset) {
ASSERT_EQ(8, kPointerSize);
ASSERT_EQ(16, sizeof(StubCache::Entry));
// The offset register holds the entry offset times four (due to masking
// and shifting optimizations).
ExternalReference key_offset(isolate->stub_cache()->key_reference(table));
Label miss;
__ LoadAddress(kScratchRegister, key_offset);
// Check that the key in the entry matches the name.
// Multiply entry offset by 16 to get the entry address. Since the
// offset register already holds the entry offset times four, multiply
// by a further four.
__ cmpl(name, Operand(kScratchRegister, offset, times_4, 0));
__ j(not_equal, &miss);
// Get the code entry from the cache.
// Use key_offset + kPointerSize, rather than loading value_offset.
__ movq(kScratchRegister,
Operand(kScratchRegister, offset, times_4, kPointerSize));
// Check that the flags match what we're looking for.
__ movl(offset, FieldOperand(kScratchRegister, Code::kFlagsOffset));
__ and_(offset, Immediate(~Code::kFlagsNotUsedInLookup));
__ cmpl(offset, Immediate(flags));
__ j(not_equal, &miss);
// Jump to the first instruction in the code stub.
__ addq(kScratchRegister, Immediate(Code::kHeaderSize - kHeapObjectTag));
__ jmp(kScratchRegister);
__ bind(&miss);
}
// Helper function used to check that the dictionary doesn't contain
// the property. This function may return false negatives, so miss_label
// must always call a backup property check that is complete.
// This function is safe to call if the receiver has fast properties.
// Name must be a symbol and receiver must be a heap object.
MUST_USE_RESULT static MaybeObject* GenerateDictionaryNegativeLookup(
MacroAssembler* masm,
Label* miss_label,
Register receiver,
String* name,
Register r0,
Register r1) {
ASSERT(name->IsSymbol());
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->negative_lookups(), 1);
__ IncrementCounter(counters->negative_lookups_miss(), 1);
__ movq(r0, FieldOperand(receiver, HeapObject::kMapOffset));
const int kInterceptorOrAccessCheckNeededMask =
(1 << Map::kHasNamedInterceptor) | (1 << Map::kIsAccessCheckNeeded);
// Bail out if the receiver has a named interceptor or requires access checks.
__ testb(FieldOperand(r0, Map::kBitFieldOffset),
Immediate(kInterceptorOrAccessCheckNeededMask));
__ j(not_zero, miss_label);
// Check that receiver is a JSObject.
__ CmpInstanceType(r0, FIRST_SPEC_OBJECT_TYPE);
__ j(below, miss_label);
// Load properties array.
Register properties = r0;
__ movq(properties, FieldOperand(receiver, JSObject::kPropertiesOffset));
// Check that the properties array is a dictionary.
__ CompareRoot(FieldOperand(properties, HeapObject::kMapOffset),
Heap::kHashTableMapRootIndex);
__ j(not_equal, miss_label);
Label done;
MaybeObject* result = StringDictionaryLookupStub::GenerateNegativeLookup(
masm,
miss_label,
&done,
properties,
name,
r1);
if (result->IsFailure()) return result;
__ bind(&done);
__ DecrementCounter(counters->negative_lookups_miss(), 1);
return result;
}
void StubCache::GenerateProbe(MacroAssembler* masm,
Code::Flags flags,
Register receiver,
Register name,
Register scratch,
Register extra,
Register extra2) {
Isolate* isolate = masm->isolate();
Label miss;
USE(extra); // The register extra is not used on the X64 platform.
USE(extra2); // The register extra2 is not used on the X64 platform.
// Make sure that code is valid. The shifting code relies on the
// entry size being 16.
ASSERT(sizeof(Entry) == 16);
// Make sure the flags do not name a specific type.
ASSERT(Code::ExtractTypeFromFlags(flags) == 0);
// Make sure that there are no register conflicts.
ASSERT(!scratch.is(receiver));
ASSERT(!scratch.is(name));
// Check scratch register is valid, extra and extra2 are unused.
ASSERT(!scratch.is(no_reg));
ASSERT(extra2.is(no_reg));
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, &miss);
// Get the map of the receiver and compute the hash.
__ movl(scratch, FieldOperand(name, String::kHashFieldOffset));
// Use only the low 32 bits of the map pointer.
__ addl(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
__ xor_(scratch, Immediate(flags));
__ and_(scratch, Immediate((kPrimaryTableSize - 1) << kHeapObjectTagSize));
// Probe the primary table.
ProbeTable(isolate, masm, flags, kPrimary, name, scratch);
// Primary miss: Compute hash for secondary probe.
__ movl(scratch, FieldOperand(name, String::kHashFieldOffset));
__ addl(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
__ xor_(scratch, Immediate(flags));
__ and_(scratch, Immediate((kPrimaryTableSize - 1) << kHeapObjectTagSize));
__ subl(scratch, name);
__ addl(scratch, Immediate(flags));
__ and_(scratch, Immediate((kSecondaryTableSize - 1) << kHeapObjectTagSize));
// Probe the secondary table.
ProbeTable(isolate, masm, flags, kSecondary, name, scratch);
// Cache miss: Fall-through and let caller handle the miss by
// entering the runtime system.
__ bind(&miss);
}
void StubCompiler::GenerateLoadGlobalFunctionPrototype(MacroAssembler* masm,
int index,
Register prototype) {
// Load the global or builtins object from the current context.
__ movq(prototype,
Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)));
// Load the global context from the global or builtins object.
__ movq(prototype,
FieldOperand(prototype, GlobalObject::kGlobalContextOffset));
// Load the function from the global context.
__ movq(prototype, Operand(prototype, Context::SlotOffset(index)));
// Load the initial map. The global functions all have initial maps.
__ movq(prototype,
FieldOperand(prototype, JSFunction::kPrototypeOrInitialMapOffset));
// Load the prototype from the initial map.
__ movq(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}
void StubCompiler::GenerateDirectLoadGlobalFunctionPrototype(
MacroAssembler* masm, int index, Register prototype, Label* miss) {
Isolate* isolate = masm->isolate();
// Check we're still in the same context.
__ Move(prototype, isolate->global());
__ cmpq(Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)),
prototype);
__ j(not_equal, miss);
// Get the global function with the given index.
JSFunction* function =
JSFunction::cast(isolate->global_context()->get(index));
// Load its initial map. The global functions all have initial maps.
__ Move(prototype, Handle<Map>(function->initial_map()));
// Load the prototype from the initial map.
__ movq(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}
void StubCompiler::GenerateLoadArrayLength(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* miss_label) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss_label);
// Check that the object is a JS array.
__ CmpObjectType(receiver, JS_ARRAY_TYPE, scratch);
__ j(not_equal, miss_label);
// Load length directly from the JS array.
__ movq(rax, FieldOperand(receiver, JSArray::kLengthOffset));
__ ret(0);
}
// Generate code to check if an object is a string. If the object is
// a string, the map's instance type is left in the scratch register.
static void GenerateStringCheck(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* smi,
Label* non_string_object) {
// Check that the object isn't a smi.
__ JumpIfSmi(receiver, smi);
// Check that the object is a string.
__ movq(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
__ movzxbq(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
STATIC_ASSERT(kNotStringTag != 0);
__ testl(scratch, Immediate(kNotStringTag));
__ j(not_zero, non_string_object);
}
void StubCompiler::GenerateLoadStringLength(MacroAssembler* masm,
Register receiver,
Register scratch1,
Register scratch2,
Label* miss,
bool support_wrappers) {
Label check_wrapper;
// Check if the object is a string leaving the instance type in the
// scratch register.
GenerateStringCheck(masm, receiver, scratch1, miss,
support_wrappers ? &check_wrapper : miss);
// Load length directly from the string.
__ movq(rax, FieldOperand(receiver, String::kLengthOffset));
__ ret(0);
if (support_wrappers) {
// Check if the object is a JSValue wrapper.
__ bind(&check_wrapper);
__ cmpl(scratch1, Immediate(JS_VALUE_TYPE));
__ j(not_equal, miss);
// Check if the wrapped value is a string and load the length
// directly if it is.
__ movq(scratch2, FieldOperand(receiver, JSValue::kValueOffset));
GenerateStringCheck(masm, scratch2, scratch1, miss, miss);
__ movq(rax, FieldOperand(scratch2, String::kLengthOffset));
__ ret(0);
}
}
void StubCompiler::GenerateLoadFunctionPrototype(MacroAssembler* masm,
Register receiver,
Register result,
Register scratch,
Label* miss_label) {
__ TryGetFunctionPrototype(receiver, result, miss_label);
if (!result.is(rax)) __ movq(rax, result);
__ ret(0);
}
// Load a fast property out of a holder object (src). In-object properties
// are loaded directly otherwise the property is loaded from the properties
// fixed array.
void StubCompiler::GenerateFastPropertyLoad(MacroAssembler* masm,
Register dst, Register src,
JSObject* holder, int index) {
// Adjust for the number of properties stored in the holder.
index -= holder->map()->inobject_properties();
if (index < 0) {
// Get the property straight out of the holder.
int offset = holder->map()->instance_size() + (index * kPointerSize);
__ movq(dst, FieldOperand(src, offset));
} else {
// Calculate the offset into the properties array.
int offset = index * kPointerSize + FixedArray::kHeaderSize;
__ movq(dst, FieldOperand(src, JSObject::kPropertiesOffset));
__ movq(dst, FieldOperand(dst, offset));
}
}
static void PushInterceptorArguments(MacroAssembler* masm,
Register receiver,
Register holder,
Register name,
JSObject* holder_obj) {
__ push(name);
InterceptorInfo* interceptor = holder_obj->GetNamedInterceptor();
ASSERT(!masm->isolate()->heap()->InNewSpace(interceptor));
__ Move(kScratchRegister, Handle<Object>(interceptor));
__ push(kScratchRegister);
__ push(receiver);
__ push(holder);
__ push(FieldOperand(kScratchRegister, InterceptorInfo::kDataOffset));
}
static void CompileCallLoadPropertyWithInterceptor(MacroAssembler* masm,
Register receiver,
Register holder,
Register name,
JSObject* holder_obj) {
PushInterceptorArguments(masm, receiver, holder, name, holder_obj);
ExternalReference ref =
ExternalReference(IC_Utility(IC::kLoadPropertyWithInterceptorOnly),
masm->isolate());
__ Set(rax, 5);
__ LoadAddress(rbx, ref);
CEntryStub stub(1);
__ CallStub(&stub);
}
// Number of pointers to be reserved on stack for fast API call.
static const int kFastApiCallArguments = 3;
// Reserves space for the extra arguments to API function in the
// caller's frame.
//
// These arguments are set by CheckPrototypes and GenerateFastApiCall.
static void ReserveSpaceForFastApiCall(MacroAssembler* masm, Register scratch) {
// ----------- S t a t e -------------
// -- rsp[0] : return address
// -- rsp[8] : last argument in the internal frame of the caller
// -----------------------------------
__ movq(scratch, Operand(rsp, 0));
__ subq(rsp, Immediate(kFastApiCallArguments * kPointerSize));
__ movq(Operand(rsp, 0), scratch);
__ Move(scratch, Smi::FromInt(0));
for (int i = 1; i <= kFastApiCallArguments; i++) {
__ movq(Operand(rsp, i * kPointerSize), scratch);
}
}
// Undoes the effects of ReserveSpaceForFastApiCall.
static void FreeSpaceForFastApiCall(MacroAssembler* masm, Register scratch) {
// ----------- S t a t e -------------
// -- rsp[0] : return address.
// -- rsp[8] : last fast api call extra argument.
// -- ...
// -- rsp[kFastApiCallArguments * 8] : first fast api call extra argument.
// -- rsp[kFastApiCallArguments * 8 + 8] : last argument in the internal
// frame.
// -----------------------------------
__ movq(scratch, Operand(rsp, 0));
__ movq(Operand(rsp, kFastApiCallArguments * kPointerSize), scratch);
__ addq(rsp, Immediate(kPointerSize * kFastApiCallArguments));
}
// Generates call to API function.
static MaybeObject* GenerateFastApiCall(MacroAssembler* masm,
const CallOptimization& optimization,
int argc) {
// ----------- S t a t e -------------
// -- rsp[0] : return address
// -- rsp[8] : object passing the type check
// (last fast api call extra argument,
// set by CheckPrototypes)
// -- rsp[16] : api function
// (first fast api call extra argument)
// -- rsp[24] : api call data
// -- rsp[32] : last argument
// -- ...
// -- rsp[(argc + 3) * 8] : first argument
// -- rsp[(argc + 4) * 8] : receiver
// -----------------------------------
// Get the function and setup the context.
JSFunction* function = optimization.constant_function();
__ Move(rdi, Handle<JSFunction>(function));
__ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// Pass the additional arguments.
__ movq(Operand(rsp, 2 * kPointerSize), rdi);
Object* call_data = optimization.api_call_info()->data();
Handle<CallHandlerInfo> api_call_info_handle(optimization.api_call_info());
if (masm->isolate()->heap()->InNewSpace(call_data)) {
__ Move(rcx, api_call_info_handle);
__ movq(rbx, FieldOperand(rcx, CallHandlerInfo::kDataOffset));
__ movq(Operand(rsp, 3 * kPointerSize), rbx);
} else {
__ Move(Operand(rsp, 3 * kPointerSize), Handle<Object>(call_data));
}
// Prepare arguments.
__ lea(rbx, Operand(rsp, 3 * kPointerSize));
Object* callback = optimization.api_call_info()->callback();
Address api_function_address = v8::ToCData<Address>(callback);
ApiFunction fun(api_function_address);
#ifdef _WIN64
// Win64 uses first register--rcx--for returned value.
Register arguments_arg = rdx;
#else
Register arguments_arg = rdi;
#endif
// Allocate the v8::Arguments structure in the arguments' space since
// it's not controlled by GC.
const int kApiStackSpace = 4;
__ PrepareCallApiFunction(kApiStackSpace);
__ movq(StackSpaceOperand(0), rbx); // v8::Arguments::implicit_args_.
__ addq(rbx, Immediate(argc * kPointerSize));
__ movq(StackSpaceOperand(1), rbx); // v8::Arguments::values_.
__ Set(StackSpaceOperand(2), argc); // v8::Arguments::length_.
// v8::Arguments::is_construct_call_.
__ Set(StackSpaceOperand(3), 0);
// v8::InvocationCallback's argument.
__ lea(arguments_arg, StackSpaceOperand(0));
// Emitting a stub call may try to allocate (if the code is not
// already generated). Do not allow the assembler to perform a
// garbage collection but instead return the allocation failure
// object.
return masm->TryCallApiFunctionAndReturn(&fun,
argc + kFastApiCallArguments + 1);
}
class CallInterceptorCompiler BASE_EMBEDDED {
public:
CallInterceptorCompiler(StubCompiler* stub_compiler,
const ParameterCount& arguments,
Register name,
Code::ExtraICState extra_ic_state)
: stub_compiler_(stub_compiler),
arguments_(arguments),
name_(name),
extra_ic_state_(extra_ic_state) {}
MaybeObject* Compile(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
String* name,
LookupResult* lookup,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
Label* miss) {
ASSERT(holder->HasNamedInterceptor());
ASSERT(!holder->GetNamedInterceptor()->getter()->IsUndefined());
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
CallOptimization optimization(lookup);
if (optimization.is_constant_call()) {
return CompileCacheable(masm,
object,
receiver,
scratch1,
scratch2,
scratch3,
holder,
lookup,
name,
optimization,
miss);
} else {
CompileRegular(masm,
object,
receiver,
scratch1,
scratch2,
scratch3,
name,
holder,
miss);
return masm->isolate()->heap()->undefined_value(); // Success.
}
}
private:
MaybeObject* CompileCacheable(MacroAssembler* masm,
JSObject* object,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
JSObject* interceptor_holder,
LookupResult* lookup,
String* name,
const CallOptimization& optimization,
Label* miss_label) {
ASSERT(optimization.is_constant_call());
ASSERT(!lookup->holder()->IsGlobalObject());
int depth1 = kInvalidProtoDepth;
int depth2 = kInvalidProtoDepth;
bool can_do_fast_api_call = false;
if (optimization.is_simple_api_call() &&
!lookup->holder()->IsGlobalObject()) {
depth1 =
optimization.GetPrototypeDepthOfExpectedType(object,
interceptor_holder);
if (depth1 == kInvalidProtoDepth) {
depth2 =
optimization.GetPrototypeDepthOfExpectedType(interceptor_holder,
lookup->holder());
}
can_do_fast_api_call = (depth1 != kInvalidProtoDepth) ||
(depth2 != kInvalidProtoDepth);
}
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->call_const_interceptor(), 1);
if (can_do_fast_api_call) {
__ IncrementCounter(counters->call_const_interceptor_fast_api(), 1);
ReserveSpaceForFastApiCall(masm, scratch1);
}
// Check that the maps from receiver to interceptor's holder
// haven't changed and thus we can invoke interceptor.
Label miss_cleanup;
Label* miss = can_do_fast_api_call ? &miss_cleanup : miss_label;
Register holder =
stub_compiler_->CheckPrototypes(object, receiver,
interceptor_holder, scratch1,
scratch2, scratch3, name, depth1, miss);
// Invoke an interceptor and if it provides a value,
// branch to |regular_invoke|.
Label regular_invoke;
LoadWithInterceptor(masm, receiver, holder, interceptor_holder,
®ular_invoke);
// Interceptor returned nothing for this property. Try to use cached
// constant function.
// Check that the maps from interceptor's holder to constant function's
// holder haven't changed and thus we can use cached constant function.
if (interceptor_holder != lookup->holder()) {
stub_compiler_->CheckPrototypes(interceptor_holder, receiver,
lookup->holder(), scratch1,
scratch2, scratch3, name, depth2, miss);
} else {
// CheckPrototypes has a side effect of fetching a 'holder'
// for API (object which is instanceof for the signature). It's
// safe to omit it here, as if present, it should be fetched
// by the previous CheckPrototypes.
ASSERT(depth2 == kInvalidProtoDepth);
}
// Invoke function.
if (can_do_fast_api_call) {
MaybeObject* result = GenerateFastApiCall(masm,
optimization,
arguments_.immediate());
if (result->IsFailure()) return result;
} else {
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(optimization.constant_function(), arguments_,
JUMP_FUNCTION, NullCallWrapper(), call_kind);
}
// Deferred code for fast API call case---clean preallocated space.
if (can_do_fast_api_call) {
__ bind(&miss_cleanup);
FreeSpaceForFastApiCall(masm, scratch1);
__ jmp(miss_label);
}
// Invoke a regular function.
__ bind(®ular_invoke);
if (can_do_fast_api_call) {
FreeSpaceForFastApiCall(masm, scratch1);
}
return masm->isolate()->heap()->undefined_value(); // Success.
}
void CompileRegular(MacroAssembler* masm,
JSObject* object,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
String* name,
JSObject* interceptor_holder,
Label* miss_label) {
Register holder =
stub_compiler_->CheckPrototypes(object, receiver, interceptor_holder,
scratch1, scratch2, scratch3, name,
miss_label);
FrameScope scope(masm, StackFrame::INTERNAL);
// Save the name_ register across the call.
__ push(name_);
PushInterceptorArguments(masm,
receiver,
holder,
name_,
interceptor_holder);
__ CallExternalReference(
ExternalReference(IC_Utility(IC::kLoadPropertyWithInterceptorForCall),
masm->isolate()),
5);
// Restore the name_ register.
__ pop(name_);
// Leave the internal frame.
}
void LoadWithInterceptor(MacroAssembler* masm,
Register receiver,
Register holder,
JSObject* holder_obj,
Label* interceptor_succeeded) {
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ push(holder); // Save the holder.
__ push(name_); // Save the name.
CompileCallLoadPropertyWithInterceptor(masm,
receiver,
holder,
name_,
holder_obj);
__ pop(name_); // Restore the name.
__ pop(receiver); // Restore the holder.
// Leave the internal frame.
}
__ CompareRoot(rax, Heap::kNoInterceptorResultSentinelRootIndex);
__ j(not_equal, interceptor_succeeded);
}
StubCompiler* stub_compiler_;
const ParameterCount& arguments_;
Register name_;
Code::ExtraICState extra_ic_state_;
};
void StubCompiler::GenerateLoadMiss(MacroAssembler* masm, Code::Kind kind) {
ASSERT(kind == Code::LOAD_IC || kind == Code::KEYED_LOAD_IC);
Code* code = NULL;
if (kind == Code::LOAD_IC) {
code = masm->isolate()->builtins()->builtin(Builtins::kLoadIC_Miss);
} else {
code = masm->isolate()->builtins()->builtin(Builtins::kKeyedLoadIC_Miss);
}
Handle<Code> ic(code);
__ Jump(ic, RelocInfo::CODE_TARGET);
}
void StubCompiler::GenerateKeyedLoadMissForceGeneric(MacroAssembler* masm) {
Code* code = masm->isolate()->builtins()->builtin(
Builtins::kKeyedLoadIC_MissForceGeneric);
Handle<Code> ic(code);
__ Jump(ic, RelocInfo::CODE_TARGET);
}
// Both name_reg and receiver_reg are preserved on jumps to miss_label,
// but may be destroyed if store is successful.
void StubCompiler::GenerateStoreField(MacroAssembler* masm,
JSObject* object,
int index,
Map* transition,
Register receiver_reg,
Register name_reg,
Register scratch,
Label* miss_label) {
// Check that the object isn't a smi.
__ JumpIfSmi(receiver_reg, miss_label);
// Check that the map of the object hasn't changed.
__ Cmp(FieldOperand(receiver_reg, HeapObject::kMapOffset),
Handle<Map>(object->map()));
__ j(not_equal, miss_label);
// Perform global security token check if needed.
if (object->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(receiver_reg, scratch, miss_label);
}
// Stub never generated for non-global objects that require access
// checks.
ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
// Perform map transition for the receiver if necessary.
if ((transition != NULL) && (object->map()->unused_property_fields() == 0)) {
// The properties must be extended before we can store the value.
// We jump to a runtime call that extends the properties array.
__ pop(scratch); // Return address.
__ push(receiver_reg);
__ Push(Handle<Map>(transition));
__ push(rax);
__ push(scratch);
__ TailCallExternalReference(
ExternalReference(IC_Utility(IC::kSharedStoreIC_ExtendStorage),
masm->isolate()),
3,
1);
return;
}
if (transition != NULL) {
// Update the map of the object; no write barrier updating is
// needed because the map is never in new space.
__ Move(FieldOperand(receiver_reg, HeapObject::kMapOffset),
Handle<Map>(transition));
}
// Adjust for the number of properties stored in the object. Even in the
// face of a transition we can use the old map here because the size of the
// object and the number of in-object properties is not going to change.
index -= object->map()->inobject_properties();
if (index < 0) {
// Set the property straight into the object.
int offset = object->map()->instance_size() + (index * kPointerSize);
__ movq(FieldOperand(receiver_reg, offset), rax);
// Update the write barrier for the array address.
// Pass the value being stored in the now unused name_reg.
__ movq(name_reg, rax);
__ RecordWriteField(
receiver_reg, offset, name_reg, scratch, kDontSaveFPRegs);
} else {
// Write to the properties array.
int offset = index * kPointerSize + FixedArray::kHeaderSize;
// Get the properties array (optimistically).
__ movq(scratch, FieldOperand(receiver_reg, JSObject::kPropertiesOffset));
__ movq(FieldOperand(scratch, offset), rax);
// Update the write barrier for the array address.
// Pass the value being stored in the now unused name_reg.
__ movq(name_reg, rax);
__ RecordWriteField(
scratch, offset, name_reg, receiver_reg, kDontSaveFPRegs);
}
// Return the value (register rax).
__ ret(0);
}
// Generate code to check that a global property cell is empty. Create
// the property cell at compilation time if no cell exists for the
// property.
MUST_USE_RESULT static MaybeObject* GenerateCheckPropertyCell(
MacroAssembler* masm,
GlobalObject* global,
String* name,
Register scratch,
Label* miss) {
Object* probe;
{ MaybeObject* maybe_probe = global->EnsurePropertyCell(name);
if (!maybe_probe->ToObject(&probe)) return maybe_probe;
}
JSGlobalPropertyCell* cell = JSGlobalPropertyCell::cast(probe);
ASSERT(cell->value()->IsTheHole());
__ Move(scratch, Handle<Object>(cell));
__ Cmp(FieldOperand(scratch, JSGlobalPropertyCell::kValueOffset),
masm->isolate()->factory()->the_hole_value());
__ j(not_equal, miss);
return cell;
}
#undef __
#define __ ACCESS_MASM((masm()))
Register StubCompiler::CheckPrototypes(JSObject* object,
Register object_reg,
JSObject* holder,
Register holder_reg,
Register scratch1,
Register scratch2,
String* name,
int save_at_depth,
Label* miss) {
// Make sure there's no overlap between holder and object registers.
ASSERT(!scratch1.is(object_reg) && !scratch1.is(holder_reg));
ASSERT(!scratch2.is(object_reg) && !scratch2.is(holder_reg)
&& !scratch2.is(scratch1));
// Keep track of the current object in register reg. On the first
// iteration, reg is an alias for object_reg, on later iterations,
// it is an alias for holder_reg.
Register reg = object_reg;
int depth = 0;
if (save_at_depth == depth) {
__ movq(Operand(rsp, kPointerSize), object_reg);
}
// Check the maps in the prototype chain.
// Traverse the prototype chain from the object and do map checks.
JSObject* current = object;
while (current != holder) {
depth++;
// Only global objects and objects that do not require access
// checks are allowed in stubs.
ASSERT(current->IsJSGlobalProxy() || !current->IsAccessCheckNeeded());
JSObject* prototype = JSObject::cast(current->GetPrototype());
if (!current->HasFastProperties() &&
!current->IsJSGlobalObject() &&
!current->IsJSGlobalProxy()) {
if (!name->IsSymbol()) {
MaybeObject* lookup_result = heap()->LookupSymbol(name);
if (lookup_result->IsFailure()) {
set_failure(Failure::cast(lookup_result));
return reg;
} else {
name = String::cast(lookup_result->ToObjectUnchecked());
}
}
ASSERT(current->property_dictionary()->FindEntry(name) ==
StringDictionary::kNotFound);
MaybeObject* negative_lookup = GenerateDictionaryNegativeLookup(masm(),
miss,
reg,
name,
scratch1,
scratch2);
if (negative_lookup->IsFailure()) {
set_failure(Failure::cast(negative_lookup));
return reg;
}
__ movq(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
reg = holder_reg; // from now the object is in holder_reg
__ movq(reg, FieldOperand(scratch1, Map::kPrototypeOffset));
} else if (heap()->InNewSpace(prototype)) {
// Get the map of the current object.
__ movq(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
__ Cmp(scratch1, Handle<Map>(current->map()));
// Branch on the result of the map check.
__ j(not_equal, miss);
// Check access rights to the global object. This has to happen
// after the map check so that we know that the object is
// actually a global object.
if (current->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(reg, scratch1, miss);
// Restore scratch register to be the map of the object.
// We load the prototype from the map in the scratch register.
__ movq(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
}
// The prototype is in new space; we cannot store a reference
// to it in the code. Load it from the map.
reg = holder_reg; // from now the object is in holder_reg
__ movq(reg, FieldOperand(scratch1, Map::kPrototypeOffset));
} else {
// Check the map of the current object.
__ Cmp(FieldOperand(reg, HeapObject::kMapOffset),
Handle<Map>(current->map()));
// Branch on the result of the map check.
__ j(not_equal, miss);
// Check access rights to the global object. This has to happen
// after the map check so that we know that the object is
// actually a global object.
if (current->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(reg, scratch1, miss);
}
// The prototype is in old space; load it directly.
reg = holder_reg; // from now the object is in holder_reg
__ Move(reg, Handle<JSObject>(prototype));
}
if (save_at_depth == depth) {
__ movq(Operand(rsp, kPointerSize), reg);
}
// Go to the next object in the prototype chain.
current = prototype;
}
// Check the holder map.
__ Cmp(FieldOperand(reg, HeapObject::kMapOffset), Handle<Map>(holder->map()));
__ j(not_equal, miss);
// Log the check depth.
LOG(isolate(), IntEvent("check-maps-depth", depth + 1));
// Perform security check for access to the global object and return
// the holder register.
ASSERT(current == holder);
ASSERT(current->IsJSGlobalProxy() || !current->IsAccessCheckNeeded());
if (current->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(reg, scratch1, miss);
}
// If we've skipped any global objects, it's not enough to verify
// that their maps haven't changed. We also need to check that the
// property cell for the property is still empty.
current = object;
while (current != holder) {
if (current->IsGlobalObject()) {
MaybeObject* cell = GenerateCheckPropertyCell(masm(),
GlobalObject::cast(current),
name,
scratch1,
miss);
if (cell->IsFailure()) {
set_failure(Failure::cast(cell));
return reg;
}
}
current = JSObject::cast(current->GetPrototype());
}
// Return the register containing the holder.
return reg;
}
void StubCompiler::GenerateLoadField(JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
int index,
String* name,
Label* miss) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// Check the prototype chain.
Register reg =
CheckPrototypes(object, receiver, holder,
scratch1, scratch2, scratch3, name, miss);
// Get the value from the properties.
GenerateFastPropertyLoad(masm(), rax, reg, holder, index);
__ ret(0);
}
MaybeObject* StubCompiler::GenerateLoadCallback(JSObject* object,
JSObject* holder,
Register receiver,
Register name_reg,
Register scratch1,
Register scratch2,
Register scratch3,
AccessorInfo* callback,
String* name,
Label* miss) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// Check that the maps haven't changed.
Register reg =
CheckPrototypes(object, receiver, holder, scratch1,
scratch2, scratch3, name, miss);
Handle<AccessorInfo> callback_handle(callback);
// Insert additional parameters into the stack frame above return address.
ASSERT(!scratch2.is(reg));
__ pop(scratch2); // Get return address to place it below.
__ push(receiver); // receiver
__ push(reg); // holder
if (heap()->InNewSpace(callback_handle->data())) {
__ Move(scratch1, callback_handle);
__ push(FieldOperand(scratch1, AccessorInfo::kDataOffset)); // data
} else {
__ Push(Handle<Object>(callback_handle->data()));
}
__ push(name_reg); // name
// Save a pointer to where we pushed the arguments pointer.
// This will be passed as the const AccessorInfo& to the C++ callback.
#ifdef _WIN64
// Win64 uses first register--rcx--for returned value.
Register accessor_info_arg = r8;
Register name_arg = rdx;
#else
Register accessor_info_arg = rsi;
Register name_arg = rdi;
#endif
ASSERT(!name_arg.is(scratch2));
__ movq(name_arg, rsp);
__ push(scratch2); // Restore return address.
// Do call through the api.
Address getter_address = v8::ToCData<Address>(callback->getter());
ApiFunction fun(getter_address);
// 3 elements array for v8::Agruments::values_ and handler for name.
const int kStackSpace = 4;
// Allocate v8::AccessorInfo in non-GCed stack space.
const int kArgStackSpace = 1;
__ PrepareCallApiFunction(kArgStackSpace);
__ lea(rax, Operand(name_arg, 3 * kPointerSize));
// v8::AccessorInfo::args_.
__ movq(StackSpaceOperand(0), rax);
// The context register (rsi) has been saved in PrepareCallApiFunction and
// could be used to pass arguments.
__ lea(accessor_info_arg, StackSpaceOperand(0));
// Emitting a stub call may try to allocate (if the code is not
// already generated). Do not allow the assembler to perform a
// garbage collection but instead return the allocation failure
// object.
return masm()->TryCallApiFunctionAndReturn(&fun, kStackSpace);
}
void StubCompiler::GenerateLoadConstant(JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
Object* value,
String* name,
Label* miss) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// Check that the maps haven't changed.
CheckPrototypes(object, receiver, holder,
scratch1, scratch2, scratch3, name, miss);
// Return the constant value.
__ Move(rax, Handle<Object>(value));
__ ret(0);
}
void StubCompiler::GenerateLoadInterceptor(JSObject* object,
JSObject* interceptor_holder,
LookupResult* lookup,
Register receiver,
Register name_reg,
Register scratch1,
Register scratch2,
Register scratch3,
String* name,
Label* miss) {
ASSERT(interceptor_holder->HasNamedInterceptor());
ASSERT(!interceptor_holder->GetNamedInterceptor()->getter()->IsUndefined());
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// So far the most popular follow ups for interceptor loads are FIELD
// and CALLBACKS, so inline only them, other cases may be added
// later.
bool compile_followup_inline = false;
if (lookup->IsProperty() && lookup->IsCacheable()) {
if (lookup->type() == FIELD) {
compile_followup_inline = true;
} else if (lookup->type() == CALLBACKS &&
lookup->GetCallbackObject()->IsAccessorInfo() &&
AccessorInfo::cast(lookup->GetCallbackObject())->getter() != NULL) {
compile_followup_inline = true;
}
}
if (compile_followup_inline) {
// Compile the interceptor call, followed by inline code to load the
// property from further up the prototype chain if the call fails.
// Check that the maps haven't changed.
Register holder_reg = CheckPrototypes(object, receiver, interceptor_holder,
scratch1, scratch2, scratch3,
name, miss);
ASSERT(holder_reg.is(receiver) || holder_reg.is(scratch1));
// Save necessary data before invoking an interceptor.
// Requires a frame to make GC aware of pushed pointers.
{
FrameScope frame_scope(masm(), StackFrame::INTERNAL);
if (lookup->type() == CALLBACKS && !receiver.is(holder_reg)) {
// CALLBACKS case needs a receiver to be passed into C++ callback.
__ push(receiver);
}
__ push(holder_reg);
__ push(name_reg);
// Invoke an interceptor. Note: map checks from receiver to
// interceptor's holder has been compiled before (see a caller
// of this method.)
CompileCallLoadPropertyWithInterceptor(masm(),
receiver,
holder_reg,
name_reg,
interceptor_holder);
// Check if interceptor provided a value for property. If it's
// the case, return immediately.
Label interceptor_failed;
__ CompareRoot(rax, Heap::kNoInterceptorResultSentinelRootIndex);
__ j(equal, &interceptor_failed);
frame_scope.GenerateLeaveFrame();
__ ret(0);
__ bind(&interceptor_failed);
__ pop(name_reg);
__ pop(holder_reg);
if (lookup->type() == CALLBACKS && !receiver.is(holder_reg)) {
__ pop(receiver);
}
// Leave the internal frame.
}
// Check that the maps from interceptor's holder to lookup's holder
// haven't changed. And load lookup's holder into |holder| register.
if (interceptor_holder != lookup->holder()) {
holder_reg = CheckPrototypes(interceptor_holder,
holder_reg,
lookup->holder(),
scratch1,
scratch2,
scratch3,
name,
miss);
}
if (lookup->type() == FIELD) {
// We found FIELD property in prototype chain of interceptor's holder.
// Retrieve a field from field's holder.
GenerateFastPropertyLoad(masm(), rax, holder_reg,
lookup->holder(), lookup->GetFieldIndex());
__ ret(0);
} else {
// We found CALLBACKS property in prototype chain of interceptor's
// holder.
ASSERT(lookup->type() == CALLBACKS);
ASSERT(lookup->GetCallbackObject()->IsAccessorInfo());
AccessorInfo* callback = AccessorInfo::cast(lookup->GetCallbackObject());
ASSERT(callback != NULL);
ASSERT(callback->getter() != NULL);
// Tail call to runtime.
// Important invariant in CALLBACKS case: the code above must be
// structured to never clobber |receiver| register.
__ pop(scratch2); // return address
__ push(receiver);
__ push(holder_reg);
__ Move(holder_reg, Handle<AccessorInfo>(callback));
__ push(FieldOperand(holder_reg, AccessorInfo::kDataOffset));
__ push(holder_reg);
__ push(name_reg);
__ push(scratch2); // restore return address
ExternalReference ref =
ExternalReference(IC_Utility(IC::kLoadCallbackProperty),
isolate());
__ TailCallExternalReference(ref, 5, 1);
}
} else { // !compile_followup_inline
// Call the runtime system to load the interceptor.
// Check that the maps haven't changed.
Register holder_reg = CheckPrototypes(object, receiver, interceptor_holder,
scratch1, scratch2, scratch3,
name, miss);
__ pop(scratch2); // save old return address
PushInterceptorArguments(masm(), receiver, holder_reg,
name_reg, interceptor_holder);
__ push(scratch2); // restore old return address
ExternalReference ref = ExternalReference(
IC_Utility(IC::kLoadPropertyWithInterceptorForLoad), isolate());
__ TailCallExternalReference(ref, 5, 1);
}
}
void CallStubCompiler::GenerateNameCheck(String* name, Label* miss) {
if (kind_ == Code::KEYED_CALL_IC) {
__ Cmp(rcx, Handle<String>(name));
__ j(not_equal, miss);
}
}
void CallStubCompiler::GenerateGlobalReceiverCheck(JSObject* object,
JSObject* holder,
String* name,
Label* miss) {
ASSERT(holder->IsGlobalObject());
// Get the number of arguments.
const int argc = arguments().immediate();
// Get the receiver from the stack.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// If the object is the holder then we know that it's a global
// object which can only happen for contextual calls. In this case,
// the receiver cannot be a smi.
if (object != holder) {
__ JumpIfSmi(rdx, miss);
}
// Check that the maps haven't changed.
CheckPrototypes(object, rdx, holder, rbx, rax, rdi, name, miss);
}
void CallStubCompiler::GenerateLoadFunctionFromCell(JSGlobalPropertyCell* cell,
JSFunction* function,
Label* miss) {
// Get the value from the cell.
__ Move(rdi, Handle<JSGlobalPropertyCell>(cell));
__ movq(rdi, FieldOperand(rdi, JSGlobalPropertyCell::kValueOffset));
// Check that the cell contains the same function.
if (heap()->InNewSpace(function)) {
// We can't embed a pointer to a function in new space so we have
// to verify that the shared function info is unchanged. This has
// the nice side effect that multiple closures based on the same
// function can all use this call IC. Before we load through the
// function, we have to verify that it still is a function.
__ JumpIfSmi(rdi, miss);
__ CmpObjectType(rdi, JS_FUNCTION_TYPE, rax);
__ j(not_equal, miss);
// Check the shared function info. Make sure it hasn't changed.
__ Move(rax, Handle<SharedFunctionInfo>(function->shared()));
__ cmpq(FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset), rax);
__ j(not_equal, miss);
} else {
__ Cmp(rdi, Handle<JSFunction>(function));
__ j(not_equal, miss);
}
}
MaybeObject* CallStubCompiler::GenerateMissBranch() {
MaybeObject* maybe_obj =
isolate()->stub_cache()->ComputeCallMiss(arguments().immediate(),
kind_,
extra_ic_state_);
Object* obj;
if (!maybe_obj->ToObject(&obj)) return maybe_obj;
__ Jump(Handle<Code>(Code::cast(obj)), RelocInfo::CODE_TARGET);
return obj;
}
MaybeObject* CallStubCompiler::CompileCallField(JSObject* object,
JSObject* holder,
int index,
String* name) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
Label miss;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss);
// Do the right check and compute the holder register.
Register reg = CheckPrototypes(object, rdx, holder, rbx, rax, rdi,
name, &miss);
GenerateFastPropertyLoad(masm(), rdi, reg, holder, index);
// Check that the function really is a function.
__ JumpIfSmi(rdi, &miss);
__ CmpObjectType(rdi, JS_FUNCTION_TYPE, rbx);
__ j(not_equal, &miss);
// Patch the receiver on the stack with the global proxy if
// necessary.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
// Invoke the function.
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(rdi, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
// Handle call cache miss.
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(FIELD, name);
}
MaybeObject* CallStubCompiler::CompileArrayPushCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not an array, bail out to regular call.
if (!object->IsJSArray() || cell != NULL) return heap()->undefined_value();
Label miss;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object),
rdx,
holder,
rbx,
rax,
rdi,
name,
&miss);
if (argc == 0) {
// Noop, return the length.
__ movq(rax, FieldOperand(rdx, JSArray::kLengthOffset));
__ ret((argc + 1) * kPointerSize);
} else {
Label call_builtin;
// Get the elements array of the object.
__ movq(rbx, FieldOperand(rdx, JSArray::kElementsOffset));
// Check that the elements are in fast mode and writable.
__ Cmp(FieldOperand(rbx, HeapObject::kMapOffset),
factory()->fixed_array_map());
__ j(not_equal, &call_builtin);
if (argc == 1) { // Otherwise fall through to call builtin.
Label attempt_to_grow_elements, with_write_barrier;
// Get the array's length into rax and calculate new length.
__ SmiToInteger32(rax, FieldOperand(rdx, JSArray::kLengthOffset));
STATIC_ASSERT(FixedArray::kMaxLength < Smi::kMaxValue);
__ addl(rax, Immediate(argc));
// Get the element's length into rcx.
__ SmiToInteger32(rcx, FieldOperand(rbx, FixedArray::kLengthOffset));
// Check if we could survive without allocation.
__ cmpl(rax, rcx);
__ j(greater, &attempt_to_grow_elements);
// Check if value is a smi.
__ movq(rcx, Operand(rsp, argc * kPointerSize));
__ JumpIfNotSmi(rcx, &with_write_barrier);
// Save new length.
__ Integer32ToSmiField(FieldOperand(rdx, JSArray::kLengthOffset), rax);
// Push the element.
__ lea(rdx, FieldOperand(rbx,
rax, times_pointer_size,
FixedArray::kHeaderSize - argc * kPointerSize));
__ movq(Operand(rdx, 0), rcx);
__ Integer32ToSmi(rax, rax); // Return new length as smi.
__ ret((argc + 1) * kPointerSize);
__ bind(&with_write_barrier);
__ movq(rdi, FieldOperand(rdx, HeapObject::kMapOffset));
__ CheckFastObjectElements(rdi, &call_builtin);
// Save new length.
__ Integer32ToSmiField(FieldOperand(rdx, JSArray::kLengthOffset), rax);
// Push the element.
__ lea(rdx, FieldOperand(rbx,
rax, times_pointer_size,
FixedArray::kHeaderSize - argc * kPointerSize));
__ movq(Operand(rdx, 0), rcx);
__ RecordWrite(
rbx, rdx, rcx, kDontSaveFPRegs, EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
__ Integer32ToSmi(rax, rax); // Return new length as smi.
__ ret((argc + 1) * kPointerSize);
__ bind(&attempt_to_grow_elements);
if (!FLAG_inline_new) {
__ jmp(&call_builtin);
}
__ movq(rdi, Operand(rsp, argc * kPointerSize));
// Growing elements that are SMI-only requires special handling in case
// the new element is non-Smi. For now, delegate to the builtin.
Label no_fast_elements_check;
__ JumpIfSmi(rdi, &no_fast_elements_check);
__ movq(rsi, FieldOperand(rdx, HeapObject::kMapOffset));
__ CheckFastObjectElements(rsi, &call_builtin, Label::kFar);
__ bind(&no_fast_elements_check);
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
ExternalReference new_space_allocation_limit =
ExternalReference::new_space_allocation_limit_address(isolate());
const int kAllocationDelta = 4;
// Load top.
__ Load(rcx, new_space_allocation_top);
// Check if it's the end of elements.
__ lea(rdx, FieldOperand(rbx,
rax, times_pointer_size,
FixedArray::kHeaderSize - argc * kPointerSize));
__ cmpq(rdx, rcx);
__ j(not_equal, &call_builtin);
__ addq(rcx, Immediate(kAllocationDelta * kPointerSize));
Operand limit_operand =
masm()->ExternalOperand(new_space_allocation_limit);
__ cmpq(rcx, limit_operand);
__ j(above, &call_builtin);
// We fit and could grow elements.
__ Store(new_space_allocation_top, rcx);
// Push the argument...
__ movq(Operand(rdx, 0), rdi);
// ... and fill the rest with holes.
__ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
for (int i = 1; i < kAllocationDelta; i++) {
__ movq(Operand(rdx, i * kPointerSize), kScratchRegister);
}
// We know the elements array is in new space so we don't need the
// remembered set, but we just pushed a value onto it so we may have to
// tell the incremental marker to rescan the object that we just grew. We
// don't need to worry about the holes because they are in old space and
// already marked black.
__ RecordWrite(rbx, rdx, rdi, kDontSaveFPRegs, OMIT_REMEMBERED_SET);
// Restore receiver to rdx as finish sequence assumes it's here.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Increment element's and array's sizes.
__ SmiAddConstant(FieldOperand(rbx, FixedArray::kLengthOffset),
Smi::FromInt(kAllocationDelta));
// Make new length a smi before returning it.
__ Integer32ToSmi(rax, rax);
__ movq(FieldOperand(rdx, JSArray::kLengthOffset), rax);
__ ret((argc + 1) * kPointerSize);
}
__ bind(&call_builtin);
__ TailCallExternalReference(ExternalReference(Builtins::c_ArrayPush,
isolate()),
argc + 1,
1);
}
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileArrayPopCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not an array, bail out to regular call.
if (!object->IsJSArray() || cell != NULL) return heap()->undefined_value();
Label miss, return_undefined, call_builtin;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object), rdx,
holder, rbx,
rax, rdi, name, &miss);
// Get the elements array of the object.
__ movq(rbx, FieldOperand(rdx, JSArray::kElementsOffset));
// Check that the elements are in fast mode and writable.
__ CompareRoot(FieldOperand(rbx, HeapObject::kMapOffset),
Heap::kFixedArrayMapRootIndex);
__ j(not_equal, &call_builtin);
// Get the array's length into rcx and calculate new length.
__ SmiToInteger32(rcx, FieldOperand(rdx, JSArray::kLengthOffset));
__ subl(rcx, Immediate(1));
__ j(negative, &return_undefined);
// Get the last element.
__ LoadRoot(r9, Heap::kTheHoleValueRootIndex);
__ movq(rax, FieldOperand(rbx,
rcx, times_pointer_size,
FixedArray::kHeaderSize));
// Check if element is already the hole.
__ cmpq(rax, r9);
// If so, call slow-case to also check prototypes for value.
__ j(equal, &call_builtin);
// Set the array's length.
__ Integer32ToSmiField(FieldOperand(rdx, JSArray::kLengthOffset), rcx);
// Fill with the hole and return original value.
__ movq(FieldOperand(rbx,
rcx, times_pointer_size,
FixedArray::kHeaderSize),
r9);
__ ret((argc + 1) * kPointerSize);
__ bind(&return_undefined);
__ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
__ ret((argc + 1) * kPointerSize);
__ bind(&call_builtin);
__ TailCallExternalReference(
ExternalReference(Builtins::c_ArrayPop, isolate()),
argc + 1,
1);
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileStringCharCodeAtCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not a string, bail out to regular call.
if (!object->IsString() || cell != NULL) return heap()->undefined_value();
const int argc = arguments().immediate();
Label miss;
Label name_miss;
Label index_out_of_range;
Label* index_out_of_range_label = &index_out_of_range;
if (kind_ == Code::CALL_IC &&
(CallICBase::StringStubState::decode(extra_ic_state_) ==
DEFAULT_STRING_STUB)) {
index_out_of_range_label = &miss;
}
GenerateNameCheck(name, &name_miss);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(masm(),
Context::STRING_FUNCTION_INDEX,
rax,
&miss);
ASSERT(object != holder);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
Register receiver = rbx;
Register index = rdi;
Register scratch = rdx;
Register result = rax;
__ movq(receiver, Operand(rsp, (argc + 1) * kPointerSize));
if (argc > 0) {
__ movq(index, Operand(rsp, (argc - 0) * kPointerSize));
} else {
__ LoadRoot(index, Heap::kUndefinedValueRootIndex);
}
StringCharCodeAtGenerator char_code_at_generator(receiver,
index,
scratch,
result,
&miss, // When not a string.
&miss, // When not a number.
index_out_of_range_label,
STRING_INDEX_IS_NUMBER);
char_code_at_generator.GenerateFast(masm());
__ ret((argc + 1) * kPointerSize);
StubRuntimeCallHelper call_helper;
char_code_at_generator.GenerateSlow(masm(), call_helper);
if (index_out_of_range.is_linked()) {
__ bind(&index_out_of_range);
__ LoadRoot(rax, Heap::kNanValueRootIndex);
__ ret((argc + 1) * kPointerSize);
}
__ bind(&miss);
// Restore function name in rcx.
__ Move(rcx, Handle<String>(name));
__ bind(&name_miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileStringCharAtCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not a string, bail out to regular call.
if (!object->IsString() || cell != NULL) return heap()->undefined_value();
const int argc = arguments().immediate();
Label miss;
Label name_miss;
Label index_out_of_range;
Label* index_out_of_range_label = &index_out_of_range;
if (kind_ == Code::CALL_IC &&
(CallICBase::StringStubState::decode(extra_ic_state_) ==
DEFAULT_STRING_STUB)) {
index_out_of_range_label = &miss;
}
GenerateNameCheck(name, &name_miss);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(masm(),
Context::STRING_FUNCTION_INDEX,
rax,
&miss);
ASSERT(object != holder);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
Register receiver = rax;
Register index = rdi;
Register scratch1 = rbx;
Register scratch2 = rdx;
Register result = rax;
__ movq(receiver, Operand(rsp, (argc + 1) * kPointerSize));
if (argc > 0) {
__ movq(index, Operand(rsp, (argc - 0) * kPointerSize));
} else {
__ LoadRoot(index, Heap::kUndefinedValueRootIndex);
}
StringCharAtGenerator char_at_generator(receiver,
index,
scratch1,
scratch2,
result,
&miss, // When not a string.
&miss, // When not a number.
index_out_of_range_label,
STRING_INDEX_IS_NUMBER);
char_at_generator.GenerateFast(masm());
__ ret((argc + 1) * kPointerSize);
StubRuntimeCallHelper call_helper;
char_at_generator.GenerateSlow(masm(), call_helper);
if (index_out_of_range.is_linked()) {
__ bind(&index_out_of_range);
__ LoadRoot(rax, Heap::kEmptyStringRootIndex);
__ ret((argc + 1) * kPointerSize);
}
__ bind(&miss);
// Restore function name in rcx.
__ Move(rcx, Handle<String>(name));
__ bind(&name_miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileStringFromCharCodeCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
const int argc = arguments().immediate();
// If the object is not a JSObject or we got an unexpected number of
// arguments, bail out to the regular call.
if (!object->IsJSObject() || argc != 1) return heap()->undefined_value();
Label miss;
GenerateNameCheck(name, &miss);
if (cell == NULL) {
__ movq(rdx, Operand(rsp, 2 * kPointerSize));
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object), rdx, holder, rbx, rax, rdi, name,
&miss);
} else {
ASSERT(cell->value() == function);
GenerateGlobalReceiverCheck(JSObject::cast(object), holder, name, &miss);
GenerateLoadFunctionFromCell(cell, function, &miss);
}
// Load the char code argument.
Register code = rbx;
__ movq(code, Operand(rsp, 1 * kPointerSize));
// Check the code is a smi.
Label slow;
__ JumpIfNotSmi(code, &slow);
// Convert the smi code to uint16.
__ SmiAndConstant(code, code, Smi::FromInt(0xffff));
StringCharFromCodeGenerator char_from_code_generator(code, rax);
char_from_code_generator.GenerateFast(masm());
__ ret(2 * kPointerSize);
StubRuntimeCallHelper call_helper;
char_from_code_generator.GenerateSlow(masm(), call_helper);
// Tail call the full function. We do not have to patch the receiver
// because the function makes no use of it.
__ bind(&slow);
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(function, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
__ bind(&miss);
// rcx: function name.
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return (cell == NULL) ? GetCode(function) : GetCode(NORMAL, name);
}
MaybeObject* CallStubCompiler::CompileMathFloorCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// TODO(872): implement this.
return heap()->undefined_value();
}
MaybeObject* CallStubCompiler::CompileMathAbsCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
const int argc = arguments().immediate();
// If the object is not a JSObject or we got an unexpected number of
// arguments, bail out to the regular call.
if (!object->IsJSObject() || argc != 1) return heap()->undefined_value();
Label miss;
GenerateNameCheck(name, &miss);
if (cell == NULL) {
__ movq(rdx, Operand(rsp, 2 * kPointerSize));
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object), rdx, holder, rbx, rax, rdi, name,
&miss);
} else {
ASSERT(cell->value() == function);
GenerateGlobalReceiverCheck(JSObject::cast(object), holder, name, &miss);
GenerateLoadFunctionFromCell(cell, function, &miss);
}
// Load the (only) argument into rax.
__ movq(rax, Operand(rsp, 1 * kPointerSize));
// Check if the argument is a smi.
Label not_smi;
STATIC_ASSERT(kSmiTag == 0);
__ JumpIfNotSmi(rax, ¬_smi);
__ SmiToInteger32(rax, rax);
// Set ebx to 1...1 (== -1) if the argument is negative, or to 0...0
// otherwise.
__ movl(rbx, rax);
__ sarl(rbx, Immediate(kBitsPerInt - 1));
// Do bitwise not or do nothing depending on ebx.
__ xorl(rax, rbx);
// Add 1 or do nothing depending on ebx.
__ subl(rax, rbx);
// If the result is still negative, go to the slow case.
// This only happens for the most negative smi.
Label slow;
__ j(negative, &slow);
// Smi case done.
__ Integer32ToSmi(rax, rax);
__ ret(2 * kPointerSize);
// Check if the argument is a heap number and load its value.
__ bind(¬_smi);
__ CheckMap(rax, factory()->heap_number_map(), &slow, DONT_DO_SMI_CHECK);
__ movq(rbx, FieldOperand(rax, HeapNumber::kValueOffset));
// Check the sign of the argument. If the argument is positive,
// just return it.
Label negative_sign;
const int sign_mask_shift =
(HeapNumber::kExponentOffset - HeapNumber::kValueOffset) * kBitsPerByte;
__ movq(rdi, static_cast<int64_t>(HeapNumber::kSignMask) << sign_mask_shift,
RelocInfo::NONE);
__ testq(rbx, rdi);
__ j(not_zero, &negative_sign);
__ ret(2 * kPointerSize);
// If the argument is negative, clear the sign, and return a new
// number. We still have the sign mask in rdi.
__ bind(&negative_sign);
__ xor_(rbx, rdi);
__ AllocateHeapNumber(rax, rdx, &slow);
__ movq(FieldOperand(rax, HeapNumber::kValueOffset), rbx);
__ ret(2 * kPointerSize);
// Tail call the full function. We do not have to patch the receiver
// because the function makes no use of it.
__ bind(&slow);
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(function, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
__ bind(&miss);
// rcx: function name.
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return (cell == NULL) ? GetCode(function) : GetCode(NORMAL, name);
}
MaybeObject* CallStubCompiler::CompileFastApiCall(
const CallOptimization& optimization,
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
ASSERT(optimization.is_simple_api_call());
// Bail out if object is a global object as we don't want to
// repatch it to global receiver.
if (object->IsGlobalObject()) return heap()->undefined_value();
if (cell != NULL) return heap()->undefined_value();
if (!object->IsJSObject()) return heap()->undefined_value();
int depth = optimization.GetPrototypeDepthOfExpectedType(
JSObject::cast(object), holder);
if (depth == kInvalidProtoDepth) return heap()->undefined_value();
Label miss, miss_before_stack_reserved;
GenerateNameCheck(name, &miss_before_stack_reserved);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss_before_stack_reserved);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->call_const(), 1);
__ IncrementCounter(counters->call_const_fast_api(), 1);
// Allocate space for v8::Arguments implicit values. Must be initialized
// before calling any runtime function.
__ subq(rsp, Immediate(kFastApiCallArguments * kPointerSize));
// Check that the maps haven't changed and find a Holder as a side effect.
CheckPrototypes(JSObject::cast(object), rdx, holder,
rbx, rax, rdi, name, depth, &miss);
// Move the return address on top of the stack.
__ movq(rax, Operand(rsp, 3 * kPointerSize));
__ movq(Operand(rsp, 0 * kPointerSize), rax);
MaybeObject* result = GenerateFastApiCall(masm(), optimization, argc);
if (result->IsFailure()) return result;
__ bind(&miss);
__ addq(rsp, Immediate(kFastApiCallArguments * kPointerSize));
__ bind(&miss_before_stack_reserved);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileCallConstant(Object* object,
JSObject* holder,
JSFunction* function,
String* name,
CheckType check) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
if (HasCustomCallGenerator(function)) {
MaybeObject* maybe_result = CompileCustomCall(
object, holder, NULL, function, name);
Object* result;
if (!maybe_result->ToObject(&result)) return maybe_result;
// undefined means bail out to regular compiler.
if (!result->IsUndefined()) return result;
}
Label miss;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
if (check != NUMBER_CHECK) {
__ JumpIfSmi(rdx, &miss);
}
// Make sure that it's okay not to patch the on stack receiver
// unless we're doing a receiver map check.
ASSERT(!object->IsGlobalObject() || check == RECEIVER_MAP_CHECK);
Counters* counters = isolate()->counters();
SharedFunctionInfo* function_info = function->shared();
switch (check) {
case RECEIVER_MAP_CHECK:
__ IncrementCounter(counters->call_const(), 1);
// Check that the maps haven't changed.
CheckPrototypes(JSObject::cast(object), rdx, holder,
rbx, rax, rdi, name, &miss);
// Patch the receiver on the stack with the global proxy if
// necessary.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
break;
case STRING_CHECK:
if (!function->IsBuiltin() && !function_info->strict_mode()) {
// Calling non-strict non-builtins with a value as the receiver
// requires boxing.
__ jmp(&miss);
} else {
// Check that the object is a two-byte string or a symbol.
__ CmpObjectType(rdx, FIRST_NONSTRING_TYPE, rax);
__ j(above_equal, &miss);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(
masm(), Context::STRING_FUNCTION_INDEX, rax, &miss);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
}
break;
case NUMBER_CHECK: {
if (!function->IsBuiltin() && !function_info->strict_mode()) {
// Calling non-strict non-builtins with a value as the receiver
// requires boxing.
__ jmp(&miss);
} else {
Label fast;
// Check that the object is a smi or a heap number.
__ JumpIfSmi(rdx, &fast);
__ CmpObjectType(rdx, HEAP_NUMBER_TYPE, rax);
__ j(not_equal, &miss);
__ bind(&fast);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(
masm(), Context::NUMBER_FUNCTION_INDEX, rax, &miss);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
}
break;
}
case BOOLEAN_CHECK: {
if (!function->IsBuiltin() && !function_info->strict_mode()) {
// Calling non-strict non-builtins with a value as the receiver
// requires boxing.
__ jmp(&miss);
} else {
Label fast;
// Check that the object is a boolean.
__ CompareRoot(rdx, Heap::kTrueValueRootIndex);
__ j(equal, &fast);
__ CompareRoot(rdx, Heap::kFalseValueRootIndex);
__ j(not_equal, &miss);
__ bind(&fast);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(
masm(), Context::BOOLEAN_FUNCTION_INDEX, rax, &miss);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
}
break;
}
default:
UNREACHABLE();
}
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(function, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
// Handle call cache miss.
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileCallInterceptor(JSObject* object,
JSObject* holder,
String* name) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
Label miss;
GenerateNameCheck(name, &miss);
// Get the number of arguments.
const int argc = arguments().immediate();
LookupResult lookup;
LookupPostInterceptor(holder, name, &lookup);
// Get the receiver from the stack.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
CallInterceptorCompiler compiler(this, arguments(), rcx, extra_ic_state_);
MaybeObject* result = compiler.Compile(masm(),
object,
holder,
name,
&lookup,
rdx,
rbx,
rdi,
rax,
&miss);
if (result->IsFailure()) return result;
// Restore receiver.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the function really is a function.
__ JumpIfSmi(rax, &miss);
__ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
__ j(not_equal, &miss);
// Patch the receiver on the stack with the global proxy if
// necessary.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
// Invoke the function.
__ movq(rdi, rax);
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(rdi, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
// Handle load cache miss.
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* CallStubCompiler::CompileCallGlobal(JSObject* object,
GlobalObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
if (HasCustomCallGenerator(function)) {
MaybeObject* maybe_result = CompileCustomCall(
object, holder, cell, function, name);
Object* result;
if (!maybe_result->ToObject(&result)) return maybe_result;
// undefined means bail out to regular compiler.
if (!result->IsUndefined()) return result;
}
Label miss;
GenerateNameCheck(name, &miss);
// Get the number of arguments.
const int argc = arguments().immediate();
GenerateGlobalReceiverCheck(object, holder, name, &miss);
GenerateLoadFunctionFromCell(cell, function, &miss);
// Patch the receiver on the stack with the global proxy.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
// Setup the context (function already in rdi).
__ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// Jump to the cached code (tail call).
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->call_global_inline(), 1);
ASSERT(function->is_compiled());
ParameterCount expected(function->shared()->formal_parameter_count());
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
if (V8::UseCrankshaft()) {
// TODO(kasperl): For now, we always call indirectly through the
// code field in the function to allow recompilation to take effect
// without changing any of the call sites.
__ movq(rdx, FieldOperand(rdi, JSFunction::kCodeEntryOffset));
__ InvokeCode(rdx, expected, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
} else {
Handle<Code> code(function->code());
__ InvokeCode(code, expected, arguments(),
RelocInfo::CODE_TARGET, JUMP_FUNCTION,
NullCallWrapper(), call_kind);
}
// Handle call cache miss.
__ bind(&miss);
__ IncrementCounter(counters->call_global_inline_miss(), 1);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(NORMAL, name);
}
MaybeObject* StoreStubCompiler::CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Generate store field code. Preserves receiver and name on jump to miss.
GenerateStoreField(masm(),
object,
index,
transition,
rdx, rcx, rbx,
&miss);
// Handle store cache miss.
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(transition == NULL ? FIELD : MAP_TRANSITION, name);
}
MaybeObject* StoreStubCompiler::CompileStoreCallback(JSObject* object,
AccessorInfo* callback,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that the object isn't a smi.
__ JumpIfSmi(rdx, &miss);
// Check that the map of the object hasn't changed.
__ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
Handle<Map>(object->map()));
__ j(not_equal, &miss);
// Perform global security token check if needed.
if (object->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(rdx, rbx, &miss);
}
// Stub never generated for non-global objects that require access
// checks.
ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
__ pop(rbx); // remove the return address
__ push(rdx); // receiver
__ Push(Handle<AccessorInfo>(callback)); // callback info
__ push(rcx); // name
__ push(rax); // value
__ push(rbx); // restore return address
// Do tail-call to the runtime system.
ExternalReference store_callback_property =
ExternalReference(IC_Utility(IC::kStoreCallbackProperty), isolate());
__ TailCallExternalReference(store_callback_property, 4, 1);
// Handle store cache miss.
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* StoreStubCompiler::CompileStoreInterceptor(JSObject* receiver,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that the object isn't a smi.
__ JumpIfSmi(rdx, &miss);
// Check that the map of the object hasn't changed.
__ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
Handle<Map>(receiver->map()));
__ j(not_equal, &miss);
// Perform global security token check if needed.
if (receiver->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(rdx, rbx, &miss);
}
// Stub never generated for non-global objects that require access
// checks.
ASSERT(receiver->IsJSGlobalProxy() || !receiver->IsAccessCheckNeeded());
__ pop(rbx); // remove the return address
__ push(rdx); // receiver
__ push(rcx); // name
__ push(rax); // value
__ Push(Smi::FromInt(strict_mode_));
__ push(rbx); // restore return address
// Do tail-call to the runtime system.
ExternalReference store_ic_property =
ExternalReference(IC_Utility(IC::kStoreInterceptorProperty), isolate());
__ TailCallExternalReference(store_ic_property, 4, 1);
// Handle store cache miss.
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* StoreStubCompiler::CompileStoreGlobal(GlobalObject* object,
JSGlobalPropertyCell* cell,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that the map of the global has not changed.
__ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
Handle<Map>(object->map()));
__ j(not_equal, &miss);
// Compute the cell operand to use.
__ Move(rbx, Handle<JSGlobalPropertyCell>(cell));
Operand cell_operand = FieldOperand(rbx, JSGlobalPropertyCell::kValueOffset);
// Check that the value in the cell is not the hole. If it is, this
// cell could have been deleted and reintroducing the global needs
// to update the property details in the property dictionary of the
// global object. We bail out to the runtime system to do that.
__ CompareRoot(cell_operand, Heap::kTheHoleValueRootIndex);
__ j(equal, &miss);
// Store the value in the cell.
__ movq(cell_operand, rax);
Label done;
__ JumpIfSmi(rax, &done);
__ movq(rcx, rax);
__ lea(rdx, cell_operand);
// Cells are always in the remembered set.
__ RecordWrite(rbx, // Object.
rdx, // Address.
rcx, // Value.
kDontSaveFPRegs,
OMIT_REMEMBERED_SET,
OMIT_SMI_CHECK);
// Return the value (register rax).
__ bind(&done);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->named_store_global_inline(), 1);
__ ret(0);
// Handle store cache miss.
__ bind(&miss);
__ IncrementCounter(counters->named_store_global_inline_miss(), 1);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, name);
}
MaybeObject* KeyedStoreStubCompiler::CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_store_field(), 1);
// Check that the name has not changed.
__ Cmp(rcx, Handle<String>(name));
__ j(not_equal, &miss);
// Generate store field code. Preserves receiver and name on jump to miss.
GenerateStoreField(masm(),
object,
index,
transition,
rdx, rcx, rbx,
&miss);
// Handle store cache miss.
__ bind(&miss);
__ DecrementCounter(counters->keyed_store_field(), 1);
Handle<Code> ic = isolate()->builtins()->KeyedStoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(transition == NULL ? FIELD : MAP_TRANSITION, name);
}
MaybeObject* KeyedStoreStubCompiler::CompileStoreElement(Map* receiver_map) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Code* stub;
ElementsKind elements_kind = receiver_map->elements_kind();
bool is_js_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
MaybeObject* maybe_stub =
KeyedStoreElementStub(is_js_array, elements_kind).TryGetCode();
if (!maybe_stub->To(&stub)) return maybe_stub;
__ DispatchMap(rdx,
Handle<Map>(receiver_map),
Handle<Code>(stub),
DO_SMI_CHECK);
Handle<Code> ic = isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, NULL);
}
MaybeObject* KeyedStoreStubCompiler::CompileStorePolymorphic(
MapList* receiver_maps,
CodeList* handler_stubs,
MapList* transitioned_maps) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
__ JumpIfSmi(rdx, &miss, Label::kNear);
__ movq(rdi, FieldOperand(rdx, HeapObject::kMapOffset));
int receiver_count = receiver_maps->length();
for (int i = 0; i < receiver_count; ++i) {
// Check map and tail call if there's a match
Handle<Map> map(receiver_maps->at(i));
__ Cmp(rdi, map);
if (transitioned_maps->at(i) == NULL) {
__ j(equal, Handle<Code>(handler_stubs->at(i)), RelocInfo::CODE_TARGET);
} else {
Label next_map;
__ j(not_equal, &next_map, Label::kNear);
__ movq(rbx,
Handle<Map>(transitioned_maps->at(i)),
RelocInfo::EMBEDDED_OBJECT);
__ jmp(Handle<Code>(handler_stubs->at(i)), RelocInfo::CODE_TARGET);
__ bind(&next_map);
}
}
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, NULL, MEGAMORPHIC);
}
MaybeObject* LoadStubCompiler::CompileLoadNonexistent(String* name,
JSObject* object,
JSObject* last) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that receiver is not a smi.
__ JumpIfSmi(rax, &miss);
// Check the maps of the full prototype chain. Also check that
// global property cells up to (but not including) the last object
// in the prototype chain are empty.
CheckPrototypes(object, rax, last, rbx, rdx, rdi, name, &miss);
// If the last object in the prototype chain is a global object,
// check that the global property cell is empty.
if (last->IsGlobalObject()) {
MaybeObject* cell = GenerateCheckPropertyCell(masm(),
GlobalObject::cast(last),
name,
rdx,
&miss);
if (cell->IsFailure()) {
miss.Unuse();
return cell;
}
}
// Return undefined if maps of the full prototype chain are still the
// same and no global property with this name contains a value.
__ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
__ ret(0);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(NONEXISTENT, heap()->empty_string());
}
MaybeObject* LoadStubCompiler::CompileLoadField(JSObject* object,
JSObject* holder,
int index,
String* name) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
GenerateLoadField(object, holder, rax, rbx, rdx, rdi, index, name, &miss);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(FIELD, name);
}
MaybeObject* LoadStubCompiler::CompileLoadCallback(String* name,
JSObject* object,
JSObject* holder,
AccessorInfo* callback) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
MaybeObject* result = GenerateLoadCallback(object, holder, rax, rcx, rdx, rbx,
rdi, callback, name, &miss);
if (result->IsFailure()) {
miss.Unuse();
return result;
}
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* LoadStubCompiler::CompileLoadConstant(JSObject* object,
JSObject* holder,
Object* value,
String* name) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
GenerateLoadConstant(object, holder, rax, rbx, rdx, rdi, value, name, &miss);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(CONSTANT_FUNCTION, name);
}
MaybeObject* LoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
JSObject* holder,
String* name) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
LookupResult lookup;
LookupPostInterceptor(holder, name, &lookup);
// TODO(368): Compile in the whole chain: all the interceptors in
// prototypes and ultimate answer.
GenerateLoadInterceptor(receiver,
holder,
&lookup,
rax,
rcx,
rdx,
rbx,
rdi,
name,
&miss);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* LoadStubCompiler::CompileLoadGlobal(JSObject* object,
GlobalObject* holder,
JSGlobalPropertyCell* cell,
String* name,
bool is_dont_delete) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// If the object is the holder then we know that it's a global
// object which can only happen for contextual loads. In this case,
// the receiver cannot be a smi.
if (object != holder) {
__ JumpIfSmi(rax, &miss);
}
// Check that the maps haven't changed.
CheckPrototypes(object, rax, holder, rbx, rdx, rdi, name, &miss);
// Get the value from the cell.
__ Move(rbx, Handle<JSGlobalPropertyCell>(cell));
__ movq(rbx, FieldOperand(rbx, JSGlobalPropertyCell::kValueOffset));
// Check for deleted property if property can actually be deleted.
if (!is_dont_delete) {
__ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
__ j(equal, &miss);
} else if (FLAG_debug_code) {
__ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
__ Check(not_equal, "DontDelete cells can't contain the hole");
}
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->named_load_global_stub(), 1);
__ movq(rax, rbx);
__ ret(0);
__ bind(&miss);
__ IncrementCounter(counters->named_load_global_stub_miss(), 1);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(NORMAL, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadField(String* name,
JSObject* receiver,
JSObject* holder,
int index) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_field(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadField(receiver, holder, rdx, rbx, rcx, rdi, index, name, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_field(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(FIELD, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadCallback(
String* name,
JSObject* receiver,
JSObject* holder,
AccessorInfo* callback) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_callback(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
MaybeObject* result = GenerateLoadCallback(receiver, holder, rdx, rax, rbx,
rcx, rdi, callback, name, &miss);
if (result->IsFailure()) {
miss.Unuse();
return result;
}
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_callback(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadConstant(String* name,
JSObject* receiver,
JSObject* holder,
Object* value) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_constant_function(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadConstant(receiver, holder, rdx, rbx, rcx, rdi,
value, name, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_constant_function(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CONSTANT_FUNCTION, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
JSObject* holder,
String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_interceptor(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
LookupResult lookup;
LookupPostInterceptor(holder, name, &lookup);
GenerateLoadInterceptor(receiver,
holder,
&lookup,
rdx,
rax,
rcx,
rbx,
rdi,
name,
&miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_interceptor(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadArrayLength(String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_array_length(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadArrayLength(masm(), rdx, rcx, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_array_length(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadStringLength(String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_string_length(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadStringLength(masm(), rdx, rcx, rbx, &miss, true);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_string_length(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadFunctionPrototype(String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_function_prototype(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadFunctionPrototype(masm(), rdx, rcx, rbx, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_function_prototype(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadElement(Map* receiver_map) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Code* stub;
ElementsKind elements_kind = receiver_map->elements_kind();
MaybeObject* maybe_stub = KeyedLoadElementStub(elements_kind).TryGetCode();
if (!maybe_stub->To(&stub)) return maybe_stub;
__ DispatchMap(rdx,
Handle<Map>(receiver_map),
Handle<Code>(stub),
DO_SMI_CHECK);
Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Miss();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, NULL);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadPolymorphic(
MapList* receiver_maps,
CodeList* handler_ics) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
__ JumpIfSmi(rdx, &miss);
Register map_reg = rbx;
__ movq(map_reg, FieldOperand(rdx, HeapObject::kMapOffset));
int receiver_count = receiver_maps->length();
for (int current = 0; current < receiver_count; ++current) {
// Check map and tail call if there's a match
Handle<Map> map(receiver_maps->at(current));
__ Cmp(map_reg, map);
__ j(equal,
Handle<Code>(handler_ics->at(current)),
RelocInfo::CODE_TARGET);
}
__ bind(&miss);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(NORMAL, NULL, MEGAMORPHIC);
}
// Specialized stub for constructing objects from functions which only have only
// simple assignments of the form this.x = ...; in their body.
MaybeObject* ConstructStubCompiler::CompileConstructStub(JSFunction* function) {
// ----------- S t a t e -------------
// -- rax : argc
// -- rdi : constructor
// -- rsp[0] : return address
// -- rsp[4] : last argument
// -----------------------------------
Label generic_stub_call;
// Use r8 for holding undefined which is used in several places below.
__ Move(r8, factory()->undefined_value());
#ifdef ENABLE_DEBUGGER_SUPPORT
// Check to see whether there are any break points in the function code. If
// there are jump to the generic constructor stub which calls the actual
// code for the function thereby hitting the break points.
__ movq(rbx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ movq(rbx, FieldOperand(rbx, SharedFunctionInfo::kDebugInfoOffset));
__ cmpq(rbx, r8);
__ j(not_equal, &generic_stub_call);
#endif
// Load the initial map and verify that it is in fact a map.
__ movq(rbx, FieldOperand(rdi, JSFunction::kPrototypeOrInitialMapOffset));
// Will both indicate a NULL and a Smi.
STATIC_ASSERT(kSmiTag == 0);
__ JumpIfSmi(rbx, &generic_stub_call);
__ CmpObjectType(rbx, MAP_TYPE, rcx);
__ j(not_equal, &generic_stub_call);
#ifdef DEBUG
// Cannot construct functions this way.
// rdi: constructor
// rbx: initial map
__ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
__ Assert(not_equal, "Function constructed by construct stub.");
#endif
// Now allocate the JSObject in new space.
// rdi: constructor
// rbx: initial map
__ movzxbq(rcx, FieldOperand(rbx, Map::kInstanceSizeOffset));
__ shl(rcx, Immediate(kPointerSizeLog2));
__ AllocateInNewSpace(rcx,
rdx,
rcx,
no_reg,
&generic_stub_call,
NO_ALLOCATION_FLAGS);
// Allocated the JSObject, now initialize the fields and add the heap tag.
// rbx: initial map
// rdx: JSObject (untagged)
__ movq(Operand(rdx, JSObject::kMapOffset), rbx);
__ Move(rbx, factory()->empty_fixed_array());
__ movq(Operand(rdx, JSObject::kPropertiesOffset), rbx);
__ movq(Operand(rdx, JSObject::kElementsOffset), rbx);
// rax: argc
// rdx: JSObject (untagged)
// Load the address of the first in-object property into r9.
__ lea(r9, Operand(rdx, JSObject::kHeaderSize));
// Calculate the location of the first argument. The stack contains only the
// return address on top of the argc arguments.
__ lea(rcx, Operand(rsp, rax, times_pointer_size, 0));
// rax: argc
// rcx: first argument
// rdx: JSObject (untagged)
// r8: undefined
// r9: first in-object property of the JSObject
// Fill the initialized properties with a constant value or a passed argument
// depending on the this.x = ...; assignment in the function.
SharedFunctionInfo* shared = function->shared();
for (int i = 0; i < shared->this_property_assignments_count(); i++) {
if (shared->IsThisPropertyAssignmentArgument(i)) {
// Check if the argument assigned to the property is actually passed.
// If argument is not passed the property is set to undefined,
// otherwise find it on the stack.
int arg_number = shared->GetThisPropertyAssignmentArgument(i);
__ movq(rbx, r8);
__ cmpq(rax, Immediate(arg_number));
__ cmovq(above, rbx, Operand(rcx, arg_number * -kPointerSize));
// Store value in the property.
__ movq(Operand(r9, i * kPointerSize), rbx);
} else {
// Set the property to the constant value.
Handle<Object> constant(shared->GetThisPropertyAssignmentConstant(i));
__ Move(Operand(r9, i * kPointerSize), constant);
}
}
// Fill the unused in-object property fields with undefined.
ASSERT(function->has_initial_map());
for (int i = shared->this_property_assignments_count();
i < function->initial_map()->inobject_properties();
i++) {
__ movq(Operand(r9, i * kPointerSize), r8);
}
// rax: argc
// rdx: JSObject (untagged)
// Move argc to rbx and the JSObject to return to rax and tag it.
__ movq(rbx, rax);
__ movq(rax, rdx);
__ or_(rax, Immediate(kHeapObjectTag));
// rax: JSObject
// rbx: argc
// Remove caller arguments and receiver from the stack and return.
__ pop(rcx);
__ lea(rsp, Operand(rsp, rbx, times_pointer_size, 1 * kPointerSize));
__ push(rcx);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->constructed_objects(), 1);
__ IncrementCounter(counters->constructed_objects_stub(), 1);
__ ret(0);
// Jump to the generic stub in case the specialized code cannot handle the
// construction.
__ bind(&generic_stub_call);
Code* code =
isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
Handle<Code> generic_construct_stub(code);
__ Jump(generic_construct_stub, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode();
}
#undef __
#define __ ACCESS_MASM(masm)
void KeyedLoadStubCompiler::GenerateLoadDictionaryElement(
MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label slow, miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
__ SmiToInteger32(rbx, rax);
__ movq(rcx, FieldOperand(rdx, JSObject::kElementsOffset));
// Check whether the elements is a number dictionary.
// rdx: receiver
// rax: key
// rbx: key as untagged int32
// rcx: elements
__ LoadFromNumberDictionary(&slow, rcx, rax, rbx, r9, rdi, rax);
__ ret(0);
__ bind(&slow);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> slow_ic =
masm->isolate()->builtins()->KeyedLoadIC_Slow();
__ jmp(slow_ic, RelocInfo::CODE_TARGET);
__ bind(&miss_force_generic);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedLoadIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedLoadStubCompiler::GenerateLoadExternalArray(
MacroAssembler* masm,
ElementsKind elements_kind) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label slow, miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
// Check that the index is in range.
__ movq(rbx, FieldOperand(rdx, JSObject::kElementsOffset));
__ SmiToInteger32(rcx, rax);
__ cmpq(rax, FieldOperand(rbx, ExternalArray::kLengthOffset));
// Unsigned comparison catches both negative and too-large values.
__ j(above_equal, &miss_force_generic);
// rax: index (as a smi)
// rdx: receiver (JSObject)
// rcx: untagged index
// rbx: elements array
__ movq(rbx, FieldOperand(rbx, ExternalArray::kExternalPointerOffset));
// rbx: base pointer of external storage
switch (elements_kind) {
case EXTERNAL_BYTE_ELEMENTS:
__ movsxbq(rcx, Operand(rbx, rcx, times_1, 0));
break;
case EXTERNAL_PIXEL_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ movzxbq(rcx, Operand(rbx, rcx, times_1, 0));
break;
case EXTERNAL_SHORT_ELEMENTS:
__ movsxwq(rcx, Operand(rbx, rcx, times_2, 0));
break;
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ movzxwq(rcx, Operand(rbx, rcx, times_2, 0));
break;
case EXTERNAL_INT_ELEMENTS:
__ movsxlq(rcx, Operand(rbx, rcx, times_4, 0));
break;
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
__ movl(rcx, Operand(rbx, rcx, times_4, 0));
break;
case EXTERNAL_FLOAT_ELEMENTS:
__ cvtss2sd(xmm0, Operand(rbx, rcx, times_4, 0));
break;
case EXTERNAL_DOUBLE_ELEMENTS:
__ movsd(xmm0, Operand(rbx, rcx, times_8, 0));
break;
default:
UNREACHABLE();
break;
}
// rax: index
// rdx: receiver
// For integer array types:
// rcx: value
// For floating-point array type:
// xmm0: value as double.
ASSERT(kSmiValueSize == 32);
if (elements_kind == EXTERNAL_UNSIGNED_INT_ELEMENTS) {
// For the UnsignedInt array type, we need to see whether
// the value can be represented in a Smi. If not, we need to convert
// it to a HeapNumber.
Label box_int;
__ JumpIfUIntNotValidSmiValue(rcx, &box_int, Label::kNear);
__ Integer32ToSmi(rax, rcx);
__ ret(0);
__ bind(&box_int);
// Allocate a HeapNumber for the int and perform int-to-double
// conversion.
// The value is zero-extended since we loaded the value from memory
// with movl.
__ cvtqsi2sd(xmm0, rcx);
__ AllocateHeapNumber(rcx, rbx, &slow);
// Set the value.
__ movsd(FieldOperand(rcx, HeapNumber::kValueOffset), xmm0);
__ movq(rax, rcx);
__ ret(0);
} else if (elements_kind == EXTERNAL_FLOAT_ELEMENTS ||
elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
// For the floating-point array type, we need to always allocate a
// HeapNumber.
__ AllocateHeapNumber(rcx, rbx, &slow);
// Set the value.
__ movsd(FieldOperand(rcx, HeapNumber::kValueOffset), xmm0);
__ movq(rax, rcx);
__ ret(0);
} else {
__ Integer32ToSmi(rax, rcx);
__ ret(0);
}
// Slow case: Jump to runtime.
__ bind(&slow);
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->keyed_load_external_array_slow(), 1);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> ic = masm->isolate()->builtins()->KeyedLoadIC_Slow();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Miss case: Jump to runtime.
__ bind(&miss_force_generic);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedLoadIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedStoreStubCompiler::GenerateStoreExternalArray(
MacroAssembler* masm,
ElementsKind elements_kind) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label slow, miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rcx, &miss_force_generic);
// Check that the index is in range.
__ movq(rbx, FieldOperand(rdx, JSObject::kElementsOffset));
__ SmiToInteger32(rdi, rcx); // Untag the index.
__ cmpq(rcx, FieldOperand(rbx, ExternalArray::kLengthOffset));
// Unsigned comparison catches both negative and too-large values.
__ j(above_equal, &miss_force_generic);
// Handle both smis and HeapNumbers in the fast path. Go to the
// runtime for all other kinds of values.
// rax: value
// rcx: key (a smi)
// rdx: receiver (a JSObject)
// rbx: elements array
// rdi: untagged key
Label check_heap_number;
if (elements_kind == EXTERNAL_PIXEL_ELEMENTS) {
// Float to pixel conversion is only implemented in the runtime for now.
__ JumpIfNotSmi(rax, &slow);
} else {
__ JumpIfNotSmi(rax, &check_heap_number, Label::kNear);
}
// No more branches to slow case on this path. Key and receiver not needed.
__ SmiToInteger32(rdx, rax);
__ movq(rbx, FieldOperand(rbx, ExternalArray::kExternalPointerOffset));
// rbx: base pointer of external storage
switch (elements_kind) {
case EXTERNAL_PIXEL_ELEMENTS:
{ // Clamp the value to [0..255].
Label done;
__ testl(rdx, Immediate(0xFFFFFF00));
__ j(zero, &done, Label::kNear);
__ setcc(negative, rdx); // 1 if negative, 0 if positive.
__ decb(rdx); // 0 if negative, 255 if positive.
__ bind(&done);
}
__ movb(Operand(rbx, rdi, times_1, 0), rdx);
break;
case EXTERNAL_BYTE_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ movb(Operand(rbx, rdi, times_1, 0), rdx);
break;
case EXTERNAL_SHORT_ELEMENTS:
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ movw(Operand(rbx, rdi, times_2, 0), rdx);
break;
case EXTERNAL_INT_ELEMENTS:
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
__ movl(Operand(rbx, rdi, times_4, 0), rdx);
break;
case EXTERNAL_FLOAT_ELEMENTS:
// Need to perform int-to-float conversion.
__ cvtlsi2ss(xmm0, rdx);
__ movss(Operand(rbx, rdi, times_4, 0), xmm0);
break;
case EXTERNAL_DOUBLE_ELEMENTS:
// Need to perform int-to-float conversion.
__ cvtlsi2sd(xmm0, rdx);
__ movsd(Operand(rbx, rdi, times_8, 0), xmm0);
break;
case FAST_ELEMENTS:
case FAST_SMI_ONLY_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
UNREACHABLE();
break;
}
__ ret(0);
// TODO(danno): handle heap number -> pixel array conversion
if (elements_kind != EXTERNAL_PIXEL_ELEMENTS) {
__ bind(&check_heap_number);
// rax: value
// rcx: key (a smi)
// rdx: receiver (a JSObject)
// rbx: elements array
// rdi: untagged key
__ CmpObjectType(rax, HEAP_NUMBER_TYPE, kScratchRegister);
__ j(not_equal, &slow);
// No more branches to slow case on this path.
// The WebGL specification leaves the behavior of storing NaN and
// +/-Infinity into integer arrays basically undefined. For more
// reproducible behavior, convert these to zero.
__ movsd(xmm0, FieldOperand(rax, HeapNumber::kValueOffset));
__ movq(rbx, FieldOperand(rbx, ExternalArray::kExternalPointerOffset));
// rdi: untagged index
// rbx: base pointer of external storage
// top of FPU stack: value
if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
__ cvtsd2ss(xmm0, xmm0);
__ movss(Operand(rbx, rdi, times_4, 0), xmm0);
__ ret(0);
} else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
__ movsd(Operand(rbx, rdi, times_8, 0), xmm0);
__ ret(0);
} else {
// Perform float-to-int conversion with truncation (round-to-zero)
// behavior.
// Convert to int32 and store the low byte/word.
// If the value is NaN or +/-infinity, the result is 0x80000000,
// which is automatically zero when taken mod 2^n, n < 32.
// rdx: value (converted to an untagged integer)
// rdi: untagged index
// rbx: base pointer of external storage
switch (elements_kind) {
case EXTERNAL_BYTE_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ cvttsd2si(rdx, xmm0);
__ movb(Operand(rbx, rdi, times_1, 0), rdx);
break;
case EXTERNAL_SHORT_ELEMENTS:
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ cvttsd2si(rdx, xmm0);
__ movw(Operand(rbx, rdi, times_2, 0), rdx);
break;
case EXTERNAL_INT_ELEMENTS:
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
// Convert to int64, so that NaN and infinities become
// 0x8000000000000000, which is zero mod 2^32.
__ cvttsd2siq(rdx, xmm0);
__ movl(Operand(rbx, rdi, times_4, 0), rdx);
break;
case EXTERNAL_PIXEL_ELEMENTS:
case EXTERNAL_FLOAT_ELEMENTS:
case EXTERNAL_DOUBLE_ELEMENTS:
case FAST_ELEMENTS:
case FAST_SMI_ONLY_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
UNREACHABLE();
break;
}
__ ret(0);
}
}
// Slow case: call runtime.
__ bind(&slow);
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> ic = masm->isolate()->builtins()->KeyedStoreIC_Slow();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Miss case: call runtime.
__ bind(&miss_force_generic);
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedStoreIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedLoadStubCompiler::GenerateLoadFastElement(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
// Get the elements array.
__ movq(rcx, FieldOperand(rdx, JSObject::kElementsOffset));
__ AssertFastElements(rcx);
// Check that the key is within bounds.
__ SmiCompare(rax, FieldOperand(rcx, FixedArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
// Load the result and make sure it's not the hole.
SmiIndex index = masm->SmiToIndex(rbx, rax, kPointerSizeLog2);
__ movq(rbx, FieldOperand(rcx,
index.reg,
index.scale,
FixedArray::kHeaderSize));
__ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
__ j(equal, &miss_force_generic);
__ movq(rax, rbx);
__ ret(0);
__ bind(&miss_force_generic);
Code* code = masm->isolate()->builtins()->builtin(
Builtins::kKeyedLoadIC_MissForceGeneric);
Handle<Code> ic(code);
__ jmp(ic, RelocInfo::CODE_TARGET);
}
void KeyedLoadStubCompiler::GenerateLoadFastDoubleElement(
MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic, slow_allocate_heapnumber;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
// Get the elements array.
__ movq(rcx, FieldOperand(rdx, JSObject::kElementsOffset));
__ AssertFastElements(rcx);
// Check that the key is within bounds.
__ SmiCompare(rax, FieldOperand(rcx, FixedArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
// Check for the hole
__ SmiToInteger32(kScratchRegister, rax);
uint32_t offset = FixedDoubleArray::kHeaderSize + sizeof(kHoleNanLower32);
__ cmpl(FieldOperand(rcx, kScratchRegister, times_8, offset),
Immediate(kHoleNanUpper32));
__ j(equal, &miss_force_generic);
// Always allocate a heap number for the result.
__ movsd(xmm0, FieldOperand(rcx, kScratchRegister, times_8,
FixedDoubleArray::kHeaderSize));
__ AllocateHeapNumber(rcx, rbx, &slow_allocate_heapnumber);
// Set the value.
__ movq(rax, rcx);
__ movsd(FieldOperand(rcx, HeapNumber::kValueOffset), xmm0);
__ ret(0);
__ bind(&slow_allocate_heapnumber);
Handle<Code> slow_ic =
masm->isolate()->builtins()->KeyedLoadIC_Slow();
__ jmp(slow_ic, RelocInfo::CODE_TARGET);
__ bind(&miss_force_generic);
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedLoadIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedStoreStubCompiler::GenerateStoreFastElement(
MacroAssembler* masm,
bool is_js_array,
ElementsKind elements_kind) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic, transition_elements_kind;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rcx, &miss_force_generic);
// Get the elements array and make sure it is a fast element array, not 'cow'.
__ movq(rdi, FieldOperand(rdx, JSObject::kElementsOffset));
__ CompareRoot(FieldOperand(rdi, HeapObject::kMapOffset),
Heap::kFixedArrayMapRootIndex);
__ j(not_equal, &miss_force_generic);
// Check that the key is within bounds.
if (is_js_array) {
__ SmiCompare(rcx, FieldOperand(rdx, JSArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
} else {
__ SmiCompare(rcx, FieldOperand(rdi, FixedArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
}
if (elements_kind == FAST_SMI_ONLY_ELEMENTS) {
__ JumpIfNotSmi(rax, &transition_elements_kind);
__ SmiToInteger32(rcx, rcx);
__ movq(FieldOperand(rdi, rcx, times_pointer_size, FixedArray::kHeaderSize),
rax);
} else {
// Do the store and update the write barrier.
ASSERT(elements_kind == FAST_ELEMENTS);
__ SmiToInteger32(rcx, rcx);
__ lea(rcx,
FieldOperand(rdi, rcx, times_pointer_size, FixedArray::kHeaderSize));
__ movq(Operand(rcx, 0), rax);
// Make sure to preserve the value in register rax.
__ movq(rdx, rax);
__ RecordWrite(rdi, rcx, rdx, kDontSaveFPRegs);
}
// Done.
__ ret(0);
// Handle store cache miss.
__ bind(&miss_force_generic);
Handle<Code> ic_force_generic =
masm->isolate()->builtins()->KeyedStoreIC_MissForceGeneric();
__ jmp(ic_force_generic, RelocInfo::CODE_TARGET);
__ bind(&transition_elements_kind);
Handle<Code> ic_miss = masm->isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic_miss, RelocInfo::CODE_TARGET);
}
void KeyedStoreStubCompiler::GenerateStoreFastDoubleElement(
MacroAssembler* masm,
bool is_js_array) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic, transition_elements_kind;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rcx, &miss_force_generic);
// Get the elements array.
__ movq(rdi, FieldOperand(rdx, JSObject::kElementsOffset));
__ AssertFastElements(rdi);
// Check that the key is within bounds.
if (is_js_array) {
__ SmiCompare(rcx, FieldOperand(rdx, JSArray::kLengthOffset));
} else {
__ SmiCompare(rcx, FieldOperand(rdi, FixedDoubleArray::kLengthOffset));
}
__ j(above_equal, &miss_force_generic);
// Handle smi values specially
__ SmiToInteger32(rcx, rcx);
__ StoreNumberToDoubleElements(rax, rdi, rcx, xmm0,
&transition_elements_kind);
__ ret(0);
// Handle store cache miss, replacing the ic with the generic stub.
__ bind(&miss_force_generic);
Handle<Code> ic_force_generic =
masm->isolate()->builtins()->KeyedStoreIC_MissForceGeneric();
__ jmp(ic_force_generic, RelocInfo::CODE_TARGET);
__ bind(&transition_elements_kind);
Handle<Code> ic_miss = masm->isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic_miss, RelocInfo::CODE_TARGET);
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_X64
Fixing bug caused by missing smi-tag.
Review URL: http://codereview.chromium.org/8240007
git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@9598 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
// Copyright 2011 the V8 project authors. 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 Google Inc. 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 COPYRIGHT
// OWNER OR CONTRIBUTORS 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 "v8.h"
#if defined(V8_TARGET_ARCH_X64)
#include "ic-inl.h"
#include "codegen.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
static void ProbeTable(Isolate* isolate,
MacroAssembler* masm,
Code::Flags flags,
StubCache::Table table,
Register name,
Register offset) {
ASSERT_EQ(8, kPointerSize);
ASSERT_EQ(16, sizeof(StubCache::Entry));
// The offset register holds the entry offset times four (due to masking
// and shifting optimizations).
ExternalReference key_offset(isolate->stub_cache()->key_reference(table));
Label miss;
__ LoadAddress(kScratchRegister, key_offset);
// Check that the key in the entry matches the name.
// Multiply entry offset by 16 to get the entry address. Since the
// offset register already holds the entry offset times four, multiply
// by a further four.
__ cmpl(name, Operand(kScratchRegister, offset, times_4, 0));
__ j(not_equal, &miss);
// Get the code entry from the cache.
// Use key_offset + kPointerSize, rather than loading value_offset.
__ movq(kScratchRegister,
Operand(kScratchRegister, offset, times_4, kPointerSize));
// Check that the flags match what we're looking for.
__ movl(offset, FieldOperand(kScratchRegister, Code::kFlagsOffset));
__ and_(offset, Immediate(~Code::kFlagsNotUsedInLookup));
__ cmpl(offset, Immediate(flags));
__ j(not_equal, &miss);
// Jump to the first instruction in the code stub.
__ addq(kScratchRegister, Immediate(Code::kHeaderSize - kHeapObjectTag));
__ jmp(kScratchRegister);
__ bind(&miss);
}
// Helper function used to check that the dictionary doesn't contain
// the property. This function may return false negatives, so miss_label
// must always call a backup property check that is complete.
// This function is safe to call if the receiver has fast properties.
// Name must be a symbol and receiver must be a heap object.
MUST_USE_RESULT static MaybeObject* GenerateDictionaryNegativeLookup(
MacroAssembler* masm,
Label* miss_label,
Register receiver,
String* name,
Register r0,
Register r1) {
ASSERT(name->IsSymbol());
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->negative_lookups(), 1);
__ IncrementCounter(counters->negative_lookups_miss(), 1);
__ movq(r0, FieldOperand(receiver, HeapObject::kMapOffset));
const int kInterceptorOrAccessCheckNeededMask =
(1 << Map::kHasNamedInterceptor) | (1 << Map::kIsAccessCheckNeeded);
// Bail out if the receiver has a named interceptor or requires access checks.
__ testb(FieldOperand(r0, Map::kBitFieldOffset),
Immediate(kInterceptorOrAccessCheckNeededMask));
__ j(not_zero, miss_label);
// Check that receiver is a JSObject.
__ CmpInstanceType(r0, FIRST_SPEC_OBJECT_TYPE);
__ j(below, miss_label);
// Load properties array.
Register properties = r0;
__ movq(properties, FieldOperand(receiver, JSObject::kPropertiesOffset));
// Check that the properties array is a dictionary.
__ CompareRoot(FieldOperand(properties, HeapObject::kMapOffset),
Heap::kHashTableMapRootIndex);
__ j(not_equal, miss_label);
Label done;
MaybeObject* result = StringDictionaryLookupStub::GenerateNegativeLookup(
masm,
miss_label,
&done,
properties,
name,
r1);
if (result->IsFailure()) return result;
__ bind(&done);
__ DecrementCounter(counters->negative_lookups_miss(), 1);
return result;
}
void StubCache::GenerateProbe(MacroAssembler* masm,
Code::Flags flags,
Register receiver,
Register name,
Register scratch,
Register extra,
Register extra2) {
Isolate* isolate = masm->isolate();
Label miss;
USE(extra); // The register extra is not used on the X64 platform.
USE(extra2); // The register extra2 is not used on the X64 platform.
// Make sure that code is valid. The shifting code relies on the
// entry size being 16.
ASSERT(sizeof(Entry) == 16);
// Make sure the flags do not name a specific type.
ASSERT(Code::ExtractTypeFromFlags(flags) == 0);
// Make sure that there are no register conflicts.
ASSERT(!scratch.is(receiver));
ASSERT(!scratch.is(name));
// Check scratch register is valid, extra and extra2 are unused.
ASSERT(!scratch.is(no_reg));
ASSERT(extra2.is(no_reg));
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, &miss);
// Get the map of the receiver and compute the hash.
__ movl(scratch, FieldOperand(name, String::kHashFieldOffset));
// Use only the low 32 bits of the map pointer.
__ addl(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
__ xor_(scratch, Immediate(flags));
__ and_(scratch, Immediate((kPrimaryTableSize - 1) << kHeapObjectTagSize));
// Probe the primary table.
ProbeTable(isolate, masm, flags, kPrimary, name, scratch);
// Primary miss: Compute hash for secondary probe.
__ movl(scratch, FieldOperand(name, String::kHashFieldOffset));
__ addl(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
__ xor_(scratch, Immediate(flags));
__ and_(scratch, Immediate((kPrimaryTableSize - 1) << kHeapObjectTagSize));
__ subl(scratch, name);
__ addl(scratch, Immediate(flags));
__ and_(scratch, Immediate((kSecondaryTableSize - 1) << kHeapObjectTagSize));
// Probe the secondary table.
ProbeTable(isolate, masm, flags, kSecondary, name, scratch);
// Cache miss: Fall-through and let caller handle the miss by
// entering the runtime system.
__ bind(&miss);
}
void StubCompiler::GenerateLoadGlobalFunctionPrototype(MacroAssembler* masm,
int index,
Register prototype) {
// Load the global or builtins object from the current context.
__ movq(prototype,
Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)));
// Load the global context from the global or builtins object.
__ movq(prototype,
FieldOperand(prototype, GlobalObject::kGlobalContextOffset));
// Load the function from the global context.
__ movq(prototype, Operand(prototype, Context::SlotOffset(index)));
// Load the initial map. The global functions all have initial maps.
__ movq(prototype,
FieldOperand(prototype, JSFunction::kPrototypeOrInitialMapOffset));
// Load the prototype from the initial map.
__ movq(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}
void StubCompiler::GenerateDirectLoadGlobalFunctionPrototype(
MacroAssembler* masm, int index, Register prototype, Label* miss) {
Isolate* isolate = masm->isolate();
// Check we're still in the same context.
__ Move(prototype, isolate->global());
__ cmpq(Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)),
prototype);
__ j(not_equal, miss);
// Get the global function with the given index.
JSFunction* function =
JSFunction::cast(isolate->global_context()->get(index));
// Load its initial map. The global functions all have initial maps.
__ Move(prototype, Handle<Map>(function->initial_map()));
// Load the prototype from the initial map.
__ movq(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}
void StubCompiler::GenerateLoadArrayLength(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* miss_label) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss_label);
// Check that the object is a JS array.
__ CmpObjectType(receiver, JS_ARRAY_TYPE, scratch);
__ j(not_equal, miss_label);
// Load length directly from the JS array.
__ movq(rax, FieldOperand(receiver, JSArray::kLengthOffset));
__ ret(0);
}
// Generate code to check if an object is a string. If the object is
// a string, the map's instance type is left in the scratch register.
static void GenerateStringCheck(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* smi,
Label* non_string_object) {
// Check that the object isn't a smi.
__ JumpIfSmi(receiver, smi);
// Check that the object is a string.
__ movq(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
__ movzxbq(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
STATIC_ASSERT(kNotStringTag != 0);
__ testl(scratch, Immediate(kNotStringTag));
__ j(not_zero, non_string_object);
}
void StubCompiler::GenerateLoadStringLength(MacroAssembler* masm,
Register receiver,
Register scratch1,
Register scratch2,
Label* miss,
bool support_wrappers) {
Label check_wrapper;
// Check if the object is a string leaving the instance type in the
// scratch register.
GenerateStringCheck(masm, receiver, scratch1, miss,
support_wrappers ? &check_wrapper : miss);
// Load length directly from the string.
__ movq(rax, FieldOperand(receiver, String::kLengthOffset));
__ ret(0);
if (support_wrappers) {
// Check if the object is a JSValue wrapper.
__ bind(&check_wrapper);
__ cmpl(scratch1, Immediate(JS_VALUE_TYPE));
__ j(not_equal, miss);
// Check if the wrapped value is a string and load the length
// directly if it is.
__ movq(scratch2, FieldOperand(receiver, JSValue::kValueOffset));
GenerateStringCheck(masm, scratch2, scratch1, miss, miss);
__ movq(rax, FieldOperand(scratch2, String::kLengthOffset));
__ ret(0);
}
}
void StubCompiler::GenerateLoadFunctionPrototype(MacroAssembler* masm,
Register receiver,
Register result,
Register scratch,
Label* miss_label) {
__ TryGetFunctionPrototype(receiver, result, miss_label);
if (!result.is(rax)) __ movq(rax, result);
__ ret(0);
}
// Load a fast property out of a holder object (src). In-object properties
// are loaded directly otherwise the property is loaded from the properties
// fixed array.
void StubCompiler::GenerateFastPropertyLoad(MacroAssembler* masm,
Register dst, Register src,
JSObject* holder, int index) {
// Adjust for the number of properties stored in the holder.
index -= holder->map()->inobject_properties();
if (index < 0) {
// Get the property straight out of the holder.
int offset = holder->map()->instance_size() + (index * kPointerSize);
__ movq(dst, FieldOperand(src, offset));
} else {
// Calculate the offset into the properties array.
int offset = index * kPointerSize + FixedArray::kHeaderSize;
__ movq(dst, FieldOperand(src, JSObject::kPropertiesOffset));
__ movq(dst, FieldOperand(dst, offset));
}
}
static void PushInterceptorArguments(MacroAssembler* masm,
Register receiver,
Register holder,
Register name,
JSObject* holder_obj) {
__ push(name);
InterceptorInfo* interceptor = holder_obj->GetNamedInterceptor();
ASSERT(!masm->isolate()->heap()->InNewSpace(interceptor));
__ Move(kScratchRegister, Handle<Object>(interceptor));
__ push(kScratchRegister);
__ push(receiver);
__ push(holder);
__ push(FieldOperand(kScratchRegister, InterceptorInfo::kDataOffset));
}
static void CompileCallLoadPropertyWithInterceptor(MacroAssembler* masm,
Register receiver,
Register holder,
Register name,
JSObject* holder_obj) {
PushInterceptorArguments(masm, receiver, holder, name, holder_obj);
ExternalReference ref =
ExternalReference(IC_Utility(IC::kLoadPropertyWithInterceptorOnly),
masm->isolate());
__ Set(rax, 5);
__ LoadAddress(rbx, ref);
CEntryStub stub(1);
__ CallStub(&stub);
}
// Number of pointers to be reserved on stack for fast API call.
static const int kFastApiCallArguments = 3;
// Reserves space for the extra arguments to API function in the
// caller's frame.
//
// These arguments are set by CheckPrototypes and GenerateFastApiCall.
static void ReserveSpaceForFastApiCall(MacroAssembler* masm, Register scratch) {
// ----------- S t a t e -------------
// -- rsp[0] : return address
// -- rsp[8] : last argument in the internal frame of the caller
// -----------------------------------
__ movq(scratch, Operand(rsp, 0));
__ subq(rsp, Immediate(kFastApiCallArguments * kPointerSize));
__ movq(Operand(rsp, 0), scratch);
__ Move(scratch, Smi::FromInt(0));
for (int i = 1; i <= kFastApiCallArguments; i++) {
__ movq(Operand(rsp, i * kPointerSize), scratch);
}
}
// Undoes the effects of ReserveSpaceForFastApiCall.
static void FreeSpaceForFastApiCall(MacroAssembler* masm, Register scratch) {
// ----------- S t a t e -------------
// -- rsp[0] : return address.
// -- rsp[8] : last fast api call extra argument.
// -- ...
// -- rsp[kFastApiCallArguments * 8] : first fast api call extra argument.
// -- rsp[kFastApiCallArguments * 8 + 8] : last argument in the internal
// frame.
// -----------------------------------
__ movq(scratch, Operand(rsp, 0));
__ movq(Operand(rsp, kFastApiCallArguments * kPointerSize), scratch);
__ addq(rsp, Immediate(kPointerSize * kFastApiCallArguments));
}
// Generates call to API function.
static MaybeObject* GenerateFastApiCall(MacroAssembler* masm,
const CallOptimization& optimization,
int argc) {
// ----------- S t a t e -------------
// -- rsp[0] : return address
// -- rsp[8] : object passing the type check
// (last fast api call extra argument,
// set by CheckPrototypes)
// -- rsp[16] : api function
// (first fast api call extra argument)
// -- rsp[24] : api call data
// -- rsp[32] : last argument
// -- ...
// -- rsp[(argc + 3) * 8] : first argument
// -- rsp[(argc + 4) * 8] : receiver
// -----------------------------------
// Get the function and setup the context.
JSFunction* function = optimization.constant_function();
__ Move(rdi, Handle<JSFunction>(function));
__ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// Pass the additional arguments.
__ movq(Operand(rsp, 2 * kPointerSize), rdi);
Object* call_data = optimization.api_call_info()->data();
Handle<CallHandlerInfo> api_call_info_handle(optimization.api_call_info());
if (masm->isolate()->heap()->InNewSpace(call_data)) {
__ Move(rcx, api_call_info_handle);
__ movq(rbx, FieldOperand(rcx, CallHandlerInfo::kDataOffset));
__ movq(Operand(rsp, 3 * kPointerSize), rbx);
} else {
__ Move(Operand(rsp, 3 * kPointerSize), Handle<Object>(call_data));
}
// Prepare arguments.
__ lea(rbx, Operand(rsp, 3 * kPointerSize));
Object* callback = optimization.api_call_info()->callback();
Address api_function_address = v8::ToCData<Address>(callback);
ApiFunction fun(api_function_address);
#ifdef _WIN64
// Win64 uses first register--rcx--for returned value.
Register arguments_arg = rdx;
#else
Register arguments_arg = rdi;
#endif
// Allocate the v8::Arguments structure in the arguments' space since
// it's not controlled by GC.
const int kApiStackSpace = 4;
__ PrepareCallApiFunction(kApiStackSpace);
__ movq(StackSpaceOperand(0), rbx); // v8::Arguments::implicit_args_.
__ addq(rbx, Immediate(argc * kPointerSize));
__ movq(StackSpaceOperand(1), rbx); // v8::Arguments::values_.
__ Set(StackSpaceOperand(2), argc); // v8::Arguments::length_.
// v8::Arguments::is_construct_call_.
__ Set(StackSpaceOperand(3), 0);
// v8::InvocationCallback's argument.
__ lea(arguments_arg, StackSpaceOperand(0));
// Emitting a stub call may try to allocate (if the code is not
// already generated). Do not allow the assembler to perform a
// garbage collection but instead return the allocation failure
// object.
return masm->TryCallApiFunctionAndReturn(&fun,
argc + kFastApiCallArguments + 1);
}
class CallInterceptorCompiler BASE_EMBEDDED {
public:
CallInterceptorCompiler(StubCompiler* stub_compiler,
const ParameterCount& arguments,
Register name,
Code::ExtraICState extra_ic_state)
: stub_compiler_(stub_compiler),
arguments_(arguments),
name_(name),
extra_ic_state_(extra_ic_state) {}
MaybeObject* Compile(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
String* name,
LookupResult* lookup,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
Label* miss) {
ASSERT(holder->HasNamedInterceptor());
ASSERT(!holder->GetNamedInterceptor()->getter()->IsUndefined());
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
CallOptimization optimization(lookup);
if (optimization.is_constant_call()) {
return CompileCacheable(masm,
object,
receiver,
scratch1,
scratch2,
scratch3,
holder,
lookup,
name,
optimization,
miss);
} else {
CompileRegular(masm,
object,
receiver,
scratch1,
scratch2,
scratch3,
name,
holder,
miss);
return masm->isolate()->heap()->undefined_value(); // Success.
}
}
private:
MaybeObject* CompileCacheable(MacroAssembler* masm,
JSObject* object,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
JSObject* interceptor_holder,
LookupResult* lookup,
String* name,
const CallOptimization& optimization,
Label* miss_label) {
ASSERT(optimization.is_constant_call());
ASSERT(!lookup->holder()->IsGlobalObject());
int depth1 = kInvalidProtoDepth;
int depth2 = kInvalidProtoDepth;
bool can_do_fast_api_call = false;
if (optimization.is_simple_api_call() &&
!lookup->holder()->IsGlobalObject()) {
depth1 =
optimization.GetPrototypeDepthOfExpectedType(object,
interceptor_holder);
if (depth1 == kInvalidProtoDepth) {
depth2 =
optimization.GetPrototypeDepthOfExpectedType(interceptor_holder,
lookup->holder());
}
can_do_fast_api_call = (depth1 != kInvalidProtoDepth) ||
(depth2 != kInvalidProtoDepth);
}
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->call_const_interceptor(), 1);
if (can_do_fast_api_call) {
__ IncrementCounter(counters->call_const_interceptor_fast_api(), 1);
ReserveSpaceForFastApiCall(masm, scratch1);
}
// Check that the maps from receiver to interceptor's holder
// haven't changed and thus we can invoke interceptor.
Label miss_cleanup;
Label* miss = can_do_fast_api_call ? &miss_cleanup : miss_label;
Register holder =
stub_compiler_->CheckPrototypes(object, receiver,
interceptor_holder, scratch1,
scratch2, scratch3, name, depth1, miss);
// Invoke an interceptor and if it provides a value,
// branch to |regular_invoke|.
Label regular_invoke;
LoadWithInterceptor(masm, receiver, holder, interceptor_holder,
®ular_invoke);
// Interceptor returned nothing for this property. Try to use cached
// constant function.
// Check that the maps from interceptor's holder to constant function's
// holder haven't changed and thus we can use cached constant function.
if (interceptor_holder != lookup->holder()) {
stub_compiler_->CheckPrototypes(interceptor_holder, receiver,
lookup->holder(), scratch1,
scratch2, scratch3, name, depth2, miss);
} else {
// CheckPrototypes has a side effect of fetching a 'holder'
// for API (object which is instanceof for the signature). It's
// safe to omit it here, as if present, it should be fetched
// by the previous CheckPrototypes.
ASSERT(depth2 == kInvalidProtoDepth);
}
// Invoke function.
if (can_do_fast_api_call) {
MaybeObject* result = GenerateFastApiCall(masm,
optimization,
arguments_.immediate());
if (result->IsFailure()) return result;
} else {
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(optimization.constant_function(), arguments_,
JUMP_FUNCTION, NullCallWrapper(), call_kind);
}
// Deferred code for fast API call case---clean preallocated space.
if (can_do_fast_api_call) {
__ bind(&miss_cleanup);
FreeSpaceForFastApiCall(masm, scratch1);
__ jmp(miss_label);
}
// Invoke a regular function.
__ bind(®ular_invoke);
if (can_do_fast_api_call) {
FreeSpaceForFastApiCall(masm, scratch1);
}
return masm->isolate()->heap()->undefined_value(); // Success.
}
void CompileRegular(MacroAssembler* masm,
JSObject* object,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
String* name,
JSObject* interceptor_holder,
Label* miss_label) {
Register holder =
stub_compiler_->CheckPrototypes(object, receiver, interceptor_holder,
scratch1, scratch2, scratch3, name,
miss_label);
FrameScope scope(masm, StackFrame::INTERNAL);
// Save the name_ register across the call.
__ push(name_);
PushInterceptorArguments(masm,
receiver,
holder,
name_,
interceptor_holder);
__ CallExternalReference(
ExternalReference(IC_Utility(IC::kLoadPropertyWithInterceptorForCall),
masm->isolate()),
5);
// Restore the name_ register.
__ pop(name_);
// Leave the internal frame.
}
void LoadWithInterceptor(MacroAssembler* masm,
Register receiver,
Register holder,
JSObject* holder_obj,
Label* interceptor_succeeded) {
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ push(holder); // Save the holder.
__ push(name_); // Save the name.
CompileCallLoadPropertyWithInterceptor(masm,
receiver,
holder,
name_,
holder_obj);
__ pop(name_); // Restore the name.
__ pop(receiver); // Restore the holder.
// Leave the internal frame.
}
__ CompareRoot(rax, Heap::kNoInterceptorResultSentinelRootIndex);
__ j(not_equal, interceptor_succeeded);
}
StubCompiler* stub_compiler_;
const ParameterCount& arguments_;
Register name_;
Code::ExtraICState extra_ic_state_;
};
void StubCompiler::GenerateLoadMiss(MacroAssembler* masm, Code::Kind kind) {
ASSERT(kind == Code::LOAD_IC || kind == Code::KEYED_LOAD_IC);
Code* code = NULL;
if (kind == Code::LOAD_IC) {
code = masm->isolate()->builtins()->builtin(Builtins::kLoadIC_Miss);
} else {
code = masm->isolate()->builtins()->builtin(Builtins::kKeyedLoadIC_Miss);
}
Handle<Code> ic(code);
__ Jump(ic, RelocInfo::CODE_TARGET);
}
void StubCompiler::GenerateKeyedLoadMissForceGeneric(MacroAssembler* masm) {
Code* code = masm->isolate()->builtins()->builtin(
Builtins::kKeyedLoadIC_MissForceGeneric);
Handle<Code> ic(code);
__ Jump(ic, RelocInfo::CODE_TARGET);
}
// Both name_reg and receiver_reg are preserved on jumps to miss_label,
// but may be destroyed if store is successful.
void StubCompiler::GenerateStoreField(MacroAssembler* masm,
JSObject* object,
int index,
Map* transition,
Register receiver_reg,
Register name_reg,
Register scratch,
Label* miss_label) {
// Check that the object isn't a smi.
__ JumpIfSmi(receiver_reg, miss_label);
// Check that the map of the object hasn't changed.
__ Cmp(FieldOperand(receiver_reg, HeapObject::kMapOffset),
Handle<Map>(object->map()));
__ j(not_equal, miss_label);
// Perform global security token check if needed.
if (object->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(receiver_reg, scratch, miss_label);
}
// Stub never generated for non-global objects that require access
// checks.
ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
// Perform map transition for the receiver if necessary.
if ((transition != NULL) && (object->map()->unused_property_fields() == 0)) {
// The properties must be extended before we can store the value.
// We jump to a runtime call that extends the properties array.
__ pop(scratch); // Return address.
__ push(receiver_reg);
__ Push(Handle<Map>(transition));
__ push(rax);
__ push(scratch);
__ TailCallExternalReference(
ExternalReference(IC_Utility(IC::kSharedStoreIC_ExtendStorage),
masm->isolate()),
3,
1);
return;
}
if (transition != NULL) {
// Update the map of the object; no write barrier updating is
// needed because the map is never in new space.
__ Move(FieldOperand(receiver_reg, HeapObject::kMapOffset),
Handle<Map>(transition));
}
// Adjust for the number of properties stored in the object. Even in the
// face of a transition we can use the old map here because the size of the
// object and the number of in-object properties is not going to change.
index -= object->map()->inobject_properties();
if (index < 0) {
// Set the property straight into the object.
int offset = object->map()->instance_size() + (index * kPointerSize);
__ movq(FieldOperand(receiver_reg, offset), rax);
// Update the write barrier for the array address.
// Pass the value being stored in the now unused name_reg.
__ movq(name_reg, rax);
__ RecordWriteField(
receiver_reg, offset, name_reg, scratch, kDontSaveFPRegs);
} else {
// Write to the properties array.
int offset = index * kPointerSize + FixedArray::kHeaderSize;
// Get the properties array (optimistically).
__ movq(scratch, FieldOperand(receiver_reg, JSObject::kPropertiesOffset));
__ movq(FieldOperand(scratch, offset), rax);
// Update the write barrier for the array address.
// Pass the value being stored in the now unused name_reg.
__ movq(name_reg, rax);
__ RecordWriteField(
scratch, offset, name_reg, receiver_reg, kDontSaveFPRegs);
}
// Return the value (register rax).
__ ret(0);
}
// Generate code to check that a global property cell is empty. Create
// the property cell at compilation time if no cell exists for the
// property.
MUST_USE_RESULT static MaybeObject* GenerateCheckPropertyCell(
MacroAssembler* masm,
GlobalObject* global,
String* name,
Register scratch,
Label* miss) {
Object* probe;
{ MaybeObject* maybe_probe = global->EnsurePropertyCell(name);
if (!maybe_probe->ToObject(&probe)) return maybe_probe;
}
JSGlobalPropertyCell* cell = JSGlobalPropertyCell::cast(probe);
ASSERT(cell->value()->IsTheHole());
__ Move(scratch, Handle<Object>(cell));
__ Cmp(FieldOperand(scratch, JSGlobalPropertyCell::kValueOffset),
masm->isolate()->factory()->the_hole_value());
__ j(not_equal, miss);
return cell;
}
#undef __
#define __ ACCESS_MASM((masm()))
Register StubCompiler::CheckPrototypes(JSObject* object,
Register object_reg,
JSObject* holder,
Register holder_reg,
Register scratch1,
Register scratch2,
String* name,
int save_at_depth,
Label* miss) {
// Make sure there's no overlap between holder and object registers.
ASSERT(!scratch1.is(object_reg) && !scratch1.is(holder_reg));
ASSERT(!scratch2.is(object_reg) && !scratch2.is(holder_reg)
&& !scratch2.is(scratch1));
// Keep track of the current object in register reg. On the first
// iteration, reg is an alias for object_reg, on later iterations,
// it is an alias for holder_reg.
Register reg = object_reg;
int depth = 0;
if (save_at_depth == depth) {
__ movq(Operand(rsp, kPointerSize), object_reg);
}
// Check the maps in the prototype chain.
// Traverse the prototype chain from the object and do map checks.
JSObject* current = object;
while (current != holder) {
depth++;
// Only global objects and objects that do not require access
// checks are allowed in stubs.
ASSERT(current->IsJSGlobalProxy() || !current->IsAccessCheckNeeded());
JSObject* prototype = JSObject::cast(current->GetPrototype());
if (!current->HasFastProperties() &&
!current->IsJSGlobalObject() &&
!current->IsJSGlobalProxy()) {
if (!name->IsSymbol()) {
MaybeObject* lookup_result = heap()->LookupSymbol(name);
if (lookup_result->IsFailure()) {
set_failure(Failure::cast(lookup_result));
return reg;
} else {
name = String::cast(lookup_result->ToObjectUnchecked());
}
}
ASSERT(current->property_dictionary()->FindEntry(name) ==
StringDictionary::kNotFound);
MaybeObject* negative_lookup = GenerateDictionaryNegativeLookup(masm(),
miss,
reg,
name,
scratch1,
scratch2);
if (negative_lookup->IsFailure()) {
set_failure(Failure::cast(negative_lookup));
return reg;
}
__ movq(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
reg = holder_reg; // from now the object is in holder_reg
__ movq(reg, FieldOperand(scratch1, Map::kPrototypeOffset));
} else if (heap()->InNewSpace(prototype)) {
// Get the map of the current object.
__ movq(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
__ Cmp(scratch1, Handle<Map>(current->map()));
// Branch on the result of the map check.
__ j(not_equal, miss);
// Check access rights to the global object. This has to happen
// after the map check so that we know that the object is
// actually a global object.
if (current->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(reg, scratch1, miss);
// Restore scratch register to be the map of the object.
// We load the prototype from the map in the scratch register.
__ movq(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
}
// The prototype is in new space; we cannot store a reference
// to it in the code. Load it from the map.
reg = holder_reg; // from now the object is in holder_reg
__ movq(reg, FieldOperand(scratch1, Map::kPrototypeOffset));
} else {
// Check the map of the current object.
__ Cmp(FieldOperand(reg, HeapObject::kMapOffset),
Handle<Map>(current->map()));
// Branch on the result of the map check.
__ j(not_equal, miss);
// Check access rights to the global object. This has to happen
// after the map check so that we know that the object is
// actually a global object.
if (current->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(reg, scratch1, miss);
}
// The prototype is in old space; load it directly.
reg = holder_reg; // from now the object is in holder_reg
__ Move(reg, Handle<JSObject>(prototype));
}
if (save_at_depth == depth) {
__ movq(Operand(rsp, kPointerSize), reg);
}
// Go to the next object in the prototype chain.
current = prototype;
}
// Check the holder map.
__ Cmp(FieldOperand(reg, HeapObject::kMapOffset), Handle<Map>(holder->map()));
__ j(not_equal, miss);
// Log the check depth.
LOG(isolate(), IntEvent("check-maps-depth", depth + 1));
// Perform security check for access to the global object and return
// the holder register.
ASSERT(current == holder);
ASSERT(current->IsJSGlobalProxy() || !current->IsAccessCheckNeeded());
if (current->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(reg, scratch1, miss);
}
// If we've skipped any global objects, it's not enough to verify
// that their maps haven't changed. We also need to check that the
// property cell for the property is still empty.
current = object;
while (current != holder) {
if (current->IsGlobalObject()) {
MaybeObject* cell = GenerateCheckPropertyCell(masm(),
GlobalObject::cast(current),
name,
scratch1,
miss);
if (cell->IsFailure()) {
set_failure(Failure::cast(cell));
return reg;
}
}
current = JSObject::cast(current->GetPrototype());
}
// Return the register containing the holder.
return reg;
}
void StubCompiler::GenerateLoadField(JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
int index,
String* name,
Label* miss) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// Check the prototype chain.
Register reg =
CheckPrototypes(object, receiver, holder,
scratch1, scratch2, scratch3, name, miss);
// Get the value from the properties.
GenerateFastPropertyLoad(masm(), rax, reg, holder, index);
__ ret(0);
}
MaybeObject* StubCompiler::GenerateLoadCallback(JSObject* object,
JSObject* holder,
Register receiver,
Register name_reg,
Register scratch1,
Register scratch2,
Register scratch3,
AccessorInfo* callback,
String* name,
Label* miss) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// Check that the maps haven't changed.
Register reg =
CheckPrototypes(object, receiver, holder, scratch1,
scratch2, scratch3, name, miss);
Handle<AccessorInfo> callback_handle(callback);
// Insert additional parameters into the stack frame above return address.
ASSERT(!scratch2.is(reg));
__ pop(scratch2); // Get return address to place it below.
__ push(receiver); // receiver
__ push(reg); // holder
if (heap()->InNewSpace(callback_handle->data())) {
__ Move(scratch1, callback_handle);
__ push(FieldOperand(scratch1, AccessorInfo::kDataOffset)); // data
} else {
__ Push(Handle<Object>(callback_handle->data()));
}
__ push(name_reg); // name
// Save a pointer to where we pushed the arguments pointer.
// This will be passed as the const AccessorInfo& to the C++ callback.
#ifdef _WIN64
// Win64 uses first register--rcx--for returned value.
Register accessor_info_arg = r8;
Register name_arg = rdx;
#else
Register accessor_info_arg = rsi;
Register name_arg = rdi;
#endif
ASSERT(!name_arg.is(scratch2));
__ movq(name_arg, rsp);
__ push(scratch2); // Restore return address.
// Do call through the api.
Address getter_address = v8::ToCData<Address>(callback->getter());
ApiFunction fun(getter_address);
// 3 elements array for v8::Agruments::values_ and handler for name.
const int kStackSpace = 4;
// Allocate v8::AccessorInfo in non-GCed stack space.
const int kArgStackSpace = 1;
__ PrepareCallApiFunction(kArgStackSpace);
__ lea(rax, Operand(name_arg, 3 * kPointerSize));
// v8::AccessorInfo::args_.
__ movq(StackSpaceOperand(0), rax);
// The context register (rsi) has been saved in PrepareCallApiFunction and
// could be used to pass arguments.
__ lea(accessor_info_arg, StackSpaceOperand(0));
// Emitting a stub call may try to allocate (if the code is not
// already generated). Do not allow the assembler to perform a
// garbage collection but instead return the allocation failure
// object.
return masm()->TryCallApiFunctionAndReturn(&fun, kStackSpace);
}
void StubCompiler::GenerateLoadConstant(JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
Object* value,
String* name,
Label* miss) {
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// Check that the maps haven't changed.
CheckPrototypes(object, receiver, holder,
scratch1, scratch2, scratch3, name, miss);
// Return the constant value.
__ Move(rax, Handle<Object>(value));
__ ret(0);
}
void StubCompiler::GenerateLoadInterceptor(JSObject* object,
JSObject* interceptor_holder,
LookupResult* lookup,
Register receiver,
Register name_reg,
Register scratch1,
Register scratch2,
Register scratch3,
String* name,
Label* miss) {
ASSERT(interceptor_holder->HasNamedInterceptor());
ASSERT(!interceptor_holder->GetNamedInterceptor()->getter()->IsUndefined());
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, miss);
// So far the most popular follow ups for interceptor loads are FIELD
// and CALLBACKS, so inline only them, other cases may be added
// later.
bool compile_followup_inline = false;
if (lookup->IsProperty() && lookup->IsCacheable()) {
if (lookup->type() == FIELD) {
compile_followup_inline = true;
} else if (lookup->type() == CALLBACKS &&
lookup->GetCallbackObject()->IsAccessorInfo() &&
AccessorInfo::cast(lookup->GetCallbackObject())->getter() != NULL) {
compile_followup_inline = true;
}
}
if (compile_followup_inline) {
// Compile the interceptor call, followed by inline code to load the
// property from further up the prototype chain if the call fails.
// Check that the maps haven't changed.
Register holder_reg = CheckPrototypes(object, receiver, interceptor_holder,
scratch1, scratch2, scratch3,
name, miss);
ASSERT(holder_reg.is(receiver) || holder_reg.is(scratch1));
// Save necessary data before invoking an interceptor.
// Requires a frame to make GC aware of pushed pointers.
{
FrameScope frame_scope(masm(), StackFrame::INTERNAL);
if (lookup->type() == CALLBACKS && !receiver.is(holder_reg)) {
// CALLBACKS case needs a receiver to be passed into C++ callback.
__ push(receiver);
}
__ push(holder_reg);
__ push(name_reg);
// Invoke an interceptor. Note: map checks from receiver to
// interceptor's holder has been compiled before (see a caller
// of this method.)
CompileCallLoadPropertyWithInterceptor(masm(),
receiver,
holder_reg,
name_reg,
interceptor_holder);
// Check if interceptor provided a value for property. If it's
// the case, return immediately.
Label interceptor_failed;
__ CompareRoot(rax, Heap::kNoInterceptorResultSentinelRootIndex);
__ j(equal, &interceptor_failed);
frame_scope.GenerateLeaveFrame();
__ ret(0);
__ bind(&interceptor_failed);
__ pop(name_reg);
__ pop(holder_reg);
if (lookup->type() == CALLBACKS && !receiver.is(holder_reg)) {
__ pop(receiver);
}
// Leave the internal frame.
}
// Check that the maps from interceptor's holder to lookup's holder
// haven't changed. And load lookup's holder into |holder| register.
if (interceptor_holder != lookup->holder()) {
holder_reg = CheckPrototypes(interceptor_holder,
holder_reg,
lookup->holder(),
scratch1,
scratch2,
scratch3,
name,
miss);
}
if (lookup->type() == FIELD) {
// We found FIELD property in prototype chain of interceptor's holder.
// Retrieve a field from field's holder.
GenerateFastPropertyLoad(masm(), rax, holder_reg,
lookup->holder(), lookup->GetFieldIndex());
__ ret(0);
} else {
// We found CALLBACKS property in prototype chain of interceptor's
// holder.
ASSERT(lookup->type() == CALLBACKS);
ASSERT(lookup->GetCallbackObject()->IsAccessorInfo());
AccessorInfo* callback = AccessorInfo::cast(lookup->GetCallbackObject());
ASSERT(callback != NULL);
ASSERT(callback->getter() != NULL);
// Tail call to runtime.
// Important invariant in CALLBACKS case: the code above must be
// structured to never clobber |receiver| register.
__ pop(scratch2); // return address
__ push(receiver);
__ push(holder_reg);
__ Move(holder_reg, Handle<AccessorInfo>(callback));
__ push(FieldOperand(holder_reg, AccessorInfo::kDataOffset));
__ push(holder_reg);
__ push(name_reg);
__ push(scratch2); // restore return address
ExternalReference ref =
ExternalReference(IC_Utility(IC::kLoadCallbackProperty),
isolate());
__ TailCallExternalReference(ref, 5, 1);
}
} else { // !compile_followup_inline
// Call the runtime system to load the interceptor.
// Check that the maps haven't changed.
Register holder_reg = CheckPrototypes(object, receiver, interceptor_holder,
scratch1, scratch2, scratch3,
name, miss);
__ pop(scratch2); // save old return address
PushInterceptorArguments(masm(), receiver, holder_reg,
name_reg, interceptor_holder);
__ push(scratch2); // restore old return address
ExternalReference ref = ExternalReference(
IC_Utility(IC::kLoadPropertyWithInterceptorForLoad), isolate());
__ TailCallExternalReference(ref, 5, 1);
}
}
void CallStubCompiler::GenerateNameCheck(String* name, Label* miss) {
if (kind_ == Code::KEYED_CALL_IC) {
__ Cmp(rcx, Handle<String>(name));
__ j(not_equal, miss);
}
}
void CallStubCompiler::GenerateGlobalReceiverCheck(JSObject* object,
JSObject* holder,
String* name,
Label* miss) {
ASSERT(holder->IsGlobalObject());
// Get the number of arguments.
const int argc = arguments().immediate();
// Get the receiver from the stack.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// If the object is the holder then we know that it's a global
// object which can only happen for contextual calls. In this case,
// the receiver cannot be a smi.
if (object != holder) {
__ JumpIfSmi(rdx, miss);
}
// Check that the maps haven't changed.
CheckPrototypes(object, rdx, holder, rbx, rax, rdi, name, miss);
}
void CallStubCompiler::GenerateLoadFunctionFromCell(JSGlobalPropertyCell* cell,
JSFunction* function,
Label* miss) {
// Get the value from the cell.
__ Move(rdi, Handle<JSGlobalPropertyCell>(cell));
__ movq(rdi, FieldOperand(rdi, JSGlobalPropertyCell::kValueOffset));
// Check that the cell contains the same function.
if (heap()->InNewSpace(function)) {
// We can't embed a pointer to a function in new space so we have
// to verify that the shared function info is unchanged. This has
// the nice side effect that multiple closures based on the same
// function can all use this call IC. Before we load through the
// function, we have to verify that it still is a function.
__ JumpIfSmi(rdi, miss);
__ CmpObjectType(rdi, JS_FUNCTION_TYPE, rax);
__ j(not_equal, miss);
// Check the shared function info. Make sure it hasn't changed.
__ Move(rax, Handle<SharedFunctionInfo>(function->shared()));
__ cmpq(FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset), rax);
__ j(not_equal, miss);
} else {
__ Cmp(rdi, Handle<JSFunction>(function));
__ j(not_equal, miss);
}
}
MaybeObject* CallStubCompiler::GenerateMissBranch() {
MaybeObject* maybe_obj =
isolate()->stub_cache()->ComputeCallMiss(arguments().immediate(),
kind_,
extra_ic_state_);
Object* obj;
if (!maybe_obj->ToObject(&obj)) return maybe_obj;
__ Jump(Handle<Code>(Code::cast(obj)), RelocInfo::CODE_TARGET);
return obj;
}
MaybeObject* CallStubCompiler::CompileCallField(JSObject* object,
JSObject* holder,
int index,
String* name) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
Label miss;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss);
// Do the right check and compute the holder register.
Register reg = CheckPrototypes(object, rdx, holder, rbx, rax, rdi,
name, &miss);
GenerateFastPropertyLoad(masm(), rdi, reg, holder, index);
// Check that the function really is a function.
__ JumpIfSmi(rdi, &miss);
__ CmpObjectType(rdi, JS_FUNCTION_TYPE, rbx);
__ j(not_equal, &miss);
// Patch the receiver on the stack with the global proxy if
// necessary.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
// Invoke the function.
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(rdi, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
// Handle call cache miss.
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(FIELD, name);
}
MaybeObject* CallStubCompiler::CompileArrayPushCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not an array, bail out to regular call.
if (!object->IsJSArray() || cell != NULL) return heap()->undefined_value();
Label miss;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object),
rdx,
holder,
rbx,
rax,
rdi,
name,
&miss);
if (argc == 0) {
// Noop, return the length.
__ movq(rax, FieldOperand(rdx, JSArray::kLengthOffset));
__ ret((argc + 1) * kPointerSize);
} else {
Label call_builtin;
// Get the elements array of the object.
__ movq(rbx, FieldOperand(rdx, JSArray::kElementsOffset));
// Check that the elements are in fast mode and writable.
__ Cmp(FieldOperand(rbx, HeapObject::kMapOffset),
factory()->fixed_array_map());
__ j(not_equal, &call_builtin);
if (argc == 1) { // Otherwise fall through to call builtin.
Label attempt_to_grow_elements, with_write_barrier;
// Get the array's length into rax and calculate new length.
__ SmiToInteger32(rax, FieldOperand(rdx, JSArray::kLengthOffset));
STATIC_ASSERT(FixedArray::kMaxLength < Smi::kMaxValue);
__ addl(rax, Immediate(argc));
// Get the element's length into rcx.
__ SmiToInteger32(rcx, FieldOperand(rbx, FixedArray::kLengthOffset));
// Check if we could survive without allocation.
__ cmpl(rax, rcx);
__ j(greater, &attempt_to_grow_elements);
// Check if value is a smi.
__ movq(rcx, Operand(rsp, argc * kPointerSize));
__ JumpIfNotSmi(rcx, &with_write_barrier);
// Save new length.
__ Integer32ToSmiField(FieldOperand(rdx, JSArray::kLengthOffset), rax);
// Push the element.
__ lea(rdx, FieldOperand(rbx,
rax, times_pointer_size,
FixedArray::kHeaderSize - argc * kPointerSize));
__ movq(Operand(rdx, 0), rcx);
__ Integer32ToSmi(rax, rax); // Return new length as smi.
__ ret((argc + 1) * kPointerSize);
__ bind(&with_write_barrier);
__ movq(rdi, FieldOperand(rdx, HeapObject::kMapOffset));
__ CheckFastObjectElements(rdi, &call_builtin);
// Save new length.
__ Integer32ToSmiField(FieldOperand(rdx, JSArray::kLengthOffset), rax);
// Push the element.
__ lea(rdx, FieldOperand(rbx,
rax, times_pointer_size,
FixedArray::kHeaderSize - argc * kPointerSize));
__ movq(Operand(rdx, 0), rcx);
__ RecordWrite(
rbx, rdx, rcx, kDontSaveFPRegs, EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
__ Integer32ToSmi(rax, rax); // Return new length as smi.
__ ret((argc + 1) * kPointerSize);
__ bind(&attempt_to_grow_elements);
if (!FLAG_inline_new) {
__ jmp(&call_builtin);
}
__ movq(rdi, Operand(rsp, argc * kPointerSize));
// Growing elements that are SMI-only requires special handling in case
// the new element is non-Smi. For now, delegate to the builtin.
Label no_fast_elements_check;
__ JumpIfSmi(rdi, &no_fast_elements_check);
__ movq(rsi, FieldOperand(rdx, HeapObject::kMapOffset));
__ CheckFastObjectElements(rsi, &call_builtin, Label::kFar);
__ bind(&no_fast_elements_check);
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
ExternalReference new_space_allocation_limit =
ExternalReference::new_space_allocation_limit_address(isolate());
const int kAllocationDelta = 4;
// Load top.
__ Load(rcx, new_space_allocation_top);
// Check if it's the end of elements.
__ lea(rdx, FieldOperand(rbx,
rax, times_pointer_size,
FixedArray::kHeaderSize - argc * kPointerSize));
__ cmpq(rdx, rcx);
__ j(not_equal, &call_builtin);
__ addq(rcx, Immediate(kAllocationDelta * kPointerSize));
Operand limit_operand =
masm()->ExternalOperand(new_space_allocation_limit);
__ cmpq(rcx, limit_operand);
__ j(above, &call_builtin);
// We fit and could grow elements.
__ Store(new_space_allocation_top, rcx);
// Push the argument...
__ movq(Operand(rdx, 0), rdi);
// ... and fill the rest with holes.
__ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
for (int i = 1; i < kAllocationDelta; i++) {
__ movq(Operand(rdx, i * kPointerSize), kScratchRegister);
}
// We know the elements array is in new space so we don't need the
// remembered set, but we just pushed a value onto it so we may have to
// tell the incremental marker to rescan the object that we just grew. We
// don't need to worry about the holes because they are in old space and
// already marked black.
__ RecordWrite(rbx, rdx, rdi, kDontSaveFPRegs, OMIT_REMEMBERED_SET);
// Restore receiver to rdx as finish sequence assumes it's here.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Increment element's and array's sizes.
__ SmiAddConstant(FieldOperand(rbx, FixedArray::kLengthOffset),
Smi::FromInt(kAllocationDelta));
// Make new length a smi before returning it.
__ Integer32ToSmi(rax, rax);
__ movq(FieldOperand(rdx, JSArray::kLengthOffset), rax);
__ ret((argc + 1) * kPointerSize);
}
__ bind(&call_builtin);
__ TailCallExternalReference(ExternalReference(Builtins::c_ArrayPush,
isolate()),
argc + 1,
1);
}
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileArrayPopCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not an array, bail out to regular call.
if (!object->IsJSArray() || cell != NULL) return heap()->undefined_value();
Label miss, return_undefined, call_builtin;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object), rdx,
holder, rbx,
rax, rdi, name, &miss);
// Get the elements array of the object.
__ movq(rbx, FieldOperand(rdx, JSArray::kElementsOffset));
// Check that the elements are in fast mode and writable.
__ CompareRoot(FieldOperand(rbx, HeapObject::kMapOffset),
Heap::kFixedArrayMapRootIndex);
__ j(not_equal, &call_builtin);
// Get the array's length into rcx and calculate new length.
__ SmiToInteger32(rcx, FieldOperand(rdx, JSArray::kLengthOffset));
__ subl(rcx, Immediate(1));
__ j(negative, &return_undefined);
// Get the last element.
__ LoadRoot(r9, Heap::kTheHoleValueRootIndex);
__ movq(rax, FieldOperand(rbx,
rcx, times_pointer_size,
FixedArray::kHeaderSize));
// Check if element is already the hole.
__ cmpq(rax, r9);
// If so, call slow-case to also check prototypes for value.
__ j(equal, &call_builtin);
// Set the array's length.
__ Integer32ToSmiField(FieldOperand(rdx, JSArray::kLengthOffset), rcx);
// Fill with the hole and return original value.
__ movq(FieldOperand(rbx,
rcx, times_pointer_size,
FixedArray::kHeaderSize),
r9);
__ ret((argc + 1) * kPointerSize);
__ bind(&return_undefined);
__ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
__ ret((argc + 1) * kPointerSize);
__ bind(&call_builtin);
__ TailCallExternalReference(
ExternalReference(Builtins::c_ArrayPop, isolate()),
argc + 1,
1);
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileStringCharCodeAtCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not a string, bail out to regular call.
if (!object->IsString() || cell != NULL) return heap()->undefined_value();
const int argc = arguments().immediate();
Label miss;
Label name_miss;
Label index_out_of_range;
Label* index_out_of_range_label = &index_out_of_range;
if (kind_ == Code::CALL_IC &&
(CallICBase::StringStubState::decode(extra_ic_state_) ==
DEFAULT_STRING_STUB)) {
index_out_of_range_label = &miss;
}
GenerateNameCheck(name, &name_miss);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(masm(),
Context::STRING_FUNCTION_INDEX,
rax,
&miss);
ASSERT(object != holder);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
Register receiver = rbx;
Register index = rdi;
Register scratch = rdx;
Register result = rax;
__ movq(receiver, Operand(rsp, (argc + 1) * kPointerSize));
if (argc > 0) {
__ movq(index, Operand(rsp, (argc - 0) * kPointerSize));
} else {
__ LoadRoot(index, Heap::kUndefinedValueRootIndex);
}
StringCharCodeAtGenerator char_code_at_generator(receiver,
index,
scratch,
result,
&miss, // When not a string.
&miss, // When not a number.
index_out_of_range_label,
STRING_INDEX_IS_NUMBER);
char_code_at_generator.GenerateFast(masm());
__ ret((argc + 1) * kPointerSize);
StubRuntimeCallHelper call_helper;
char_code_at_generator.GenerateSlow(masm(), call_helper);
if (index_out_of_range.is_linked()) {
__ bind(&index_out_of_range);
__ LoadRoot(rax, Heap::kNanValueRootIndex);
__ ret((argc + 1) * kPointerSize);
}
__ bind(&miss);
// Restore function name in rcx.
__ Move(rcx, Handle<String>(name));
__ bind(&name_miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileStringCharAtCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
// If object is not a string, bail out to regular call.
if (!object->IsString() || cell != NULL) return heap()->undefined_value();
const int argc = arguments().immediate();
Label miss;
Label name_miss;
Label index_out_of_range;
Label* index_out_of_range_label = &index_out_of_range;
if (kind_ == Code::CALL_IC &&
(CallICBase::StringStubState::decode(extra_ic_state_) ==
DEFAULT_STRING_STUB)) {
index_out_of_range_label = &miss;
}
GenerateNameCheck(name, &name_miss);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(masm(),
Context::STRING_FUNCTION_INDEX,
rax,
&miss);
ASSERT(object != holder);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
Register receiver = rax;
Register index = rdi;
Register scratch1 = rbx;
Register scratch2 = rdx;
Register result = rax;
__ movq(receiver, Operand(rsp, (argc + 1) * kPointerSize));
if (argc > 0) {
__ movq(index, Operand(rsp, (argc - 0) * kPointerSize));
} else {
__ LoadRoot(index, Heap::kUndefinedValueRootIndex);
}
StringCharAtGenerator char_at_generator(receiver,
index,
scratch1,
scratch2,
result,
&miss, // When not a string.
&miss, // When not a number.
index_out_of_range_label,
STRING_INDEX_IS_NUMBER);
char_at_generator.GenerateFast(masm());
__ ret((argc + 1) * kPointerSize);
StubRuntimeCallHelper call_helper;
char_at_generator.GenerateSlow(masm(), call_helper);
if (index_out_of_range.is_linked()) {
__ bind(&index_out_of_range);
__ LoadRoot(rax, Heap::kEmptyStringRootIndex);
__ ret((argc + 1) * kPointerSize);
}
__ bind(&miss);
// Restore function name in rcx.
__ Move(rcx, Handle<String>(name));
__ bind(&name_miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileStringFromCharCodeCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
const int argc = arguments().immediate();
// If the object is not a JSObject or we got an unexpected number of
// arguments, bail out to the regular call.
if (!object->IsJSObject() || argc != 1) return heap()->undefined_value();
Label miss;
GenerateNameCheck(name, &miss);
if (cell == NULL) {
__ movq(rdx, Operand(rsp, 2 * kPointerSize));
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object), rdx, holder, rbx, rax, rdi, name,
&miss);
} else {
ASSERT(cell->value() == function);
GenerateGlobalReceiverCheck(JSObject::cast(object), holder, name, &miss);
GenerateLoadFunctionFromCell(cell, function, &miss);
}
// Load the char code argument.
Register code = rbx;
__ movq(code, Operand(rsp, 1 * kPointerSize));
// Check the code is a smi.
Label slow;
__ JumpIfNotSmi(code, &slow);
// Convert the smi code to uint16.
__ SmiAndConstant(code, code, Smi::FromInt(0xffff));
StringCharFromCodeGenerator char_from_code_generator(code, rax);
char_from_code_generator.GenerateFast(masm());
__ ret(2 * kPointerSize);
StubRuntimeCallHelper call_helper;
char_from_code_generator.GenerateSlow(masm(), call_helper);
// Tail call the full function. We do not have to patch the receiver
// because the function makes no use of it.
__ bind(&slow);
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(function, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
__ bind(&miss);
// rcx: function name.
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return (cell == NULL) ? GetCode(function) : GetCode(NORMAL, name);
}
MaybeObject* CallStubCompiler::CompileMathFloorCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// TODO(872): implement this.
return heap()->undefined_value();
}
MaybeObject* CallStubCompiler::CompileMathAbsCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// -- rcx : function name
// -- rsp[0] : return address
// -- rsp[(argc - n) * 8] : arg[n] (zero-based)
// -- ...
// -- rsp[(argc + 1) * 8] : receiver
// -----------------------------------
const int argc = arguments().immediate();
// If the object is not a JSObject or we got an unexpected number of
// arguments, bail out to the regular call.
if (!object->IsJSObject() || argc != 1) return heap()->undefined_value();
Label miss;
GenerateNameCheck(name, &miss);
if (cell == NULL) {
__ movq(rdx, Operand(rsp, 2 * kPointerSize));
__ JumpIfSmi(rdx, &miss);
CheckPrototypes(JSObject::cast(object), rdx, holder, rbx, rax, rdi, name,
&miss);
} else {
ASSERT(cell->value() == function);
GenerateGlobalReceiverCheck(JSObject::cast(object), holder, name, &miss);
GenerateLoadFunctionFromCell(cell, function, &miss);
}
// Load the (only) argument into rax.
__ movq(rax, Operand(rsp, 1 * kPointerSize));
// Check if the argument is a smi.
Label not_smi;
STATIC_ASSERT(kSmiTag == 0);
__ JumpIfNotSmi(rax, ¬_smi);
__ SmiToInteger32(rax, rax);
// Set ebx to 1...1 (== -1) if the argument is negative, or to 0...0
// otherwise.
__ movl(rbx, rax);
__ sarl(rbx, Immediate(kBitsPerInt - 1));
// Do bitwise not or do nothing depending on ebx.
__ xorl(rax, rbx);
// Add 1 or do nothing depending on ebx.
__ subl(rax, rbx);
// If the result is still negative, go to the slow case.
// This only happens for the most negative smi.
Label slow;
__ j(negative, &slow);
// Smi case done.
__ Integer32ToSmi(rax, rax);
__ ret(2 * kPointerSize);
// Check if the argument is a heap number and load its value.
__ bind(¬_smi);
__ CheckMap(rax, factory()->heap_number_map(), &slow, DONT_DO_SMI_CHECK);
__ movq(rbx, FieldOperand(rax, HeapNumber::kValueOffset));
// Check the sign of the argument. If the argument is positive,
// just return it.
Label negative_sign;
const int sign_mask_shift =
(HeapNumber::kExponentOffset - HeapNumber::kValueOffset) * kBitsPerByte;
__ movq(rdi, static_cast<int64_t>(HeapNumber::kSignMask) << sign_mask_shift,
RelocInfo::NONE);
__ testq(rbx, rdi);
__ j(not_zero, &negative_sign);
__ ret(2 * kPointerSize);
// If the argument is negative, clear the sign, and return a new
// number. We still have the sign mask in rdi.
__ bind(&negative_sign);
__ xor_(rbx, rdi);
__ AllocateHeapNumber(rax, rdx, &slow);
__ movq(FieldOperand(rax, HeapNumber::kValueOffset), rbx);
__ ret(2 * kPointerSize);
// Tail call the full function. We do not have to patch the receiver
// because the function makes no use of it.
__ bind(&slow);
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(function, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
__ bind(&miss);
// rcx: function name.
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return (cell == NULL) ? GetCode(function) : GetCode(NORMAL, name);
}
MaybeObject* CallStubCompiler::CompileFastApiCall(
const CallOptimization& optimization,
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
ASSERT(optimization.is_simple_api_call());
// Bail out if object is a global object as we don't want to
// repatch it to global receiver.
if (object->IsGlobalObject()) return heap()->undefined_value();
if (cell != NULL) return heap()->undefined_value();
if (!object->IsJSObject()) return heap()->undefined_value();
int depth = optimization.GetPrototypeDepthOfExpectedType(
JSObject::cast(object), holder);
if (depth == kInvalidProtoDepth) return heap()->undefined_value();
Label miss, miss_before_stack_reserved;
GenerateNameCheck(name, &miss_before_stack_reserved);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
__ JumpIfSmi(rdx, &miss_before_stack_reserved);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->call_const(), 1);
__ IncrementCounter(counters->call_const_fast_api(), 1);
// Allocate space for v8::Arguments implicit values. Must be initialized
// before calling any runtime function.
__ subq(rsp, Immediate(kFastApiCallArguments * kPointerSize));
// Check that the maps haven't changed and find a Holder as a side effect.
CheckPrototypes(JSObject::cast(object), rdx, holder,
rbx, rax, rdi, name, depth, &miss);
// Move the return address on top of the stack.
__ movq(rax, Operand(rsp, 3 * kPointerSize));
__ movq(Operand(rsp, 0 * kPointerSize), rax);
MaybeObject* result = GenerateFastApiCall(masm(), optimization, argc);
if (result->IsFailure()) return result;
__ bind(&miss);
__ addq(rsp, Immediate(kFastApiCallArguments * kPointerSize));
__ bind(&miss_before_stack_reserved);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileCallConstant(Object* object,
JSObject* holder,
JSFunction* function,
String* name,
CheckType check) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
if (HasCustomCallGenerator(function)) {
MaybeObject* maybe_result = CompileCustomCall(
object, holder, NULL, function, name);
Object* result;
if (!maybe_result->ToObject(&result)) return maybe_result;
// undefined means bail out to regular compiler.
if (!result->IsUndefined()) return result;
}
Label miss;
GenerateNameCheck(name, &miss);
// Get the receiver from the stack.
const int argc = arguments().immediate();
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the receiver isn't a smi.
if (check != NUMBER_CHECK) {
__ JumpIfSmi(rdx, &miss);
}
// Make sure that it's okay not to patch the on stack receiver
// unless we're doing a receiver map check.
ASSERT(!object->IsGlobalObject() || check == RECEIVER_MAP_CHECK);
Counters* counters = isolate()->counters();
SharedFunctionInfo* function_info = function->shared();
switch (check) {
case RECEIVER_MAP_CHECK:
__ IncrementCounter(counters->call_const(), 1);
// Check that the maps haven't changed.
CheckPrototypes(JSObject::cast(object), rdx, holder,
rbx, rax, rdi, name, &miss);
// Patch the receiver on the stack with the global proxy if
// necessary.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
break;
case STRING_CHECK:
if (!function->IsBuiltin() && !function_info->strict_mode()) {
// Calling non-strict non-builtins with a value as the receiver
// requires boxing.
__ jmp(&miss);
} else {
// Check that the object is a two-byte string or a symbol.
__ CmpObjectType(rdx, FIRST_NONSTRING_TYPE, rax);
__ j(above_equal, &miss);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(
masm(), Context::STRING_FUNCTION_INDEX, rax, &miss);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
}
break;
case NUMBER_CHECK: {
if (!function->IsBuiltin() && !function_info->strict_mode()) {
// Calling non-strict non-builtins with a value as the receiver
// requires boxing.
__ jmp(&miss);
} else {
Label fast;
// Check that the object is a smi or a heap number.
__ JumpIfSmi(rdx, &fast);
__ CmpObjectType(rdx, HEAP_NUMBER_TYPE, rax);
__ j(not_equal, &miss);
__ bind(&fast);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(
masm(), Context::NUMBER_FUNCTION_INDEX, rax, &miss);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
}
break;
}
case BOOLEAN_CHECK: {
if (!function->IsBuiltin() && !function_info->strict_mode()) {
// Calling non-strict non-builtins with a value as the receiver
// requires boxing.
__ jmp(&miss);
} else {
Label fast;
// Check that the object is a boolean.
__ CompareRoot(rdx, Heap::kTrueValueRootIndex);
__ j(equal, &fast);
__ CompareRoot(rdx, Heap::kFalseValueRootIndex);
__ j(not_equal, &miss);
__ bind(&fast);
// Check that the maps starting from the prototype haven't changed.
GenerateDirectLoadGlobalFunctionPrototype(
masm(), Context::BOOLEAN_FUNCTION_INDEX, rax, &miss);
CheckPrototypes(JSObject::cast(object->GetPrototype()), rax, holder,
rbx, rdx, rdi, name, &miss);
}
break;
}
default:
UNREACHABLE();
}
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(function, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
// Handle call cache miss.
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(function);
}
MaybeObject* CallStubCompiler::CompileCallInterceptor(JSObject* object,
JSObject* holder,
String* name) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
Label miss;
GenerateNameCheck(name, &miss);
// Get the number of arguments.
const int argc = arguments().immediate();
LookupResult lookup;
LookupPostInterceptor(holder, name, &lookup);
// Get the receiver from the stack.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
CallInterceptorCompiler compiler(this, arguments(), rcx, extra_ic_state_);
MaybeObject* result = compiler.Compile(masm(),
object,
holder,
name,
&lookup,
rdx,
rbx,
rdi,
rax,
&miss);
if (result->IsFailure()) return result;
// Restore receiver.
__ movq(rdx, Operand(rsp, (argc + 1) * kPointerSize));
// Check that the function really is a function.
__ JumpIfSmi(rax, &miss);
__ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
__ j(not_equal, &miss);
// Patch the receiver on the stack with the global proxy if
// necessary.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
// Invoke the function.
__ movq(rdi, rax);
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
__ InvokeFunction(rdi, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
// Handle load cache miss.
__ bind(&miss);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* CallStubCompiler::CompileCallGlobal(JSObject* object,
GlobalObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
// ----------- S t a t e -------------
// rcx : function name
// rsp[0] : return address
// rsp[8] : argument argc
// rsp[16] : argument argc - 1
// ...
// rsp[argc * 8] : argument 1
// rsp[(argc + 1) * 8] : argument 0 = receiver
// -----------------------------------
if (HasCustomCallGenerator(function)) {
MaybeObject* maybe_result = CompileCustomCall(
object, holder, cell, function, name);
Object* result;
if (!maybe_result->ToObject(&result)) return maybe_result;
// undefined means bail out to regular compiler.
if (!result->IsUndefined()) return result;
}
Label miss;
GenerateNameCheck(name, &miss);
// Get the number of arguments.
const int argc = arguments().immediate();
GenerateGlobalReceiverCheck(object, holder, name, &miss);
GenerateLoadFunctionFromCell(cell, function, &miss);
// Patch the receiver on the stack with the global proxy.
if (object->IsGlobalObject()) {
__ movq(rdx, FieldOperand(rdx, GlobalObject::kGlobalReceiverOffset));
__ movq(Operand(rsp, (argc + 1) * kPointerSize), rdx);
}
// Setup the context (function already in rdi).
__ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// Jump to the cached code (tail call).
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->call_global_inline(), 1);
ASSERT(function->is_compiled());
ParameterCount expected(function->shared()->formal_parameter_count());
CallKind call_kind = CallICBase::Contextual::decode(extra_ic_state_)
? CALL_AS_FUNCTION
: CALL_AS_METHOD;
if (V8::UseCrankshaft()) {
// TODO(kasperl): For now, we always call indirectly through the
// code field in the function to allow recompilation to take effect
// without changing any of the call sites.
__ movq(rdx, FieldOperand(rdi, JSFunction::kCodeEntryOffset));
__ InvokeCode(rdx, expected, arguments(), JUMP_FUNCTION,
NullCallWrapper(), call_kind);
} else {
Handle<Code> code(function->code());
__ InvokeCode(code, expected, arguments(),
RelocInfo::CODE_TARGET, JUMP_FUNCTION,
NullCallWrapper(), call_kind);
}
// Handle call cache miss.
__ bind(&miss);
__ IncrementCounter(counters->call_global_inline_miss(), 1);
MaybeObject* maybe_result = GenerateMissBranch();
if (maybe_result->IsFailure()) return maybe_result;
// Return the generated code.
return GetCode(NORMAL, name);
}
MaybeObject* StoreStubCompiler::CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Generate store field code. Preserves receiver and name on jump to miss.
GenerateStoreField(masm(),
object,
index,
transition,
rdx, rcx, rbx,
&miss);
// Handle store cache miss.
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(transition == NULL ? FIELD : MAP_TRANSITION, name);
}
MaybeObject* StoreStubCompiler::CompileStoreCallback(JSObject* object,
AccessorInfo* callback,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that the object isn't a smi.
__ JumpIfSmi(rdx, &miss);
// Check that the map of the object hasn't changed.
__ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
Handle<Map>(object->map()));
__ j(not_equal, &miss);
// Perform global security token check if needed.
if (object->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(rdx, rbx, &miss);
}
// Stub never generated for non-global objects that require access
// checks.
ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
__ pop(rbx); // remove the return address
__ push(rdx); // receiver
__ Push(Handle<AccessorInfo>(callback)); // callback info
__ push(rcx); // name
__ push(rax); // value
__ push(rbx); // restore return address
// Do tail-call to the runtime system.
ExternalReference store_callback_property =
ExternalReference(IC_Utility(IC::kStoreCallbackProperty), isolate());
__ TailCallExternalReference(store_callback_property, 4, 1);
// Handle store cache miss.
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* StoreStubCompiler::CompileStoreInterceptor(JSObject* receiver,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that the object isn't a smi.
__ JumpIfSmi(rdx, &miss);
// Check that the map of the object hasn't changed.
__ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
Handle<Map>(receiver->map()));
__ j(not_equal, &miss);
// Perform global security token check if needed.
if (receiver->IsJSGlobalProxy()) {
__ CheckAccessGlobalProxy(rdx, rbx, &miss);
}
// Stub never generated for non-global objects that require access
// checks.
ASSERT(receiver->IsJSGlobalProxy() || !receiver->IsAccessCheckNeeded());
__ pop(rbx); // remove the return address
__ push(rdx); // receiver
__ push(rcx); // name
__ push(rax); // value
__ Push(Smi::FromInt(strict_mode_));
__ push(rbx); // restore return address
// Do tail-call to the runtime system.
ExternalReference store_ic_property =
ExternalReference(IC_Utility(IC::kStoreInterceptorProperty), isolate());
__ TailCallExternalReference(store_ic_property, 4, 1);
// Handle store cache miss.
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* StoreStubCompiler::CompileStoreGlobal(GlobalObject* object,
JSGlobalPropertyCell* cell,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : name
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that the map of the global has not changed.
__ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
Handle<Map>(object->map()));
__ j(not_equal, &miss);
// Compute the cell operand to use.
__ Move(rbx, Handle<JSGlobalPropertyCell>(cell));
Operand cell_operand = FieldOperand(rbx, JSGlobalPropertyCell::kValueOffset);
// Check that the value in the cell is not the hole. If it is, this
// cell could have been deleted and reintroducing the global needs
// to update the property details in the property dictionary of the
// global object. We bail out to the runtime system to do that.
__ CompareRoot(cell_operand, Heap::kTheHoleValueRootIndex);
__ j(equal, &miss);
// Store the value in the cell.
__ movq(cell_operand, rax);
Label done;
__ JumpIfSmi(rax, &done);
__ movq(rcx, rax);
__ lea(rdx, cell_operand);
// Cells are always in the remembered set.
__ RecordWrite(rbx, // Object.
rdx, // Address.
rcx, // Value.
kDontSaveFPRegs,
OMIT_REMEMBERED_SET,
OMIT_SMI_CHECK);
// Return the value (register rax).
__ bind(&done);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->named_store_global_inline(), 1);
__ ret(0);
// Handle store cache miss.
__ bind(&miss);
__ IncrementCounter(counters->named_store_global_inline_miss(), 1);
Handle<Code> ic = isolate()->builtins()->StoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, name);
}
MaybeObject* KeyedStoreStubCompiler::CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_store_field(), 1);
// Check that the name has not changed.
__ Cmp(rcx, Handle<String>(name));
__ j(not_equal, &miss);
// Generate store field code. Preserves receiver and name on jump to miss.
GenerateStoreField(masm(),
object,
index,
transition,
rdx, rcx, rbx,
&miss);
// Handle store cache miss.
__ bind(&miss);
__ DecrementCounter(counters->keyed_store_field(), 1);
Handle<Code> ic = isolate()->builtins()->KeyedStoreIC_Miss();
__ Jump(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(transition == NULL ? FIELD : MAP_TRANSITION, name);
}
MaybeObject* KeyedStoreStubCompiler::CompileStoreElement(Map* receiver_map) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Code* stub;
ElementsKind elements_kind = receiver_map->elements_kind();
bool is_js_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
MaybeObject* maybe_stub =
KeyedStoreElementStub(is_js_array, elements_kind).TryGetCode();
if (!maybe_stub->To(&stub)) return maybe_stub;
__ DispatchMap(rdx,
Handle<Map>(receiver_map),
Handle<Code>(stub),
DO_SMI_CHECK);
Handle<Code> ic = isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, NULL);
}
MaybeObject* KeyedStoreStubCompiler::CompileStorePolymorphic(
MapList* receiver_maps,
CodeList* handler_stubs,
MapList* transitioned_maps) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
__ JumpIfSmi(rdx, &miss, Label::kNear);
__ movq(rdi, FieldOperand(rdx, HeapObject::kMapOffset));
int receiver_count = receiver_maps->length();
for (int i = 0; i < receiver_count; ++i) {
// Check map and tail call if there's a match
Handle<Map> map(receiver_maps->at(i));
__ Cmp(rdi, map);
if (transitioned_maps->at(i) == NULL) {
__ j(equal, Handle<Code>(handler_stubs->at(i)), RelocInfo::CODE_TARGET);
} else {
Label next_map;
__ j(not_equal, &next_map, Label::kNear);
__ movq(rbx,
Handle<Map>(transitioned_maps->at(i)),
RelocInfo::EMBEDDED_OBJECT);
__ jmp(Handle<Code>(handler_stubs->at(i)), RelocInfo::CODE_TARGET);
__ bind(&next_map);
}
}
__ bind(&miss);
Handle<Code> ic = isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, NULL, MEGAMORPHIC);
}
MaybeObject* LoadStubCompiler::CompileLoadNonexistent(String* name,
JSObject* object,
JSObject* last) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// Check that receiver is not a smi.
__ JumpIfSmi(rax, &miss);
// Check the maps of the full prototype chain. Also check that
// global property cells up to (but not including) the last object
// in the prototype chain are empty.
CheckPrototypes(object, rax, last, rbx, rdx, rdi, name, &miss);
// If the last object in the prototype chain is a global object,
// check that the global property cell is empty.
if (last->IsGlobalObject()) {
MaybeObject* cell = GenerateCheckPropertyCell(masm(),
GlobalObject::cast(last),
name,
rdx,
&miss);
if (cell->IsFailure()) {
miss.Unuse();
return cell;
}
}
// Return undefined if maps of the full prototype chain are still the
// same and no global property with this name contains a value.
__ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
__ ret(0);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(NONEXISTENT, heap()->empty_string());
}
MaybeObject* LoadStubCompiler::CompileLoadField(JSObject* object,
JSObject* holder,
int index,
String* name) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
GenerateLoadField(object, holder, rax, rbx, rdx, rdi, index, name, &miss);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(FIELD, name);
}
MaybeObject* LoadStubCompiler::CompileLoadCallback(String* name,
JSObject* object,
JSObject* holder,
AccessorInfo* callback) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
MaybeObject* result = GenerateLoadCallback(object, holder, rax, rcx, rdx, rbx,
rdi, callback, name, &miss);
if (result->IsFailure()) {
miss.Unuse();
return result;
}
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* LoadStubCompiler::CompileLoadConstant(JSObject* object,
JSObject* holder,
Object* value,
String* name) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
GenerateLoadConstant(object, holder, rax, rbx, rdx, rdi, value, name, &miss);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(CONSTANT_FUNCTION, name);
}
MaybeObject* LoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
JSObject* holder,
String* name) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
LookupResult lookup;
LookupPostInterceptor(holder, name, &lookup);
// TODO(368): Compile in the whole chain: all the interceptors in
// prototypes and ultimate answer.
GenerateLoadInterceptor(receiver,
holder,
&lookup,
rax,
rcx,
rdx,
rbx,
rdi,
name,
&miss);
__ bind(&miss);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* LoadStubCompiler::CompileLoadGlobal(JSObject* object,
GlobalObject* holder,
JSGlobalPropertyCell* cell,
String* name,
bool is_dont_delete) {
// ----------- S t a t e -------------
// -- rax : receiver
// -- rcx : name
// -- rsp[0] : return address
// -----------------------------------
Label miss;
// If the object is the holder then we know that it's a global
// object which can only happen for contextual loads. In this case,
// the receiver cannot be a smi.
if (object != holder) {
__ JumpIfSmi(rax, &miss);
}
// Check that the maps haven't changed.
CheckPrototypes(object, rax, holder, rbx, rdx, rdi, name, &miss);
// Get the value from the cell.
__ Move(rbx, Handle<JSGlobalPropertyCell>(cell));
__ movq(rbx, FieldOperand(rbx, JSGlobalPropertyCell::kValueOffset));
// Check for deleted property if property can actually be deleted.
if (!is_dont_delete) {
__ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
__ j(equal, &miss);
} else if (FLAG_debug_code) {
__ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
__ Check(not_equal, "DontDelete cells can't contain the hole");
}
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->named_load_global_stub(), 1);
__ movq(rax, rbx);
__ ret(0);
__ bind(&miss);
__ IncrementCounter(counters->named_load_global_stub_miss(), 1);
GenerateLoadMiss(masm(), Code::LOAD_IC);
// Return the generated code.
return GetCode(NORMAL, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadField(String* name,
JSObject* receiver,
JSObject* holder,
int index) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_field(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadField(receiver, holder, rdx, rbx, rcx, rdi, index, name, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_field(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(FIELD, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadCallback(
String* name,
JSObject* receiver,
JSObject* holder,
AccessorInfo* callback) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_callback(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
MaybeObject* result = GenerateLoadCallback(receiver, holder, rdx, rax, rbx,
rcx, rdi, callback, name, &miss);
if (result->IsFailure()) {
miss.Unuse();
return result;
}
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_callback(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadConstant(String* name,
JSObject* receiver,
JSObject* holder,
Object* value) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_constant_function(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadConstant(receiver, holder, rdx, rbx, rcx, rdi,
value, name, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_constant_function(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CONSTANT_FUNCTION, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
JSObject* holder,
String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_interceptor(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
LookupResult lookup;
LookupPostInterceptor(holder, name, &lookup);
GenerateLoadInterceptor(receiver,
holder,
&lookup,
rdx,
rax,
rcx,
rbx,
rdi,
name,
&miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_interceptor(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(INTERCEPTOR, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadArrayLength(String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_array_length(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadArrayLength(masm(), rdx, rcx, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_array_length(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadStringLength(String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_string_length(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadStringLength(masm(), rdx, rcx, rbx, &miss, true);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_string_length(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadFunctionPrototype(String* name) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->keyed_load_function_prototype(), 1);
// Check that the name has not changed.
__ Cmp(rax, Handle<String>(name));
__ j(not_equal, &miss);
GenerateLoadFunctionPrototype(masm(), rdx, rcx, rbx, &miss);
__ bind(&miss);
__ DecrementCounter(counters->keyed_load_function_prototype(), 1);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(CALLBACKS, name);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadElement(Map* receiver_map) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Code* stub;
ElementsKind elements_kind = receiver_map->elements_kind();
MaybeObject* maybe_stub = KeyedLoadElementStub(elements_kind).TryGetCode();
if (!maybe_stub->To(&stub)) return maybe_stub;
__ DispatchMap(rdx,
Handle<Map>(receiver_map),
Handle<Code>(stub),
DO_SMI_CHECK);
Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Miss();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode(NORMAL, NULL);
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadPolymorphic(
MapList* receiver_maps,
CodeList* handler_ics) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss;
__ JumpIfSmi(rdx, &miss);
Register map_reg = rbx;
__ movq(map_reg, FieldOperand(rdx, HeapObject::kMapOffset));
int receiver_count = receiver_maps->length();
for (int current = 0; current < receiver_count; ++current) {
// Check map and tail call if there's a match
Handle<Map> map(receiver_maps->at(current));
__ Cmp(map_reg, map);
__ j(equal,
Handle<Code>(handler_ics->at(current)),
RelocInfo::CODE_TARGET);
}
__ bind(&miss);
GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);
// Return the generated code.
return GetCode(NORMAL, NULL, MEGAMORPHIC);
}
// Specialized stub for constructing objects from functions which only have only
// simple assignments of the form this.x = ...; in their body.
MaybeObject* ConstructStubCompiler::CompileConstructStub(JSFunction* function) {
// ----------- S t a t e -------------
// -- rax : argc
// -- rdi : constructor
// -- rsp[0] : return address
// -- rsp[4] : last argument
// -----------------------------------
Label generic_stub_call;
// Use r8 for holding undefined which is used in several places below.
__ Move(r8, factory()->undefined_value());
#ifdef ENABLE_DEBUGGER_SUPPORT
// Check to see whether there are any break points in the function code. If
// there are jump to the generic constructor stub which calls the actual
// code for the function thereby hitting the break points.
__ movq(rbx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ movq(rbx, FieldOperand(rbx, SharedFunctionInfo::kDebugInfoOffset));
__ cmpq(rbx, r8);
__ j(not_equal, &generic_stub_call);
#endif
// Load the initial map and verify that it is in fact a map.
__ movq(rbx, FieldOperand(rdi, JSFunction::kPrototypeOrInitialMapOffset));
// Will both indicate a NULL and a Smi.
STATIC_ASSERT(kSmiTag == 0);
__ JumpIfSmi(rbx, &generic_stub_call);
__ CmpObjectType(rbx, MAP_TYPE, rcx);
__ j(not_equal, &generic_stub_call);
#ifdef DEBUG
// Cannot construct functions this way.
// rdi: constructor
// rbx: initial map
__ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
__ Assert(not_equal, "Function constructed by construct stub.");
#endif
// Now allocate the JSObject in new space.
// rdi: constructor
// rbx: initial map
__ movzxbq(rcx, FieldOperand(rbx, Map::kInstanceSizeOffset));
__ shl(rcx, Immediate(kPointerSizeLog2));
__ AllocateInNewSpace(rcx,
rdx,
rcx,
no_reg,
&generic_stub_call,
NO_ALLOCATION_FLAGS);
// Allocated the JSObject, now initialize the fields and add the heap tag.
// rbx: initial map
// rdx: JSObject (untagged)
__ movq(Operand(rdx, JSObject::kMapOffset), rbx);
__ Move(rbx, factory()->empty_fixed_array());
__ movq(Operand(rdx, JSObject::kPropertiesOffset), rbx);
__ movq(Operand(rdx, JSObject::kElementsOffset), rbx);
// rax: argc
// rdx: JSObject (untagged)
// Load the address of the first in-object property into r9.
__ lea(r9, Operand(rdx, JSObject::kHeaderSize));
// Calculate the location of the first argument. The stack contains only the
// return address on top of the argc arguments.
__ lea(rcx, Operand(rsp, rax, times_pointer_size, 0));
// rax: argc
// rcx: first argument
// rdx: JSObject (untagged)
// r8: undefined
// r9: first in-object property of the JSObject
// Fill the initialized properties with a constant value or a passed argument
// depending on the this.x = ...; assignment in the function.
SharedFunctionInfo* shared = function->shared();
for (int i = 0; i < shared->this_property_assignments_count(); i++) {
if (shared->IsThisPropertyAssignmentArgument(i)) {
// Check if the argument assigned to the property is actually passed.
// If argument is not passed the property is set to undefined,
// otherwise find it on the stack.
int arg_number = shared->GetThisPropertyAssignmentArgument(i);
__ movq(rbx, r8);
__ cmpq(rax, Immediate(arg_number));
__ cmovq(above, rbx, Operand(rcx, arg_number * -kPointerSize));
// Store value in the property.
__ movq(Operand(r9, i * kPointerSize), rbx);
} else {
// Set the property to the constant value.
Handle<Object> constant(shared->GetThisPropertyAssignmentConstant(i));
__ Move(Operand(r9, i * kPointerSize), constant);
}
}
// Fill the unused in-object property fields with undefined.
ASSERT(function->has_initial_map());
for (int i = shared->this_property_assignments_count();
i < function->initial_map()->inobject_properties();
i++) {
__ movq(Operand(r9, i * kPointerSize), r8);
}
// rax: argc
// rdx: JSObject (untagged)
// Move argc to rbx and the JSObject to return to rax and tag it.
__ movq(rbx, rax);
__ movq(rax, rdx);
__ or_(rax, Immediate(kHeapObjectTag));
// rax: JSObject
// rbx: argc
// Remove caller arguments and receiver from the stack and return.
__ pop(rcx);
__ lea(rsp, Operand(rsp, rbx, times_pointer_size, 1 * kPointerSize));
__ push(rcx);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->constructed_objects(), 1);
__ IncrementCounter(counters->constructed_objects_stub(), 1);
__ ret(0);
// Jump to the generic stub in case the specialized code cannot handle the
// construction.
__ bind(&generic_stub_call);
Code* code =
isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
Handle<Code> generic_construct_stub(code);
__ Jump(generic_construct_stub, RelocInfo::CODE_TARGET);
// Return the generated code.
return GetCode();
}
#undef __
#define __ ACCESS_MASM(masm)
void KeyedLoadStubCompiler::GenerateLoadDictionaryElement(
MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label slow, miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
__ SmiToInteger32(rbx, rax);
__ movq(rcx, FieldOperand(rdx, JSObject::kElementsOffset));
// Check whether the elements is a number dictionary.
// rdx: receiver
// rax: key
// rbx: key as untagged int32
// rcx: elements
__ LoadFromNumberDictionary(&slow, rcx, rax, rbx, r9, rdi, rax);
__ ret(0);
__ bind(&slow);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> slow_ic =
masm->isolate()->builtins()->KeyedLoadIC_Slow();
__ jmp(slow_ic, RelocInfo::CODE_TARGET);
__ bind(&miss_force_generic);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedLoadIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedLoadStubCompiler::GenerateLoadExternalArray(
MacroAssembler* masm,
ElementsKind elements_kind) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label slow, miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
// Check that the index is in range.
__ movq(rbx, FieldOperand(rdx, JSObject::kElementsOffset));
__ SmiToInteger32(rcx, rax);
__ cmpq(rax, FieldOperand(rbx, ExternalArray::kLengthOffset));
// Unsigned comparison catches both negative and too-large values.
__ j(above_equal, &miss_force_generic);
// rax: index (as a smi)
// rdx: receiver (JSObject)
// rcx: untagged index
// rbx: elements array
__ movq(rbx, FieldOperand(rbx, ExternalArray::kExternalPointerOffset));
// rbx: base pointer of external storage
switch (elements_kind) {
case EXTERNAL_BYTE_ELEMENTS:
__ movsxbq(rcx, Operand(rbx, rcx, times_1, 0));
break;
case EXTERNAL_PIXEL_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ movzxbq(rcx, Operand(rbx, rcx, times_1, 0));
break;
case EXTERNAL_SHORT_ELEMENTS:
__ movsxwq(rcx, Operand(rbx, rcx, times_2, 0));
break;
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ movzxwq(rcx, Operand(rbx, rcx, times_2, 0));
break;
case EXTERNAL_INT_ELEMENTS:
__ movsxlq(rcx, Operand(rbx, rcx, times_4, 0));
break;
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
__ movl(rcx, Operand(rbx, rcx, times_4, 0));
break;
case EXTERNAL_FLOAT_ELEMENTS:
__ cvtss2sd(xmm0, Operand(rbx, rcx, times_4, 0));
break;
case EXTERNAL_DOUBLE_ELEMENTS:
__ movsd(xmm0, Operand(rbx, rcx, times_8, 0));
break;
default:
UNREACHABLE();
break;
}
// rax: index
// rdx: receiver
// For integer array types:
// rcx: value
// For floating-point array type:
// xmm0: value as double.
ASSERT(kSmiValueSize == 32);
if (elements_kind == EXTERNAL_UNSIGNED_INT_ELEMENTS) {
// For the UnsignedInt array type, we need to see whether
// the value can be represented in a Smi. If not, we need to convert
// it to a HeapNumber.
Label box_int;
__ JumpIfUIntNotValidSmiValue(rcx, &box_int, Label::kNear);
__ Integer32ToSmi(rax, rcx);
__ ret(0);
__ bind(&box_int);
// Allocate a HeapNumber for the int and perform int-to-double
// conversion.
// The value is zero-extended since we loaded the value from memory
// with movl.
__ cvtqsi2sd(xmm0, rcx);
__ AllocateHeapNumber(rcx, rbx, &slow);
// Set the value.
__ movsd(FieldOperand(rcx, HeapNumber::kValueOffset), xmm0);
__ movq(rax, rcx);
__ ret(0);
} else if (elements_kind == EXTERNAL_FLOAT_ELEMENTS ||
elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
// For the floating-point array type, we need to always allocate a
// HeapNumber.
__ AllocateHeapNumber(rcx, rbx, &slow);
// Set the value.
__ movsd(FieldOperand(rcx, HeapNumber::kValueOffset), xmm0);
__ movq(rax, rcx);
__ ret(0);
} else {
__ Integer32ToSmi(rax, rcx);
__ ret(0);
}
// Slow case: Jump to runtime.
__ bind(&slow);
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->keyed_load_external_array_slow(), 1);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> ic = masm->isolate()->builtins()->KeyedLoadIC_Slow();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Miss case: Jump to runtime.
__ bind(&miss_force_generic);
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedLoadIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedStoreStubCompiler::GenerateStoreExternalArray(
MacroAssembler* masm,
ElementsKind elements_kind) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label slow, miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rcx, &miss_force_generic);
// Check that the index is in range.
__ movq(rbx, FieldOperand(rdx, JSObject::kElementsOffset));
__ SmiToInteger32(rdi, rcx); // Untag the index.
__ cmpq(rcx, FieldOperand(rbx, ExternalArray::kLengthOffset));
// Unsigned comparison catches both negative and too-large values.
__ j(above_equal, &miss_force_generic);
// Handle both smis and HeapNumbers in the fast path. Go to the
// runtime for all other kinds of values.
// rax: value
// rcx: key (a smi)
// rdx: receiver (a JSObject)
// rbx: elements array
// rdi: untagged key
Label check_heap_number;
if (elements_kind == EXTERNAL_PIXEL_ELEMENTS) {
// Float to pixel conversion is only implemented in the runtime for now.
__ JumpIfNotSmi(rax, &slow);
} else {
__ JumpIfNotSmi(rax, &check_heap_number, Label::kNear);
}
// No more branches to slow case on this path. Key and receiver not needed.
__ SmiToInteger32(rdx, rax);
__ movq(rbx, FieldOperand(rbx, ExternalArray::kExternalPointerOffset));
// rbx: base pointer of external storage
switch (elements_kind) {
case EXTERNAL_PIXEL_ELEMENTS:
{ // Clamp the value to [0..255].
Label done;
__ testl(rdx, Immediate(0xFFFFFF00));
__ j(zero, &done, Label::kNear);
__ setcc(negative, rdx); // 1 if negative, 0 if positive.
__ decb(rdx); // 0 if negative, 255 if positive.
__ bind(&done);
}
__ movb(Operand(rbx, rdi, times_1, 0), rdx);
break;
case EXTERNAL_BYTE_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ movb(Operand(rbx, rdi, times_1, 0), rdx);
break;
case EXTERNAL_SHORT_ELEMENTS:
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ movw(Operand(rbx, rdi, times_2, 0), rdx);
break;
case EXTERNAL_INT_ELEMENTS:
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
__ movl(Operand(rbx, rdi, times_4, 0), rdx);
break;
case EXTERNAL_FLOAT_ELEMENTS:
// Need to perform int-to-float conversion.
__ cvtlsi2ss(xmm0, rdx);
__ movss(Operand(rbx, rdi, times_4, 0), xmm0);
break;
case EXTERNAL_DOUBLE_ELEMENTS:
// Need to perform int-to-float conversion.
__ cvtlsi2sd(xmm0, rdx);
__ movsd(Operand(rbx, rdi, times_8, 0), xmm0);
break;
case FAST_ELEMENTS:
case FAST_SMI_ONLY_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
UNREACHABLE();
break;
}
__ ret(0);
// TODO(danno): handle heap number -> pixel array conversion
if (elements_kind != EXTERNAL_PIXEL_ELEMENTS) {
__ bind(&check_heap_number);
// rax: value
// rcx: key (a smi)
// rdx: receiver (a JSObject)
// rbx: elements array
// rdi: untagged key
__ CmpObjectType(rax, HEAP_NUMBER_TYPE, kScratchRegister);
__ j(not_equal, &slow);
// No more branches to slow case on this path.
// The WebGL specification leaves the behavior of storing NaN and
// +/-Infinity into integer arrays basically undefined. For more
// reproducible behavior, convert these to zero.
__ movsd(xmm0, FieldOperand(rax, HeapNumber::kValueOffset));
__ movq(rbx, FieldOperand(rbx, ExternalArray::kExternalPointerOffset));
// rdi: untagged index
// rbx: base pointer of external storage
// top of FPU stack: value
if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
__ cvtsd2ss(xmm0, xmm0);
__ movss(Operand(rbx, rdi, times_4, 0), xmm0);
__ ret(0);
} else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
__ movsd(Operand(rbx, rdi, times_8, 0), xmm0);
__ ret(0);
} else {
// Perform float-to-int conversion with truncation (round-to-zero)
// behavior.
// Convert to int32 and store the low byte/word.
// If the value is NaN or +/-infinity, the result is 0x80000000,
// which is automatically zero when taken mod 2^n, n < 32.
// rdx: value (converted to an untagged integer)
// rdi: untagged index
// rbx: base pointer of external storage
switch (elements_kind) {
case EXTERNAL_BYTE_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ cvttsd2si(rdx, xmm0);
__ movb(Operand(rbx, rdi, times_1, 0), rdx);
break;
case EXTERNAL_SHORT_ELEMENTS:
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ cvttsd2si(rdx, xmm0);
__ movw(Operand(rbx, rdi, times_2, 0), rdx);
break;
case EXTERNAL_INT_ELEMENTS:
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
// Convert to int64, so that NaN and infinities become
// 0x8000000000000000, which is zero mod 2^32.
__ cvttsd2siq(rdx, xmm0);
__ movl(Operand(rbx, rdi, times_4, 0), rdx);
break;
case EXTERNAL_PIXEL_ELEMENTS:
case EXTERNAL_FLOAT_ELEMENTS:
case EXTERNAL_DOUBLE_ELEMENTS:
case FAST_ELEMENTS:
case FAST_SMI_ONLY_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
UNREACHABLE();
break;
}
__ ret(0);
}
}
// Slow case: call runtime.
__ bind(&slow);
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> ic = masm->isolate()->builtins()->KeyedStoreIC_Slow();
__ jmp(ic, RelocInfo::CODE_TARGET);
// Miss case: call runtime.
__ bind(&miss_force_generic);
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedStoreIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedLoadStubCompiler::GenerateLoadFastElement(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
// Get the elements array.
__ movq(rcx, FieldOperand(rdx, JSObject::kElementsOffset));
__ AssertFastElements(rcx);
// Check that the key is within bounds.
__ SmiCompare(rax, FieldOperand(rcx, FixedArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
// Load the result and make sure it's not the hole.
SmiIndex index = masm->SmiToIndex(rbx, rax, kPointerSizeLog2);
__ movq(rbx, FieldOperand(rcx,
index.reg,
index.scale,
FixedArray::kHeaderSize));
__ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
__ j(equal, &miss_force_generic);
__ movq(rax, rbx);
__ ret(0);
__ bind(&miss_force_generic);
Code* code = masm->isolate()->builtins()->builtin(
Builtins::kKeyedLoadIC_MissForceGeneric);
Handle<Code> ic(code);
__ jmp(ic, RelocInfo::CODE_TARGET);
}
void KeyedLoadStubCompiler::GenerateLoadFastDoubleElement(
MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic, slow_allocate_heapnumber;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rax, &miss_force_generic);
// Get the elements array.
__ movq(rcx, FieldOperand(rdx, JSObject::kElementsOffset));
__ AssertFastElements(rcx);
// Check that the key is within bounds.
__ SmiCompare(rax, FieldOperand(rcx, FixedArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
// Check for the hole
__ SmiToInteger32(kScratchRegister, rax);
uint32_t offset = FixedDoubleArray::kHeaderSize + sizeof(kHoleNanLower32);
__ cmpl(FieldOperand(rcx, kScratchRegister, times_8, offset),
Immediate(kHoleNanUpper32));
__ j(equal, &miss_force_generic);
// Always allocate a heap number for the result.
__ movsd(xmm0, FieldOperand(rcx, kScratchRegister, times_8,
FixedDoubleArray::kHeaderSize));
__ AllocateHeapNumber(rcx, rbx, &slow_allocate_heapnumber);
// Set the value.
__ movq(rax, rcx);
__ movsd(FieldOperand(rcx, HeapNumber::kValueOffset), xmm0);
__ ret(0);
__ bind(&slow_allocate_heapnumber);
Handle<Code> slow_ic =
masm->isolate()->builtins()->KeyedLoadIC_Slow();
__ jmp(slow_ic, RelocInfo::CODE_TARGET);
__ bind(&miss_force_generic);
Handle<Code> miss_ic =
masm->isolate()->builtins()->KeyedLoadIC_MissForceGeneric();
__ jmp(miss_ic, RelocInfo::CODE_TARGET);
}
void KeyedStoreStubCompiler::GenerateStoreFastElement(
MacroAssembler* masm,
bool is_js_array,
ElementsKind elements_kind) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic, transition_elements_kind;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rcx, &miss_force_generic);
// Get the elements array and make sure it is a fast element array, not 'cow'.
__ movq(rdi, FieldOperand(rdx, JSObject::kElementsOffset));
__ CompareRoot(FieldOperand(rdi, HeapObject::kMapOffset),
Heap::kFixedArrayMapRootIndex);
__ j(not_equal, &miss_force_generic);
// Check that the key is within bounds.
if (is_js_array) {
__ SmiCompare(rcx, FieldOperand(rdx, JSArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
} else {
__ SmiCompare(rcx, FieldOperand(rdi, FixedArray::kLengthOffset));
__ j(above_equal, &miss_force_generic);
}
if (elements_kind == FAST_SMI_ONLY_ELEMENTS) {
__ JumpIfNotSmi(rax, &transition_elements_kind);
__ SmiToInteger32(rcx, rcx);
__ movq(FieldOperand(rdi, rcx, times_pointer_size, FixedArray::kHeaderSize),
rax);
} else {
// Do the store and update the write barrier.
ASSERT(elements_kind == FAST_ELEMENTS);
__ SmiToInteger32(rcx, rcx);
__ lea(rcx,
FieldOperand(rdi, rcx, times_pointer_size, FixedArray::kHeaderSize));
__ movq(Operand(rcx, 0), rax);
// Make sure to preserve the value in register rax.
__ movq(rdx, rax);
__ RecordWrite(rdi, rcx, rdx, kDontSaveFPRegs);
}
// Done.
__ ret(0);
// Handle store cache miss.
__ bind(&miss_force_generic);
Handle<Code> ic_force_generic =
masm->isolate()->builtins()->KeyedStoreIC_MissForceGeneric();
__ jmp(ic_force_generic, RelocInfo::CODE_TARGET);
__ bind(&transition_elements_kind);
Handle<Code> ic_miss = masm->isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic_miss, RelocInfo::CODE_TARGET);
}
void KeyedStoreStubCompiler::GenerateStoreFastDoubleElement(
MacroAssembler* masm,
bool is_js_array) {
// ----------- S t a t e -------------
// -- rax : value
// -- rcx : key
// -- rdx : receiver
// -- rsp[0] : return address
// -----------------------------------
Label miss_force_generic, transition_elements_kind;
// This stub is meant to be tail-jumped to, the receiver must already
// have been verified by the caller to not be a smi.
// Check that the key is a smi.
__ JumpIfNotSmi(rcx, &miss_force_generic);
// Get the elements array.
__ movq(rdi, FieldOperand(rdx, JSObject::kElementsOffset));
__ AssertFastElements(rdi);
// Check that the key is within bounds.
if (is_js_array) {
__ SmiCompare(rcx, FieldOperand(rdx, JSArray::kLengthOffset));
} else {
__ SmiCompare(rcx, FieldOperand(rdi, FixedDoubleArray::kLengthOffset));
}
__ j(above_equal, &miss_force_generic);
// Handle smi values specially
__ SmiToInteger32(rcx, rcx);
__ StoreNumberToDoubleElements(rax, rdi, rcx, xmm0,
&transition_elements_kind);
__ ret(0);
// Handle store cache miss, replacing the ic with the generic stub.
__ bind(&miss_force_generic);
Handle<Code> ic_force_generic =
masm->isolate()->builtins()->KeyedStoreIC_MissForceGeneric();
__ jmp(ic_force_generic, RelocInfo::CODE_TARGET);
__ bind(&transition_elements_kind);
// Restore smi-tagging of rcx.
__ Integer32ToSmi(rcx, rcx);
Handle<Code> ic_miss = masm->isolate()->builtins()->KeyedStoreIC_Miss();
__ jmp(ic_miss, RelocInfo::CODE_TARGET);
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_X64
|
/*
SWARM
Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe
This program 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.
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/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
uint64_t arch_get_memused()
{
#ifdef _WIN32
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo(GetCurrentProcess(),
&pmc,
sizeof(PROCESS_MEMORY_COUNTERS));
return pmc.PeakWorkingSetSize;
#else
struct rusage r_usage;
getrusage(RUSAGE_SELF, & r_usage);
# ifdef __APPLE__
/* Mac: ru_maxrss gives the size in bytes */
return static_cast<uint64_t>(r_usage.ru_maxrss);
# else
/* Linux: ru_maxrss gives the size in kilobytes */
return static_cast<uint64_t>(r_usage.ru_maxrss * 1024);
# endif
#endif
}
uint64_t arch_get_memtotal()
{
#ifdef _WIN32
MEMORYSTATUSEX ms;
ms.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&ms);
return ms.ullTotalPhys;
#elif defined(__APPLE__)
int mib [] = { CTL_HW, HW_MEMSIZE };
int64_t ram = 0;
size_t length = sizeof(ram);
if(sysctl(mib, 2, &ram, &length, nullptr, 0) == -1)
fatal("Cannot determine amount of RAM");
return static_cast<uint64_t>(ram);
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
int64_t phys_pages = sysconf(_SC_PHYS_PAGES);
int64_t pagesize = sysconf(_SC_PAGESIZE);
if ((phys_pages == -1) || (pagesize == -1))
fatal("Cannot determine amount of RAM");
return static_cast<uint64_t>(pagesize * phys_pages);
#else
struct sysinfo si;
if (sysinfo(&si))
fatal("Cannot determine amount of RAM");
return si.totalram * si.mem_unit;
#endif
}
void arch_srandom(unsigned int seed)
{
/* initialize pseudo-random number generator */
if (seed == 0)
{
#ifdef _WIN32
srand(GetTickCount());
#else
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0)
fatal("Unable to open /dev/urandom");
if (read(fd, & seed, sizeof(seed)) < 0)
fatal("Unable to read from /dev/urandom");
close(fd);
srandom(seed);
#endif
}
else
{
#ifdef _WIN32
srand(seed);
#else
srandom(seed);
#endif
}
}
uint64_t arch_random()
{
#ifdef _WIN32
return static_cast<uint64_t>(rand());
#else
return static_cast<uint64_t>(random());
#endif
}
Remove unused code for random seed init
/*
SWARM
Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe
This program 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.
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/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
uint64_t arch_get_memused()
{
#ifdef _WIN32
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo(GetCurrentProcess(),
&pmc,
sizeof(PROCESS_MEMORY_COUNTERS));
return pmc.PeakWorkingSetSize;
#else
struct rusage r_usage;
getrusage(RUSAGE_SELF, & r_usage);
# ifdef __APPLE__
/* Mac: ru_maxrss gives the size in bytes */
return static_cast<uint64_t>(r_usage.ru_maxrss);
# else
/* Linux: ru_maxrss gives the size in kilobytes */
return static_cast<uint64_t>(r_usage.ru_maxrss * 1024);
# endif
#endif
}
uint64_t arch_get_memtotal()
{
#ifdef _WIN32
MEMORYSTATUSEX ms;
ms.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&ms);
return ms.ullTotalPhys;
#elif defined(__APPLE__)
int mib [] = { CTL_HW, HW_MEMSIZE };
int64_t ram = 0;
size_t length = sizeof(ram);
if(sysctl(mib, 2, &ram, &length, nullptr, 0) == -1)
fatal("Cannot determine amount of RAM");
return static_cast<uint64_t>(ram);
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
int64_t phys_pages = sysconf(_SC_PHYS_PAGES);
int64_t pagesize = sysconf(_SC_PAGESIZE);
if ((phys_pages == -1) || (pagesize == -1))
fatal("Cannot determine amount of RAM");
return static_cast<uint64_t>(pagesize * phys_pages);
#else
struct sysinfo si;
if (sysinfo(&si))
fatal("Cannot determine amount of RAM");
return si.totalram * si.mem_unit;
#endif
}
void arch_srandom(unsigned int seed)
{
/* initialize pseudo-random number generator */
#ifdef _WIN32
srand(seed);
#else
srandom(seed);
#endif
}
uint64_t arch_random()
{
#ifdef _WIN32
return static_cast<uint64_t>(rand());
#else
return static_cast<uint64_t>(random());
#endif
}
|
/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* Driver for PseudoSensorOccupancyTracker tests.
*/
#include <stdint.h>
#include <gtest/gtest.h>
#include <OTV0p2Base.h>
#include "OTV0P2BASE_SensorAmbientLightOccupancy.h"
// Basic operation (duration of occupancy from trigger), etc.
TEST(PseudoSensorOccupancyTracker,basics)
{
// Set up default occupancy tracker.
OTV0P2BASE::PseudoSensorOccupancyTracker o1;
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
o1.markAsOccupied();
ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
// Run for half the nominal time and ensure still marked as occupied.
for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2; ++i) { o1.read(); ASSERT_TRUE(o1.isLikelyOccupied()); }
// Run again for about half the nominal time and ensure now not occupied.
for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2 + 1; ++i) { o1.read(); }
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Put in holiday mode; show marked very vacant.
o1.setHolidayMode();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsOccupied() brings status back to occupied.
o1.markAsOccupied();
ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
// Put in holiday mode; show marked very vacant.
o1.setHolidayMode();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsPossiblyOccupied() brings status back to occupied.
o1.markAsPossiblyOccupied();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
// Put in holiday mode; show marked very vacant.
o1.setHolidayMode();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsJustPossiblyOccupied() DOES NOT move status to occupied.
o1.markAsJustPossiblyOccupied();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsJustPossiblyOccupied() does indicate occupancy when system not very torpid.
o1.reset();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
o1.markAsJustPossiblyOccupied();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
}
TODO-1070: WIP
/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* Driver for PseudoSensorOccupancyTracker tests.
*/
#include <stdint.h>
#include <gtest/gtest.h>
#include <OTV0p2Base.h>
#include "OTV0P2BASE_SensorAmbientLightOccupancy.h"
// Basic operation (duration of occupancy from trigger), etc.
TEST(PseudoSensorOccupancyTracker,basics)
{
// Set up default occupancy tracker.
OTV0P2BASE::PseudoSensorOccupancyTracker o1;
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
o1.markAsOccupied();
ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
// Run for half the nominal time and ensure still marked as occupied.
for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2; ++i) { o1.read(); ASSERT_TRUE(o1.isLikelyOccupied()); }
// Run again for about half the nominal time and ensure now not occupied.
for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2 + 1; ++i) { o1.read(); }
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Put in holiday mode; show marked very vacant.
o1.setHolidayMode();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsOccupied() brings status back to occupied.
o1.markAsOccupied();
ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
// Put in holiday mode; show marked very vacant.
o1.setHolidayMode();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsPossiblyOccupied() brings status back to occupied.
o1.markAsPossiblyOccupied();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
// Put in holiday mode; show marked very vacant.
o1.setHolidayMode();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsJustPossiblyOccupied() DOES NOT move status to occupied.
o1.markAsJustPossiblyOccupied();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
// Show that markAsJustPossiblyOccupied() does indicate some occupancy when system not very torpid.
o1.reset();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_FALSE(o1.isLikelyOccupied());
ASSERT_TRUE(o1.isLikelyUnoccupied());
o1.markAsJustPossiblyOccupied();
ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
ASSERT_TRUE(o1.isLikelyOccupied());
ASSERT_FALSE(o1.isLikelyUnoccupied());
}
|
/* Copyright (c) 2010-2012, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include "assembler.h"
#include "vector.h"
#define CAST1(x) reinterpret_cast<UnaryOperationType>(x)
#define CAST2(x) reinterpret_cast<BinaryOperationType>(x)
#define CAST3(x) reinterpret_cast<TernaryOperationType>(x)
#define CAST_BRANCH(x) reinterpret_cast<BranchOperationType>(x)
using namespace vm;
namespace {
namespace isa {
// SYSTEM REGISTERS
const int FPSID = 0x0;
const int FPSCR = 0x1;
const int FPEXC = 0x8;
// INSTRUCTION OPTIONS
enum CONDITION { EQ, NE, CS, CC, MI, PL, VS, VC, HI, LS, GE, LT, GT, LE, AL, NV };
enum SHIFTOP { LSL, LSR, ASR, ROR };
// INSTRUCTION FORMATS
inline int DATA(int cond, int opcode, int S, int Rn, int Rd, int shift, int Sh, int Rm)
{ return cond<<28 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | shift<<7 | Sh<<5 | Rm; }
inline int DATAS(int cond, int opcode, int S, int Rn, int Rd, int Rs, int Sh, int Rm)
{ return cond<<28 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | Rs<<8 | Sh<<5 | 1<<4 | Rm; }
inline int DATAI(int cond, int opcode, int S, int Rn, int Rd, int rot, int imm)
{ return cond<<28 | 1<<25 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | rot<<8 | (imm&0xff); }
inline int BRANCH(int cond, int L, int offset)
{ return cond<<28 | 5<<25 | L<<24 | (offset&0xffffff); }
inline int BRANCHX(int cond, int L, int Rm)
{ return cond<<28 | 0x4bffc<<6 | L<<5 | 1<<4 | Rm; }
inline int MULTIPLY(int cond, int mul, int S, int Rd, int Rn, int Rs, int Rm)
{ return cond<<28 | mul<<21 | S<<20 | Rd<<16 | Rn<<12 | Rs<<8 | 9<<4 | Rm; }
inline int XFER(int cond, int P, int U, int B, int W, int L, int Rn, int Rd, int shift, int Sh, int Rm)
{ return cond<<28 | 3<<25 | P<<24 | U<<23 | B<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | shift<<7 | Sh<<5 | Rm; }
inline int XFERI(int cond, int P, int U, int B, int W, int L, int Rn, int Rd, int offset)
{ return cond<<28 | 2<<25 | P<<24 | U<<23 | B<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | (offset&0xfff); }
inline int XFER2(int cond, int P, int U, int W, int L, int Rn, int Rd, int S, int H, int Rm)
{ return cond<<28 | P<<24 | U<<23 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | 1<<7 | S<<6 | H<<5 | 1<<4 | Rm; }
inline int XFER2I(int cond, int P, int U, int W, int L, int Rn, int Rd, int offsetH, int S, int H, int offsetL)
{ return cond<<28 | P<<24 | U<<23 | 1<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | offsetH<<8 | 1<<7 | S<<6 | H<<5 | 1<<4 | (offsetL&0xf); }
inline int BLOCKXFER(int cond, int P, int U, int S, int W, int L, int Rn, int rlist)
{ return cond<<28 | 4<<25 | P<<24 | U<<23 | S<<22 | W<<21 | L<<20 | Rn<<16 | rlist; }
inline int SWI(int cond, int imm)
{ return cond<<28 | 0x0f<<24 | (imm&0xffffff); }
inline int SWAP(int cond, int B, int Rn, int Rd, int Rm)
{ return cond<<28 | 1<<24 | B<<22 | Rn<<16 | Rd<<12 | 9<<4 | Rm; }
inline int COOP(int cond, int opcode_1, int CRn, int CRd, int cp_num, int opcode_2, int CRm)
{ return cond<<28 | 0xe<<24 | opcode_1<<20 | CRn<<16 | CRd<<12 | cp_num<<8 | opcode_2<<5 | CRm; }
inline int COXFER(int cond, int P, int U, int N, int W, int L, int Rn, int CRd, int cp_num, int offset)
{ return cond<<28 | 0x6<<25 | P<<24 | U<<23 | N<<22 | W<<21 | L<<20 | Rn<<16 | CRd<<12 | cp_num<<8 | (offset&0xff); }
inline int COREG(int cond, int opcode_1, int L, int CRn, int Rd, int cp_num, int opcode_2, int CRm)
{ return cond<<28 | 0xe<<24 | opcode_1<<21 | L<<20 | CRn<<16 | Rd<<12 | cp_num<<8 | opcode_2<<5 | 1<<4 | CRm; }
inline int COREG2(int cond, int L, int Rn, int Rd, int cp_num, int opcode, int CRm)
{ return cond<<28 | 0xc4<<20 | L<<20 | Rn<<16 | Rd<<12 | cp_num<<8 | opcode<<4 | CRm;}
// FIELD CALCULATORS
inline int calcU(int imm) { return imm >= 0 ? 1 : 0; }
// INSTRUCTIONS
// The "cond" and "S" fields are set using the SETCOND() and SETS() functions
inline int b(int offset) { return BRANCH(AL, 0, offset); }
inline int bl(int offset) { return BRANCH(AL, 1, offset); }
inline int bx(int Rm) { return BRANCHX(AL, 0, Rm); }
inline int blx(int Rm) { return BRANCHX(AL, 1, Rm); }
inline int swi(int imm) { return SWI(AL, imm); }
inline int and_(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x0, 0, Rn, Rd, shift, Sh, Rm); }
inline int eor(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x1, 0, Rn, Rd, shift, Sh, Rm); }
inline int sub(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x2, 0, Rn, Rd, shift, Sh, Rm); }
inline int rsb(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x3, 0, Rn, Rd, shift, Sh, Rm); }
inline int add(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x4, 0, Rn, Rd, shift, Sh, Rm); }
inline int adc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x5, 0, Rn, Rd, shift, Sh, Rm); }
inline int sbc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x6, 0, Rn, Rd, shift, Sh, Rm); }
inline int rsc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x7, 0, Rn, Rd, shift, Sh, Rm); }
inline int tst(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x8, 1, Rn, 0, shift, Sh, Rm); }
inline int teq(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x9, 1, Rn, 0, shift, Sh, Rm); }
inline int cmp(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xa, 1, Rn, 0, shift, Sh, Rm); }
inline int cmn(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xb, 1, Rn, 0, shift, Sh, Rm); }
inline int orr(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xc, 0, Rn, Rd, shift, Sh, Rm); }
inline int mov(int Rd, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xd, 0, 0, Rd, shift, Sh, Rm); }
inline int bic(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xe, 0, Rn, Rd, shift, Sh, Rm); }
inline int mvn(int Rd, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xf, 0, 0, Rd, shift, Sh, Rm); }
inline int andi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x0, 0, Rn, Rd, rot, imm); }
inline int eori(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x1, 0, Rn, Rd, rot, imm); }
inline int subi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x2, 0, Rn, Rd, rot, imm); }
inline int rsbi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x3, 0, Rn, Rd, rot, imm); }
inline int addi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x4, 0, Rn, Rd, rot, imm); }
inline int adci(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x5, 0, Rn, Rd, rot, imm); }
inline int bici(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0xe, 0, Rn, Rd, rot, imm); }
inline int cmpi(int Rn, int imm, int rot=0) { return DATAI(AL, 0xa, 1, Rn, 0, rot, imm); }
inline int orri(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0xc, 0, Rn, Rd, rot, imm); }
inline int movi(int Rd, int imm, int rot=0) { return DATAI(AL, 0xd, 0, 0, Rd, rot, imm); }
inline int orrsh(int Rd, int Rn, int Rm, int Rs, int Sh) { return DATAS(AL, 0xc, 0, Rn, Rd, Rs, Sh, Rm); }
inline int movsh(int Rd, int Rm, int Rs, int Sh) { return DATAS(AL, 0xd, 0, 0, Rd, Rs, Sh, Rm); }
inline int mul(int Rd, int Rm, int Rs) { return MULTIPLY(AL, 0, 0, Rd, 0, Rs, Rm); }
inline int mla(int Rd, int Rm, int Rs, int Rn) { return MULTIPLY(AL, 1, 0, Rd, Rn, Rs, Rm); }
inline int umull(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 4, 0, RdHi, RdLo, Rs, Rm); }
inline int umlal(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 5, 0, RdHi, RdLo, Rs, Rm); }
inline int smull(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 6, 0, RdHi, RdLo, Rs, Rm); }
inline int smlal(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 7, 0, RdHi, RdLo, Rs, Rm); }
inline int ldr(int Rd, int Rn, int Rm, int W=0) { return XFER(AL, 1, 1, 0, W, 1, Rn, Rd, 0, 0, Rm); }
inline int ldri(int Rd, int Rn, int imm, int W=0) { return XFERI(AL, 1, calcU(imm), 0, W, 1, Rn, Rd, abs(imm)); }
inline int ldrb(int Rd, int Rn, int Rm) { return XFER(AL, 1, 1, 1, 0, 1, Rn, Rd, 0, 0, Rm); }
inline int ldrbi(int Rd, int Rn, int imm) { return XFERI(AL, 1, calcU(imm), 1, 0, 1, Rn, Rd, abs(imm)); }
inline int str(int Rd, int Rn, int Rm, int W=0) { return XFER(AL, 1, 1, 0, W, 0, Rn, Rd, 0, 0, Rm); }
inline int stri(int Rd, int Rn, int imm, int W=0) { return XFERI(AL, 1, calcU(imm), 0, W, 0, Rn, Rd, abs(imm)); }
inline int strb(int Rd, int Rn, int Rm) { return XFER(AL, 1, 1, 1, 0, 0, Rn, Rd, 0, 0, Rm); }
inline int strbi(int Rd, int Rn, int imm) { return XFERI(AL, 1, calcU(imm), 1, 0, 0, Rn, Rd, abs(imm)); }
inline int ldrh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 0, 1, Rm); }
inline int ldrhi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 0, 1, abs(imm)&0xf); }
inline int strh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 0, Rn, Rd, 0, 1, Rm); }
inline int strhi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 0, Rn, Rd, abs(imm)>>4 & 0xf, 0, 1, abs(imm)&0xf); }
inline int ldrsh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 1, Rm); }
inline int ldrshi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 1, 1, abs(imm)&0xf); }
inline int ldrsb(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 0, Rm); }
inline int ldrsbi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 1, 0, abs(imm)&0xf); }
inline int pop(int Rd) { return XFERI(AL, 0, 1, 0, 0, 1, 13, Rd, 4); }
inline int ldmfd(int Rn, int rlist) { return BLOCKXFER(AL, 0, 1, 0, 1, 1, Rn, rlist); }
inline int stmfd(int Rn, int rlist) { return BLOCKXFER(AL, 1, 0, 0, 1, 0, Rn, rlist); }
inline int swp(int Rd, int Rm, int Rn) { return SWAP(AL, 0, Rn, Rd, Rm); }
inline int swpb(int Rd, int Rm, int Rn) { return SWAP(AL, 1, Rn, Rd, Rm); }
// breakpoint instruction, this really has its own instruction format
inline int bkpt(int16_t immed) { return 0xe1200070 | (((unsigned)immed & 0xffff) >> 4 << 8) | (immed & 0xf); }
// COPROCESSOR INSTRUCTIONS
inline int cdp(int coproc, int opcode_1, int CRd, int CRn, int CRm, int opcode_2) { return COOP(AL, opcode_1, CRn, CRd, coproc, opcode_2, CRm); }
inline int mcr(int coproc, int opcode_1, int Rd, int CRn, int CRm, int opcode_2=0) { return COREG(AL, opcode_1, 0, CRn, Rd, coproc, opcode_2, CRm); }
inline int mcrr(int coproc, int opcode, int Rd, int Rn, int CRm) { return COREG2(AL, 0, Rn, Rd, coproc, opcode, CRm); }
inline int mrc(int coproc, int opcode_1, int Rd, int CRn, int CRm, int opcode_2=0) { return COREG(AL, opcode_1, 1, CRn, Rd, coproc, opcode_2, CRm); }
inline int mrrc(int coproc, int opcode, int Rd, int Rn, int CRm) { return COREG2(AL, 1, Rn, Rd, coproc, opcode, CRm); }
inline int ldc(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 0, W, 1, Rn, CRd, coproc, offset); }
inline int ldcl(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 1, W, 1, Rn, CRd, coproc, offset); }
inline int stc(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 0, W, 0, Rn, CRd, coproc, offset); }
inline int stcl(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 1, W, 0, Rn, CRd, coproc, offset); }
// VFP FLOATING-POINT INSTRUCTIONS
inline int fmacs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fnmacs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fmscs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|1, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fnmscs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|1, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fmuls(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fnmuls(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fadds(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|3, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fsubs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|3, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fdivs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|8, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fmacd(int Dd, int Dn, int Dm) { return COOP(AL, 0, Dn, Dd, 11, 0, Dm); }
inline int fnmacd(int Dd, int Dn, int Dm) { return COOP(AL, 0, Dn, Dd, 11, 2, Dm); }
inline int fmscd(int Dd, int Dn, int Dm) { return COOP(AL, 1, Dn, Dd, 11, 0, Dm); }
inline int fnmscd(int Dd, int Dn, int Dm) { return COOP(AL, 1, Dn, Dd, 11, 2, Dm); }
inline int fmuld(int Dd, int Dn, int Dm) { return COOP(AL, 2, Dn, Dd, 11, 0, Dm); }
inline int fnmuld(int Dd, int Dn, int Dm) { return COOP(AL, 2, Dn, Dd, 11, 2, Dm); }
inline int faddd(int Dd, int Dn, int Dm) { return COOP(AL, 3, Dn, Dd, 11, 0, Dm); }
inline int fsubd(int Dd, int Dn, int Dm) { return COOP(AL, 3, Dn, Dd, 11, 2, Dm); }
inline int fdivd(int Dd, int Dn, int Dm) { return COOP(AL, 8, Dn, Dd, 11, 0, Dm); }
inline int fcpys(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fabss(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fnegs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 1, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fsqrts(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 1, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fcmps(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 4, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fcmpes(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 4, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fcmpzs(int Sd) { return COOP(AL, 0xb|(Sd&1)<<2, 5, Sd>>1, 10, 2, 0); }
inline int fcmpezs(int Sd) { return COOP(AL, 0xb|(Sd&1)<<2, 5, Sd>>1, 10, 6, 0); }
inline int fcvtds(int Dd, int Sm) { return COOP(AL, 0xb, 7, Dd, 10, 6|(Sm&1), Sm>>1); }
inline int fuitos(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 8, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fsitos(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 8, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int ftouis(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int ftouizs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int ftosis(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int ftosizs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fcpyd(int Dd, int Dm) { return COOP(AL, 0xb, 0, Dd, 11, 2, Dm); }
inline int fabsd(int Dd, int Dm) { return COOP(AL, 0xb, 0, Dd, 11, 6, Dm); }
inline int fnegd(int Dd, int Dm) { return COOP(AL, 0xb, 1, Dd, 11, 2, Dm); }
inline int fsqrtd(int Dd, int Dm) { return COOP(AL, 0xb, 1, Dd, 11, 6, Dm); }
inline int fcmpd(int Dd, int Dm) { return COOP(AL, 0xb, 4, Dd, 11, 2, Dm); }
inline int fcmped(int Dd, int Dm) { return COOP(AL, 0xb, 4, Dd, 11, 6, Dm); }
inline int fcmpzd(int Dd) { return COOP(AL, 0xb, 5, Dd, 11, 2, 0); }
inline int fcmpezd(int Dd) { return COOP(AL, 0xb, 5, Dd, 11, 6, 0); }
inline int fcvtsd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 7, Sd>>1, 11, 6, Dm); }
inline int fuitod(int Dd, int Sm) { return COOP(AL, 0xb, 8, Dd, 11, 2|(Sm&1), Sm>>1); }
inline int fsitod(int Dd, int Sm) { return COOP(AL, 0xb, 8, Dd, 11, 6|(Sm&1), Sm>>1); }
inline int ftouid(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 11, 2, Dm); }
inline int ftouizd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 11, 6, Dm); }
inline int ftosid(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 11, 2, Dm); }
inline int ftosizd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 11, 6, Dm); }
inline int fldms(int Rn, int Sd, int count) { return COXFER(AL, 0, 1, Sd&1, 0, 1, Rn, Sd>>1, 10, count); }
inline int fldmd(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 1, Rn, Dd, 11, count<<1); }
inline int fldmx(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 1, Rn, Dd, 11, count<<1|1); }
inline int fstms(int Rn, int Sd, int count) { return COXFER(AL, 0, 1, Sd&1, 0, 0, Rn, Sd>>1, 10, count); }
inline int fstmd(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 0, Rn, Dd, 11, count<<1); }
inline int fstmx(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 0, Rn, Dd, 11, count<<1|1); }
inline int flds(int Sd, int Rn, int offset=0) { return COXFER(AL, 1, 1, Sd&1, 0, 1, Rn, Sd>>1, 10, offset); };
inline int fldd(int Dd, int Rn, int offset=0) { return COXFER(AL, 1, 1, 0, 0, 1, Rn, Dd, 11, offset); };
inline int fsts(int Sd, int Rn, int offset=0) { return COXFER(AL, 1, 1, Sd&1, 0, 0, Rn, Sd>>1, 10, offset); };
inline int fstd(int Dd, int Rn, int offset=0) { return COXFER(AL, 1, 1, 0, 0, 0, Rn, Dd, 11, offset); };
inline int fmsr(int Sn, int Rd) { return mcr(10, 0, Rd, Sn>>1, 0, (Sn&1)<<2); }
inline int fmrs(int Rd, int Sn) { return mrc(10, 0, Rd, Sn>>1, 0, (Sn&1)<<2); }
inline int fmdlr(int Dn, int Rd) { return mcr(11, 0, Rd, Dn, 0); }
inline int fmrdl(int Rd, int Dn) { return mrc(11, 0, Rd, Dn, 0); }
inline int fmdhr(int Dn, int Rd) { return mcr(11, 1, Rd, Dn, 0); }
inline int fmrdh(int Rd, int Dn) { return mrc(11, 1, Rd, Dn, 0); }
inline int fmxr(int reg, int Rd) { return mcr(10, 7, Rd, reg, 0); }
inline int fmrx(int Rd, int reg) { return mrc(10, 7, Rd, reg, 0); }
inline int fmsrr(int Sm, int Rd, int Rn) { return mcrr(10, 1 | ((Sm&1)<<1), Rd, Rn, Sm>>1); }
inline int fmrrs(int Rd, int Rn, int Sm) { return mrrc(10, 1 | ((Sm&1)<<1), Rd, Rn, Sm>>1); }
inline int fmdrr(int Dm, int Rd, int Rn) { return mcrr(11, 1, Rd, Rn, Dm); }
inline int fmrrd(int Rd, int Rn, int Dm) { return mrrc(11, 1, Rd, Rn, Dm); }
// FLAG SETTERS
inline int SETCOND(int ins, int cond) { return ((ins&0x0fffffff) | (cond<<28)); }
inline int SETS(int ins) { return ins | 1<<20; }
// PSEUDO-INSTRUCTIONS
inline int nop() { return mov(0, 0); }
inline int lsl(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, LSL); }
inline int lsli(int Rd, int Rm, int imm) { return mov(Rd, Rm, LSL, imm); }
inline int lsr(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, LSR); }
inline int lsri(int Rd, int Rm, int imm) { return mov(Rd, Rm, LSR, imm); }
inline int asr(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, ASR); }
inline int asri(int Rd, int Rm, int imm) { return mov(Rd, Rm, ASR, imm); }
inline int ror(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, ROR); }
inline int beq(int offset) { return SETCOND(b(offset), EQ); }
inline int bne(int offset) { return SETCOND(b(offset), NE); }
inline int bls(int offset) { return SETCOND(b(offset), LS); }
inline int bhi(int offset) { return SETCOND(b(offset), HI); }
inline int blt(int offset) { return SETCOND(b(offset), LT); }
inline int bgt(int offset) { return SETCOND(b(offset), GT); }
inline int ble(int offset) { return SETCOND(b(offset), LE); }
inline int bge(int offset) { return SETCOND(b(offset), GE); }
inline int blo(int offset) { return SETCOND(b(offset), CC); }
inline int bhs(int offset) { return SETCOND(b(offset), CS); }
inline int bpl(int offset) { return SETCOND(b(offset), PL); }
inline int fmstat() { return fmrx(15, FPSCR); }
// HARDWARE FLAGS
bool vfpSupported() {
return true; // TODO
}
}
const uint64_t MASK_LO32 = 0xffffffff;
const unsigned MASK_LO16 = 0xffff;
const unsigned MASK_LO8 = 0xff;
inline unsigned lo32(int64_t i) { return (unsigned)(i&MASK_LO32); }
inline unsigned hi32(int64_t i) { return (unsigned)(i>>32); }
inline unsigned lo16(int64_t i) { return (unsigned)(i&MASK_LO16); }
inline unsigned hi16(int64_t i) { return lo16(i>>16); }
inline unsigned lo8(int64_t i) { return (unsigned)(i&MASK_LO8); }
inline unsigned hi8(int64_t i) { return lo8(i>>8); }
inline int ha16(int32_t i) {
return ((i >> 16) + ((i & 0x8000) ? 1 : 0)) & 0xffff;
}
inline int unha16(int32_t high, int32_t low) {
return ((high - ((low & 0x8000) ? 1 : 0)) << 16) | low;
}
inline bool isInt8(target_intptr_t v) { return v == static_cast<int8_t>(v); }
inline bool isInt16(target_intptr_t v) { return v == static_cast<int16_t>(v); }
inline bool isInt24(target_intptr_t v) { return v == (v & 0xffffff); }
inline bool isInt32(target_intptr_t v) { return v == static_cast<int32_t>(v); }
inline int carry16(target_intptr_t v) { return static_cast<int16_t>(v) < 0 ? 1 : 0; }
inline bool isOfWidth(int64_t i, int size) { return static_cast<uint64_t>(i) >> size == 0; }
inline bool isOfWidth(int i, int size) { return static_cast<unsigned>(i) >> size == 0; }
const int N_GPRS = 16;
const int N_FPRS = 16;
const uint32_t GPR_MASK = 0xffff;
const uint32_t FPR_MASK = 0xffff0000;
inline bool isFpr(Assembler::Register* reg) {
return reg->low >= N_GPRS;
}
inline int toFpr(Assembler::Register* reg) {
return reg->low - N_GPRS;
}
const unsigned FrameHeaderSize = 1;
const unsigned StackAlignmentInBytes = 8;
const unsigned StackAlignmentInWords
= StackAlignmentInBytes / TargetBytesPerWord;
const int ThreadRegister = 8;
const int StackRegister = 13;
const int LinkRegister = 14;
const int ProgramCounter = 15;
const int32_t PoolOffsetMask = 0xFFF;
const bool DebugPool = false;
class Context;
class MyBlock;
class PoolOffset;
class PoolEvent;
void
resolve(MyBlock*);
unsigned
padding(MyBlock*, unsigned);
class MyBlock: public Assembler::Block {
public:
MyBlock(Context* context, unsigned offset):
context(context), next(0), poolOffsetHead(0), poolOffsetTail(0),
lastPoolOffsetTail(0), poolEventHead(0), poolEventTail(0),
lastEventOffset(0), offset(offset), start(~0), size(0)
{ }
virtual unsigned resolve(unsigned start, Assembler::Block* next) {
this->start = start;
this->next = static_cast<MyBlock*>(next);
::resolve(this);
return start + size + padding(this, size);
}
Context* context;
MyBlock* next;
PoolOffset* poolOffsetHead;
PoolOffset* poolOffsetTail;
PoolOffset* lastPoolOffsetTail;
PoolEvent* poolEventHead;
PoolEvent* poolEventTail;
unsigned lastEventOffset;
unsigned offset;
unsigned start;
unsigned size;
};
class Task;
class ConstantPoolEntry;
class Context {
public:
Context(System* s, Allocator* a, Zone* zone):
s(s), zone(zone), client(0), code(s, a, 1024), tasks(0), result(0),
firstBlock(new(zone) MyBlock(this, 0)),
lastBlock(firstBlock), poolOffsetHead(0), poolOffsetTail(0),
constantPool(0), constantPoolCount(0)
{ }
System* s;
Zone* zone;
Assembler::Client* client;
Vector code;
Task* tasks;
uint8_t* result;
MyBlock* firstBlock;
MyBlock* lastBlock;
PoolOffset* poolOffsetHead;
PoolOffset* poolOffsetTail;
ConstantPoolEntry* constantPool;
unsigned constantPoolCount;
};
class Task {
public:
Task(Task* next): next(next) { }
virtual void run(Context* c) = 0;
Task* next;
};
typedef void (*OperationType)(Context*);
typedef void (*UnaryOperationType)(Context*, unsigned, Assembler::Operand*);
typedef void (*BinaryOperationType)
(Context*, unsigned, Assembler::Operand*, unsigned, Assembler::Operand*);
typedef void (*TernaryOperationType)
(Context*, unsigned, Assembler::Operand*, Assembler::Operand*,
Assembler::Operand*);
typedef void (*BranchOperationType)
(Context*, TernaryOperation, unsigned, Assembler::Operand*,
Assembler::Operand*, Assembler::Operand*);
class ArchitectureContext {
public:
ArchitectureContext(System* s): s(s) { }
System* s;
OperationType operations[OperationCount];
UnaryOperationType unaryOperations[UnaryOperationCount
* OperandTypeCount];
BinaryOperationType binaryOperations
[BinaryOperationCount * OperandTypeCount * OperandTypeCount];
TernaryOperationType ternaryOperations
[NonBranchTernaryOperationCount * OperandTypeCount];
BranchOperationType branchOperations
[BranchOperationCount * OperandTypeCount * OperandTypeCount];
};
inline void NO_RETURN
abort(Context* c)
{
abort(c->s);
}
inline void NO_RETURN
abort(ArchitectureContext* c)
{
abort(c->s);
}
#ifndef NDEBUG
inline void
assert(Context* c, bool v)
{
assert(c->s, v);
}
inline void
assert(ArchitectureContext* c, bool v)
{
assert(c->s, v);
}
#endif // not NDEBUG
inline void
expect(Context* c, bool v)
{
expect(c->s, v);
}
class Offset: public Promise {
public:
Offset(Context* c, MyBlock* block, unsigned offset, bool forTrace):
c(c), block(block), offset(offset), forTrace(forTrace)
{ }
virtual bool resolved() {
return block->start != static_cast<unsigned>(~0);
}
virtual int64_t value() {
assert(c, resolved());
unsigned o = offset - block->offset;
return block->start + padding
(block, forTrace ? o - TargetBytesPerWord : o) + o;
}
Context* c;
MyBlock* block;
unsigned offset;
bool forTrace;
};
Promise*
offset(Context* c, bool forTrace = false)
{
return new(c->zone) Offset(c, c->lastBlock, c->code.length(), forTrace);
}
bool
bounded(int right, int left, int32_t v)
{
return ((v << left) >> left) == v and ((v >> right) << right) == v;
}
void*
updateOffset(System* s, uint8_t* instruction, int64_t value)
{
// ARM's PC is two words ahead, and branches drop the bottom 2 bits.
int32_t v = (reinterpret_cast<uint8_t*>(value) - (instruction + 8)) >> 2;
int32_t mask;
expect(s, bounded(0, 8, v));
mask = 0xFFFFFF;
int32_t* p = reinterpret_cast<int32_t*>(instruction);
*p = (v & mask) | ((~mask) & *p);
return instruction + 4;
}
class OffsetListener: public Promise::Listener {
public:
OffsetListener(System* s, uint8_t* instruction):
s(s),
instruction(instruction)
{ }
virtual bool resolve(int64_t value, void** location) {
void* p = updateOffset(s, instruction, value);
if (location) *location = p;
return false;
}
System* s;
uint8_t* instruction;
};
class OffsetTask: public Task {
public:
OffsetTask(Task* next, Promise* promise, Promise* instructionOffset):
Task(next),
promise(promise),
instructionOffset(instructionOffset)
{ }
virtual void run(Context* c) {
if (promise->resolved()) {
updateOffset
(c->s, c->result + instructionOffset->value(), promise->value());
} else {
new (promise->listen(sizeof(OffsetListener)))
OffsetListener(c->s, c->result + instructionOffset->value());
}
}
Promise* promise;
Promise* instructionOffset;
};
void
appendOffsetTask(Context* c, Promise* promise, Promise* instructionOffset)
{
c->tasks = new(c->zone) OffsetTask(c->tasks, promise, instructionOffset);
}
inline unsigned
index(ArchitectureContext*, UnaryOperation operation, OperandType operand)
{
return operation + (UnaryOperationCount * operand);
}
inline unsigned
index(ArchitectureContext*,
BinaryOperation operation,
OperandType operand1,
OperandType operand2)
{
return operation
+ (BinaryOperationCount * operand1)
+ (BinaryOperationCount * OperandTypeCount * operand2);
}
bool
isBranch(TernaryOperation op)
{
return op > FloatMin;
}
bool
isFloatBranch(TernaryOperation op)
{
return op > JumpIfNotEqual;
}
inline unsigned
index(ArchitectureContext* c UNUSED,
TernaryOperation operation,
OperandType operand1)
{
assert(c, not isBranch(operation));
return operation + (NonBranchTernaryOperationCount * operand1);
}
unsigned
branchIndex(ArchitectureContext* c UNUSED, OperandType operand1,
OperandType operand2)
{
return operand1 + (OperandTypeCount * operand2);
}
// BEGIN OPERATION COMPILERS
using namespace isa;
// shortcut functions
inline void emit(Context* con, int code) { con->code.append4(code); }
inline int newTemp(Context* con) {
return con->client->acquireTemporary();
}
inline int newTemp(Context* con, unsigned mask) {
return con->client->acquireTemporary(mask);
}
inline void freeTemp(Context* con, int r) {
con->client->releaseTemporary(r);
}
inline int64_t getValue(Assembler::Constant* c) {
return c->value->value();
}
inline Assembler::Register makeTemp(Context* con) {
Assembler::Register tmp(newTemp(con));
return tmp;
}
inline Assembler::Register makeTemp64(Context* con) {
Assembler::Register tmp(newTemp(con), newTemp(con));
return tmp;
}
inline void freeTemp(Context* con, const Assembler::Register& tmp) {
if (tmp.low != NoRegister) freeTemp(con, tmp.low);
if (tmp.high != NoRegister) freeTemp(con, tmp.high);
}
inline void
write4(uint8_t* dst, uint32_t v)
{
memcpy(dst, &v, 4);
}
void shiftLeftR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t)
{
if (size == 8) {
int tmp1 = newTemp(con), tmp2 = newTemp(con);
emit(con, lsl(tmp1, b->high, a->low));
emit(con, rsbi(tmp2, a->low, 32));
emit(con, orrsh(tmp1, tmp1, b->low, tmp2, LSR));
emit(con, SETS(subi(t->high, a->low, 32)));
emit(con, SETCOND(mov(t->high, tmp1), MI));
emit(con, SETCOND(lsl(t->high, b->low, t->high), PL));
emit(con, lsl(t->low, b->low, a->low));
freeTemp(con, tmp1); freeTemp(con, tmp2);
} else {
emit(con, lsl(t->low, b->low, a->low));
}
}
void shiftLeftC(Context* con, unsigned size UNUSED, Assembler::Constant* a, Assembler::Register* b, Assembler::Register* t)
{
assert(con, size == TargetBytesPerWord);
emit(con, lsli(t->low, b->low, getValue(a)));
}
void shiftRightR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t)
{
if (size == 8) {
int tmp1 = newTemp(con), tmp2 = newTemp(con);
emit(con, lsr(tmp1, b->low, a->low));
emit(con, rsbi(tmp2, a->low, 32));
emit(con, orrsh(tmp1, tmp1, b->high, tmp2, LSL));
emit(con, SETS(subi(t->low, a->low, 32)));
emit(con, SETCOND(mov(t->low, tmp1), MI));
emit(con, SETCOND(asr(t->low, b->high, t->low), PL));
emit(con, asr(t->high, b->high, a->low));
freeTemp(con, tmp1); freeTemp(con, tmp2);
} else {
emit(con, asr(t->low, b->low, a->low));
}
}
void shiftRightC(Context* con, unsigned size UNUSED, Assembler::Constant* a, Assembler::Register* b, Assembler::Register* t)
{
assert(con, size == TargetBytesPerWord);
emit(con, asri(t->low, b->low, getValue(a)));
}
void unsignedShiftRightR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t)
{
emit(con, lsr(t->low, b->low, a->low));
if (size == 8) {
int tmpHi = newTemp(con), tmpLo = newTemp(con);
emit(con, SETS(rsbi(tmpHi, a->low, 32)));
emit(con, lsl(tmpLo, b->high, tmpHi));
emit(con, orr(t->low, t->low, tmpLo));
emit(con, addi(tmpHi, a->low, -32));
emit(con, lsr(tmpLo, b->high, tmpHi));
emit(con, orr(t->low, t->low, tmpLo));
emit(con, lsr(t->high, b->high, a->low));
freeTemp(con, tmpHi); freeTemp(con, tmpLo);
}
}
void unsignedShiftRightC(Context* con, unsigned size UNUSED, Assembler::Constant* a, Assembler::Register* b, Assembler::Register* t)
{
assert(con, size == TargetBytesPerWord);
emit(con, lsri(t->low, b->low, getValue(a)));
}
class ConstantPoolEntry: public Promise {
public:
ConstantPoolEntry(Context* c, Promise* constant, ConstantPoolEntry* next,
Promise* callOffset):
c(c), constant(constant), next(next), callOffset(callOffset),
address(0)
{ }
virtual int64_t value() {
assert(c, resolved());
return reinterpret_cast<int64_t>(address);
}
virtual bool resolved() {
return address != 0;
}
Context* c;
Promise* constant;
ConstantPoolEntry* next;
Promise* callOffset;
void* address;
unsigned constantPoolCount;
};
class ConstantPoolListener: public Promise::Listener {
public:
ConstantPoolListener(System* s, target_uintptr_t* address,
uint8_t* returnAddress):
s(s),
address(address),
returnAddress(returnAddress)
{ }
virtual bool resolve(int64_t value, void** location) {
*address = value;
if (location) {
*location = returnAddress ? static_cast<void*>(returnAddress) : address;
}
return true;
}
System* s;
target_uintptr_t* address;
uint8_t* returnAddress;
};
class PoolOffset {
public:
PoolOffset(MyBlock* block, ConstantPoolEntry* entry, unsigned offset):
block(block), entry(entry), next(0), offset(offset)
{ }
MyBlock* block;
ConstantPoolEntry* entry;
PoolOffset* next;
unsigned offset;
};
class PoolEvent {
public:
PoolEvent(PoolOffset* poolOffsetHead, PoolOffset* poolOffsetTail,
unsigned offset):
poolOffsetHead(poolOffsetHead), poolOffsetTail(poolOffsetTail), next(0),
offset(offset)
{ }
PoolOffset* poolOffsetHead;
PoolOffset* poolOffsetTail;
PoolEvent* next;
unsigned offset;
};
void
appendConstantPoolEntry(Context* c, Promise* constant, Promise* callOffset)
{
if (constant->resolved()) {
// make a copy, since the original might be allocated on the
// stack, and we need our copy to live until assembly is complete
constant = new(c->zone) ResolvedPromise(constant->value());
}
c->constantPool = new(c->zone) ConstantPoolEntry(c, constant, c->constantPool, callOffset);
++ c->constantPoolCount;
PoolOffset* o = new(c->zone) PoolOffset(c->lastBlock, c->constantPool, c->code.length() - c->lastBlock->offset);
if (DebugPool) {
fprintf(stderr, "add pool offset %p %d to block %p\n",
o, o->offset, c->lastBlock);
}
if (c->lastBlock->poolOffsetTail) {
c->lastBlock->poolOffsetTail->next = o;
} else {
c->lastBlock->poolOffsetHead = o;
}
c->lastBlock->poolOffsetTail = o;
}
void
appendPoolEvent(Context* c, MyBlock* b, unsigned offset, PoolOffset* head,
PoolOffset* tail)
{
PoolEvent* e = new(c->zone) PoolEvent(head, tail, offset);
if (b->poolEventTail) {
b->poolEventTail->next = e;
} else {
b->poolEventHead = e;
}
b->poolEventTail = e;
}
bool
needJump(MyBlock* b)
{
return b->next or b->size != (b->size & PoolOffsetMask);
}
unsigned
padding(MyBlock* b, unsigned offset)
{
unsigned total = 0;
for (PoolEvent* e = b->poolEventHead; e; e = e->next) {
if (e->offset <= offset) {
if (needJump(b)) {
total += TargetBytesPerWord;
}
for (PoolOffset* o = e->poolOffsetHead; o; o = o->next) {
total += TargetBytesPerWord;
}
} else {
break;
}
}
return total;
}
void
resolve(MyBlock* b)
{
Context* c = b->context;
if (b->poolOffsetHead) {
if (c->poolOffsetTail) {
c->poolOffsetTail->next = b->poolOffsetHead;
} else {
c->poolOffsetHead = b->poolOffsetHead;
}
c->poolOffsetTail = b->poolOffsetTail;
}
if (c->poolOffsetHead) {
bool append;
if (b->next == 0 or b->next->poolEventHead) {
append = true;
} else {
int32_t v = (b->start + b->size + b->next->size + TargetBytesPerWord - 8)
- (c->poolOffsetHead->offset + c->poolOffsetHead->block->start);
append = (v != (v & PoolOffsetMask));
if (DebugPool) {
fprintf(stderr,
"current %p %d %d next %p %d %d\n",
b, b->start, b->size, b->next, b->start + b->size,
b->next->size);
fprintf(stderr,
"offset %p %d is of distance %d to next block; append? %d\n",
c->poolOffsetHead, c->poolOffsetHead->offset, v, append);
}
}
if (append) {
#ifndef NDEBUG
int32_t v = (b->start + b->size - 8)
- (c->poolOffsetHead->offset + c->poolOffsetHead->block->start);
expect(c, v == (v & PoolOffsetMask));
#endif // not NDEBUG
appendPoolEvent(c, b, b->size, c->poolOffsetHead, c->poolOffsetTail);
if (DebugPool) {
for (PoolOffset* o = c->poolOffsetHead; o; o = o->next) {
fprintf(stderr,
"include %p %d in pool event %p at offset %d in block %p\n",
o, o->offset, b->poolEventTail, b->size, b);
}
}
c->poolOffsetHead = 0;
c->poolOffsetTail = 0;
}
}
}
void
jumpR(Context* c, unsigned size UNUSED, Assembler::Register* target)
{
assert(c, size == TargetBytesPerWord);
emit(c, bx(target->low));
}
void
moveRR(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned dstSize, Assembler::Register* dst);
void
swapRR(Context* c, unsigned aSize, Assembler::Register* a,
unsigned bSize, Assembler::Register* b)
{
assert(c, aSize == TargetBytesPerWord);
assert(c, bSize == TargetBytesPerWord);
Assembler::Register tmp(c->client->acquireTemporary());
moveRR(c, aSize, a, bSize, &tmp);
moveRR(c, bSize, b, aSize, a);
moveRR(c, bSize, &tmp, bSize, b);
c->client->releaseTemporary(tmp.low);
}
void
moveRR(Context* con, unsigned srcSize, Assembler::Register* src,
unsigned dstSize, Assembler::Register* dst)
{
bool srcIsFpr = isFpr(src);
bool dstIsFpr = isFpr(dst);
if (srcIsFpr || dstIsFpr) { // floating-point register(s) involved
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- %d\n", dst->low, src->low);
// FPR to FPR
if (srcIsFpr && dstIsFpr) emit(con, fcpys(toFpr(dst), toFpr(src)));
// FPR to GPR
else if (srcIsFpr) emit(con, fmrs(dst->low, toFpr(src)));
// GPR to FPR
else emit(con, fmsr(toFpr(dst), src->low));
return;
}
switch (srcSize) {
case 1:
emit(con, lsli(dst->low, src->low, 24));
emit(con, asri(dst->low, dst->low, 24));
break;
case 2:
emit(con, lsli(dst->low, src->low, 16));
emit(con, asri(dst->low, dst->low, 16));
break;
case 4:
case 8:
if (srcSize == 4 and dstSize == 8) {
moveRR(con, 4, src, 4, dst);
emit(con, asri(dst->high, src->low, 31));
} else if (srcSize == 8 and dstSize == 8) {
Assembler::Register srcHigh(src->high);
Assembler::Register dstHigh(dst->high);
if (src->high == dst->low) {
if (src->low == dst->high) {
swapRR(con, 4, src, 4, dst);
} else {
moveRR(con, 4, &srcHigh, 4, &dstHigh);
moveRR(con, 4, src, 4, dst);
}
} else {
moveRR(con, 4, src, 4, dst);
moveRR(con, 4, &srcHigh, 4, &dstHigh);
}
} else if (src->low != dst->low) {
emit(con, mov(dst->low, src->low));
}
break;
default: abort(con);
}
}
void
moveZRR(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned, Assembler::Register* dst)
{
switch (srcSize) {
case 2:
emit(c, lsli(dst->low, src->low, 16));
emit(c, lsri(dst->low, dst->low, 16));
break;
default: abort(c);
}
}
void
moveCR2(Context* con, unsigned size, Assembler::Constant* src,
Assembler::Register* dst, Promise* callOffset)
{
if (isFpr(dst)) { // floating-point
Assembler::Register tmp = makeTemp(con);
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- 0x%llx\n", tmp.low, getValue(src));
moveCR2(con, size, src, &tmp, 0);
moveRR(con, size, &tmp, size, dst);
freeTemp(con, tmp);
} else if (size <= 4) {
if (src->value->resolved() and isOfWidth(getValue(src), 8)) {
emit(con, movi(dst->low, lo8(getValue(src))));
} else {
appendConstantPoolEntry(con, src->value, callOffset);
emit(con, ldri(dst->low, ProgramCounter, 0));
}
} else {
abort(con); // todo
}
}
void
moveCR(Context* con, unsigned size, Assembler::Constant* src,
unsigned, Assembler::Register* dst)
{
moveCR2(con, size, src, dst, 0);
}
void addR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, SETS(add(t->low, a->low, b->low)));
emit(con, adc(t->high, a->high, b->high));
} else {
emit(con, add(t->low, a->low, b->low));
}
}
void subR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, SETS(rsb(t->low, a->low, b->low)));
emit(con, rsc(t->high, a->high, b->high));
} else {
emit(con, rsb(t->low, a->low, b->low));
}
}
void
addC(Context* c, unsigned size, Assembler::Constant* a,
Assembler::Register* b, Assembler::Register* dst)
{
assert(c, size == TargetBytesPerWord);
int32_t v = a->value->value();
if (v) {
if (v > 0 and v < 256) {
emit(c, addi(dst->low, b->low, v));
} else if (v > 0 and v < 1024 and v % 4 == 0) {
emit(c, addi(dst->low, b->low, v >> 2, 15));
} else {
// todo
abort(c);
}
} else {
moveRR(c, size, b, size, dst);
}
}
void
subC(Context* c, unsigned size, Assembler::Constant* a,
Assembler::Register* b, Assembler::Register* dst)
{
assert(c, size == TargetBytesPerWord);
int32_t v = a->value->value();
if (v) {
if (v > 0 and v < 256) {
emit(c, subi(dst->low, b->low, v));
} else if (v > 0 and v < 1024 and v % 4 == 0) {
emit(c, subi(dst->low, b->low, v >> 2, 15));
} else {
// todo
abort(c);
}
} else {
moveRR(c, size, b, size, dst);
}
}
void multiplyR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
bool useTemporaries = b->low == t->low;
int tmpLow = useTemporaries ? con->client->acquireTemporary() : t->low;
int tmpHigh = useTemporaries ? con->client->acquireTemporary() : t->high;
emit(con, umull(tmpLow, tmpHigh, a->low, b->low));
emit(con, mla(tmpHigh, a->low, b->high, tmpHigh));
emit(con, mla(tmpHigh, a->high, b->low, tmpHigh));
if (useTemporaries) {
emit(con, mov(t->low, tmpLow));
emit(con, mov(t->high, tmpHigh));
con->client->releaseTemporary(tmpLow);
con->client->releaseTemporary(tmpHigh);
}
} else {
emit(con, mul(t->low, a->low, b->low));
}
}
void floatAbsoluteRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
emit(con, fabsd(b->low, a->low));
} else {
emit(con, fabss(b->low, a->low));
}
}
void floatNegateRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> invalid 64-bit Scheiße\n");
emit(con, fnegd(b->low, a->low));
} else {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- -%d\n", b->low, a->low);
emit(con, fnegs(b->low, a->low));
}
}
void float2FloatRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
emit(con, fcvtsd(b->low, a->low));
} else {
emit(con, fcvtds(b->low, a->low));
}
}
void float2IntRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
int tmp = newTemp(con, FPR_MASK);
if (size == 8) { // double to int
emit(con, ftosid(tmp, a->low));
} else { // float to int
emit(con, ftosis(tmp, a->low));
} // else thunked
emit(con, fmrs(b->low, tmp));
freeTemp(con, tmp);
}
void int2FloatRR(Context* con, unsigned UNUSED, Assembler::Register* a, unsigned size, Assembler::Register* b) {
emit(con, fmsr(b->low, a->low));
if (size == 8) { // int to double
emit(con, fsitod(b->low, b->low));
} else { // int to float
emit(con, fsitos(b->low, b->low));
} // else thunked
}
void floatSqrtRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
emit(con, fsqrtd(b->low, a->low));
} else {
emit(con, fsqrts(b->low, a->low));
}
}
void floatAddR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, faddd(t->low, a->low, b->low));
} else {
fprintf(stderr, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %d <- %d + %d\n", toFpr(t), toFpr(a), toFpr(b));
emit(con, fadds(toFpr(t), toFpr(a), toFpr(b)));
}
}
void floatSubtractR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, fsubd(t->low, a->low, b->low));
} else {
emit(con, fsubs(t->low, a->low, b->low));
}
}
void floatMultiplyR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, fmuld(t->low, a->low, b->low));
} else {
emit(con, fmuls(t->low, a->low, b->low));
}
}
void floatDivideR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, fdivd(t->low, a->low, b->low));
} else {
emit(con, fdivs(t->low, a->low, b->low));
}
}
int
normalize(Context* c, int offset, int index, unsigned scale,
bool* preserveIndex, bool* release)
{
if (offset != 0 or scale != 1) {
Assembler::Register normalizedIndex
(*preserveIndex ? c->client->acquireTemporary() : index);
if (*preserveIndex) {
*release = true;
*preserveIndex = false;
} else {
*release = false;
}
int scaled;
if (scale != 1) {
Assembler::Register unscaledIndex(index);
ResolvedPromise scalePromise(log(scale));
Assembler::Constant scaleConstant(&scalePromise);
shiftLeftC(c, TargetBytesPerWord, &scaleConstant,
&unscaledIndex, &normalizedIndex);
scaled = normalizedIndex.low;
} else {
scaled = index;
}
if (offset != 0) {
Assembler::Register untranslatedIndex(scaled);
ResolvedPromise offsetPromise(offset);
Assembler::Constant offsetConstant(&offsetPromise);
Assembler::Register tmp(c->client->acquireTemporary());
moveCR(c, TargetBytesPerWord, &offsetConstant, TargetBytesPerWord, &tmp);
addR(c, TargetBytesPerWord, &tmp, &untranslatedIndex, &normalizedIndex);
c->client->releaseTemporary(tmp.low);
}
return normalizedIndex.low;
} else {
*release = false;
return index;
}
}
void
store(Context* con, unsigned size, Assembler::Register* src,
int base, int offset, int index, unsigned scale, bool preserveIndex)
{
if (index != NoRegister) {
bool release;
int normalized = normalize
(con, offset, index, scale, &preserveIndex, &release);
if (isFpr(src)) { // floating-point store
if (size == 4) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> fpr store base-indexed\n");
Assembler::Register base_(base),
normalized_(normalized),
absAddr = makeTemp(con);
addR(con, size, &base_, &normalized_, &absAddr);
emit(con, fsts(toFpr(src), absAddr.low));
freeTemp(con, absAddr);
}
else abort(con);
} else {
switch (size) {
case 1:
emit(con, strb(src->low, base, normalized));
break;
case 2:
emit(con, strh(src->low, base, normalized));
break;
case 4:
emit(con, str(src->low, base, normalized));
break;
case 8: {
Assembler::Register srcHigh(src->high);
store(con, 4, &srcHigh, base, 0, normalized, 1, preserveIndex);
store(con, 4, src, base, 4, normalized, 1, preserveIndex);
} break;
default: abort(con);
}
}
if (release) con->client->releaseTemporary(normalized);
} else if (size == 8
or abs(offset) == (abs(offset) & 0xFF)
or (size != 2 and abs(offset) == (abs(offset) & 0xFFF)))
{
if (isFpr(src)) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> [%d + 0x%x] <- %d\n", base, offset, src->low);
if (size == 4) emit(con, fsts(toFpr(src), base, offset));
else abort(con);
} else {
switch (size) {
case 1:
emit(con, strbi(src->low, base, offset));
break;
case 2:
emit(con, strhi(src->low, base, offset));
break;
case 4:
emit(con, stri(src->low, base, offset));
break;
case 8: {
Assembler::Register srcHigh(src->high);
store(con, 4, &srcHigh, base, offset, NoRegister, 1, false);
store(con, 4, src, base, offset + 4, NoRegister, 1, false);
} break;
default: abort(con);
}
}
} else {
Assembler::Register tmp(con->client->acquireTemporary());
ResolvedPromise offsetPromise(offset);
Assembler::Constant offsetConstant(&offsetPromise);
moveCR(con, TargetBytesPerWord, &offsetConstant,
TargetBytesPerWord, &tmp);
store(con, size, src, base, 0, tmp.low, 1, false);
con->client->releaseTemporary(tmp.low);
}
}
void
moveRM(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned dstSize UNUSED, Assembler::Memory* dst)
{
assert(c, srcSize == dstSize);
store(c, srcSize, src, dst->base, dst->offset, dst->index, dst->scale, true);
}
void
moveAndUpdateRM(Context* c, unsigned srcSize UNUSED, Assembler::Register* src,
unsigned dstSize UNUSED, Assembler::Memory* dst)
{
assert(c, srcSize == TargetBytesPerWord);
assert(c, dstSize == TargetBytesPerWord);
if (dst->index == NoRegister) {
emit(c, stri(src->low, dst->base, dst->offset, dst->offset ? 1 : 0));
} else {
assert(c, dst->offset == 0);
assert(c, dst->scale == 1);
emit(c, str(src->low, dst->base, dst->index, 1));
}
}
void
load(Context* con, unsigned srcSize, int base, int offset, int index,
unsigned scale, unsigned dstSize, Assembler::Register* dst,
bool preserveIndex, bool signExtend)
{
if (index != NoRegister) {
bool release;
int normalized = normalize
(con, offset, index, scale, &preserveIndex, &release);
if (isFpr(dst)) { // floating-point store
if (srcSize == 4) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> fpr load base-indexed\n");
Assembler::Register base_(base),
normalized_(normalized),
absAddr = makeTemp(con);
addR(con, srcSize, &base_, &normalized_, &absAddr);
emit(con, flds(toFpr(dst), absAddr.low));
freeTemp(con, absAddr);
}
else abort(con);
} else {
switch (srcSize) {
case 1:
if (signExtend) {
emit(con, ldrsb(dst->low, base, normalized));
} else {
emit(con, ldrb(dst->low, base, normalized));
}
break;
case 2:
if (signExtend) {
emit(con, ldrsh(dst->low, base, normalized));
} else {
emit(con, ldrh(dst->low, base, normalized));
}
break;
case 4:
case 8: {
if (srcSize == 4 and dstSize == 8) {
load(con, 4, base, 0, normalized, 1, 4, dst, preserveIndex,
false);
moveRR(con, 4, dst, 8, dst);
} else if (srcSize == 8 and dstSize == 8) {
Assembler::Register dstHigh(dst->high);
load(con, 4, base, 0, normalized, 1, 4, &dstHigh,
preserveIndex, false);
load(con, 4, base, 4, normalized, 1, 4, dst, preserveIndex,
false);
} else {
emit(con, ldr(dst->low, base, normalized));
}
} break;
default: abort(con);
}
}
if (release) con->client->releaseTemporary(normalized);
} else if ((srcSize == 8 and dstSize == 8)
or abs(offset) == (abs(offset) & 0xFF)
or (srcSize != 2
and (srcSize != 1 or not signExtend)
and abs(offset) == (abs(offset) & 0xFFF)))
{
if (isFpr(dst)) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- [%d + 0x%x]\n", dst->low, base, offset);
if (srcSize == 4) emit(con, flds(toFpr(dst), base, offset));
else abort(con);
} else {
switch (srcSize) {
case 1:
if (signExtend) {
emit(con, ldrsbi(dst->low, base, offset));
} else {
emit(con, ldrbi(dst->low, base, offset));
}
break;
case 2:
if (signExtend) {
emit(con, ldrshi(dst->low, base, offset));
} else {
emit(con, ldrhi(dst->low, base, offset));
}
break;
case 4:
emit(con, ldri(dst->low, base, offset));
break;
case 8: {
if (dstSize == 8) {
Assembler::Register dstHigh(dst->high);
load(con, 4, base, offset, NoRegister, 1, 4, &dstHigh, false,
false);
load(con, 4, base, offset + 4, NoRegister, 1, 4, dst, false,
false);
} else {
emit(con, ldri(dst->low, base, offset));
}
} break;
default: abort(con);
}
}
} else {
Assembler::Register tmp(con->client->acquireTemporary());
ResolvedPromise offsetPromise(offset);
Assembler::Constant offsetConstant(&offsetPromise);
moveCR(con, TargetBytesPerWord, &offsetConstant, TargetBytesPerWord,
&tmp);
load(con, srcSize, base, 0, tmp.low, 1, dstSize, dst, false,
signExtend);
con->client->releaseTemporary(tmp.low);
}
}
void
moveMR(Context* c, unsigned srcSize, Assembler::Memory* src,
unsigned dstSize, Assembler::Register* dst)
{
load(c, srcSize, src->base, src->offset, src->index, src->scale,
dstSize, dst, true, true);
}
void
moveZMR(Context* c, unsigned srcSize, Assembler::Memory* src,
unsigned dstSize, Assembler::Register* dst)
{
load(c, srcSize, src->base, src->offset, src->index, src->scale,
dstSize, dst, true, false);
}
void
andR(Context* c, unsigned size, Assembler::Register* a,
Assembler::Register* b, Assembler::Register* dst)
{
if (size == 8) emit(c, and_(dst->high, a->high, b->high));
emit(c, and_(dst->low, a->low, b->low));
}
void
andC(Context* c, unsigned size, Assembler::Constant* a,
Assembler::Register* b, Assembler::Register* dst)
{
int64_t v = a->value->value();
if (size == 8) {
ResolvedPromise high((v >> 32) & 0xFFFFFFFF);
Assembler::Constant ah(&high);
ResolvedPromise low(v & 0xFFFFFFFF);
Assembler::Constant al(&low);
Assembler::Register bh(b->high);
Assembler::Register dh(dst->high);
andC(c, 4, &al, b, dst);
andC(c, 4, &ah, &bh, &dh);
} else {
uint32_t v32 = static_cast<uint32_t>(v);
if (v32 != 0xFFFFFFFF) {
if ((v32 & 0xFFFFFF00) == 0xFFFFFF00) {
emit(c, bici(dst->low, b->low, (~(v32 & 0xFF)) & 0xFF));
} else if ((v32 & 0xFFFFFF00) == 0) {
emit(c, andi(dst->low, b->low, v32 & 0xFF));
} else {
// todo: there are other cases we can handle in one
// instruction
bool useTemporary = b->low == dst->low;
Assembler::Register tmp(dst->low);
if (useTemporary) {
tmp.low = c->client->acquireTemporary();
}
moveCR(c, 4, a, 4, &tmp);
andR(c, 4, b, &tmp, dst);
if (useTemporary) {
c->client->releaseTemporary(tmp.low);
}
}
} else {
moveRR(c, size, b, size, dst);
}
}
}
void
orR(Context* c, unsigned size, Assembler::Register* a,
Assembler::Register* b, Assembler::Register* dst)
{
if (size == 8) emit(c, orr(dst->high, a->high, b->high));
emit(c, orr(dst->low, a->low, b->low));
}
void
xorR(Context* con, unsigned size, Assembler::Register* a,
Assembler::Register* b, Assembler::Register* dst)
{
if (size == 8) emit(con, eor(dst->high, a->high, b->high));
emit(con, eor(dst->low, a->low, b->low));
}
void
moveAR2(Context* c, unsigned srcSize, Assembler::Address* src,
unsigned dstSize, Assembler::Register* dst)
{
assert(c, srcSize == 4 and dstSize == 4);
Assembler::Constant constant(src->address);
moveCR(c, srcSize, &constant, dstSize, dst);
Assembler::Memory memory(dst->low, 0, -1, 0);
moveMR(c, dstSize, &memory, dstSize, dst);
}
void
moveAR(Context* c, unsigned srcSize, Assembler::Address* src,
unsigned dstSize, Assembler::Register* dst)
{
moveAR2(c, srcSize, src, dstSize, dst);
}
void
compareRR(Context* c, unsigned aSize UNUSED, Assembler::Register* a,
unsigned bSize UNUSED, Assembler::Register* b)
{
assert(c, aSize == 4 and bSize == 4);
assert(c, b->low != a->low);
assert(c, !(isFpr(a) ^ isFpr(b)));
if (isFpr(a)) {
emit(c, fcmps(toFpr(b), toFpr(a)));
emit(c, fmstat());
}
else emit(c, cmp(b->low, a->low));
}
void
compareCR(Context* c, unsigned aSize, Assembler::Constant* a,
unsigned bSize, Assembler::Register* b)
{
assert(c, aSize == 4 and bSize == 4);
if (!isFpr(b) && a->value->resolved() &&
isOfWidth(a->value->value(), 8)) {
emit(c, cmpi(b->low, a->value->value()));
} else {
Assembler::Register tmp(c->client->acquireTemporary());
moveCR(c, aSize, a, bSize, &tmp);
compareRR(c, bSize, &tmp, bSize, b);
c->client->releaseTemporary(tmp.low);
}
}
void
compareCM(Context* c, unsigned aSize, Assembler::Constant* a,
unsigned bSize, Assembler::Memory* b)
{
assert(c, aSize == 4 and bSize == 4);
Assembler::Register tmp(c->client->acquireTemporary());
moveMR(c, bSize, b, bSize, &tmp);
compareCR(c, aSize, a, bSize, &tmp);
c->client->releaseTemporary(tmp.low);
}
void
compareRM(Context* c, unsigned aSize, Assembler::Register* a,
unsigned bSize, Assembler::Memory* b)
{
assert(c, aSize == 4 and bSize == 4);
Assembler::Register tmp(c->client->acquireTemporary());
moveMR(c, bSize, b, bSize, &tmp);
compareRR(c, aSize, a, bSize, &tmp);
c->client->releaseTemporary(tmp.low);
}
int32_t
branch(Context* c, TernaryOperation op)
{
switch (op) {
case JumpIfEqual:
case JumpIfFloatEqual:
return beq(0);
case JumpIfNotEqual:
case JumpIfFloatNotEqual:
return bne(0);
case JumpIfLess:
case JumpIfFloatLess:
case JumpIfFloatLessOrUnordered:
return blt(0);
case JumpIfGreater:
case JumpIfFloatGreater:
return bgt(0);
case JumpIfLessOrEqual:
case JumpIfFloatLessOrEqual:
case JumpIfFloatLessOrEqualOrUnordered:
return ble(0);
case JumpIfGreaterOrEqual:
case JumpIfFloatGreaterOrEqual:
return bge(0);
case JumpIfFloatGreaterOrUnordered:
return bhi(0);
case JumpIfFloatGreaterOrEqualOrUnordered:
return bpl(0);
default:
abort(c);
}
}
void
conditional(Context* c, int32_t branch, Assembler::Constant* target)
{
appendOffsetTask(c, target->value, offset(c));
emit(c, branch);
}
void
branch(Context* c, TernaryOperation op, Assembler::Constant* target)
{
conditional(c, branch(c, op), target);
}
void
branchLong(Context* c, TernaryOperation op, Assembler::Operand* al,
Assembler::Operand* ah, Assembler::Operand* bl,
Assembler::Operand* bh, Assembler::Constant* target,
BinaryOperationType compareSigned,
BinaryOperationType compareUnsigned)
{
compareSigned(c, 4, ah, 4, bh);
unsigned next = 0;
switch (op) {
case JumpIfEqual:
next = c->code.length();
emit(c, bne(0));
compareSigned(c, 4, al, 4, bl);
conditional(c, beq(0), target);
break;
case JumpIfNotEqual:
conditional(c, bne(0), target);
compareSigned(c, 4, al, 4, bl);
conditional(c, bne(0), target);
break;
case JumpIfLess:
conditional(c, blt(0), target);
next = c->code.length();
emit(c, bgt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, blo(0), target);
break;
case JumpIfGreater:
conditional(c, bgt(0), target);
next = c->code.length();
emit(c, blt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, bhi(0), target);
break;
case JumpIfLessOrEqual:
conditional(c, blt(0), target);
next = c->code.length();
emit(c, bgt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, bls(0), target);
break;
case JumpIfGreaterOrEqual:
conditional(c, bgt(0), target);
next = c->code.length();
emit(c, blt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, bhs(0), target);
break;
default:
abort(c);
}
if (next) {
updateOffset
(c->s, c->code.data + next, reinterpret_cast<intptr_t>
(c->code.data + c->code.length()));
}
}
void
branchRR(Context* c, TernaryOperation op, unsigned size,
Assembler::Register* a, Assembler::Register* b,
Assembler::Constant* target)
{
if (size > TargetBytesPerWord) {
Assembler::Register ah(a->high);
Assembler::Register bh(b->high);
branchLong(c, op, a, &ah, b, &bh, target, CAST2(compareRR),
CAST2(compareRR));
} else {
compareRR(c, size, a, size, b);
branch(c, op, target);
}
}
void
branchCR(Context* con, TernaryOperation op, unsigned size,
Assembler::Constant* a, Assembler::Register* b,
Assembler::Constant* target)
{
assert(con, !isFloatBranch(op));
if (size > TargetBytesPerWord) {
int64_t v = a->value->value();
ResolvedPromise low(v & ~static_cast<target_uintptr_t>(0));
Assembler::Constant al(&low);
ResolvedPromise high((v >> 32) & ~static_cast<target_uintptr_t>(0));
Assembler::Constant ah(&high);
Assembler::Register bh(b->high);
branchLong(con, op, &al, &ah, b, &bh, target, CAST2(compareCR),
CAST2(compareCR));
} else {
compareCR(con, size, a, size, b);
branch(con, op, target);
}
}
void
branchRM(Context* con, TernaryOperation op, unsigned size,
Assembler::Register* a, Assembler::Memory* b,
Assembler::Constant* target)
{
assert(con, !isFloatBranch(op));
assert(con, size <= TargetBytesPerWord);
compareRM(con, size, a, size, b);
branch(con, op, target);
}
void
branchCM(Context* con, TernaryOperation op, unsigned size,
Assembler::Constant* a, Assembler::Memory* b,
Assembler::Constant* target)
{
assert(con, !isFloatBranch(op));
assert(con, size <= TargetBytesPerWord);
compareCM(con, size, a, size, b);
branch(con, op, target);
}
ShiftMaskPromise*
shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask)
{
return new(c->zone) ShiftMaskPromise(base, shift, mask);
}
void
moveCM(Context* c, unsigned srcSize, Assembler::Constant* src,
unsigned dstSize, Assembler::Memory* dst)
{
switch (dstSize) {
case 8: {
Assembler::Constant srcHigh
(shiftMaskPromise(c, src->value, 32, 0xFFFFFFFF));
Assembler::Constant srcLow
(shiftMaskPromise(c, src->value, 0, 0xFFFFFFFF));
Assembler::Memory dstLow
(dst->base, dst->offset + 4, dst->index, dst->scale);
moveCM(c, 4, &srcLow, 4, &dstLow);
moveCM(c, 4, &srcHigh, 4, dst);
} break;
default:
Assembler::Register tmp(c->client->acquireTemporary());
moveCR(c, srcSize, src, dstSize, &tmp);
moveRM(c, dstSize, &tmp, dstSize, dst);
c->client->releaseTemporary(tmp.low);
}
}
void
negateRR(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned dstSize UNUSED, Assembler::Register* dst)
{
assert(c, srcSize == dstSize);
emit(c, mvn(dst->low, src->low));
emit(c, SETS(addi(dst->low, dst->low, 1)));
if (srcSize == 8) {
emit(c, mvn(dst->high, src->high));
emit(c, adci(dst->high, dst->high, 0));
}
}
void
callR(Context* c, unsigned size UNUSED, Assembler::Register* target)
{
assert(c, size == TargetBytesPerWord);
emit(c, blx(target->low));
}
void
callC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
appendOffsetTask(c, target->value, offset(c));
emit(c, bl(0));
}
void
longCallC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
Assembler::Register tmp(4);
moveCR2(c, TargetBytesPerWord, target, &tmp, offset(c));
callR(c, TargetBytesPerWord, &tmp);
}
void
longJumpC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
Assembler::Register tmp(4); // a non-arg reg that we don't mind clobbering
moveCR2(c, TargetBytesPerWord, target, &tmp, offset(c));
jumpR(c, TargetBytesPerWord, &tmp);
}
void
jumpC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
appendOffsetTask(c, target->value, offset(c));
emit(c, b(0));
}
void
return_(Context* c)
{
emit(c, bx(LinkRegister));
}
void
trap(Context* c)
{
emit(c, bkpt());
}
void
memoryBarrier(Context*) {}
// END OPERATION COMPILERS
unsigned
argumentFootprint(unsigned footprint)
{
return max(pad(footprint, StackAlignmentInWords), StackAlignmentInWords);
}
void
nextFrame(ArchitectureContext* c, uint32_t* start, unsigned size UNUSED,
unsigned footprint, void* link, bool,
unsigned targetParameterFootprint UNUSED, void** ip, void** stack)
{
assert(c, *ip >= start);
assert(c, *ip <= start + (size / TargetBytesPerWord));
uint32_t* instruction = static_cast<uint32_t*>(*ip);
if ((*start >> 20) == 0xe59) {
// skip stack overflow check
start += 3;
}
if (instruction <= start) {
*ip = link;
return;
}
unsigned offset = footprint + FrameHeaderSize;
if (instruction <= start + 2) {
*ip = link;
*stack = static_cast<void**>(*stack) + offset;
return;
}
if (*instruction == 0xe12fff1e) { // return
*ip = link;
return;
}
if (TailCalls) {
if (argumentFootprint(targetParameterFootprint) > StackAlignmentInWords) {
offset += argumentFootprint(targetParameterFootprint)
- StackAlignmentInWords;
}
// check for post-non-tail-call stack adjustment of the form "add
// sp, sp, #offset":
if ((*instruction >> 12) == 0xe24dd) {
unsigned value = *instruction & 0xff;
unsigned rotation = (*instruction >> 8) & 0xf;
switch (rotation) {
case 0: offset -= value / TargetBytesPerWord; break;
case 15: offset -= value; break;
default: abort(c);
}
}
// todo: check for and handle tail calls
}
*ip = static_cast<void**>(*stack)[offset - 1];
*stack = static_cast<void**>(*stack) + offset;
}
void
populateTables(ArchitectureContext* c)
{
const OperandType C = ConstantOperand;
const OperandType A = AddressOperand;
const OperandType R = RegisterOperand;
const OperandType M = MemoryOperand;
OperationType* zo = c->operations;
UnaryOperationType* uo = c->unaryOperations;
BinaryOperationType* bo = c->binaryOperations;
TernaryOperationType* to = c->ternaryOperations;
BranchOperationType* bro = c->branchOperations;
zo[Return] = return_;
zo[LoadBarrier] = memoryBarrier;
zo[StoreStoreBarrier] = memoryBarrier;
zo[StoreLoadBarrier] = memoryBarrier;
zo[Trap] = trap;
uo[index(c, LongCall, C)] = CAST1(longCallC);
uo[index(c, AlignedLongCall, C)] = CAST1(longCallC);
uo[index(c, LongJump, C)] = CAST1(longJumpC);
uo[index(c, AlignedLongJump, C)] = CAST1(longJumpC);
uo[index(c, Jump, R)] = CAST1(jumpR);
uo[index(c, Jump, C)] = CAST1(jumpC);
uo[index(c, AlignedJump, R)] = CAST1(jumpR);
uo[index(c, AlignedJump, C)] = CAST1(jumpC);
uo[index(c, Call, C)] = CAST1(callC);
uo[index(c, Call, R)] = CAST1(callR);
uo[index(c, AlignedCall, C)] = CAST1(callC);
uo[index(c, AlignedCall, R)] = CAST1(callR);
bo[index(c, Move, R, R)] = CAST2(moveRR);
bo[index(c, Move, C, R)] = CAST2(moveCR);
bo[index(c, Move, C, M)] = CAST2(moveCM);
bo[index(c, Move, M, R)] = CAST2(moveMR);
bo[index(c, Move, R, M)] = CAST2(moveRM);
bo[index(c, Move, A, R)] = CAST2(moveAR);
bo[index(c, MoveZ, R, R)] = CAST2(moveZRR);
bo[index(c, MoveZ, M, R)] = CAST2(moveZMR);
bo[index(c, MoveZ, C, R)] = CAST2(moveCR);
bo[index(c, Negate, R, R)] = CAST2(negateRR);
bo[index(c, FloatAbsolute, R, R)] = CAST2(floatAbsoluteRR);
bo[index(c, FloatNegate, R, R)] = CAST2(floatNegateRR);
bo[index(c, Float2Float, R, R)] = CAST2(float2FloatRR);
bo[index(c, Float2Int, R, R)] = CAST2(float2IntRR);
bo[index(c, Int2Float, R, R)] = CAST2(int2FloatRR);
bo[index(c, FloatSquareRoot, R, R)] = CAST2(floatSqrtRR);
to[index(c, Add, R)] = CAST3(addR);
to[index(c, Subtract, R)] = CAST3(subR);
to[index(c, Multiply, R)] = CAST3(multiplyR);
to[index(c, FloatAdd, R)] = CAST3(floatAddR);
to[index(c, FloatSubtract, R)] = CAST3(floatSubtractR);
to[index(c, FloatMultiply, R)] = CAST3(floatMultiplyR);
to[index(c, FloatDivide, R)] = CAST3(floatDivideR);
to[index(c, ShiftLeft, R)] = CAST3(shiftLeftR);
to[index(c, ShiftLeft, C)] = CAST3(shiftLeftC);
to[index(c, ShiftRight, R)] = CAST3(shiftRightR);
to[index(c, ShiftRight, C)] = CAST3(shiftRightC);
to[index(c, UnsignedShiftRight, R)] = CAST3(unsignedShiftRightR);
to[index(c, UnsignedShiftRight, C)] = CAST3(unsignedShiftRightC);
to[index(c, And, R)] = CAST3(andR);
to[index(c, And, C)] = CAST3(andC);
to[index(c, Or, R)] = CAST3(orR);
to[index(c, Xor, R)] = CAST3(xorR);
bro[branchIndex(c, R, R)] = CAST_BRANCH(branchRR);
bro[branchIndex(c, C, R)] = CAST_BRANCH(branchCR);
bro[branchIndex(c, C, M)] = CAST_BRANCH(branchCM);
bro[branchIndex(c, R, M)] = CAST_BRANCH(branchRM);
}
class MyArchitecture: public Assembler::Architecture {
public:
MyArchitecture(System* system): c(system), referenceCount(0) {
populateTables(&c);
}
virtual unsigned floatRegisterSize() {
return vfpSupported() ? 4 : 0;
}
virtual uint32_t generalRegisterMask() {
return GPR_MASK;
}
virtual uint32_t floatRegisterMask() {
return vfpSupported() ? FPR_MASK : 0;
}
virtual int scratch() {
return 5;
}
virtual int stack() {
return StackRegister;
}
virtual int thread() {
return ThreadRegister;
}
virtual int returnLow() {
return 0;
}
virtual int returnHigh() {
return 1;
}
virtual int virtualCallTarget() {
return 4;
}
virtual int virtualCallIndex() {
return 3;
}
virtual bool bigEndian() {
return false;
}
virtual uintptr_t maximumImmediateJump() {
return 0x1FFFFFF;
}
virtual bool reserved(int register_) {
switch (register_) {
case LinkRegister:
case StackRegister:
case ThreadRegister:
case ProgramCounter:
return true;
default:
return false;
}
}
virtual unsigned frameFootprint(unsigned footprint) {
return max(footprint, StackAlignmentInWords);
}
virtual unsigned argumentFootprint(unsigned footprint) {
return ::argumentFootprint(footprint);
}
virtual bool argumentAlignment() {
#ifdef __APPLE__
return false;
#else
return true;
#endif
}
virtual bool argumentRegisterAlignment() {
#ifdef __APPLE__
return false;
#else
return true;
#endif
}
virtual unsigned argumentRegisterCount() {
return 4;
}
virtual int argumentRegister(unsigned index) {
assert(&c, index < argumentRegisterCount());
return index;
}
virtual bool hasLinkRegister() {
return true;
}
virtual unsigned stackAlignmentInWords() {
return StackAlignmentInWords;
}
virtual bool matchCall(void* returnAddress, void* target) {
uint32_t* instruction = static_cast<uint32_t*>(returnAddress) - 1;
return *instruction == static_cast<uint32_t>
(bl(static_cast<uint8_t*>(target)
- reinterpret_cast<uint8_t*>(instruction)));
}
virtual void updateCall(UnaryOperation op UNUSED,
void* returnAddress,
void* newTarget)
{
switch (op) {
case Call:
case Jump:
case AlignedCall:
case AlignedJump: {
updateOffset(c.s, static_cast<uint8_t*>(returnAddress) - 4,
reinterpret_cast<intptr_t>(newTarget));
} break;
case LongCall:
case LongJump:
case AlignedLongCall:
case AlignedLongJump: {
uint32_t* p = static_cast<uint32_t*>(returnAddress) - 2;
*reinterpret_cast<void**>(p + (((*p & PoolOffsetMask) + 8) / 4))
= newTarget;
} break;
default: abort(&c);
}
}
virtual unsigned constantCallSize() {
return 4;
}
virtual void setConstant(void* dst, uint64_t constant) {
*static_cast<target_uintptr_t*>(dst) = constant;
}
virtual unsigned alignFrameSize(unsigned sizeInWords) {
return pad(sizeInWords + FrameHeaderSize, StackAlignmentInWords)
- FrameHeaderSize;
}
virtual void nextFrame(void* start, unsigned size, unsigned footprint,
void* link, bool mostRecent,
unsigned targetParameterFootprint, void** ip,
void** stack)
{
::nextFrame(&c, static_cast<uint32_t*>(start), size, footprint, link,
mostRecent, targetParameterFootprint, ip, stack);
}
virtual void* frameIp(void* stack) {
return stack ? static_cast<void**>(stack)[returnAddressOffset()] : 0;
}
virtual unsigned frameHeaderSize() {
return FrameHeaderSize;
}
virtual unsigned frameReturnAddressSize() {
return 0;
}
virtual unsigned frameFooterSize() {
return 0;
}
virtual int returnAddressOffset() {
return -1;
}
virtual int framePointerOffset() {
return 0;
}
virtual BinaryOperation hasBinaryIntrinsic(Thread*, object) {
return NoBinaryOperation;
}
virtual TernaryOperation hasTernaryIntrinsic(Thread*, object) {
return NoTernaryOperation;
}
virtual bool alwaysCondensed(BinaryOperation) {
return false;
}
virtual bool alwaysCondensed(TernaryOperation) {
return false;
}
virtual void plan
(UnaryOperation,
unsigned, uint8_t* aTypeMask, uint64_t* aRegisterMask,
bool* thunk)
{
*aTypeMask = (1 << RegisterOperand) | (1 << ConstantOperand);
*aRegisterMask = ~static_cast<uint64_t>(0);
*thunk = false;
}
virtual void planSource
(BinaryOperation op,
unsigned aSize, uint8_t* aTypeMask, uint64_t* aRegisterMask,
unsigned bSize, bool* thunk)
{
*thunk = false;
*aTypeMask = ~0;
*aRegisterMask = ~static_cast<uint64_t>(0);
switch (op) {
case Negate:
*aTypeMask = (1 << RegisterOperand);
break;
case Absolute:
case FloatAbsolute:
case FloatSquareRoot:
case FloatNegate:
case Float2Float:
if (vfpSupported()) {
*aTypeMask = (1 << RegisterOperand);
*aRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
case Float2Int:
if (vfpSupported() && bSize == 4 && aSize == 4) {
*aTypeMask = (1 << RegisterOperand);
*aRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
case Int2Float:
if (vfpSupported() && aSize == 4 && bSize == 4) {
*aTypeMask = (1 << RegisterOperand);
*aRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
default:
break;
}
}
virtual void planDestination
(BinaryOperation op,
unsigned, uint8_t, uint64_t,
unsigned, uint8_t* bTypeMask, uint64_t* bRegisterMask)
{
*bTypeMask = (1 << RegisterOperand) | (1 << MemoryOperand);
*bRegisterMask = ~static_cast<uint64_t>(0);
switch (op) {
case Negate:
*bTypeMask = (1 << RegisterOperand);
break;
default:
break;
}
}
virtual void planMove
(unsigned, uint8_t* srcTypeMask, uint64_t* srcRegisterMask,
uint8_t* tmpTypeMask, uint64_t* tmpRegisterMask,
uint8_t dstTypeMask, uint64_t)
{
*srcTypeMask = ~0;
*srcRegisterMask = ~static_cast<uint64_t>(0);
*tmpTypeMask = 0;
*tmpRegisterMask = 0;
if (dstTypeMask & (1 << MemoryOperand)) {
// can't move directly from memory or constant to memory
*srcTypeMask = 1 << RegisterOperand;
*tmpTypeMask = 1 << RegisterOperand;
*tmpRegisterMask = ~static_cast<uint64_t>(0);
}
}
virtual void planSource
(TernaryOperation op,
unsigned, uint8_t* aTypeMask, uint64_t* aRegisterMask,
unsigned bSize, uint8_t* bTypeMask, uint64_t* bRegisterMask,
unsigned, bool* thunk)
{
*aTypeMask = (1 << RegisterOperand) | (1 << ConstantOperand);
*aRegisterMask = ~static_cast<uint64_t>(0);
*bTypeMask = (1 << RegisterOperand);
*bRegisterMask = ~static_cast<uint64_t>(0);
*thunk = false;
switch (op) {
case ShiftLeft:
case ShiftRight:
case UnsignedShiftRight:
if (bSize == 8) *aTypeMask = *bTypeMask = (1 << RegisterOperand);
break;
case Add:
case Subtract:
case Or:
case Xor:
case Multiply:
*aTypeMask = *bTypeMask = (1 << RegisterOperand);
break;
case Divide:
case Remainder:
*thunk = true;
break;
case FloatAdd:
case FloatSubtract:
case FloatMultiply:
case FloatDivide:
case FloatRemainder:
case JumpIfFloatEqual:
case JumpIfFloatNotEqual:
case JumpIfFloatLess:
case JumpIfFloatGreater:
case JumpIfFloatLessOrEqual:
case JumpIfFloatGreaterOrEqual:
case JumpIfFloatLessOrUnordered:
case JumpIfFloatGreaterOrUnordered:
case JumpIfFloatLessOrEqualOrUnordered:
case JumpIfFloatGreaterOrEqualOrUnordered:
if (vfpSupported()) {
*aTypeMask = *bTypeMask = (1 << RegisterOperand);
*aRegisterMask = *bRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
default:
break;
}
}
virtual void planDestination
(TernaryOperation op,
unsigned, uint8_t, uint64_t,
unsigned, uint8_t, const uint64_t,
unsigned, uint8_t* cTypeMask, uint64_t* cRegisterMask)
{
if (isBranch(op)) {
*cTypeMask = (1 << ConstantOperand);
*cRegisterMask = 0;
} else {
*cTypeMask = (1 << RegisterOperand);
*cRegisterMask = ~static_cast<uint64_t>(0);
}
}
virtual void acquire() {
++ referenceCount;
}
virtual void release() {
if (-- referenceCount == 0) {
c.s->free(this);
}
}
ArchitectureContext c;
unsigned referenceCount;
};
class MyAssembler: public Assembler {
public:
MyAssembler(System* s, Allocator* a, Zone* zone, MyArchitecture* arch):
c(s, a, zone), arch_(arch)
{ }
virtual void setClient(Client* client) {
assert(&c, c.client == 0);
c.client = client;
}
virtual Architecture* arch() {
return arch_;
}
virtual void checkStackOverflow(uintptr_t handler,
unsigned stackLimitOffsetFromThread)
{
Register stack(StackRegister);
Memory stackLimit(ThreadRegister, stackLimitOffsetFromThread);
Constant handlerConstant(new(c.zone) ResolvedPromise(handler));
branchRM(&c, JumpIfGreaterOrEqual, TargetBytesPerWord, &stack, &stackLimit,
&handlerConstant);
}
virtual void saveFrame(unsigned stackOffset, unsigned ipOffset) {
Register link(LinkRegister);
Memory linkDst(ThreadRegister, ipOffset);
moveRM(&c, TargetBytesPerWord, &link, TargetBytesPerWord, &linkDst);
Register stack(StackRegister);
Memory stackDst(ThreadRegister, stackOffset);
moveRM(&c, TargetBytesPerWord, &stack, TargetBytesPerWord, &stackDst);
}
virtual void pushFrame(unsigned argumentCount, ...) {
struct {
unsigned size;
OperandType type;
Operand* operand;
} arguments[argumentCount];
va_list a; va_start(a, argumentCount);
unsigned footprint = 0;
for (unsigned i = 0; i < argumentCount; ++i) {
arguments[i].size = va_arg(a, unsigned);
arguments[i].type = static_cast<OperandType>(va_arg(a, int));
arguments[i].operand = va_arg(a, Operand*);
footprint += ceiling(arguments[i].size, TargetBytesPerWord);
}
va_end(a);
allocateFrame(arch_->alignFrameSize(footprint));
unsigned offset = 0;
for (unsigned i = 0; i < argumentCount; ++i) {
if (i < arch_->argumentRegisterCount()) {
Register dst(arch_->argumentRegister(i));
apply(Move,
arguments[i].size, arguments[i].type, arguments[i].operand,
pad(arguments[i].size, TargetBytesPerWord), RegisterOperand,
&dst);
offset += ceiling(arguments[i].size, TargetBytesPerWord);
} else {
Memory dst(StackRegister, offset * TargetBytesPerWord);
apply(Move,
arguments[i].size, arguments[i].type, arguments[i].operand,
pad(arguments[i].size, TargetBytesPerWord), MemoryOperand, &dst);
offset += ceiling(arguments[i].size, TargetBytesPerWord);
}
}
}
virtual void allocateFrame(unsigned footprint) {
footprint += FrameHeaderSize;
// larger frames may require multiple subtract/add instructions
// to allocate/deallocate, and nextFrame will need to be taught
// how to handle them:
assert(&c, footprint < 256);
Register stack(StackRegister);
ResolvedPromise footprintPromise(footprint * TargetBytesPerWord);
Constant footprintConstant(&footprintPromise);
subC(&c, TargetBytesPerWord, &footprintConstant, &stack, &stack);
Register returnAddress(LinkRegister);
Memory returnAddressDst
(StackRegister, (footprint - 1) * TargetBytesPerWord);
moveRM(&c, TargetBytesPerWord, &returnAddress, TargetBytesPerWord,
&returnAddressDst);
}
virtual void adjustFrame(unsigned difference) {
Register stack(StackRegister);
ResolvedPromise differencePromise(difference * TargetBytesPerWord);
Constant differenceConstant(&differencePromise);
subC(&c, TargetBytesPerWord, &differenceConstant, &stack, &stack);
}
virtual void popFrame(unsigned footprint) {
footprint += FrameHeaderSize;
Register returnAddress(LinkRegister);
Memory returnAddressSrc
(StackRegister, (footprint - 1) * TargetBytesPerWord);
moveMR(&c, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord,
&returnAddress);
Register stack(StackRegister);
ResolvedPromise footprintPromise(footprint * TargetBytesPerWord);
Constant footprintConstant(&footprintPromise);
addC(&c, TargetBytesPerWord, &footprintConstant, &stack, &stack);
}
virtual void popFrameForTailCall(unsigned footprint,
int offset,
int returnAddressSurrogate,
int framePointerSurrogate UNUSED)
{
assert(&c, framePointerSurrogate == NoRegister);
if (TailCalls) {
if (offset) {
footprint += FrameHeaderSize;
Register link(LinkRegister);
Memory returnAddressSrc
(StackRegister, (footprint - 1) * TargetBytesPerWord);
moveMR(&c, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord,
&link);
Register stack(StackRegister);
ResolvedPromise footprintPromise
((footprint - offset) * TargetBytesPerWord);
Constant footprintConstant(&footprintPromise);
addC(&c, TargetBytesPerWord, &footprintConstant, &stack, &stack);
if (returnAddressSurrogate != NoRegister) {
assert(&c, offset > 0);
Register ras(returnAddressSurrogate);
Memory dst(StackRegister, (offset - 1) * TargetBytesPerWord);
moveRM(&c, TargetBytesPerWord, &ras, TargetBytesPerWord, &dst);
}
} else {
popFrame(footprint);
}
} else {
abort(&c);
}
}
virtual void popFrameAndPopArgumentsAndReturn(unsigned frameFootprint,
unsigned argumentFootprint)
{
popFrame(frameFootprint);
assert(&c, argumentFootprint >= StackAlignmentInWords);
assert(&c, (argumentFootprint % StackAlignmentInWords) == 0);
unsigned offset;
if (TailCalls and argumentFootprint > StackAlignmentInWords) {
offset = argumentFootprint - StackAlignmentInWords;
Register stack(StackRegister);
ResolvedPromise adjustmentPromise(offset * TargetBytesPerWord);
Constant adjustment(&adjustmentPromise);
addC(&c, TargetBytesPerWord, &adjustment, &stack, &stack);
} else {
offset = 0;
}
return_(&c);
}
virtual void popFrameAndUpdateStackAndReturn(unsigned frameFootprint,
unsigned stackOffsetFromThread)
{
popFrame(frameFootprint);
Register stack(StackRegister);
Memory newStackSrc(ThreadRegister, stackOffsetFromThread);
moveMR(&c, TargetBytesPerWord, &newStackSrc, TargetBytesPerWord, &stack);
return_(&c);
}
virtual void apply(Operation op) {
arch_->c.operations[op](&c);
}
virtual void apply(UnaryOperation op,
unsigned aSize, OperandType aType, Operand* aOperand)
{
arch_->c.unaryOperations[index(&(arch_->c), op, aType)]
(&c, aSize, aOperand);
}
virtual void apply(BinaryOperation op,
unsigned aSize, OperandType aType, Operand* aOperand,
unsigned bSize, OperandType bType, Operand* bOperand)
{
arch_->c.binaryOperations[index(&(arch_->c), op, aType, bType)]
(&c, aSize, aOperand, bSize, bOperand);
}
virtual void apply(TernaryOperation op,
unsigned aSize, OperandType aType, Operand* aOperand,
unsigned bSize, OperandType bType UNUSED,
Operand* bOperand,
unsigned cSize UNUSED, OperandType cType UNUSED,
Operand* cOperand)
{
if (isBranch(op)) {
assert(&c, aSize == bSize);
assert(&c, cSize == TargetBytesPerWord);
assert(&c, cType == ConstantOperand);
arch_->c.branchOperations[branchIndex(&(arch_->c), aType, bType)]
(&c, op, aSize, aOperand, bOperand, cOperand);
} else {
assert(&c, bSize == cSize);
assert(&c, bType == RegisterOperand);
assert(&c, cType == RegisterOperand);
arch_->c.ternaryOperations[index(&(arch_->c), op, aType)]
(&c, bSize, aOperand, bOperand, cOperand);
}
}
virtual void setDestination(uint8_t* dst) {
c.result = dst;
}
virtual void write() {
uint8_t* dst = c.result;
unsigned dstOffset = 0;
for (MyBlock* b = c.firstBlock; b; b = b->next) {
if (DebugPool) {
fprintf(stderr, "write block %p\n", b);
}
unsigned blockOffset = 0;
for (PoolEvent* e = b->poolEventHead; e; e = e->next) {
unsigned size = e->offset - blockOffset;
memcpy(dst + dstOffset, c.code.data + b->offset + blockOffset, size);
blockOffset = e->offset;
dstOffset += size;
unsigned poolSize = 0;
for (PoolOffset* o = e->poolOffsetHead; o; o = o->next) {
if (DebugPool) {
fprintf(stderr, "visit pool offset %p %d in block %p\n",
o, o->offset, b);
}
unsigned entry = dstOffset + poolSize;
if (needJump(b)) {
entry += TargetBytesPerWord;
}
o->entry->address = dst + entry;
unsigned instruction = o->block->start
+ padding(o->block, o->offset) + o->offset;
int32_t v = (entry - 8) - instruction;
expect(&c, v == (v & PoolOffsetMask));
int32_t* p = reinterpret_cast<int32_t*>(dst + instruction);
*p = (v & PoolOffsetMask) | ((~PoolOffsetMask) & *p);
poolSize += TargetBytesPerWord;
}
bool jump = needJump(b);
if (jump) {
write4
(dst + dstOffset, ::b((poolSize + TargetBytesPerWord - 8) >> 2));
}
dstOffset += poolSize + (jump ? TargetBytesPerWord : 0);
}
unsigned size = b->size - blockOffset;
memcpy(dst + dstOffset,
c.code.data + b->offset + blockOffset,
size);
dstOffset += size;
}
for (Task* t = c.tasks; t; t = t->next) {
t->run(&c);
}
for (ConstantPoolEntry* e = c.constantPool; e; e = e->next) {
if (e->constant->resolved()) {
*static_cast<target_uintptr_t*>(e->address) = e->constant->value();
} else {
new (e->constant->listen(sizeof(ConstantPoolListener)))
ConstantPoolListener(c.s, static_cast<target_uintptr_t*>(e->address),
e->callOffset
? dst + e->callOffset->value() + 8
: 0);
}
// fprintf(stderr, "constant %p at %p\n", reinterpret_cast<void*>(e->constant->value()), e->address);
}
}
virtual Promise* offset(bool forTrace) {
return ::offset(&c, forTrace);
}
virtual Block* endBlock(bool startNew) {
MyBlock* b = c.lastBlock;
b->size = c.code.length() - b->offset;
if (startNew) {
c.lastBlock = new (c.zone) MyBlock(&c, c.code.length());
} else {
c.lastBlock = 0;
}
return b;
}
virtual void endEvent() {
MyBlock* b = c.lastBlock;
unsigned thisEventOffset = c.code.length() - b->offset;
if (b->poolOffsetHead) {
int32_t v = (thisEventOffset + TargetBytesPerWord - 8)
- b->poolOffsetHead->offset;
if (v > 0 and v != (v & PoolOffsetMask)) {
appendPoolEvent
(&c, b, b->lastEventOffset, b->poolOffsetHead,
b->lastPoolOffsetTail);
if (DebugPool) {
for (PoolOffset* o = b->poolOffsetHead;
o != b->lastPoolOffsetTail->next; o = o->next)
{
fprintf(stderr,
"in endEvent, include %p %d in pool event %p at offset %d "
"in block %p\n",
o, o->offset, b->poolEventTail, b->lastEventOffset, b);
}
}
b->poolOffsetHead = b->lastPoolOffsetTail->next;
b->lastPoolOffsetTail->next = 0;
if (b->poolOffsetHead == 0) {
b->poolOffsetTail = 0;
}
}
}
b->lastEventOffset = thisEventOffset;
b->lastPoolOffsetTail = b->poolOffsetTail;
}
virtual unsigned length() {
return c.code.length();
}
virtual unsigned footerSize() {
return 0;
}
virtual void dispose() {
c.code.dispose();
}
Context c;
MyArchitecture* arch_;
};
} // namespace
namespace vm {
Assembler::Architecture*
makeArchitecture(System* system, bool)
{
return new (allocate(system, sizeof(MyArchitecture))) MyArchitecture(system);
}
Assembler*
makeAssembler(System* system, Allocator* allocator, Zone* zone,
Assembler::Architecture* architecture)
{
return new(zone) MyAssembler(system, allocator, zone,
static_cast<MyArchitecture*>(architecture));
}
} // namespace vm
added immediate to bkpt instruction
/* Copyright (c) 2010-2012, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include "assembler.h"
#include "vector.h"
#define CAST1(x) reinterpret_cast<UnaryOperationType>(x)
#define CAST2(x) reinterpret_cast<BinaryOperationType>(x)
#define CAST3(x) reinterpret_cast<TernaryOperationType>(x)
#define CAST_BRANCH(x) reinterpret_cast<BranchOperationType>(x)
using namespace vm;
namespace {
namespace isa {
// SYSTEM REGISTERS
const int FPSID = 0x0;
const int FPSCR = 0x1;
const int FPEXC = 0x8;
// INSTRUCTION OPTIONS
enum CONDITION { EQ, NE, CS, CC, MI, PL, VS, VC, HI, LS, GE, LT, GT, LE, AL, NV };
enum SHIFTOP { LSL, LSR, ASR, ROR };
// INSTRUCTION FORMATS
inline int DATA(int cond, int opcode, int S, int Rn, int Rd, int shift, int Sh, int Rm)
{ return cond<<28 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | shift<<7 | Sh<<5 | Rm; }
inline int DATAS(int cond, int opcode, int S, int Rn, int Rd, int Rs, int Sh, int Rm)
{ return cond<<28 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | Rs<<8 | Sh<<5 | 1<<4 | Rm; }
inline int DATAI(int cond, int opcode, int S, int Rn, int Rd, int rot, int imm)
{ return cond<<28 | 1<<25 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | rot<<8 | (imm&0xff); }
inline int BRANCH(int cond, int L, int offset)
{ return cond<<28 | 5<<25 | L<<24 | (offset&0xffffff); }
inline int BRANCHX(int cond, int L, int Rm)
{ return cond<<28 | 0x4bffc<<6 | L<<5 | 1<<4 | Rm; }
inline int MULTIPLY(int cond, int mul, int S, int Rd, int Rn, int Rs, int Rm)
{ return cond<<28 | mul<<21 | S<<20 | Rd<<16 | Rn<<12 | Rs<<8 | 9<<4 | Rm; }
inline int XFER(int cond, int P, int U, int B, int W, int L, int Rn, int Rd, int shift, int Sh, int Rm)
{ return cond<<28 | 3<<25 | P<<24 | U<<23 | B<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | shift<<7 | Sh<<5 | Rm; }
inline int XFERI(int cond, int P, int U, int B, int W, int L, int Rn, int Rd, int offset)
{ return cond<<28 | 2<<25 | P<<24 | U<<23 | B<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | (offset&0xfff); }
inline int XFER2(int cond, int P, int U, int W, int L, int Rn, int Rd, int S, int H, int Rm)
{ return cond<<28 | P<<24 | U<<23 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | 1<<7 | S<<6 | H<<5 | 1<<4 | Rm; }
inline int XFER2I(int cond, int P, int U, int W, int L, int Rn, int Rd, int offsetH, int S, int H, int offsetL)
{ return cond<<28 | P<<24 | U<<23 | 1<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | offsetH<<8 | 1<<7 | S<<6 | H<<5 | 1<<4 | (offsetL&0xf); }
inline int BLOCKXFER(int cond, int P, int U, int S, int W, int L, int Rn, int rlist)
{ return cond<<28 | 4<<25 | P<<24 | U<<23 | S<<22 | W<<21 | L<<20 | Rn<<16 | rlist; }
inline int SWI(int cond, int imm)
{ return cond<<28 | 0x0f<<24 | (imm&0xffffff); }
inline int SWAP(int cond, int B, int Rn, int Rd, int Rm)
{ return cond<<28 | 1<<24 | B<<22 | Rn<<16 | Rd<<12 | 9<<4 | Rm; }
inline int COOP(int cond, int opcode_1, int CRn, int CRd, int cp_num, int opcode_2, int CRm)
{ return cond<<28 | 0xe<<24 | opcode_1<<20 | CRn<<16 | CRd<<12 | cp_num<<8 | opcode_2<<5 | CRm; }
inline int COXFER(int cond, int P, int U, int N, int W, int L, int Rn, int CRd, int cp_num, int offset)
{ return cond<<28 | 0x6<<25 | P<<24 | U<<23 | N<<22 | W<<21 | L<<20 | Rn<<16 | CRd<<12 | cp_num<<8 | (offset&0xff); }
inline int COREG(int cond, int opcode_1, int L, int CRn, int Rd, int cp_num, int opcode_2, int CRm)
{ return cond<<28 | 0xe<<24 | opcode_1<<21 | L<<20 | CRn<<16 | Rd<<12 | cp_num<<8 | opcode_2<<5 | 1<<4 | CRm; }
inline int COREG2(int cond, int L, int Rn, int Rd, int cp_num, int opcode, int CRm)
{ return cond<<28 | 0xc4<<20 | L<<20 | Rn<<16 | Rd<<12 | cp_num<<8 | opcode<<4 | CRm;}
// FIELD CALCULATORS
inline int calcU(int imm) { return imm >= 0 ? 1 : 0; }
// INSTRUCTIONS
// The "cond" and "S" fields are set using the SETCOND() and SETS() functions
inline int b(int offset) { return BRANCH(AL, 0, offset); }
inline int bl(int offset) { return BRANCH(AL, 1, offset); }
inline int bx(int Rm) { return BRANCHX(AL, 0, Rm); }
inline int blx(int Rm) { return BRANCHX(AL, 1, Rm); }
inline int swi(int imm) { return SWI(AL, imm); }
inline int and_(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x0, 0, Rn, Rd, shift, Sh, Rm); }
inline int eor(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x1, 0, Rn, Rd, shift, Sh, Rm); }
inline int sub(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x2, 0, Rn, Rd, shift, Sh, Rm); }
inline int rsb(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x3, 0, Rn, Rd, shift, Sh, Rm); }
inline int add(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x4, 0, Rn, Rd, shift, Sh, Rm); }
inline int adc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x5, 0, Rn, Rd, shift, Sh, Rm); }
inline int sbc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x6, 0, Rn, Rd, shift, Sh, Rm); }
inline int rsc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x7, 0, Rn, Rd, shift, Sh, Rm); }
inline int tst(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x8, 1, Rn, 0, shift, Sh, Rm); }
inline int teq(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x9, 1, Rn, 0, shift, Sh, Rm); }
inline int cmp(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xa, 1, Rn, 0, shift, Sh, Rm); }
inline int cmn(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xb, 1, Rn, 0, shift, Sh, Rm); }
inline int orr(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xc, 0, Rn, Rd, shift, Sh, Rm); }
inline int mov(int Rd, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xd, 0, 0, Rd, shift, Sh, Rm); }
inline int bic(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xe, 0, Rn, Rd, shift, Sh, Rm); }
inline int mvn(int Rd, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xf, 0, 0, Rd, shift, Sh, Rm); }
inline int andi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x0, 0, Rn, Rd, rot, imm); }
inline int eori(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x1, 0, Rn, Rd, rot, imm); }
inline int subi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x2, 0, Rn, Rd, rot, imm); }
inline int rsbi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x3, 0, Rn, Rd, rot, imm); }
inline int addi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x4, 0, Rn, Rd, rot, imm); }
inline int adci(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x5, 0, Rn, Rd, rot, imm); }
inline int bici(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0xe, 0, Rn, Rd, rot, imm); }
inline int cmpi(int Rn, int imm, int rot=0) { return DATAI(AL, 0xa, 1, Rn, 0, rot, imm); }
inline int orri(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0xc, 0, Rn, Rd, rot, imm); }
inline int movi(int Rd, int imm, int rot=0) { return DATAI(AL, 0xd, 0, 0, Rd, rot, imm); }
inline int orrsh(int Rd, int Rn, int Rm, int Rs, int Sh) { return DATAS(AL, 0xc, 0, Rn, Rd, Rs, Sh, Rm); }
inline int movsh(int Rd, int Rm, int Rs, int Sh) { return DATAS(AL, 0xd, 0, 0, Rd, Rs, Sh, Rm); }
inline int mul(int Rd, int Rm, int Rs) { return MULTIPLY(AL, 0, 0, Rd, 0, Rs, Rm); }
inline int mla(int Rd, int Rm, int Rs, int Rn) { return MULTIPLY(AL, 1, 0, Rd, Rn, Rs, Rm); }
inline int umull(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 4, 0, RdHi, RdLo, Rs, Rm); }
inline int umlal(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 5, 0, RdHi, RdLo, Rs, Rm); }
inline int smull(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 6, 0, RdHi, RdLo, Rs, Rm); }
inline int smlal(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 7, 0, RdHi, RdLo, Rs, Rm); }
inline int ldr(int Rd, int Rn, int Rm, int W=0) { return XFER(AL, 1, 1, 0, W, 1, Rn, Rd, 0, 0, Rm); }
inline int ldri(int Rd, int Rn, int imm, int W=0) { return XFERI(AL, 1, calcU(imm), 0, W, 1, Rn, Rd, abs(imm)); }
inline int ldrb(int Rd, int Rn, int Rm) { return XFER(AL, 1, 1, 1, 0, 1, Rn, Rd, 0, 0, Rm); }
inline int ldrbi(int Rd, int Rn, int imm) { return XFERI(AL, 1, calcU(imm), 1, 0, 1, Rn, Rd, abs(imm)); }
inline int str(int Rd, int Rn, int Rm, int W=0) { return XFER(AL, 1, 1, 0, W, 0, Rn, Rd, 0, 0, Rm); }
inline int stri(int Rd, int Rn, int imm, int W=0) { return XFERI(AL, 1, calcU(imm), 0, W, 0, Rn, Rd, abs(imm)); }
inline int strb(int Rd, int Rn, int Rm) { return XFER(AL, 1, 1, 1, 0, 0, Rn, Rd, 0, 0, Rm); }
inline int strbi(int Rd, int Rn, int imm) { return XFERI(AL, 1, calcU(imm), 1, 0, 0, Rn, Rd, abs(imm)); }
inline int ldrh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 0, 1, Rm); }
inline int ldrhi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 0, 1, abs(imm)&0xf); }
inline int strh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 0, Rn, Rd, 0, 1, Rm); }
inline int strhi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 0, Rn, Rd, abs(imm)>>4 & 0xf, 0, 1, abs(imm)&0xf); }
inline int ldrsh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 1, Rm); }
inline int ldrshi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 1, 1, abs(imm)&0xf); }
inline int ldrsb(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 0, Rm); }
inline int ldrsbi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 1, 0, abs(imm)&0xf); }
inline int pop(int Rd) { return XFERI(AL, 0, 1, 0, 0, 1, 13, Rd, 4); }
inline int ldmfd(int Rn, int rlist) { return BLOCKXFER(AL, 0, 1, 0, 1, 1, Rn, rlist); }
inline int stmfd(int Rn, int rlist) { return BLOCKXFER(AL, 1, 0, 0, 1, 0, Rn, rlist); }
inline int swp(int Rd, int Rm, int Rn) { return SWAP(AL, 0, Rn, Rd, Rm); }
inline int swpb(int Rd, int Rm, int Rn) { return SWAP(AL, 1, Rn, Rd, Rm); }
// breakpoint instruction, this really has its own instruction format
inline int bkpt(int16_t immed) { return 0xe1200070 | (((unsigned)immed & 0xffff) >> 4 << 8) | (immed & 0xf); }
// COPROCESSOR INSTRUCTIONS
inline int cdp(int coproc, int opcode_1, int CRd, int CRn, int CRm, int opcode_2) { return COOP(AL, opcode_1, CRn, CRd, coproc, opcode_2, CRm); }
inline int mcr(int coproc, int opcode_1, int Rd, int CRn, int CRm, int opcode_2=0) { return COREG(AL, opcode_1, 0, CRn, Rd, coproc, opcode_2, CRm); }
inline int mcrr(int coproc, int opcode, int Rd, int Rn, int CRm) { return COREG2(AL, 0, Rn, Rd, coproc, opcode, CRm); }
inline int mrc(int coproc, int opcode_1, int Rd, int CRn, int CRm, int opcode_2=0) { return COREG(AL, opcode_1, 1, CRn, Rd, coproc, opcode_2, CRm); }
inline int mrrc(int coproc, int opcode, int Rd, int Rn, int CRm) { return COREG2(AL, 1, Rn, Rd, coproc, opcode, CRm); }
inline int ldc(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 0, W, 1, Rn, CRd, coproc, offset); }
inline int ldcl(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 1, W, 1, Rn, CRd, coproc, offset); }
inline int stc(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 0, W, 0, Rn, CRd, coproc, offset); }
inline int stcl(int coproc, int CRd, int Rn, int offset=0, int W=0) { return COXFER(AL, 1, 1, 1, W, 0, Rn, CRd, coproc, offset); }
// VFP FLOATING-POINT INSTRUCTIONS
inline int fmacs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fnmacs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fmscs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|1, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fnmscs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|1, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fmuls(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fnmuls(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fadds(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|3, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fsubs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|3, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); }
inline int fdivs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|8, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); }
inline int fmacd(int Dd, int Dn, int Dm) { return COOP(AL, 0, Dn, Dd, 11, 0, Dm); }
inline int fnmacd(int Dd, int Dn, int Dm) { return COOP(AL, 0, Dn, Dd, 11, 2, Dm); }
inline int fmscd(int Dd, int Dn, int Dm) { return COOP(AL, 1, Dn, Dd, 11, 0, Dm); }
inline int fnmscd(int Dd, int Dn, int Dm) { return COOP(AL, 1, Dn, Dd, 11, 2, Dm); }
inline int fmuld(int Dd, int Dn, int Dm) { return COOP(AL, 2, Dn, Dd, 11, 0, Dm); }
inline int fnmuld(int Dd, int Dn, int Dm) { return COOP(AL, 2, Dn, Dd, 11, 2, Dm); }
inline int faddd(int Dd, int Dn, int Dm) { return COOP(AL, 3, Dn, Dd, 11, 0, Dm); }
inline int fsubd(int Dd, int Dn, int Dm) { return COOP(AL, 3, Dn, Dd, 11, 2, Dm); }
inline int fdivd(int Dd, int Dn, int Dm) { return COOP(AL, 8, Dn, Dd, 11, 0, Dm); }
inline int fcpys(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fabss(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fnegs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 1, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fsqrts(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 1, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fcmps(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 4, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fcmpes(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 4, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fcmpzs(int Sd) { return COOP(AL, 0xb|(Sd&1)<<2, 5, Sd>>1, 10, 2, 0); }
inline int fcmpezs(int Sd) { return COOP(AL, 0xb|(Sd&1)<<2, 5, Sd>>1, 10, 6, 0); }
inline int fcvtds(int Dd, int Sm) { return COOP(AL, 0xb, 7, Dd, 10, 6|(Sm&1), Sm>>1); }
inline int fuitos(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 8, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int fsitos(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 8, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int ftouis(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int ftouizs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int ftosis(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 10, 2|(Sm&1), Sm>>1); }
inline int ftosizs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 10, 6|(Sm&1), Sm>>1); }
inline int fcpyd(int Dd, int Dm) { return COOP(AL, 0xb, 0, Dd, 11, 2, Dm); }
inline int fabsd(int Dd, int Dm) { return COOP(AL, 0xb, 0, Dd, 11, 6, Dm); }
inline int fnegd(int Dd, int Dm) { return COOP(AL, 0xb, 1, Dd, 11, 2, Dm); }
inline int fsqrtd(int Dd, int Dm) { return COOP(AL, 0xb, 1, Dd, 11, 6, Dm); }
inline int fcmpd(int Dd, int Dm) { return COOP(AL, 0xb, 4, Dd, 11, 2, Dm); }
inline int fcmped(int Dd, int Dm) { return COOP(AL, 0xb, 4, Dd, 11, 6, Dm); }
inline int fcmpzd(int Dd) { return COOP(AL, 0xb, 5, Dd, 11, 2, 0); }
inline int fcmpezd(int Dd) { return COOP(AL, 0xb, 5, Dd, 11, 6, 0); }
inline int fcvtsd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 7, Sd>>1, 11, 6, Dm); }
inline int fuitod(int Dd, int Sm) { return COOP(AL, 0xb, 8, Dd, 11, 2|(Sm&1), Sm>>1); }
inline int fsitod(int Dd, int Sm) { return COOP(AL, 0xb, 8, Dd, 11, 6|(Sm&1), Sm>>1); }
inline int ftouid(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 11, 2, Dm); }
inline int ftouizd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xc, Sd>>1, 11, 6, Dm); }
inline int ftosid(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 11, 2, Dm); }
inline int ftosizd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 11, 6, Dm); }
inline int fldms(int Rn, int Sd, int count) { return COXFER(AL, 0, 1, Sd&1, 0, 1, Rn, Sd>>1, 10, count); }
inline int fldmd(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 1, Rn, Dd, 11, count<<1); }
inline int fldmx(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 1, Rn, Dd, 11, count<<1|1); }
inline int fstms(int Rn, int Sd, int count) { return COXFER(AL, 0, 1, Sd&1, 0, 0, Rn, Sd>>1, 10, count); }
inline int fstmd(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 0, Rn, Dd, 11, count<<1); }
inline int fstmx(int Rn, int Dd, int count) { return COXFER(AL, 0, 1, 0, 0, 0, Rn, Dd, 11, count<<1|1); }
inline int flds(int Sd, int Rn, int offset=0) { return COXFER(AL, 1, 1, Sd&1, 0, 1, Rn, Sd>>1, 10, offset); };
inline int fldd(int Dd, int Rn, int offset=0) { return COXFER(AL, 1, 1, 0, 0, 1, Rn, Dd, 11, offset); };
inline int fsts(int Sd, int Rn, int offset=0) { return COXFER(AL, 1, 1, Sd&1, 0, 0, Rn, Sd>>1, 10, offset); };
inline int fstd(int Dd, int Rn, int offset=0) { return COXFER(AL, 1, 1, 0, 0, 0, Rn, Dd, 11, offset); };
inline int fmsr(int Sn, int Rd) { return mcr(10, 0, Rd, Sn>>1, 0, (Sn&1)<<2); }
inline int fmrs(int Rd, int Sn) { return mrc(10, 0, Rd, Sn>>1, 0, (Sn&1)<<2); }
inline int fmdlr(int Dn, int Rd) { return mcr(11, 0, Rd, Dn, 0); }
inline int fmrdl(int Rd, int Dn) { return mrc(11, 0, Rd, Dn, 0); }
inline int fmdhr(int Dn, int Rd) { return mcr(11, 1, Rd, Dn, 0); }
inline int fmrdh(int Rd, int Dn) { return mrc(11, 1, Rd, Dn, 0); }
inline int fmxr(int reg, int Rd) { return mcr(10, 7, Rd, reg, 0); }
inline int fmrx(int Rd, int reg) { return mrc(10, 7, Rd, reg, 0); }
inline int fmsrr(int Sm, int Rd, int Rn) { return mcrr(10, 1 | ((Sm&1)<<1), Rd, Rn, Sm>>1); }
inline int fmrrs(int Rd, int Rn, int Sm) { return mrrc(10, 1 | ((Sm&1)<<1), Rd, Rn, Sm>>1); }
inline int fmdrr(int Dm, int Rd, int Rn) { return mcrr(11, 1, Rd, Rn, Dm); }
inline int fmrrd(int Rd, int Rn, int Dm) { return mrrc(11, 1, Rd, Rn, Dm); }
// FLAG SETTERS
inline int SETCOND(int ins, int cond) { return ((ins&0x0fffffff) | (cond<<28)); }
inline int SETS(int ins) { return ins | 1<<20; }
// PSEUDO-INSTRUCTIONS
inline int nop() { return mov(0, 0); }
inline int lsl(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, LSL); }
inline int lsli(int Rd, int Rm, int imm) { return mov(Rd, Rm, LSL, imm); }
inline int lsr(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, LSR); }
inline int lsri(int Rd, int Rm, int imm) { return mov(Rd, Rm, LSR, imm); }
inline int asr(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, ASR); }
inline int asri(int Rd, int Rm, int imm) { return mov(Rd, Rm, ASR, imm); }
inline int ror(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, ROR); }
inline int beq(int offset) { return SETCOND(b(offset), EQ); }
inline int bne(int offset) { return SETCOND(b(offset), NE); }
inline int bls(int offset) { return SETCOND(b(offset), LS); }
inline int bhi(int offset) { return SETCOND(b(offset), HI); }
inline int blt(int offset) { return SETCOND(b(offset), LT); }
inline int bgt(int offset) { return SETCOND(b(offset), GT); }
inline int ble(int offset) { return SETCOND(b(offset), LE); }
inline int bge(int offset) { return SETCOND(b(offset), GE); }
inline int blo(int offset) { return SETCOND(b(offset), CC); }
inline int bhs(int offset) { return SETCOND(b(offset), CS); }
inline int bpl(int offset) { return SETCOND(b(offset), PL); }
inline int fmstat() { return fmrx(15, FPSCR); }
// HARDWARE FLAGS
bool vfpSupported() {
return true; // TODO
}
}
const uint64_t MASK_LO32 = 0xffffffff;
const unsigned MASK_LO16 = 0xffff;
const unsigned MASK_LO8 = 0xff;
inline unsigned lo32(int64_t i) { return (unsigned)(i&MASK_LO32); }
inline unsigned hi32(int64_t i) { return (unsigned)(i>>32); }
inline unsigned lo16(int64_t i) { return (unsigned)(i&MASK_LO16); }
inline unsigned hi16(int64_t i) { return lo16(i>>16); }
inline unsigned lo8(int64_t i) { return (unsigned)(i&MASK_LO8); }
inline unsigned hi8(int64_t i) { return lo8(i>>8); }
inline int ha16(int32_t i) {
return ((i >> 16) + ((i & 0x8000) ? 1 : 0)) & 0xffff;
}
inline int unha16(int32_t high, int32_t low) {
return ((high - ((low & 0x8000) ? 1 : 0)) << 16) | low;
}
inline bool isInt8(target_intptr_t v) { return v == static_cast<int8_t>(v); }
inline bool isInt16(target_intptr_t v) { return v == static_cast<int16_t>(v); }
inline bool isInt24(target_intptr_t v) { return v == (v & 0xffffff); }
inline bool isInt32(target_intptr_t v) { return v == static_cast<int32_t>(v); }
inline int carry16(target_intptr_t v) { return static_cast<int16_t>(v) < 0 ? 1 : 0; }
inline bool isOfWidth(int64_t i, int size) { return static_cast<uint64_t>(i) >> size == 0; }
inline bool isOfWidth(int i, int size) { return static_cast<unsigned>(i) >> size == 0; }
const int N_GPRS = 16;
const int N_FPRS = 16;
const uint32_t GPR_MASK = 0xffff;
const uint32_t FPR_MASK = 0xffff0000;
inline bool isFpr(Assembler::Register* reg) {
return reg->low >= N_GPRS;
}
inline int toFpr(Assembler::Register* reg) {
return reg->low - N_GPRS;
}
const unsigned FrameHeaderSize = 1;
const unsigned StackAlignmentInBytes = 8;
const unsigned StackAlignmentInWords
= StackAlignmentInBytes / TargetBytesPerWord;
const int ThreadRegister = 8;
const int StackRegister = 13;
const int LinkRegister = 14;
const int ProgramCounter = 15;
const int32_t PoolOffsetMask = 0xFFF;
const bool DebugPool = false;
class Context;
class MyBlock;
class PoolOffset;
class PoolEvent;
void
resolve(MyBlock*);
unsigned
padding(MyBlock*, unsigned);
class MyBlock: public Assembler::Block {
public:
MyBlock(Context* context, unsigned offset):
context(context), next(0), poolOffsetHead(0), poolOffsetTail(0),
lastPoolOffsetTail(0), poolEventHead(0), poolEventTail(0),
lastEventOffset(0), offset(offset), start(~0), size(0)
{ }
virtual unsigned resolve(unsigned start, Assembler::Block* next) {
this->start = start;
this->next = static_cast<MyBlock*>(next);
::resolve(this);
return start + size + padding(this, size);
}
Context* context;
MyBlock* next;
PoolOffset* poolOffsetHead;
PoolOffset* poolOffsetTail;
PoolOffset* lastPoolOffsetTail;
PoolEvent* poolEventHead;
PoolEvent* poolEventTail;
unsigned lastEventOffset;
unsigned offset;
unsigned start;
unsigned size;
};
class Task;
class ConstantPoolEntry;
class Context {
public:
Context(System* s, Allocator* a, Zone* zone):
s(s), zone(zone), client(0), code(s, a, 1024), tasks(0), result(0),
firstBlock(new(zone) MyBlock(this, 0)),
lastBlock(firstBlock), poolOffsetHead(0), poolOffsetTail(0),
constantPool(0), constantPoolCount(0)
{ }
System* s;
Zone* zone;
Assembler::Client* client;
Vector code;
Task* tasks;
uint8_t* result;
MyBlock* firstBlock;
MyBlock* lastBlock;
PoolOffset* poolOffsetHead;
PoolOffset* poolOffsetTail;
ConstantPoolEntry* constantPool;
unsigned constantPoolCount;
};
class Task {
public:
Task(Task* next): next(next) { }
virtual void run(Context* c) = 0;
Task* next;
};
typedef void (*OperationType)(Context*);
typedef void (*UnaryOperationType)(Context*, unsigned, Assembler::Operand*);
typedef void (*BinaryOperationType)
(Context*, unsigned, Assembler::Operand*, unsigned, Assembler::Operand*);
typedef void (*TernaryOperationType)
(Context*, unsigned, Assembler::Operand*, Assembler::Operand*,
Assembler::Operand*);
typedef void (*BranchOperationType)
(Context*, TernaryOperation, unsigned, Assembler::Operand*,
Assembler::Operand*, Assembler::Operand*);
class ArchitectureContext {
public:
ArchitectureContext(System* s): s(s) { }
System* s;
OperationType operations[OperationCount];
UnaryOperationType unaryOperations[UnaryOperationCount
* OperandTypeCount];
BinaryOperationType binaryOperations
[BinaryOperationCount * OperandTypeCount * OperandTypeCount];
TernaryOperationType ternaryOperations
[NonBranchTernaryOperationCount * OperandTypeCount];
BranchOperationType branchOperations
[BranchOperationCount * OperandTypeCount * OperandTypeCount];
};
inline void NO_RETURN
abort(Context* c)
{
abort(c->s);
}
inline void NO_RETURN
abort(ArchitectureContext* c)
{
abort(c->s);
}
#ifndef NDEBUG
inline void
assert(Context* c, bool v)
{
assert(c->s, v);
}
inline void
assert(ArchitectureContext* c, bool v)
{
assert(c->s, v);
}
#endif // not NDEBUG
inline void
expect(Context* c, bool v)
{
expect(c->s, v);
}
class Offset: public Promise {
public:
Offset(Context* c, MyBlock* block, unsigned offset, bool forTrace):
c(c), block(block), offset(offset), forTrace(forTrace)
{ }
virtual bool resolved() {
return block->start != static_cast<unsigned>(~0);
}
virtual int64_t value() {
assert(c, resolved());
unsigned o = offset - block->offset;
return block->start + padding
(block, forTrace ? o - TargetBytesPerWord : o) + o;
}
Context* c;
MyBlock* block;
unsigned offset;
bool forTrace;
};
Promise*
offset(Context* c, bool forTrace = false)
{
return new(c->zone) Offset(c, c->lastBlock, c->code.length(), forTrace);
}
bool
bounded(int right, int left, int32_t v)
{
return ((v << left) >> left) == v and ((v >> right) << right) == v;
}
void*
updateOffset(System* s, uint8_t* instruction, int64_t value)
{
// ARM's PC is two words ahead, and branches drop the bottom 2 bits.
int32_t v = (reinterpret_cast<uint8_t*>(value) - (instruction + 8)) >> 2;
int32_t mask;
expect(s, bounded(0, 8, v));
mask = 0xFFFFFF;
int32_t* p = reinterpret_cast<int32_t*>(instruction);
*p = (v & mask) | ((~mask) & *p);
return instruction + 4;
}
class OffsetListener: public Promise::Listener {
public:
OffsetListener(System* s, uint8_t* instruction):
s(s),
instruction(instruction)
{ }
virtual bool resolve(int64_t value, void** location) {
void* p = updateOffset(s, instruction, value);
if (location) *location = p;
return false;
}
System* s;
uint8_t* instruction;
};
class OffsetTask: public Task {
public:
OffsetTask(Task* next, Promise* promise, Promise* instructionOffset):
Task(next),
promise(promise),
instructionOffset(instructionOffset)
{ }
virtual void run(Context* c) {
if (promise->resolved()) {
updateOffset
(c->s, c->result + instructionOffset->value(), promise->value());
} else {
new (promise->listen(sizeof(OffsetListener)))
OffsetListener(c->s, c->result + instructionOffset->value());
}
}
Promise* promise;
Promise* instructionOffset;
};
void
appendOffsetTask(Context* c, Promise* promise, Promise* instructionOffset)
{
c->tasks = new(c->zone) OffsetTask(c->tasks, promise, instructionOffset);
}
inline unsigned
index(ArchitectureContext*, UnaryOperation operation, OperandType operand)
{
return operation + (UnaryOperationCount * operand);
}
inline unsigned
index(ArchitectureContext*,
BinaryOperation operation,
OperandType operand1,
OperandType operand2)
{
return operation
+ (BinaryOperationCount * operand1)
+ (BinaryOperationCount * OperandTypeCount * operand2);
}
bool
isBranch(TernaryOperation op)
{
return op > FloatMin;
}
bool
isFloatBranch(TernaryOperation op)
{
return op > JumpIfNotEqual;
}
inline unsigned
index(ArchitectureContext* c UNUSED,
TernaryOperation operation,
OperandType operand1)
{
assert(c, not isBranch(operation));
return operation + (NonBranchTernaryOperationCount * operand1);
}
unsigned
branchIndex(ArchitectureContext* c UNUSED, OperandType operand1,
OperandType operand2)
{
return operand1 + (OperandTypeCount * operand2);
}
// BEGIN OPERATION COMPILERS
using namespace isa;
// shortcut functions
inline void emit(Context* con, int code) { con->code.append4(code); }
inline int newTemp(Context* con) {
return con->client->acquireTemporary();
}
inline int newTemp(Context* con, unsigned mask) {
return con->client->acquireTemporary(mask);
}
inline void freeTemp(Context* con, int r) {
con->client->releaseTemporary(r);
}
inline int64_t getValue(Assembler::Constant* c) {
return c->value->value();
}
inline Assembler::Register makeTemp(Context* con) {
Assembler::Register tmp(newTemp(con));
return tmp;
}
inline Assembler::Register makeTemp64(Context* con) {
Assembler::Register tmp(newTemp(con), newTemp(con));
return tmp;
}
inline void freeTemp(Context* con, const Assembler::Register& tmp) {
if (tmp.low != NoRegister) freeTemp(con, tmp.low);
if (tmp.high != NoRegister) freeTemp(con, tmp.high);
}
inline void
write4(uint8_t* dst, uint32_t v)
{
memcpy(dst, &v, 4);
}
void shiftLeftR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t)
{
if (size == 8) {
int tmp1 = newTemp(con), tmp2 = newTemp(con);
emit(con, lsl(tmp1, b->high, a->low));
emit(con, rsbi(tmp2, a->low, 32));
emit(con, orrsh(tmp1, tmp1, b->low, tmp2, LSR));
emit(con, SETS(subi(t->high, a->low, 32)));
emit(con, SETCOND(mov(t->high, tmp1), MI));
emit(con, SETCOND(lsl(t->high, b->low, t->high), PL));
emit(con, lsl(t->low, b->low, a->low));
freeTemp(con, tmp1); freeTemp(con, tmp2);
} else {
emit(con, lsl(t->low, b->low, a->low));
}
}
void shiftLeftC(Context* con, unsigned size UNUSED, Assembler::Constant* a, Assembler::Register* b, Assembler::Register* t)
{
assert(con, size == TargetBytesPerWord);
emit(con, lsli(t->low, b->low, getValue(a)));
}
void shiftRightR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t)
{
if (size == 8) {
int tmp1 = newTemp(con), tmp2 = newTemp(con);
emit(con, lsr(tmp1, b->low, a->low));
emit(con, rsbi(tmp2, a->low, 32));
emit(con, orrsh(tmp1, tmp1, b->high, tmp2, LSL));
emit(con, SETS(subi(t->low, a->low, 32)));
emit(con, SETCOND(mov(t->low, tmp1), MI));
emit(con, SETCOND(asr(t->low, b->high, t->low), PL));
emit(con, asr(t->high, b->high, a->low));
freeTemp(con, tmp1); freeTemp(con, tmp2);
} else {
emit(con, asr(t->low, b->low, a->low));
}
}
void shiftRightC(Context* con, unsigned size UNUSED, Assembler::Constant* a, Assembler::Register* b, Assembler::Register* t)
{
assert(con, size == TargetBytesPerWord);
emit(con, asri(t->low, b->low, getValue(a)));
}
void unsignedShiftRightR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t)
{
emit(con, lsr(t->low, b->low, a->low));
if (size == 8) {
int tmpHi = newTemp(con), tmpLo = newTemp(con);
emit(con, SETS(rsbi(tmpHi, a->low, 32)));
emit(con, lsl(tmpLo, b->high, tmpHi));
emit(con, orr(t->low, t->low, tmpLo));
emit(con, addi(tmpHi, a->low, -32));
emit(con, lsr(tmpLo, b->high, tmpHi));
emit(con, orr(t->low, t->low, tmpLo));
emit(con, lsr(t->high, b->high, a->low));
freeTemp(con, tmpHi); freeTemp(con, tmpLo);
}
}
void unsignedShiftRightC(Context* con, unsigned size UNUSED, Assembler::Constant* a, Assembler::Register* b, Assembler::Register* t)
{
assert(con, size == TargetBytesPerWord);
emit(con, lsri(t->low, b->low, getValue(a)));
}
class ConstantPoolEntry: public Promise {
public:
ConstantPoolEntry(Context* c, Promise* constant, ConstantPoolEntry* next,
Promise* callOffset):
c(c), constant(constant), next(next), callOffset(callOffset),
address(0)
{ }
virtual int64_t value() {
assert(c, resolved());
return reinterpret_cast<int64_t>(address);
}
virtual bool resolved() {
return address != 0;
}
Context* c;
Promise* constant;
ConstantPoolEntry* next;
Promise* callOffset;
void* address;
unsigned constantPoolCount;
};
class ConstantPoolListener: public Promise::Listener {
public:
ConstantPoolListener(System* s, target_uintptr_t* address,
uint8_t* returnAddress):
s(s),
address(address),
returnAddress(returnAddress)
{ }
virtual bool resolve(int64_t value, void** location) {
*address = value;
if (location) {
*location = returnAddress ? static_cast<void*>(returnAddress) : address;
}
return true;
}
System* s;
target_uintptr_t* address;
uint8_t* returnAddress;
};
class PoolOffset {
public:
PoolOffset(MyBlock* block, ConstantPoolEntry* entry, unsigned offset):
block(block), entry(entry), next(0), offset(offset)
{ }
MyBlock* block;
ConstantPoolEntry* entry;
PoolOffset* next;
unsigned offset;
};
class PoolEvent {
public:
PoolEvent(PoolOffset* poolOffsetHead, PoolOffset* poolOffsetTail,
unsigned offset):
poolOffsetHead(poolOffsetHead), poolOffsetTail(poolOffsetTail), next(0),
offset(offset)
{ }
PoolOffset* poolOffsetHead;
PoolOffset* poolOffsetTail;
PoolEvent* next;
unsigned offset;
};
void
appendConstantPoolEntry(Context* c, Promise* constant, Promise* callOffset)
{
if (constant->resolved()) {
// make a copy, since the original might be allocated on the
// stack, and we need our copy to live until assembly is complete
constant = new(c->zone) ResolvedPromise(constant->value());
}
c->constantPool = new(c->zone) ConstantPoolEntry(c, constant, c->constantPool, callOffset);
++ c->constantPoolCount;
PoolOffset* o = new(c->zone) PoolOffset(c->lastBlock, c->constantPool, c->code.length() - c->lastBlock->offset);
if (DebugPool) {
fprintf(stderr, "add pool offset %p %d to block %p\n",
o, o->offset, c->lastBlock);
}
if (c->lastBlock->poolOffsetTail) {
c->lastBlock->poolOffsetTail->next = o;
} else {
c->lastBlock->poolOffsetHead = o;
}
c->lastBlock->poolOffsetTail = o;
}
void
appendPoolEvent(Context* c, MyBlock* b, unsigned offset, PoolOffset* head,
PoolOffset* tail)
{
PoolEvent* e = new(c->zone) PoolEvent(head, tail, offset);
if (b->poolEventTail) {
b->poolEventTail->next = e;
} else {
b->poolEventHead = e;
}
b->poolEventTail = e;
}
bool
needJump(MyBlock* b)
{
return b->next or b->size != (b->size & PoolOffsetMask);
}
unsigned
padding(MyBlock* b, unsigned offset)
{
unsigned total = 0;
for (PoolEvent* e = b->poolEventHead; e; e = e->next) {
if (e->offset <= offset) {
if (needJump(b)) {
total += TargetBytesPerWord;
}
for (PoolOffset* o = e->poolOffsetHead; o; o = o->next) {
total += TargetBytesPerWord;
}
} else {
break;
}
}
return total;
}
void
resolve(MyBlock* b)
{
Context* c = b->context;
if (b->poolOffsetHead) {
if (c->poolOffsetTail) {
c->poolOffsetTail->next = b->poolOffsetHead;
} else {
c->poolOffsetHead = b->poolOffsetHead;
}
c->poolOffsetTail = b->poolOffsetTail;
}
if (c->poolOffsetHead) {
bool append;
if (b->next == 0 or b->next->poolEventHead) {
append = true;
} else {
int32_t v = (b->start + b->size + b->next->size + TargetBytesPerWord - 8)
- (c->poolOffsetHead->offset + c->poolOffsetHead->block->start);
append = (v != (v & PoolOffsetMask));
if (DebugPool) {
fprintf(stderr,
"current %p %d %d next %p %d %d\n",
b, b->start, b->size, b->next, b->start + b->size,
b->next->size);
fprintf(stderr,
"offset %p %d is of distance %d to next block; append? %d\n",
c->poolOffsetHead, c->poolOffsetHead->offset, v, append);
}
}
if (append) {
#ifndef NDEBUG
int32_t v = (b->start + b->size - 8)
- (c->poolOffsetHead->offset + c->poolOffsetHead->block->start);
expect(c, v == (v & PoolOffsetMask));
#endif // not NDEBUG
appendPoolEvent(c, b, b->size, c->poolOffsetHead, c->poolOffsetTail);
if (DebugPool) {
for (PoolOffset* o = c->poolOffsetHead; o; o = o->next) {
fprintf(stderr,
"include %p %d in pool event %p at offset %d in block %p\n",
o, o->offset, b->poolEventTail, b->size, b);
}
}
c->poolOffsetHead = 0;
c->poolOffsetTail = 0;
}
}
}
void
jumpR(Context* c, unsigned size UNUSED, Assembler::Register* target)
{
assert(c, size == TargetBytesPerWord);
emit(c, bx(target->low));
}
void
moveRR(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned dstSize, Assembler::Register* dst);
void
swapRR(Context* c, unsigned aSize, Assembler::Register* a,
unsigned bSize, Assembler::Register* b)
{
assert(c, aSize == TargetBytesPerWord);
assert(c, bSize == TargetBytesPerWord);
Assembler::Register tmp(c->client->acquireTemporary());
moveRR(c, aSize, a, bSize, &tmp);
moveRR(c, bSize, b, aSize, a);
moveRR(c, bSize, &tmp, bSize, b);
c->client->releaseTemporary(tmp.low);
}
void
moveRR(Context* con, unsigned srcSize, Assembler::Register* src,
unsigned dstSize, Assembler::Register* dst)
{
bool srcIsFpr = isFpr(src);
bool dstIsFpr = isFpr(dst);
if (srcIsFpr || dstIsFpr) { // floating-point register(s) involved
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- %d\n", dst->low, src->low);
// FPR to FPR
if (srcIsFpr && dstIsFpr) emit(con, fcpys(toFpr(dst), toFpr(src)));
// FPR to GPR
else if (srcIsFpr) emit(con, fmrs(dst->low, toFpr(src)));
// GPR to FPR
else emit(con, fmsr(toFpr(dst), src->low));
return;
}
switch (srcSize) {
case 1:
emit(con, lsli(dst->low, src->low, 24));
emit(con, asri(dst->low, dst->low, 24));
break;
case 2:
emit(con, lsli(dst->low, src->low, 16));
emit(con, asri(dst->low, dst->low, 16));
break;
case 4:
case 8:
if (srcSize == 4 and dstSize == 8) {
moveRR(con, 4, src, 4, dst);
emit(con, asri(dst->high, src->low, 31));
} else if (srcSize == 8 and dstSize == 8) {
Assembler::Register srcHigh(src->high);
Assembler::Register dstHigh(dst->high);
if (src->high == dst->low) {
if (src->low == dst->high) {
swapRR(con, 4, src, 4, dst);
} else {
moveRR(con, 4, &srcHigh, 4, &dstHigh);
moveRR(con, 4, src, 4, dst);
}
} else {
moveRR(con, 4, src, 4, dst);
moveRR(con, 4, &srcHigh, 4, &dstHigh);
}
} else if (src->low != dst->low) {
emit(con, mov(dst->low, src->low));
}
break;
default: abort(con);
}
}
void
moveZRR(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned, Assembler::Register* dst)
{
switch (srcSize) {
case 2:
emit(c, lsli(dst->low, src->low, 16));
emit(c, lsri(dst->low, dst->low, 16));
break;
default: abort(c);
}
}
void
moveCR2(Context* con, unsigned size, Assembler::Constant* src,
Assembler::Register* dst, Promise* callOffset)
{
if (isFpr(dst)) { // floating-point
Assembler::Register tmp = makeTemp(con);
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- 0x%llx\n", tmp.low, getValue(src));
moveCR2(con, size, src, &tmp, 0);
moveRR(con, size, &tmp, size, dst);
freeTemp(con, tmp);
} else if (size <= 4) {
if (src->value->resolved() and isOfWidth(getValue(src), 8)) {
emit(con, movi(dst->low, lo8(getValue(src))));
} else {
appendConstantPoolEntry(con, src->value, callOffset);
emit(con, ldri(dst->low, ProgramCounter, 0));
}
} else {
abort(con); // todo
}
}
void
moveCR(Context* con, unsigned size, Assembler::Constant* src,
unsigned, Assembler::Register* dst)
{
moveCR2(con, size, src, dst, 0);
}
void addR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, SETS(add(t->low, a->low, b->low)));
emit(con, adc(t->high, a->high, b->high));
} else {
emit(con, add(t->low, a->low, b->low));
}
}
void subR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, SETS(rsb(t->low, a->low, b->low)));
emit(con, rsc(t->high, a->high, b->high));
} else {
emit(con, rsb(t->low, a->low, b->low));
}
}
void
addC(Context* c, unsigned size, Assembler::Constant* a,
Assembler::Register* b, Assembler::Register* dst)
{
assert(c, size == TargetBytesPerWord);
int32_t v = a->value->value();
if (v) {
if (v > 0 and v < 256) {
emit(c, addi(dst->low, b->low, v));
} else if (v > 0 and v < 1024 and v % 4 == 0) {
emit(c, addi(dst->low, b->low, v >> 2, 15));
} else {
// todo
abort(c);
}
} else {
moveRR(c, size, b, size, dst);
}
}
void
subC(Context* c, unsigned size, Assembler::Constant* a,
Assembler::Register* b, Assembler::Register* dst)
{
assert(c, size == TargetBytesPerWord);
int32_t v = a->value->value();
if (v) {
if (v > 0 and v < 256) {
emit(c, subi(dst->low, b->low, v));
} else if (v > 0 and v < 1024 and v % 4 == 0) {
emit(c, subi(dst->low, b->low, v >> 2, 15));
} else {
// todo
abort(c);
}
} else {
moveRR(c, size, b, size, dst);
}
}
void multiplyR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
bool useTemporaries = b->low == t->low;
int tmpLow = useTemporaries ? con->client->acquireTemporary() : t->low;
int tmpHigh = useTemporaries ? con->client->acquireTemporary() : t->high;
emit(con, umull(tmpLow, tmpHigh, a->low, b->low));
emit(con, mla(tmpHigh, a->low, b->high, tmpHigh));
emit(con, mla(tmpHigh, a->high, b->low, tmpHigh));
if (useTemporaries) {
emit(con, mov(t->low, tmpLow));
emit(con, mov(t->high, tmpHigh));
con->client->releaseTemporary(tmpLow);
con->client->releaseTemporary(tmpHigh);
}
} else {
emit(con, mul(t->low, a->low, b->low));
}
}
void floatAbsoluteRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
emit(con, fabsd(b->low, a->low));
} else {
emit(con, fabss(b->low, a->low));
}
}
void floatNegateRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> invalid 64-bit Scheiße\n");
emit(con, fnegd(b->low, a->low));
} else {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- -%d\n", b->low, a->low);
emit(con, fnegs(b->low, a->low));
}
}
void float2FloatRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
emit(con, fcvtsd(b->low, a->low));
} else {
emit(con, fcvtds(b->low, a->low));
}
}
void float2IntRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
int tmp = newTemp(con, FPR_MASK);
if (size == 8) { // double to int
emit(con, ftosid(tmp, a->low));
} else { // float to int
emit(con, ftosis(tmp, a->low));
} // else thunked
emit(con, fmrs(b->low, tmp));
freeTemp(con, tmp);
}
void int2FloatRR(Context* con, unsigned UNUSED, Assembler::Register* a, unsigned size, Assembler::Register* b) {
emit(con, fmsr(b->low, a->low));
if (size == 8) { // int to double
emit(con, fsitod(b->low, b->low));
} else { // int to float
emit(con, fsitos(b->low, b->low));
} // else thunked
}
void floatSqrtRR(Context* con, unsigned size, Assembler::Register* a, unsigned UNUSED, Assembler::Register* b) {
if (size == 8) {
emit(con, fsqrtd(b->low, a->low));
} else {
emit(con, fsqrts(b->low, a->low));
}
}
void floatAddR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, faddd(t->low, a->low, b->low));
} else {
fprintf(stderr, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %d <- %d + %d\n", toFpr(t), toFpr(a), toFpr(b));
emit(con, fadds(toFpr(t), toFpr(a), toFpr(b)));
}
}
void floatSubtractR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, fsubd(t->low, a->low, b->low));
} else {
emit(con, fsubs(t->low, a->low, b->low));
}
}
void floatMultiplyR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, fmuld(t->low, a->low, b->low));
} else {
emit(con, fmuls(t->low, a->low, b->low));
}
}
void floatDivideR(Context* con, unsigned size, Assembler::Register* a, Assembler::Register* b, Assembler::Register* t) {
if (size == 8) {
emit(con, fdivd(t->low, a->low, b->low));
} else {
emit(con, fdivs(t->low, a->low, b->low));
}
}
int
normalize(Context* c, int offset, int index, unsigned scale,
bool* preserveIndex, bool* release)
{
if (offset != 0 or scale != 1) {
Assembler::Register normalizedIndex
(*preserveIndex ? c->client->acquireTemporary() : index);
if (*preserveIndex) {
*release = true;
*preserveIndex = false;
} else {
*release = false;
}
int scaled;
if (scale != 1) {
Assembler::Register unscaledIndex(index);
ResolvedPromise scalePromise(log(scale));
Assembler::Constant scaleConstant(&scalePromise);
shiftLeftC(c, TargetBytesPerWord, &scaleConstant,
&unscaledIndex, &normalizedIndex);
scaled = normalizedIndex.low;
} else {
scaled = index;
}
if (offset != 0) {
Assembler::Register untranslatedIndex(scaled);
ResolvedPromise offsetPromise(offset);
Assembler::Constant offsetConstant(&offsetPromise);
Assembler::Register tmp(c->client->acquireTemporary());
moveCR(c, TargetBytesPerWord, &offsetConstant, TargetBytesPerWord, &tmp);
addR(c, TargetBytesPerWord, &tmp, &untranslatedIndex, &normalizedIndex);
c->client->releaseTemporary(tmp.low);
}
return normalizedIndex.low;
} else {
*release = false;
return index;
}
}
void
store(Context* con, unsigned size, Assembler::Register* src,
int base, int offset, int index, unsigned scale, bool preserveIndex)
{
if (index != NoRegister) {
bool release;
int normalized = normalize
(con, offset, index, scale, &preserveIndex, &release);
if (isFpr(src)) { // floating-point store
if (size == 4) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> fpr store base-indexed\n");
Assembler::Register base_(base),
normalized_(normalized),
absAddr = makeTemp(con);
addR(con, size, &base_, &normalized_, &absAddr);
emit(con, fsts(toFpr(src), absAddr.low));
freeTemp(con, absAddr);
}
else abort(con);
} else {
switch (size) {
case 1:
emit(con, strb(src->low, base, normalized));
break;
case 2:
emit(con, strh(src->low, base, normalized));
break;
case 4:
emit(con, str(src->low, base, normalized));
break;
case 8: {
Assembler::Register srcHigh(src->high);
store(con, 4, &srcHigh, base, 0, normalized, 1, preserveIndex);
store(con, 4, src, base, 4, normalized, 1, preserveIndex);
} break;
default: abort(con);
}
}
if (release) con->client->releaseTemporary(normalized);
} else if (size == 8
or abs(offset) == (abs(offset) & 0xFF)
or (size != 2 and abs(offset) == (abs(offset) & 0xFFF)))
{
if (isFpr(src)) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> [%d + 0x%x] <- %d\n", base, offset, src->low);
if (size == 4) emit(con, fsts(toFpr(src), base, offset));
else abort(con);
} else {
switch (size) {
case 1:
emit(con, strbi(src->low, base, offset));
break;
case 2:
emit(con, strhi(src->low, base, offset));
break;
case 4:
emit(con, stri(src->low, base, offset));
break;
case 8: {
Assembler::Register srcHigh(src->high);
store(con, 4, &srcHigh, base, offset, NoRegister, 1, false);
store(con, 4, src, base, offset + 4, NoRegister, 1, false);
} break;
default: abort(con);
}
}
} else {
Assembler::Register tmp(con->client->acquireTemporary());
ResolvedPromise offsetPromise(offset);
Assembler::Constant offsetConstant(&offsetPromise);
moveCR(con, TargetBytesPerWord, &offsetConstant,
TargetBytesPerWord, &tmp);
store(con, size, src, base, 0, tmp.low, 1, false);
con->client->releaseTemporary(tmp.low);
}
}
void
moveRM(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned dstSize UNUSED, Assembler::Memory* dst)
{
assert(c, srcSize == dstSize);
store(c, srcSize, src, dst->base, dst->offset, dst->index, dst->scale, true);
}
void
moveAndUpdateRM(Context* c, unsigned srcSize UNUSED, Assembler::Register* src,
unsigned dstSize UNUSED, Assembler::Memory* dst)
{
assert(c, srcSize == TargetBytesPerWord);
assert(c, dstSize == TargetBytesPerWord);
if (dst->index == NoRegister) {
emit(c, stri(src->low, dst->base, dst->offset, dst->offset ? 1 : 0));
} else {
assert(c, dst->offset == 0);
assert(c, dst->scale == 1);
emit(c, str(src->low, dst->base, dst->index, 1));
}
}
void
load(Context* con, unsigned srcSize, int base, int offset, int index,
unsigned scale, unsigned dstSize, Assembler::Register* dst,
bool preserveIndex, bool signExtend)
{
if (index != NoRegister) {
bool release;
int normalized = normalize
(con, offset, index, scale, &preserveIndex, &release);
if (isFpr(dst)) { // floating-point store
if (srcSize == 4) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> fpr load base-indexed\n");
Assembler::Register base_(base),
normalized_(normalized),
absAddr = makeTemp(con);
addR(con, srcSize, &base_, &normalized_, &absAddr);
emit(con, flds(toFpr(dst), absAddr.low));
freeTemp(con, absAddr);
}
else abort(con);
} else {
switch (srcSize) {
case 1:
if (signExtend) {
emit(con, ldrsb(dst->low, base, normalized));
} else {
emit(con, ldrb(dst->low, base, normalized));
}
break;
case 2:
if (signExtend) {
emit(con, ldrsh(dst->low, base, normalized));
} else {
emit(con, ldrh(dst->low, base, normalized));
}
break;
case 4:
case 8: {
if (srcSize == 4 and dstSize == 8) {
load(con, 4, base, 0, normalized, 1, 4, dst, preserveIndex,
false);
moveRR(con, 4, dst, 8, dst);
} else if (srcSize == 8 and dstSize == 8) {
Assembler::Register dstHigh(dst->high);
load(con, 4, base, 0, normalized, 1, 4, &dstHigh,
preserveIndex, false);
load(con, 4, base, 4, normalized, 1, 4, dst, preserveIndex,
false);
} else {
emit(con, ldr(dst->low, base, normalized));
}
} break;
default: abort(con);
}
}
if (release) con->client->releaseTemporary(normalized);
} else if ((srcSize == 8 and dstSize == 8)
or abs(offset) == (abs(offset) & 0xFF)
or (srcSize != 2
and (srcSize != 1 or not signExtend)
and abs(offset) == (abs(offset) & 0xFFF)))
{
if (isFpr(dst)) {
/**/fprintf(stderr, ">>>>>>>>>>>>>>>>>>>>>>>> %d <- [%d + 0x%x]\n", dst->low, base, offset);
if (srcSize == 4) emit(con, flds(toFpr(dst), base, offset));
else abort(con);
} else {
switch (srcSize) {
case 1:
if (signExtend) {
emit(con, ldrsbi(dst->low, base, offset));
} else {
emit(con, ldrbi(dst->low, base, offset));
}
break;
case 2:
if (signExtend) {
emit(con, ldrshi(dst->low, base, offset));
} else {
emit(con, ldrhi(dst->low, base, offset));
}
break;
case 4:
emit(con, ldri(dst->low, base, offset));
break;
case 8: {
if (dstSize == 8) {
Assembler::Register dstHigh(dst->high);
load(con, 4, base, offset, NoRegister, 1, 4, &dstHigh, false,
false);
load(con, 4, base, offset + 4, NoRegister, 1, 4, dst, false,
false);
} else {
emit(con, ldri(dst->low, base, offset));
}
} break;
default: abort(con);
}
}
} else {
Assembler::Register tmp(con->client->acquireTemporary());
ResolvedPromise offsetPromise(offset);
Assembler::Constant offsetConstant(&offsetPromise);
moveCR(con, TargetBytesPerWord, &offsetConstant, TargetBytesPerWord,
&tmp);
load(con, srcSize, base, 0, tmp.low, 1, dstSize, dst, false,
signExtend);
con->client->releaseTemporary(tmp.low);
}
}
void
moveMR(Context* c, unsigned srcSize, Assembler::Memory* src,
unsigned dstSize, Assembler::Register* dst)
{
load(c, srcSize, src->base, src->offset, src->index, src->scale,
dstSize, dst, true, true);
}
void
moveZMR(Context* c, unsigned srcSize, Assembler::Memory* src,
unsigned dstSize, Assembler::Register* dst)
{
load(c, srcSize, src->base, src->offset, src->index, src->scale,
dstSize, dst, true, false);
}
void
andR(Context* c, unsigned size, Assembler::Register* a,
Assembler::Register* b, Assembler::Register* dst)
{
if (size == 8) emit(c, and_(dst->high, a->high, b->high));
emit(c, and_(dst->low, a->low, b->low));
}
void
andC(Context* c, unsigned size, Assembler::Constant* a,
Assembler::Register* b, Assembler::Register* dst)
{
int64_t v = a->value->value();
if (size == 8) {
ResolvedPromise high((v >> 32) & 0xFFFFFFFF);
Assembler::Constant ah(&high);
ResolvedPromise low(v & 0xFFFFFFFF);
Assembler::Constant al(&low);
Assembler::Register bh(b->high);
Assembler::Register dh(dst->high);
andC(c, 4, &al, b, dst);
andC(c, 4, &ah, &bh, &dh);
} else {
uint32_t v32 = static_cast<uint32_t>(v);
if (v32 != 0xFFFFFFFF) {
if ((v32 & 0xFFFFFF00) == 0xFFFFFF00) {
emit(c, bici(dst->low, b->low, (~(v32 & 0xFF)) & 0xFF));
} else if ((v32 & 0xFFFFFF00) == 0) {
emit(c, andi(dst->low, b->low, v32 & 0xFF));
} else {
// todo: there are other cases we can handle in one
// instruction
bool useTemporary = b->low == dst->low;
Assembler::Register tmp(dst->low);
if (useTemporary) {
tmp.low = c->client->acquireTemporary();
}
moveCR(c, 4, a, 4, &tmp);
andR(c, 4, b, &tmp, dst);
if (useTemporary) {
c->client->releaseTemporary(tmp.low);
}
}
} else {
moveRR(c, size, b, size, dst);
}
}
}
void
orR(Context* c, unsigned size, Assembler::Register* a,
Assembler::Register* b, Assembler::Register* dst)
{
if (size == 8) emit(c, orr(dst->high, a->high, b->high));
emit(c, orr(dst->low, a->low, b->low));
}
void
xorR(Context* con, unsigned size, Assembler::Register* a,
Assembler::Register* b, Assembler::Register* dst)
{
if (size == 8) emit(con, eor(dst->high, a->high, b->high));
emit(con, eor(dst->low, a->low, b->low));
}
void
moveAR2(Context* c, unsigned srcSize, Assembler::Address* src,
unsigned dstSize, Assembler::Register* dst)
{
assert(c, srcSize == 4 and dstSize == 4);
Assembler::Constant constant(src->address);
moveCR(c, srcSize, &constant, dstSize, dst);
Assembler::Memory memory(dst->low, 0, -1, 0);
moveMR(c, dstSize, &memory, dstSize, dst);
}
void
moveAR(Context* c, unsigned srcSize, Assembler::Address* src,
unsigned dstSize, Assembler::Register* dst)
{
moveAR2(c, srcSize, src, dstSize, dst);
}
void
compareRR(Context* c, unsigned aSize UNUSED, Assembler::Register* a,
unsigned bSize UNUSED, Assembler::Register* b)
{
assert(c, aSize == 4 and bSize == 4);
assert(c, b->low != a->low);
assert(c, !(isFpr(a) ^ isFpr(b)));
if (isFpr(a)) {
emit(c, fcmps(toFpr(b), toFpr(a)));
emit(c, fmstat());
}
else emit(c, cmp(b->low, a->low));
}
void
compareCR(Context* c, unsigned aSize, Assembler::Constant* a,
unsigned bSize, Assembler::Register* b)
{
assert(c, aSize == 4 and bSize == 4);
if (!isFpr(b) && a->value->resolved() &&
isOfWidth(a->value->value(), 8)) {
emit(c, cmpi(b->low, a->value->value()));
} else {
Assembler::Register tmp(c->client->acquireTemporary());
moveCR(c, aSize, a, bSize, &tmp);
compareRR(c, bSize, &tmp, bSize, b);
c->client->releaseTemporary(tmp.low);
}
}
void
compareCM(Context* c, unsigned aSize, Assembler::Constant* a,
unsigned bSize, Assembler::Memory* b)
{
assert(c, aSize == 4 and bSize == 4);
Assembler::Register tmp(c->client->acquireTemporary());
moveMR(c, bSize, b, bSize, &tmp);
compareCR(c, aSize, a, bSize, &tmp);
c->client->releaseTemporary(tmp.low);
}
void
compareRM(Context* c, unsigned aSize, Assembler::Register* a,
unsigned bSize, Assembler::Memory* b)
{
assert(c, aSize == 4 and bSize == 4);
Assembler::Register tmp(c->client->acquireTemporary());
moveMR(c, bSize, b, bSize, &tmp);
compareRR(c, aSize, a, bSize, &tmp);
c->client->releaseTemporary(tmp.low);
}
int32_t
branch(Context* c, TernaryOperation op)
{
switch (op) {
case JumpIfEqual:
case JumpIfFloatEqual:
return beq(0);
case JumpIfNotEqual:
case JumpIfFloatNotEqual:
return bne(0);
case JumpIfLess:
case JumpIfFloatLess:
case JumpIfFloatLessOrUnordered:
return blt(0);
case JumpIfGreater:
case JumpIfFloatGreater:
return bgt(0);
case JumpIfLessOrEqual:
case JumpIfFloatLessOrEqual:
case JumpIfFloatLessOrEqualOrUnordered:
return ble(0);
case JumpIfGreaterOrEqual:
case JumpIfFloatGreaterOrEqual:
return bge(0);
case JumpIfFloatGreaterOrUnordered:
return bhi(0);
case JumpIfFloatGreaterOrEqualOrUnordered:
return bpl(0);
default:
abort(c);
}
}
void
conditional(Context* c, int32_t branch, Assembler::Constant* target)
{
appendOffsetTask(c, target->value, offset(c));
emit(c, branch);
}
void
branch(Context* c, TernaryOperation op, Assembler::Constant* target)
{
conditional(c, branch(c, op), target);
}
void
branchLong(Context* c, TernaryOperation op, Assembler::Operand* al,
Assembler::Operand* ah, Assembler::Operand* bl,
Assembler::Operand* bh, Assembler::Constant* target,
BinaryOperationType compareSigned,
BinaryOperationType compareUnsigned)
{
compareSigned(c, 4, ah, 4, bh);
unsigned next = 0;
switch (op) {
case JumpIfEqual:
next = c->code.length();
emit(c, bne(0));
compareSigned(c, 4, al, 4, bl);
conditional(c, beq(0), target);
break;
case JumpIfNotEqual:
conditional(c, bne(0), target);
compareSigned(c, 4, al, 4, bl);
conditional(c, bne(0), target);
break;
case JumpIfLess:
conditional(c, blt(0), target);
next = c->code.length();
emit(c, bgt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, blo(0), target);
break;
case JumpIfGreater:
conditional(c, bgt(0), target);
next = c->code.length();
emit(c, blt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, bhi(0), target);
break;
case JumpIfLessOrEqual:
conditional(c, blt(0), target);
next = c->code.length();
emit(c, bgt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, bls(0), target);
break;
case JumpIfGreaterOrEqual:
conditional(c, bgt(0), target);
next = c->code.length();
emit(c, blt(0));
compareUnsigned(c, 4, al, 4, bl);
conditional(c, bhs(0), target);
break;
default:
abort(c);
}
if (next) {
updateOffset
(c->s, c->code.data + next, reinterpret_cast<intptr_t>
(c->code.data + c->code.length()));
}
}
void
branchRR(Context* c, TernaryOperation op, unsigned size,
Assembler::Register* a, Assembler::Register* b,
Assembler::Constant* target)
{
if (size > TargetBytesPerWord) {
Assembler::Register ah(a->high);
Assembler::Register bh(b->high);
branchLong(c, op, a, &ah, b, &bh, target, CAST2(compareRR),
CAST2(compareRR));
} else {
compareRR(c, size, a, size, b);
branch(c, op, target);
}
}
void
branchCR(Context* con, TernaryOperation op, unsigned size,
Assembler::Constant* a, Assembler::Register* b,
Assembler::Constant* target)
{
assert(con, !isFloatBranch(op));
if (size > TargetBytesPerWord) {
int64_t v = a->value->value();
ResolvedPromise low(v & ~static_cast<target_uintptr_t>(0));
Assembler::Constant al(&low);
ResolvedPromise high((v >> 32) & ~static_cast<target_uintptr_t>(0));
Assembler::Constant ah(&high);
Assembler::Register bh(b->high);
branchLong(con, op, &al, &ah, b, &bh, target, CAST2(compareCR),
CAST2(compareCR));
} else {
compareCR(con, size, a, size, b);
branch(con, op, target);
}
}
void
branchRM(Context* con, TernaryOperation op, unsigned size,
Assembler::Register* a, Assembler::Memory* b,
Assembler::Constant* target)
{
assert(con, !isFloatBranch(op));
assert(con, size <= TargetBytesPerWord);
compareRM(con, size, a, size, b);
branch(con, op, target);
}
void
branchCM(Context* con, TernaryOperation op, unsigned size,
Assembler::Constant* a, Assembler::Memory* b,
Assembler::Constant* target)
{
assert(con, !isFloatBranch(op));
assert(con, size <= TargetBytesPerWord);
compareCM(con, size, a, size, b);
branch(con, op, target);
}
ShiftMaskPromise*
shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask)
{
return new(c->zone) ShiftMaskPromise(base, shift, mask);
}
void
moveCM(Context* c, unsigned srcSize, Assembler::Constant* src,
unsigned dstSize, Assembler::Memory* dst)
{
switch (dstSize) {
case 8: {
Assembler::Constant srcHigh
(shiftMaskPromise(c, src->value, 32, 0xFFFFFFFF));
Assembler::Constant srcLow
(shiftMaskPromise(c, src->value, 0, 0xFFFFFFFF));
Assembler::Memory dstLow
(dst->base, dst->offset + 4, dst->index, dst->scale);
moveCM(c, 4, &srcLow, 4, &dstLow);
moveCM(c, 4, &srcHigh, 4, dst);
} break;
default:
Assembler::Register tmp(c->client->acquireTemporary());
moveCR(c, srcSize, src, dstSize, &tmp);
moveRM(c, dstSize, &tmp, dstSize, dst);
c->client->releaseTemporary(tmp.low);
}
}
void
negateRR(Context* c, unsigned srcSize, Assembler::Register* src,
unsigned dstSize UNUSED, Assembler::Register* dst)
{
assert(c, srcSize == dstSize);
emit(c, mvn(dst->low, src->low));
emit(c, SETS(addi(dst->low, dst->low, 1)));
if (srcSize == 8) {
emit(c, mvn(dst->high, src->high));
emit(c, adci(dst->high, dst->high, 0));
}
}
void
callR(Context* c, unsigned size UNUSED, Assembler::Register* target)
{
assert(c, size == TargetBytesPerWord);
emit(c, blx(target->low));
}
void
callC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
appendOffsetTask(c, target->value, offset(c));
emit(c, bl(0));
}
void
longCallC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
Assembler::Register tmp(4);
moveCR2(c, TargetBytesPerWord, target, &tmp, offset(c));
callR(c, TargetBytesPerWord, &tmp);
}
void
longJumpC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
Assembler::Register tmp(4); // a non-arg reg that we don't mind clobbering
moveCR2(c, TargetBytesPerWord, target, &tmp, offset(c));
jumpR(c, TargetBytesPerWord, &tmp);
}
void
jumpC(Context* c, unsigned size UNUSED, Assembler::Constant* target)
{
assert(c, size == TargetBytesPerWord);
appendOffsetTask(c, target->value, offset(c));
emit(c, b(0));
}
void
return_(Context* c)
{
emit(c, bx(LinkRegister));
}
void
trap(Context* c)
{
emit(c, bkpt(0));
}
void
memoryBarrier(Context*) {}
// END OPERATION COMPILERS
unsigned
argumentFootprint(unsigned footprint)
{
return max(pad(footprint, StackAlignmentInWords), StackAlignmentInWords);
}
void
nextFrame(ArchitectureContext* c, uint32_t* start, unsigned size UNUSED,
unsigned footprint, void* link, bool,
unsigned targetParameterFootprint UNUSED, void** ip, void** stack)
{
assert(c, *ip >= start);
assert(c, *ip <= start + (size / TargetBytesPerWord));
uint32_t* instruction = static_cast<uint32_t*>(*ip);
if ((*start >> 20) == 0xe59) {
// skip stack overflow check
start += 3;
}
if (instruction <= start) {
*ip = link;
return;
}
unsigned offset = footprint + FrameHeaderSize;
if (instruction <= start + 2) {
*ip = link;
*stack = static_cast<void**>(*stack) + offset;
return;
}
if (*instruction == 0xe12fff1e) { // return
*ip = link;
return;
}
if (TailCalls) {
if (argumentFootprint(targetParameterFootprint) > StackAlignmentInWords) {
offset += argumentFootprint(targetParameterFootprint)
- StackAlignmentInWords;
}
// check for post-non-tail-call stack adjustment of the form "add
// sp, sp, #offset":
if ((*instruction >> 12) == 0xe24dd) {
unsigned value = *instruction & 0xff;
unsigned rotation = (*instruction >> 8) & 0xf;
switch (rotation) {
case 0: offset -= value / TargetBytesPerWord; break;
case 15: offset -= value; break;
default: abort(c);
}
}
// todo: check for and handle tail calls
}
*ip = static_cast<void**>(*stack)[offset - 1];
*stack = static_cast<void**>(*stack) + offset;
}
void
populateTables(ArchitectureContext* c)
{
const OperandType C = ConstantOperand;
const OperandType A = AddressOperand;
const OperandType R = RegisterOperand;
const OperandType M = MemoryOperand;
OperationType* zo = c->operations;
UnaryOperationType* uo = c->unaryOperations;
BinaryOperationType* bo = c->binaryOperations;
TernaryOperationType* to = c->ternaryOperations;
BranchOperationType* bro = c->branchOperations;
zo[Return] = return_;
zo[LoadBarrier] = memoryBarrier;
zo[StoreStoreBarrier] = memoryBarrier;
zo[StoreLoadBarrier] = memoryBarrier;
zo[Trap] = trap;
uo[index(c, LongCall, C)] = CAST1(longCallC);
uo[index(c, AlignedLongCall, C)] = CAST1(longCallC);
uo[index(c, LongJump, C)] = CAST1(longJumpC);
uo[index(c, AlignedLongJump, C)] = CAST1(longJumpC);
uo[index(c, Jump, R)] = CAST1(jumpR);
uo[index(c, Jump, C)] = CAST1(jumpC);
uo[index(c, AlignedJump, R)] = CAST1(jumpR);
uo[index(c, AlignedJump, C)] = CAST1(jumpC);
uo[index(c, Call, C)] = CAST1(callC);
uo[index(c, Call, R)] = CAST1(callR);
uo[index(c, AlignedCall, C)] = CAST1(callC);
uo[index(c, AlignedCall, R)] = CAST1(callR);
bo[index(c, Move, R, R)] = CAST2(moveRR);
bo[index(c, Move, C, R)] = CAST2(moveCR);
bo[index(c, Move, C, M)] = CAST2(moveCM);
bo[index(c, Move, M, R)] = CAST2(moveMR);
bo[index(c, Move, R, M)] = CAST2(moveRM);
bo[index(c, Move, A, R)] = CAST2(moveAR);
bo[index(c, MoveZ, R, R)] = CAST2(moveZRR);
bo[index(c, MoveZ, M, R)] = CAST2(moveZMR);
bo[index(c, MoveZ, C, R)] = CAST2(moveCR);
bo[index(c, Negate, R, R)] = CAST2(negateRR);
bo[index(c, FloatAbsolute, R, R)] = CAST2(floatAbsoluteRR);
bo[index(c, FloatNegate, R, R)] = CAST2(floatNegateRR);
bo[index(c, Float2Float, R, R)] = CAST2(float2FloatRR);
bo[index(c, Float2Int, R, R)] = CAST2(float2IntRR);
bo[index(c, Int2Float, R, R)] = CAST2(int2FloatRR);
bo[index(c, FloatSquareRoot, R, R)] = CAST2(floatSqrtRR);
to[index(c, Add, R)] = CAST3(addR);
to[index(c, Subtract, R)] = CAST3(subR);
to[index(c, Multiply, R)] = CAST3(multiplyR);
to[index(c, FloatAdd, R)] = CAST3(floatAddR);
to[index(c, FloatSubtract, R)] = CAST3(floatSubtractR);
to[index(c, FloatMultiply, R)] = CAST3(floatMultiplyR);
to[index(c, FloatDivide, R)] = CAST3(floatDivideR);
to[index(c, ShiftLeft, R)] = CAST3(shiftLeftR);
to[index(c, ShiftLeft, C)] = CAST3(shiftLeftC);
to[index(c, ShiftRight, R)] = CAST3(shiftRightR);
to[index(c, ShiftRight, C)] = CAST3(shiftRightC);
to[index(c, UnsignedShiftRight, R)] = CAST3(unsignedShiftRightR);
to[index(c, UnsignedShiftRight, C)] = CAST3(unsignedShiftRightC);
to[index(c, And, R)] = CAST3(andR);
to[index(c, And, C)] = CAST3(andC);
to[index(c, Or, R)] = CAST3(orR);
to[index(c, Xor, R)] = CAST3(xorR);
bro[branchIndex(c, R, R)] = CAST_BRANCH(branchRR);
bro[branchIndex(c, C, R)] = CAST_BRANCH(branchCR);
bro[branchIndex(c, C, M)] = CAST_BRANCH(branchCM);
bro[branchIndex(c, R, M)] = CAST_BRANCH(branchRM);
}
class MyArchitecture: public Assembler::Architecture {
public:
MyArchitecture(System* system): c(system), referenceCount(0) {
populateTables(&c);
}
virtual unsigned floatRegisterSize() {
return vfpSupported() ? 4 : 0;
}
virtual uint32_t generalRegisterMask() {
return GPR_MASK;
}
virtual uint32_t floatRegisterMask() {
return vfpSupported() ? FPR_MASK : 0;
}
virtual int scratch() {
return 5;
}
virtual int stack() {
return StackRegister;
}
virtual int thread() {
return ThreadRegister;
}
virtual int returnLow() {
return 0;
}
virtual int returnHigh() {
return 1;
}
virtual int virtualCallTarget() {
return 4;
}
virtual int virtualCallIndex() {
return 3;
}
virtual bool bigEndian() {
return false;
}
virtual uintptr_t maximumImmediateJump() {
return 0x1FFFFFF;
}
virtual bool reserved(int register_) {
switch (register_) {
case LinkRegister:
case StackRegister:
case ThreadRegister:
case ProgramCounter:
return true;
default:
return false;
}
}
virtual unsigned frameFootprint(unsigned footprint) {
return max(footprint, StackAlignmentInWords);
}
virtual unsigned argumentFootprint(unsigned footprint) {
return ::argumentFootprint(footprint);
}
virtual bool argumentAlignment() {
#ifdef __APPLE__
return false;
#else
return true;
#endif
}
virtual bool argumentRegisterAlignment() {
#ifdef __APPLE__
return false;
#else
return true;
#endif
}
virtual unsigned argumentRegisterCount() {
return 4;
}
virtual int argumentRegister(unsigned index) {
assert(&c, index < argumentRegisterCount());
return index;
}
virtual bool hasLinkRegister() {
return true;
}
virtual unsigned stackAlignmentInWords() {
return StackAlignmentInWords;
}
virtual bool matchCall(void* returnAddress, void* target) {
uint32_t* instruction = static_cast<uint32_t*>(returnAddress) - 1;
return *instruction == static_cast<uint32_t>
(bl(static_cast<uint8_t*>(target)
- reinterpret_cast<uint8_t*>(instruction)));
}
virtual void updateCall(UnaryOperation op UNUSED,
void* returnAddress,
void* newTarget)
{
switch (op) {
case Call:
case Jump:
case AlignedCall:
case AlignedJump: {
updateOffset(c.s, static_cast<uint8_t*>(returnAddress) - 4,
reinterpret_cast<intptr_t>(newTarget));
} break;
case LongCall:
case LongJump:
case AlignedLongCall:
case AlignedLongJump: {
uint32_t* p = static_cast<uint32_t*>(returnAddress) - 2;
*reinterpret_cast<void**>(p + (((*p & PoolOffsetMask) + 8) / 4))
= newTarget;
} break;
default: abort(&c);
}
}
virtual unsigned constantCallSize() {
return 4;
}
virtual void setConstant(void* dst, uint64_t constant) {
*static_cast<target_uintptr_t*>(dst) = constant;
}
virtual unsigned alignFrameSize(unsigned sizeInWords) {
return pad(sizeInWords + FrameHeaderSize, StackAlignmentInWords)
- FrameHeaderSize;
}
virtual void nextFrame(void* start, unsigned size, unsigned footprint,
void* link, bool mostRecent,
unsigned targetParameterFootprint, void** ip,
void** stack)
{
::nextFrame(&c, static_cast<uint32_t*>(start), size, footprint, link,
mostRecent, targetParameterFootprint, ip, stack);
}
virtual void* frameIp(void* stack) {
return stack ? static_cast<void**>(stack)[returnAddressOffset()] : 0;
}
virtual unsigned frameHeaderSize() {
return FrameHeaderSize;
}
virtual unsigned frameReturnAddressSize() {
return 0;
}
virtual unsigned frameFooterSize() {
return 0;
}
virtual int returnAddressOffset() {
return -1;
}
virtual int framePointerOffset() {
return 0;
}
virtual BinaryOperation hasBinaryIntrinsic(Thread*, object) {
return NoBinaryOperation;
}
virtual TernaryOperation hasTernaryIntrinsic(Thread*, object) {
return NoTernaryOperation;
}
virtual bool alwaysCondensed(BinaryOperation) {
return false;
}
virtual bool alwaysCondensed(TernaryOperation) {
return false;
}
virtual void plan
(UnaryOperation,
unsigned, uint8_t* aTypeMask, uint64_t* aRegisterMask,
bool* thunk)
{
*aTypeMask = (1 << RegisterOperand) | (1 << ConstantOperand);
*aRegisterMask = ~static_cast<uint64_t>(0);
*thunk = false;
}
virtual void planSource
(BinaryOperation op,
unsigned aSize, uint8_t* aTypeMask, uint64_t* aRegisterMask,
unsigned bSize, bool* thunk)
{
*thunk = false;
*aTypeMask = ~0;
*aRegisterMask = ~static_cast<uint64_t>(0);
switch (op) {
case Negate:
*aTypeMask = (1 << RegisterOperand);
break;
case Absolute:
case FloatAbsolute:
case FloatSquareRoot:
case FloatNegate:
case Float2Float:
if (vfpSupported()) {
*aTypeMask = (1 << RegisterOperand);
*aRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
case Float2Int:
if (vfpSupported() && bSize == 4 && aSize == 4) {
*aTypeMask = (1 << RegisterOperand);
*aRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
case Int2Float:
if (vfpSupported() && aSize == 4 && bSize == 4) {
*aTypeMask = (1 << RegisterOperand);
*aRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
default:
break;
}
}
virtual void planDestination
(BinaryOperation op,
unsigned, uint8_t, uint64_t,
unsigned, uint8_t* bTypeMask, uint64_t* bRegisterMask)
{
*bTypeMask = (1 << RegisterOperand) | (1 << MemoryOperand);
*bRegisterMask = ~static_cast<uint64_t>(0);
switch (op) {
case Negate:
*bTypeMask = (1 << RegisterOperand);
break;
default:
break;
}
}
virtual void planMove
(unsigned, uint8_t* srcTypeMask, uint64_t* srcRegisterMask,
uint8_t* tmpTypeMask, uint64_t* tmpRegisterMask,
uint8_t dstTypeMask, uint64_t)
{
*srcTypeMask = ~0;
*srcRegisterMask = ~static_cast<uint64_t>(0);
*tmpTypeMask = 0;
*tmpRegisterMask = 0;
if (dstTypeMask & (1 << MemoryOperand)) {
// can't move directly from memory or constant to memory
*srcTypeMask = 1 << RegisterOperand;
*tmpTypeMask = 1 << RegisterOperand;
*tmpRegisterMask = ~static_cast<uint64_t>(0);
}
}
virtual void planSource
(TernaryOperation op,
unsigned, uint8_t* aTypeMask, uint64_t* aRegisterMask,
unsigned bSize, uint8_t* bTypeMask, uint64_t* bRegisterMask,
unsigned, bool* thunk)
{
*aTypeMask = (1 << RegisterOperand) | (1 << ConstantOperand);
*aRegisterMask = ~static_cast<uint64_t>(0);
*bTypeMask = (1 << RegisterOperand);
*bRegisterMask = ~static_cast<uint64_t>(0);
*thunk = false;
switch (op) {
case ShiftLeft:
case ShiftRight:
case UnsignedShiftRight:
if (bSize == 8) *aTypeMask = *bTypeMask = (1 << RegisterOperand);
break;
case Add:
case Subtract:
case Or:
case Xor:
case Multiply:
*aTypeMask = *bTypeMask = (1 << RegisterOperand);
break;
case Divide:
case Remainder:
*thunk = true;
break;
case FloatAdd:
case FloatSubtract:
case FloatMultiply:
case FloatDivide:
case FloatRemainder:
case JumpIfFloatEqual:
case JumpIfFloatNotEqual:
case JumpIfFloatLess:
case JumpIfFloatGreater:
case JumpIfFloatLessOrEqual:
case JumpIfFloatGreaterOrEqual:
case JumpIfFloatLessOrUnordered:
case JumpIfFloatGreaterOrUnordered:
case JumpIfFloatLessOrEqualOrUnordered:
case JumpIfFloatGreaterOrEqualOrUnordered:
if (vfpSupported()) {
*aTypeMask = *bTypeMask = (1 << RegisterOperand);
*aRegisterMask = *bRegisterMask = FPR_MASK;
} else {
*thunk = true;
}
break;
default:
break;
}
}
virtual void planDestination
(TernaryOperation op,
unsigned, uint8_t, uint64_t,
unsigned, uint8_t, const uint64_t,
unsigned, uint8_t* cTypeMask, uint64_t* cRegisterMask)
{
if (isBranch(op)) {
*cTypeMask = (1 << ConstantOperand);
*cRegisterMask = 0;
} else {
*cTypeMask = (1 << RegisterOperand);
*cRegisterMask = ~static_cast<uint64_t>(0);
}
}
virtual void acquire() {
++ referenceCount;
}
virtual void release() {
if (-- referenceCount == 0) {
c.s->free(this);
}
}
ArchitectureContext c;
unsigned referenceCount;
};
class MyAssembler: public Assembler {
public:
MyAssembler(System* s, Allocator* a, Zone* zone, MyArchitecture* arch):
c(s, a, zone), arch_(arch)
{ }
virtual void setClient(Client* client) {
assert(&c, c.client == 0);
c.client = client;
}
virtual Architecture* arch() {
return arch_;
}
virtual void checkStackOverflow(uintptr_t handler,
unsigned stackLimitOffsetFromThread)
{
Register stack(StackRegister);
Memory stackLimit(ThreadRegister, stackLimitOffsetFromThread);
Constant handlerConstant(new(c.zone) ResolvedPromise(handler));
branchRM(&c, JumpIfGreaterOrEqual, TargetBytesPerWord, &stack, &stackLimit,
&handlerConstant);
}
virtual void saveFrame(unsigned stackOffset, unsigned ipOffset) {
Register link(LinkRegister);
Memory linkDst(ThreadRegister, ipOffset);
moveRM(&c, TargetBytesPerWord, &link, TargetBytesPerWord, &linkDst);
Register stack(StackRegister);
Memory stackDst(ThreadRegister, stackOffset);
moveRM(&c, TargetBytesPerWord, &stack, TargetBytesPerWord, &stackDst);
}
virtual void pushFrame(unsigned argumentCount, ...) {
struct {
unsigned size;
OperandType type;
Operand* operand;
} arguments[argumentCount];
va_list a; va_start(a, argumentCount);
unsigned footprint = 0;
for (unsigned i = 0; i < argumentCount; ++i) {
arguments[i].size = va_arg(a, unsigned);
arguments[i].type = static_cast<OperandType>(va_arg(a, int));
arguments[i].operand = va_arg(a, Operand*);
footprint += ceiling(arguments[i].size, TargetBytesPerWord);
}
va_end(a);
allocateFrame(arch_->alignFrameSize(footprint));
unsigned offset = 0;
for (unsigned i = 0; i < argumentCount; ++i) {
if (i < arch_->argumentRegisterCount()) {
Register dst(arch_->argumentRegister(i));
apply(Move,
arguments[i].size, arguments[i].type, arguments[i].operand,
pad(arguments[i].size, TargetBytesPerWord), RegisterOperand,
&dst);
offset += ceiling(arguments[i].size, TargetBytesPerWord);
} else {
Memory dst(StackRegister, offset * TargetBytesPerWord);
apply(Move,
arguments[i].size, arguments[i].type, arguments[i].operand,
pad(arguments[i].size, TargetBytesPerWord), MemoryOperand, &dst);
offset += ceiling(arguments[i].size, TargetBytesPerWord);
}
}
}
virtual void allocateFrame(unsigned footprint) {
footprint += FrameHeaderSize;
// larger frames may require multiple subtract/add instructions
// to allocate/deallocate, and nextFrame will need to be taught
// how to handle them:
assert(&c, footprint < 256);
Register stack(StackRegister);
ResolvedPromise footprintPromise(footprint * TargetBytesPerWord);
Constant footprintConstant(&footprintPromise);
subC(&c, TargetBytesPerWord, &footprintConstant, &stack, &stack);
Register returnAddress(LinkRegister);
Memory returnAddressDst
(StackRegister, (footprint - 1) * TargetBytesPerWord);
moveRM(&c, TargetBytesPerWord, &returnAddress, TargetBytesPerWord,
&returnAddressDst);
}
virtual void adjustFrame(unsigned difference) {
Register stack(StackRegister);
ResolvedPromise differencePromise(difference * TargetBytesPerWord);
Constant differenceConstant(&differencePromise);
subC(&c, TargetBytesPerWord, &differenceConstant, &stack, &stack);
}
virtual void popFrame(unsigned footprint) {
footprint += FrameHeaderSize;
Register returnAddress(LinkRegister);
Memory returnAddressSrc
(StackRegister, (footprint - 1) * TargetBytesPerWord);
moveMR(&c, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord,
&returnAddress);
Register stack(StackRegister);
ResolvedPromise footprintPromise(footprint * TargetBytesPerWord);
Constant footprintConstant(&footprintPromise);
addC(&c, TargetBytesPerWord, &footprintConstant, &stack, &stack);
}
virtual void popFrameForTailCall(unsigned footprint,
int offset,
int returnAddressSurrogate,
int framePointerSurrogate UNUSED)
{
assert(&c, framePointerSurrogate == NoRegister);
if (TailCalls) {
if (offset) {
footprint += FrameHeaderSize;
Register link(LinkRegister);
Memory returnAddressSrc
(StackRegister, (footprint - 1) * TargetBytesPerWord);
moveMR(&c, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord,
&link);
Register stack(StackRegister);
ResolvedPromise footprintPromise
((footprint - offset) * TargetBytesPerWord);
Constant footprintConstant(&footprintPromise);
addC(&c, TargetBytesPerWord, &footprintConstant, &stack, &stack);
if (returnAddressSurrogate != NoRegister) {
assert(&c, offset > 0);
Register ras(returnAddressSurrogate);
Memory dst(StackRegister, (offset - 1) * TargetBytesPerWord);
moveRM(&c, TargetBytesPerWord, &ras, TargetBytesPerWord, &dst);
}
} else {
popFrame(footprint);
}
} else {
abort(&c);
}
}
virtual void popFrameAndPopArgumentsAndReturn(unsigned frameFootprint,
unsigned argumentFootprint)
{
popFrame(frameFootprint);
assert(&c, argumentFootprint >= StackAlignmentInWords);
assert(&c, (argumentFootprint % StackAlignmentInWords) == 0);
unsigned offset;
if (TailCalls and argumentFootprint > StackAlignmentInWords) {
offset = argumentFootprint - StackAlignmentInWords;
Register stack(StackRegister);
ResolvedPromise adjustmentPromise(offset * TargetBytesPerWord);
Constant adjustment(&adjustmentPromise);
addC(&c, TargetBytesPerWord, &adjustment, &stack, &stack);
} else {
offset = 0;
}
return_(&c);
}
virtual void popFrameAndUpdateStackAndReturn(unsigned frameFootprint,
unsigned stackOffsetFromThread)
{
popFrame(frameFootprint);
Register stack(StackRegister);
Memory newStackSrc(ThreadRegister, stackOffsetFromThread);
moveMR(&c, TargetBytesPerWord, &newStackSrc, TargetBytesPerWord, &stack);
return_(&c);
}
virtual void apply(Operation op) {
arch_->c.operations[op](&c);
}
virtual void apply(UnaryOperation op,
unsigned aSize, OperandType aType, Operand* aOperand)
{
arch_->c.unaryOperations[index(&(arch_->c), op, aType)]
(&c, aSize, aOperand);
}
virtual void apply(BinaryOperation op,
unsigned aSize, OperandType aType, Operand* aOperand,
unsigned bSize, OperandType bType, Operand* bOperand)
{
arch_->c.binaryOperations[index(&(arch_->c), op, aType, bType)]
(&c, aSize, aOperand, bSize, bOperand);
}
virtual void apply(TernaryOperation op,
unsigned aSize, OperandType aType, Operand* aOperand,
unsigned bSize, OperandType bType UNUSED,
Operand* bOperand,
unsigned cSize UNUSED, OperandType cType UNUSED,
Operand* cOperand)
{
if (isBranch(op)) {
assert(&c, aSize == bSize);
assert(&c, cSize == TargetBytesPerWord);
assert(&c, cType == ConstantOperand);
arch_->c.branchOperations[branchIndex(&(arch_->c), aType, bType)]
(&c, op, aSize, aOperand, bOperand, cOperand);
} else {
assert(&c, bSize == cSize);
assert(&c, bType == RegisterOperand);
assert(&c, cType == RegisterOperand);
arch_->c.ternaryOperations[index(&(arch_->c), op, aType)]
(&c, bSize, aOperand, bOperand, cOperand);
}
}
virtual void setDestination(uint8_t* dst) {
c.result = dst;
}
virtual void write() {
uint8_t* dst = c.result;
unsigned dstOffset = 0;
for (MyBlock* b = c.firstBlock; b; b = b->next) {
if (DebugPool) {
fprintf(stderr, "write block %p\n", b);
}
unsigned blockOffset = 0;
for (PoolEvent* e = b->poolEventHead; e; e = e->next) {
unsigned size = e->offset - blockOffset;
memcpy(dst + dstOffset, c.code.data + b->offset + blockOffset, size);
blockOffset = e->offset;
dstOffset += size;
unsigned poolSize = 0;
for (PoolOffset* o = e->poolOffsetHead; o; o = o->next) {
if (DebugPool) {
fprintf(stderr, "visit pool offset %p %d in block %p\n",
o, o->offset, b);
}
unsigned entry = dstOffset + poolSize;
if (needJump(b)) {
entry += TargetBytesPerWord;
}
o->entry->address = dst + entry;
unsigned instruction = o->block->start
+ padding(o->block, o->offset) + o->offset;
int32_t v = (entry - 8) - instruction;
expect(&c, v == (v & PoolOffsetMask));
int32_t* p = reinterpret_cast<int32_t*>(dst + instruction);
*p = (v & PoolOffsetMask) | ((~PoolOffsetMask) & *p);
poolSize += TargetBytesPerWord;
}
bool jump = needJump(b);
if (jump) {
write4
(dst + dstOffset, ::b((poolSize + TargetBytesPerWord - 8) >> 2));
}
dstOffset += poolSize + (jump ? TargetBytesPerWord : 0);
}
unsigned size = b->size - blockOffset;
memcpy(dst + dstOffset,
c.code.data + b->offset + blockOffset,
size);
dstOffset += size;
}
for (Task* t = c.tasks; t; t = t->next) {
t->run(&c);
}
for (ConstantPoolEntry* e = c.constantPool; e; e = e->next) {
if (e->constant->resolved()) {
*static_cast<target_uintptr_t*>(e->address) = e->constant->value();
} else {
new (e->constant->listen(sizeof(ConstantPoolListener)))
ConstantPoolListener(c.s, static_cast<target_uintptr_t*>(e->address),
e->callOffset
? dst + e->callOffset->value() + 8
: 0);
}
// fprintf(stderr, "constant %p at %p\n", reinterpret_cast<void*>(e->constant->value()), e->address);
}
}
virtual Promise* offset(bool forTrace) {
return ::offset(&c, forTrace);
}
virtual Block* endBlock(bool startNew) {
MyBlock* b = c.lastBlock;
b->size = c.code.length() - b->offset;
if (startNew) {
c.lastBlock = new (c.zone) MyBlock(&c, c.code.length());
} else {
c.lastBlock = 0;
}
return b;
}
virtual void endEvent() {
MyBlock* b = c.lastBlock;
unsigned thisEventOffset = c.code.length() - b->offset;
if (b->poolOffsetHead) {
int32_t v = (thisEventOffset + TargetBytesPerWord - 8)
- b->poolOffsetHead->offset;
if (v > 0 and v != (v & PoolOffsetMask)) {
appendPoolEvent
(&c, b, b->lastEventOffset, b->poolOffsetHead,
b->lastPoolOffsetTail);
if (DebugPool) {
for (PoolOffset* o = b->poolOffsetHead;
o != b->lastPoolOffsetTail->next; o = o->next)
{
fprintf(stderr,
"in endEvent, include %p %d in pool event %p at offset %d "
"in block %p\n",
o, o->offset, b->poolEventTail, b->lastEventOffset, b);
}
}
b->poolOffsetHead = b->lastPoolOffsetTail->next;
b->lastPoolOffsetTail->next = 0;
if (b->poolOffsetHead == 0) {
b->poolOffsetTail = 0;
}
}
}
b->lastEventOffset = thisEventOffset;
b->lastPoolOffsetTail = b->poolOffsetTail;
}
virtual unsigned length() {
return c.code.length();
}
virtual unsigned footerSize() {
return 0;
}
virtual void dispose() {
c.code.dispose();
}
Context c;
MyArchitecture* arch_;
};
} // namespace
namespace vm {
Assembler::Architecture*
makeArchitecture(System* system, bool)
{
return new (allocate(system, sizeof(MyArchitecture))) MyArchitecture(system);
}
Assembler*
makeAssembler(System* system, Allocator* allocator, Zone* zone,
Assembler::Architecture* architecture)
{
return new(zone) MyAssembler(system, allocator, zone,
static_cast<MyArchitecture*>(architecture));
}
} // namespace vm
|
//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 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.
//
// FFLDv2 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 FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Intersector.h"
#include "LBFGS.h"
#include "Mixture.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace Eigen;
using namespace FFLD;
using namespace std;
Mixture::Mixture() : cached_(false), zero_(true)
{
}
Mixture::Mixture(const vector<Model> & models) : models_(models), cached_(false), zero_(true)
{
}
Mixture::Mixture(int nbComponents, const vector<Scene> & scenes, Object::Name name) :
cached_(false), zero_(true)
{
// Create an empty mixture if any of the given parameters is invalid
if ((nbComponents <= 0) || scenes.empty()) {
cerr << "Attempting to create an empty mixture" << endl;
return;
}
// Compute the root filters' sizes using Felzenszwalb's heuristic
const vector<pair<int, int> > sizes = FilterSizes(nbComponents, scenes, name);
// Early return in case the root filters' sizes could not be determined
if (sizes.size() != nbComponents)
return;
// Initialize the models (with symmetry) to those sizes
models_.resize(2 * nbComponents);
for (int i = 0; i < nbComponents; ++i) {
models_[2 * i ] = Model(sizes[i]);
models_[2 * i + 1] = Model(sizes[i]);
}
}
bool Mixture::empty() const
{
return models_.empty();
}
const vector<Model> & Mixture::models() const
{
return models_;
}
vector<Model> & Mixture::models()
{
return models_;
}
pair<int, int> Mixture::minSize() const
{
pair<int, int> size(0, 0);
if (!models_.empty()) {
size = models_[0].rootSize();
for (int i = 1; i < models_.size(); ++i) {
size.first = min(size.first, models_[i].rootSize().first);
size.second = min(size.second, models_[i].rootSize().second);
}
}
return size;
}
pair<int, int> Mixture::maxSize() const
{
pair<int, int> size(0, 0);
if (!models_.empty()) {
size = models_[0].rootSize();
for (int i = 1; i < models_.size(); ++i) {
size.first = max(size.first, models_[i].rootSize().first);
size.second = max(size.second, models_[i].rootSize().second);
}
}
return size;
}
double Mixture::train(const vector<Scene> & scenes, Object::Name name, int padx, int pady,
int interval, int nbRelabel, int nbDatamine, int maxNegatives, double C,
double J, double overlap)
{
if (empty() || scenes.empty() || (padx < 1) || (pady < 1) || (interval < 1) ||
(nbRelabel < 1) || (nbDatamine < 1) || (maxNegatives < models_.size()) || (C <= 0.0) ||
(J <= 0.0) || (overlap <= 0.0) || (overlap >= 1.0)) {
cerr << "Invalid training parameters" << endl;
return numeric_limits<double>::quiet_NaN();
}
// Test if the models are really zero by looking at the first cell of the first filter of the
// first model
if (!models_[0].empty() && models_[0].parts()[0].filter.size() &&
!models_[0].parts()[0].filter(0, 0).isZero())
zero_ = false;
double loss = numeric_limits<double>::infinity();
for (int relabel = 0; relabel < nbRelabel; ++relabel) {
// Sample all the positives
vector<pair<Model, int> > positives;
posLatentSearch(scenes, name, padx, pady, interval, overlap, positives);
// Left-right clustering at the first iteration
if (zero_)
Cluster(static_cast<int>(models_.size()), positives);
// Cache of hard negative samples of maximum size maxNegatives
vector<pair<Model, int> > negatives;
// Previous loss on the cache
double prevLoss = -numeric_limits<double>::infinity();
for (int datamine = 0; datamine < nbDatamine; ++datamine) {
// Remove easy samples (keep hard ones)
int j = 0;
for (int i = 0; i < negatives.size(); ++i)
if ((negatives[i].first.parts()[0].deformation(3) =
models_[negatives[i].second].dot(negatives[i].first)) > -1.01)
negatives[j++] = negatives[i];
negatives.resize(j);
// Sample new hard negatives
negLatentSearch(scenes, name, padx, pady, interval, maxNegatives, negatives);
// Stop if there are no new hard negatives
if (datamine && (negatives.size() == j))
break;
// Merge the left / right samples for more efficient training
vector<int> posComponents(positives.size());
for (int i = 0; i < positives.size(); ++i) {
posComponents[i] = positives[i].second;
if (positives[i].second & 1)
positives[i].first = positives[i].first.flip();
positives[i].second >>= 1;
}
vector<int> negComponents(negatives.size());
for (int i = 0; i < negatives.size(); ++i) {
negComponents[i] = negatives[i].second;
if (negatives[i].second & 1)
negatives[i].first = negatives[i].first.flip();
negatives[i].second >>= 1;
}
// Merge the left / right models for more efficient training
for (int i = 1; i < models_.size() / 2; ++i)
models_[i] = models_[i * 2];
models_.resize(models_.size() / 2);
const int maxIterations =
min(max(10.0 * sqrt(static_cast<double>(positives.size())), 100.0), 1000.0);
loss = train(positives, negatives, C, J, maxIterations);
cout << "Relabel: " << relabel << ", datamine: " << datamine
<< ", # positives: " << positives.size() << ", # hard negatives: " << j
<< " (already in the cache) + " << (negatives.size() - j) << " (new) = "
<< negatives.size() << ", loss (cache): " << loss << endl;
// Unmerge the left / right samples
for (int i = 0; i < positives.size(); ++i) {
positives[i].second = posComponents[i];
if (positives[i].second & 1)
positives[i].first = positives[i].first.flip();
}
for (int i = 0; i < negatives.size(); ++i) {
negatives[i].second = negComponents[i];
if (negatives[i].second & 1)
negatives[i].first = negatives[i].first.flip();
}
// Unmerge the left / right models
models_.resize(models_.size() * 2);
for (int i = static_cast<int>(models_.size()) / 2 - 1; i >= 0; --i) {
models_[i * 2 ] = models_[i];
models_[i * 2 + 1] = models_[i].flip();
}
// The filters definitely changed
filterCache_.clear();
cached_ = false;
zero_ = false;
// Save the latest model so as to be able to look at it while training
ofstream out("tmp.txt");
out << (*this);
// Stop if we are not making progress
if ((0.999 * loss < prevLoss) && (negatives.size() < maxNegatives))
break;
prevLoss = loss;
}
}
return loss;
}
void Mixture::initializeParts(int nbParts, pair<int, int> partSize)
{
for (int i = 0; i < models_.size(); i += 2) {
models_[i].initializeParts(nbParts, partSize);
models_[i + 1] = models_[i].flip();
}
// The filters definitely changed
filterCache_.clear();
cached_ = false;
zero_ = false;
}
void Mixture::convolve(const HOGPyramid & pyramid, vector<HOGPyramid::Matrix> & scores,
vector<Indices> & argmaxes,
vector<vector<vector<Model::Positions> > > * positions) const
{
if (empty() || pyramid.empty()) {
scores.clear();
argmaxes.clear();
if (positions)
positions->clear();
return;
}
const int nbModels = static_cast<int>(models_.size());
const int nbLevels = static_cast<int>(pyramid.levels().size());
// Convolve with all the models
vector<vector<HOGPyramid::Matrix> > convolutions;
convolve(pyramid, convolutions, positions);
// In case of error
if (convolutions.empty()) {
scores.clear();
argmaxes.clear();
if (positions)
positions->clear();
return;
}
// Resize the scores and argmaxes
scores.resize(nbLevels);
argmaxes.resize(nbLevels);
#pragma omp parallel for
for (int z = 0; z < nbLevels; ++z) {
int rows = static_cast<int>(convolutions[0][z].rows());
int cols = static_cast<int>(convolutions[0][z].cols());
for (int i = 1; i < nbModels; ++i) {
rows = min(rows, static_cast<int>(convolutions[i][z].rows()));
cols = min(cols, static_cast<int>(convolutions[i][z].cols()));
}
scores[z].resize(rows, cols);
argmaxes[z].resize(rows, cols);
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
int argmax = 0;
for (int i = 1; i < nbModels; ++i)
if (convolutions[i][z](y, x) > convolutions[argmax][z](y, x))
argmax = i;
scores[z](y, x) = convolutions[argmax][z](y, x);
argmaxes[z](y, x) = argmax;
}
}
}
}
void Mixture::cacheFilters() const
{
// Count the number of filters
int nbFilters = 0;
for (int i = 0; i < models_.size(); ++i)
nbFilters += models_[i].parts().size();
// Transform all the filters
filterCache_.resize(nbFilters);
for (int i = 0, j = 0; i < models_.size(); ++i) {
#pragma omp parallel for
for (int k = 0; k < models_[i].parts().size(); ++k)
Patchwork::TransformFilter(models_[i].parts()[k].filter, filterCache_[j + k]);
j += models_[i].parts().size();
}
cached_ = true;
}
static inline void clipBndBox(Rectangle & bndbox, const Scene & scene, double alpha = 0.0)
{
// Compromise between clamping the bounding box to the image and penalizing bounding boxes
// extending outside the image
if (bndbox.left() < 0)
bndbox.setLeft(bndbox.left() * alpha - 0.5);
if (bndbox.top() < 0)
bndbox.setTop(bndbox.top() * alpha - 0.5);
if (bndbox.right() >= scene.width())
bndbox.setRight(scene.width() - 1 + (bndbox.right() - scene.width() + 1) * alpha + 0.5);
if (bndbox.bottom() >= scene.height())
bndbox.setBottom(scene.height() - 1 + (bndbox.bottom() - scene.height() + 1) * alpha + 0.5);
}
void Mixture::posLatentSearch(const vector<Scene> & scenes, Object::Name name, int padx, int pady,
int interval, double overlap,
vector<pair<Model, int> > & positives) const
{
if (scenes.empty() || (padx < 1) || (pady < 1) || (interval < 1) || (overlap <= 0.0) ||
(overlap >= 1.0)) {
positives.clear();
cerr << "Invalid training paramters" << endl;
return;
}
positives.clear();
for (int i = 0; i < scenes.size(); ++i) {
// Skip negative scenes
bool negative = true;
for (int j = 0; j < scenes[i].objects().size(); ++j)
if ((scenes[i].objects()[j].name() == name) && !scenes[i].objects()[j].difficult())
negative = false;
if (negative)
continue;
const JPEGImage image(scenes[i].filename());
if (image.empty()) {
positives.clear();
return;
}
const HOGPyramid pyramid(image, padx, pady, interval);
if (pyramid.empty()) {
positives.clear();
return;
}
vector<HOGPyramid::Matrix> scores;
vector<Indices> argmaxes;
vector<vector<vector<Model::Positions> > > positions;
if (!zero_)
convolve(pyramid, scores, argmaxes, &positions);
// For each object, set as positive the best (highest score or else most intersecting)
// position
for (int j = 0; j < scenes[i].objects().size(); ++j) {
// Ignore objects with a different name or difficult objects
if ((scenes[i].objects()[j].name() != name) || scenes[i].objects()[j].difficult())
continue;
const Intersector intersector(scenes[i].objects()[j].bndbox(), overlap);
// The model, level, position, score, and intersection of the best example
int argModel = -1;
int argX = -1;
int argY = -1;
int argZ = -1;
double maxScore = -numeric_limits<double>::infinity();
double maxInter = 0.0;
for (int z = 0; z < pyramid.levels().size(); ++z) {
const double scale = pow(2.0, static_cast<double>(z) / interval + 2);
int rows = 0;
int cols = 0;
if (!zero_) {
rows = static_cast<int>(scores[z].rows());
cols = static_cast<int>(scores[z].cols());
}
else if (z >= interval) {
rows = static_cast<int>(pyramid.levels()[z].rows()) - maxSize().first + 1;
cols = static_cast<int>(pyramid.levels()[z].cols()) - maxSize().second + 1;
}
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
// Find the best matching model (highest score or else most intersecting)
int model = zero_ ? 0 : argmaxes[z](y, x);
double intersection = 0.0;
// Try all models and keep the most intersecting one
if (zero_) {
for (int k = 0; k < models_.size(); ++k) {
// The bounding box of the model at this position
Rectangle bndbox;
bndbox.setX((x - padx) * scale + 0.5);
bndbox.setY((y - pady) * scale + 0.5);
bndbox.setWidth(models_[k].rootSize().second * scale + 0.5);
bndbox.setHeight(models_[k].rootSize().first * scale + 0.5);
// Trade-off between clipping and penalizing
clipBndBox(bndbox, scenes[i], 0.5);
double inter = 0.0;
if (intersector(bndbox, &inter)) {
if (inter > intersection) {
model = k;
intersection = inter;
}
}
}
}
// Just take the model with the best score
else {
// The bounding box of the model at this position
Rectangle bndbox;
bndbox.setX((x - padx) * scale + 0.5);
bndbox.setY((y - pady) * scale + 0.5);
bndbox.setWidth(models_[model].rootSize().second * scale + 0.5);
bndbox.setHeight(models_[model].rootSize().first * scale + 0.5);
clipBndBox(bndbox, scenes[i]);
intersector(bndbox, &intersection);
}
if ((intersection > maxInter) && (zero_ || (scores[z](y, x) > maxScore))) {
argModel = model;
argX = x;
argY = y;
argZ = z;
if (!zero_)
maxScore = scores[z](y, x);
maxInter = intersection;
}
}
}
}
if (maxInter >= overlap) {
Model sample;
models_[argModel].initializeSample(pyramid, argX, argY, argZ, sample,
zero_ ? 0 : &positions[argModel]);
if (!sample.empty())
positives.push_back(make_pair(sample, argModel));
}
}
}
}
static inline bool operator==(const Model & a, const Model & b)
{
return (a.parts()[0].offset == b.parts()[0].offset) &&
(a.parts()[0].deformation(0) == b.parts()[0].deformation(0)) &&
(a.parts()[0].deformation(1) == b.parts()[0].deformation(1));
}
static inline bool operator<(const Model & a, const Model & b)
{
return (a.parts()[0].offset(0) < b.parts()[0].offset(0)) ||
((a.parts()[0].offset(0) == b.parts()[0].offset(0)) &&
((a.parts()[0].offset(1) < b.parts()[0].offset(1)) ||
((a.parts()[0].offset(1) == b.parts()[0].offset(1)) &&
((a.parts()[0].deformation(0) < b.parts()[0].deformation(0)) ||
((a.parts()[0].deformation(0) == b.parts()[0].deformation(0)) &&
((a.parts()[0].deformation(1) < b.parts()[0].deformation(1))))))));
}
void Mixture::negLatentSearch(const vector<Scene> & scenes, Object::Name name, int padx, int pady,
int interval, int maxNegatives,
vector<pair<Model, int> > & negatives) const
{
// Sample at most (maxNegatives - negatives.size()) negatives with a score above -1.0
if (scenes.empty() || (padx < 1) || (pady < 1) || (interval < 1) || (maxNegatives <= 0) ||
(negatives.size() >= maxNegatives)) {
negatives.clear();
cerr << "Invalid training paramters" << endl;
return;
}
// The number of negatives already in the cache
const int nbCached = static_cast<int>(negatives.size());
for (int i = 0, j = 0; i < scenes.size(); ++i) {
// Skip positive scenes
bool positive = false;
for (int k = 0; k < scenes[i].objects().size(); ++k)
if (scenes[i].objects()[k].name() == name)
positive = true;
if (positive)
continue;
const JPEGImage image(scenes[i].filename());
if (image.empty()) {
negatives.clear();
return;
}
const HOGPyramid pyramid(image, padx, pady, interval);
if (pyramid.empty()) {
negatives.clear();
return;
}
vector<HOGPyramid::Matrix> scores;
vector<Indices> argmaxes;
vector<vector<vector<Model::Positions> > > positions;
if (!zero_)
convolve(pyramid, scores, argmaxes, &positions);
for (int z = 0; z < pyramid.levels().size(); ++z) {
int rows = 0;
int cols = 0;
if (!zero_) {
rows = static_cast<int>(scores[z].rows());
cols = static_cast<int>(scores[z].cols());
}
else if (z >= interval) {
rows = static_cast<int>(pyramid.levels()[z].rows()) - maxSize().first + 1;
cols = static_cast<int>(pyramid.levels()[z].cols()) - maxSize().second + 1;
}
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
const int argmax = zero_ ? (rand() % models_.size()) : argmaxes[z](y, x);
if (zero_ || (scores[z](y, x) > -1)) {
Model sample;
models_[argmax].initializeSample(pyramid, x, y, z, sample,
zero_ ? 0 : &positions[argmax]);
if (!sample.empty()) {
// Store all the information about the sample in the offset and
// deformation of its root
sample.parts()[0].offset(0) = i;
sample.parts()[0].offset(1) = z;
sample.parts()[0].deformation(0) = y;
sample.parts()[0].deformation(1) = x;
sample.parts()[0].deformation(2) = argmax;
sample.parts()[0].deformation(3) = zero_ ? 0.0 : scores[z](y, x);
// Look if the same sample was already sampled
while ((j < nbCached) && (negatives[j].first < sample))
++j;
// Make sure not to put the same sample twice
if ((j >= nbCached) || !(negatives[j].first == sample)) {
negatives.push_back(make_pair(sample, argmax));
if (negatives.size() == maxNegatives)
return;
}
}
}
}
}
}
}
}
namespace FFLD
{
namespace detail
{
class Loss : public LBFGS::IFunction
{
public:
Loss(vector<Model> & models, const vector<pair<Model, int> > & positives,
const vector<pair<Model, int> > & negatives, double C, double J, int maxIterations) :
models_(models), positives_(positives), negatives_(negatives), C_(C), J_(J),
maxIterations_(maxIterations)
{
}
virtual int dim() const
{
int d = 0;
for (int i = 0; i < models_.size(); ++i) {
for (int j = 0; j < models_[i].parts().size(); ++j) {
d += models_[i].parts()[j].filter.size() * HOGPyramid::NbFeatures; // Filter
if (j)
d += 6; // Deformation
}
++d; // Bias
}
return d;
}
virtual double operator()(const double * x, double * g = 0) const
{
// Recopy the features into the models
ToModels(x, models_);
// Compute the loss and gradient over the samples
double loss = 0.0;
vector<Model> gradients;
if (g) {
gradients.resize(models_.size());
for (int i = 0; i < models_.size(); ++i)
gradients[i] = Model(models_[i].rootSize(),
static_cast<int>(models_[i].parts().size()) - 1,
models_[i].partSize());
}
vector<double> posMargins(positives_.size());
#pragma omp parallel for
for (int i = 0; i < positives_.size(); ++i)
posMargins[i] = models_[positives_[i].second].dot(positives_[i].first);
for (int i = 0; i < positives_.size(); ++i) {
if (posMargins[i] < 1.0) {
loss += 1.0 - posMargins[i];
if (g)
gradients[positives_[i].second] -= positives_[i].first;
}
}
// Reweight the positives
if (J_ != 1.0) {
loss *= J_;
if (g) {
for (int i = 0; i < models_.size(); ++i)
gradients[i] *= J_;
}
}
vector<double> negMargins(negatives_.size());
#pragma omp parallel for
for (int i = 0; i < negatives_.size(); ++i)
negMargins[i] = models_[negatives_[i].second].dot(negatives_[i].first);
for (int i = 0; i < negatives_.size(); ++i) {
if (negMargins[i] > -1.0) {
loss += 1.0 + negMargins[i];
if (g)
gradients[negatives_[i].second] += negatives_[i].first;
}
}
// Add the loss and gradient of the regularization term
double maxNorm = 0.0;
int argNorm = 0;
for (int i = 0; i < models_.size(); ++i) {
if (g)
gradients[i] *= C_;
const double norm = models_[i].norm();
if (norm > maxNorm) {
maxNorm = norm;
argNorm = i;
}
}
// Recopy the gradient if needed
if (g) {
// Regularization gradient
gradients[argNorm] += models_[argNorm];
// Regularize the deformation 10 times more
for (int i = 1; i < gradients[argNorm].parts().size(); ++i)
gradients[argNorm].parts()[i].deformation +=
9.0 * models_[argNorm].parts()[i].deformation;
// Do not regularize the bias
gradients[argNorm].bias() -= models_[argNorm].bias();
// In case minimum constraints were applied
for (int i = 0; i < models_.size(); ++i) {
for (int j = 1; j < models_[i].parts().size(); ++j) {
if (models_[i].parts()[j].deformation(0) >= -0.005)
gradients[i].parts()[j].deformation(0) =
max(gradients[i].parts()[j].deformation(0), 0.0);
if (models_[i].parts()[j].deformation(2) >= -0.005)
gradients[i].parts()[j].deformation(2) =
max(gradients[i].parts()[j].deformation(2), 0.0);
if (models_[i].parts()[j].deformation(4) >= -0.005)
gradients[i].parts()[j].deformation(4) =
max(gradients[i].parts()[j].deformation(4), 0.0);
}
}
FromModels(gradients, g);
}
return 0.5 * maxNorm * maxNorm + C_ * loss;
}
static void ToModels(const double * x, vector<Model> & models)
{
for (int i = 0, j = 0; i < models.size(); ++i) {
for (int k = 0; k < models[i].parts().size(); ++k) {
const int nbFeatures = static_cast<int>(models[i].parts()[k].filter.size()) *
HOGPyramid::NbFeatures;
copy(x + j, x + j + nbFeatures, models[i].parts()[k].filter.data()->data());
j += nbFeatures;
if (k) {
// Apply minimum constraints
models[i].parts()[k].deformation(0) = min((x + j)[0],-0.005);
models[i].parts()[k].deformation(1) = (x + j)[1];
models[i].parts()[k].deformation(2) = min((x + j)[2],-0.005);
models[i].parts()[k].deformation(3) = (x + j)[3];
models[i].parts()[k].deformation(4) = min((x + j)[4],-0.005);
models[i].parts()[k].deformation(5) = (x + j)[5];
j += 6;
}
}
models[i].bias() = x[j];
++j;
}
}
static void FromModels(const vector<Model> & models, double * x)
{
for (int i = 0, j = 0; i < models.size(); ++i) {
for (int k = 0; k < models[i].parts().size(); ++k) {
const int nbFeatures = static_cast<int>(models[i].parts()[k].filter.size()) *
HOGPyramid::NbFeatures;
copy(models[i].parts()[k].filter.data()->data(),
models[i].parts()[k].filter.data()->data() + nbFeatures, x + j);
j += nbFeatures;
if (k) {
copy(models[i].parts()[k].deformation.data(),
models[i].parts()[k].deformation.data() + 6, x + j);
j += 6;
}
}
x[j] = models[i].bias();
++j;
}
}
private:
vector<Model> & models_;
const vector<pair<Model, int> > & positives_;
const vector<pair<Model, int> > & negatives_;
double C_;
double J_;
int maxIterations_;
};}
}
double Mixture::train(const vector<pair<Model, int> > & positives,
const vector<pair<Model, int> > & negatives, double C, double J,
int maxIterations)
{
detail::Loss loss(models_, positives, negatives, C, J, maxIterations);
LBFGS lbfgs(&loss, 0.001, maxIterations, 20, 20);
// Start from the current models
VectorXd x(loss.dim());
detail::Loss::FromModels(models_, x.data());
const double l = lbfgs(x.data());
detail::Loss::ToModels(x.data(), models_);
return l;
}
void Mixture::convolve(const HOGPyramid & pyramid,
vector<vector<HOGPyramid::Matrix> > & scores,
vector<vector<vector<Model::Positions> > > * positions) const
{
if (empty() || pyramid.empty()) {
scores.clear();
if (positions)
positions->clear();
return;
}
const int nbModels = static_cast<int>(models_.size());
// Resize the scores and positions
scores.resize(nbModels);
if (positions)
positions->resize(nbModels);
// Transform the filters if needed
#ifndef FFLD_MIXTURE_STANDARD_CONVOLUTION
#pragma omp critical
if (!cached_)
cacheFilters();
while (!cached_);
// Create a patchwork
const Patchwork patchwork(pyramid);
// Convolve the patchwork with the filters
vector<vector<HOGPyramid::Matrix> > convolutions(filterCache_.size());
patchwork.convolve(filterCache_, convolutions);
// In case of error
if (convolutions.empty()) {
scores.clear();
if (positions)
positions->clear();
return;
}
// Save the offsets of each model in the filter list
vector<int> offsets(nbModels);
for (int i = 0, j = 0; i < nbModels; ++i) {
offsets[i] = j;
j += models_[i].parts().size();
}
// For each model
#pragma omp parallel for
for (int i = 0; i < nbModels; ++i) {
vector<vector<HOGPyramid::Matrix> > tmp(models_[i].parts().size());
for (int j = 0; j < tmp.size(); ++j)
tmp[j].swap(convolutions[offsets[i] + j]);
models_[i].convolve(pyramid, scores[i], positions ? &(*positions)[i] : 0, &tmp);
}
// In case of error
for (int i = 0; i < nbModels; ++i) {
if (scores[i].empty()) {
scores.clear();
if (positions)
positions->clear();
}
}
#else
#pragma omp parallel for
for (int i = 0; i < nbModels; ++i)
models_[i].convolve(pyramid, scores[i], positions ? &(*positions)[i] : 0);
#endif
}
vector<pair<int, int> > Mixture::FilterSizes(int nbComponents, const vector<Scene> & scenes,
Object::Name name)
{
const string Names[80] =
{
"airplane", "apple", "backpack", "banana", "baseball bat",
"baseball glove", "bear", "bed", "bench", "bicycle", "bird",
"boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
"car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
"cow", "cup", "dining table", "dog", "donut", "elephant",
"fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
"handbag", "horse", "hot_dog", "keyboard", "kite", "knife",
"laptop", "microwave", "motorcycle", "mouse", "orange",
"oven", "parking meter", "person", "pizza", "potted plant",
"refrigerator", "remote", "sandwich", "scissors", "sheep",
"sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
"stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
"tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
"truck", "tv", "umbrella", "vase", "wine", "zebra"
};
// Early return in case the filters or the dataset are empty
if ((nbComponents <= 0) || scenes.empty())
return vector<pair<int, int> >();
// Sort the aspect ratio of all the (non difficult) samples
vector<double> ratios;
for (int i = 0; i < scenes.size(); ++i) {
for (int j = 0; j < scenes[i].objects().size(); ++j) {
const Object & obj = scenes[i].objects()[j];
if ((obj.name() == name) && !obj.difficult()){
ratios.push_back(static_cast<double>(obj.bndbox().width()) / obj.bndbox().height());
}
}
}
// Early return if there is no object
if (ratios.empty())
return vector<pair<int, int> >();
// Sort the aspect ratio of all the samples
sort(ratios.begin(), ratios.end());
// For each mixture model
vector<double> references(nbComponents);
for (int i = 0; i < nbComponents; ++i)
references[i] = ratios[(i * ratios.size()) / nbComponents];
// Store the areas of the objects associated to each component
vector<vector<int> > areas(nbComponents);
for (int i = 0; i < scenes.size(); ++i) {
for (int j = 0; j < scenes[i].objects().size(); ++j) {
const Object & obj = scenes[i].objects()[j];
if ((obj.name() == name) && !obj.difficult()) {
double width = obj.bndbox().width();
double height = obj.bndbox().height();
if (width > 0 && height > 0){
const double r = static_cast<double>(width / height);
int k = 0;
while ((k + 1 < nbComponents) && (r >= references[k + 1]))
++k;
areas[k].push_back(width * height);
}
}
}
}
// For each component in reverse order
vector<pair<int, int> > sizes(nbComponents);
for (int i = nbComponents - 1; i >= 0; --i) {
if (!areas[i].empty()) {
sort(areas[i].begin(), areas[i].end());
const int area = min(max(areas[i][(areas[i].size() * 2) / 10], 3000), 5000);
const double ratio = ratios[(ratios.size() * (i * 2 + 1)) / (nbComponents * 2)];
sizes[i].first = sqrt(area / ratio) / 8.0 + 0.5;
std::cout << "Size " << i << " first :" << sizes[i].first << std::endl;
sizes[i].second = sqrt(area * ratio) / 8.0 + 0.5;
std::cout << "Size " << i << " second :" << sizes[i].second << std::endl;
}
else {
sizes[i] = sizes[i + 1];
}
}
return sizes;
}
void Mixture::Cluster(int nbComponents, vector<pair<Model, int> > & samples)
{
// Early return in case the filters or the dataset are empty
if ((nbComponents <= 0) || samples.empty())
return;
// For each model
for (int i = nbComponents - 1; i >= 0; --i) {
// Indices of the positives
vector<int> permutation;
// For each positive
for (int j = 0; j < samples.size(); ++j)
if (samples[j].second / 2 == i)
permutation.push_back(j);
// Next model if this one has no associated positives
if (permutation.empty())
continue;
// Score of the best split so far
double best = 0.0;
// Do 1000 clustering trials
for (int j = 0; j < 1000; ++j) {
random_shuffle(permutation.begin(), permutation.end());
vector<bool> assignment(permutation.size(), false);
Model left = samples[permutation[0]].first;
for (int k = 1; k < permutation.size(); ++k) {
const Model & positive = samples[permutation[k]].first;
if (positive.dot(left) > positive.dot(left.flip())) {
left += positive;
}
else {
left += positive.flip();
assignment[k] = true;
}
}
left *= 1.0 / permutation.size();
const Model right = left.flip();
double dots = 0.0;
for (int k = 0; k < permutation.size(); ++k)
dots += samples[permutation[k]].first.dot(assignment[k] ? right : left);
if (dots > best) {
for (int k = 0; k < permutation.size(); ++k)
samples[permutation[k]].second = 2 * i + assignment[k];
best = dots;
}
}
}
}
ostream & FFLD::operator<<(ostream & os, const Mixture & mixture)
{
// Save the number of models (mixture components)
os << mixture.models().size() << endl;
// Save the models themselves
for (int i = 0; i < mixture.models().size(); ++i)
os << mixture.models()[i] << endl;
return os;
}
istream & FFLD::operator>>(istream & is, Mixture & mixture)
{
int nbModels;
is >> nbModels;
if (!is || (nbModels <= 0)) {
mixture = Mixture();
return is;
}
vector<Model> models(nbModels);
for (int i = 0; i < nbModels; ++i) {
is >> models[i];
if (!is || models[i].empty()) {
mixture = Mixture();
return is;
}
}
mixture.models().swap(models);
return is;
}
id empty models
//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 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.
//
// FFLDv2 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 FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Intersector.h"
#include "LBFGS.h"
#include "Mixture.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace Eigen;
using namespace FFLD;
using namespace std;
Mixture::Mixture() : cached_(false), zero_(true)
{
}
Mixture::Mixture(const vector<Model> & models) : models_(models), cached_(false), zero_(true)
{
}
Mixture::Mixture(int nbComponents, const vector<Scene> & scenes, Object::Name name) :
cached_(false), zero_(true)
{
// Create an empty mixture if any of the given parameters is invalid
if ((nbComponents <= 0) || scenes.empty()) {
cerr << "Attempting to create an empty mixture" << endl;
return;
}
// Compute the root filters' sizes using Felzenszwalb's heuristic
const vector<pair<int, int> > sizes = FilterSizes(nbComponents, scenes, name);
// Early return in case the root filters' sizes could not be determined
if (sizes.size() != nbComponents)
return;
// Initialize the models (with symmetry) to those sizes
models_.resize(2 * nbComponents);
for (int i = 0; i < nbComponents; ++i) {
models_[2 * i ] = Model(sizes[i]);
models_[2 * i + 1] = Model(sizes[i]);
}
}
bool Mixture::empty() const
{
return models_.empty();
}
const vector<Model> & Mixture::models() const
{
return models_;
}
vector<Model> & Mixture::models()
{
return models_;
}
pair<int, int> Mixture::minSize() const
{
pair<int, int> size(0, 0);
if (!models_.empty()) {
size = models_[0].rootSize();
for (int i = 1; i < models_.size(); ++i) {
size.first = min(size.first, models_[i].rootSize().first);
size.second = min(size.second, models_[i].rootSize().second);
}
}
return size;
}
pair<int, int> Mixture::maxSize() const
{
pair<int, int> size(0, 0);
if (!models_.empty()) {
size = models_[0].rootSize();
for (int i = 1; i < models_.size(); ++i) {
size.first = max(size.first, models_[i].rootSize().first);
size.second = max(size.second, models_[i].rootSize().second);
}
}
return size;
}
double Mixture::train(const vector<Scene> & scenes, Object::Name name, int padx, int pady,
int interval, int nbRelabel, int nbDatamine, int maxNegatives, double C,
double J, double overlap)
{
if (empty() || scenes.empty() || (padx < 1) || (pady < 1) || (interval < 1) ||
(nbRelabel < 1) || (nbDatamine < 1) || (maxNegatives < models_.size()) || (C <= 0.0) ||
(J <= 0.0) || (overlap <= 0.0) || (overlap >= 1.0)) {
cerr << "Invalid training parameters" << endl;
return numeric_limits<double>::quiet_NaN();
}
// Test if the models are really zero by looking at the first cell of the first filter of the
// first model
if (!models_[0].empty() && models_[0].parts()[0].filter.size() &&
!models_[0].parts()[0].filter(0, 0).isZero())
zero_ = false;
double loss = numeric_limits<double>::infinity();
for (int relabel = 0; relabel < nbRelabel; ++relabel) {
// Sample all the positives
vector<pair<Model, int> > positives;
posLatentSearch(scenes, name, padx, pady, interval, overlap, positives);
// Left-right clustering at the first iteration
if (zero_)
Cluster(static_cast<int>(models_.size()), positives);
// Cache of hard negative samples of maximum size maxNegatives
vector<pair<Model, int> > negatives;
// Previous loss on the cache
double prevLoss = -numeric_limits<double>::infinity();
for (int datamine = 0; datamine < nbDatamine; ++datamine) {
// Remove easy samples (keep hard ones)
int j = 0;
for (int i = 0; i < negatives.size(); ++i)
if ((negatives[i].first.parts()[0].deformation(3) =
models_[negatives[i].second].dot(negatives[i].first)) > -1.01)
negatives[j++] = negatives[i];
negatives.resize(j);
// Sample new hard negatives
negLatentSearch(scenes, name, padx, pady, interval, maxNegatives, negatives);
// Stop if there are no new hard negatives
if (datamine && (negatives.size() == j))
break;
// Merge the left / right samples for more efficient training
vector<int> posComponents(positives.size());
for (int i = 0; i < positives.size(); ++i) {
posComponents[i] = positives[i].second;
if (positives[i].second & 1)
positives[i].first = positives[i].first.flip();
positives[i].second >>= 1;
}
vector<int> negComponents(negatives.size());
for (int i = 0; i < negatives.size(); ++i) {
negComponents[i] = negatives[i].second;
if (negatives[i].second & 1)
negatives[i].first = negatives[i].first.flip();
negatives[i].second >>= 1;
}
// Merge the left / right models for more efficient training
for (int i = 1; i < models_.size() / 2; ++i)
models_[i] = models_[i * 2];
models_.resize(models_.size() / 2);
const int maxIterations =
min(max(10.0 * sqrt(static_cast<double>(positives.size())), 100.0), 1000.0);
loss = train(positives, negatives, C, J, maxIterations);
cout << "Relabel: " << relabel << ", datamine: " << datamine
<< ", # positives: " << positives.size() << ", # hard negatives: " << j
<< " (already in the cache) + " << (negatives.size() - j) << " (new) = "
<< negatives.size() << ", loss (cache): " << loss << endl;
// Unmerge the left / right samples
for (int i = 0; i < positives.size(); ++i) {
positives[i].second = posComponents[i];
if (positives[i].second & 1)
positives[i].first = positives[i].first.flip();
}
for (int i = 0; i < negatives.size(); ++i) {
negatives[i].second = negComponents[i];
if (negatives[i].second & 1)
negatives[i].first = negatives[i].first.flip();
}
// Unmerge the left / right models
models_.resize(models_.size() * 2);
for (int i = static_cast<int>(models_.size()) / 2 - 1; i >= 0; --i) {
models_[i * 2 ] = models_[i];
models_[i * 2 + 1] = models_[i].flip();
}
// The filters definitely changed
filterCache_.clear();
cached_ = false;
zero_ = false;
// Save the latest model so as to be able to look at it while training
ofstream out("tmp.txt");
out << (*this);
// Stop if we are not making progress
if ((0.999 * loss < prevLoss) && (negatives.size() < maxNegatives))
break;
prevLoss = loss;
}
}
return loss;
}
void Mixture::initializeParts(int nbParts, pair<int, int> partSize)
{
for (int i = 0; i < models_.size(); i += 2) {
models_[i].initializeParts(nbParts, partSize);
models_[i + 1] = models_[i].flip();
}
// The filters definitely changed
filterCache_.clear();
cached_ = false;
zero_ = false;
}
void Mixture::convolve(const HOGPyramid & pyramid, vector<HOGPyramid::Matrix> & scores,
vector<Indices> & argmaxes,
vector<vector<vector<Model::Positions> > > * positions) const
{
if (empty() || pyramid.empty()) {
scores.clear();
argmaxes.clear();
if (positions)
positions->clear();
return;
}
const int nbModels = static_cast<int>(models_.size());
const int nbLevels = static_cast<int>(pyramid.levels().size());
// Convolve with all the models
vector<vector<HOGPyramid::Matrix> > convolutions;
convolve(pyramid, convolutions, positions);
// In case of error
if (convolutions.empty()) {
scores.clear();
argmaxes.clear();
if (positions)
positions->clear();
return;
}
// Resize the scores and argmaxes
scores.resize(nbLevels);
argmaxes.resize(nbLevels);
#pragma omp parallel for
for (int z = 0; z < nbLevels; ++z) {
int rows = static_cast<int>(convolutions[0][z].rows());
int cols = static_cast<int>(convolutions[0][z].cols());
for (int i = 1; i < nbModels; ++i) {
rows = min(rows, static_cast<int>(convolutions[i][z].rows()));
cols = min(cols, static_cast<int>(convolutions[i][z].cols()));
}
scores[z].resize(rows, cols);
argmaxes[z].resize(rows, cols);
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
int argmax = 0;
for (int i = 1; i < nbModels; ++i)
if (convolutions[i][z](y, x) > convolutions[argmax][z](y, x))
argmax = i;
scores[z](y, x) = convolutions[argmax][z](y, x);
argmaxes[z](y, x) = argmax;
}
}
}
}
void Mixture::cacheFilters() const
{
// Count the number of filters
int nbFilters = 0;
for (int i = 0; i < models_.size(); ++i)
nbFilters += models_[i].parts().size();
// Transform all the filters
filterCache_.resize(nbFilters);
for (int i = 0, j = 0; i < models_.size(); ++i) {
#pragma omp parallel for
for (int k = 0; k < models_[i].parts().size(); ++k)
Patchwork::TransformFilter(models_[i].parts()[k].filter, filterCache_[j + k]);
j += models_[i].parts().size();
}
cached_ = true;
}
static inline void clipBndBox(Rectangle & bndbox, const Scene & scene, double alpha = 0.0)
{
// Compromise between clamping the bounding box to the image and penalizing bounding boxes
// extending outside the image
if (bndbox.left() < 0)
bndbox.setLeft(bndbox.left() * alpha - 0.5);
if (bndbox.top() < 0)
bndbox.setTop(bndbox.top() * alpha - 0.5);
if (bndbox.right() >= scene.width())
bndbox.setRight(scene.width() - 1 + (bndbox.right() - scene.width() + 1) * alpha + 0.5);
if (bndbox.bottom() >= scene.height())
bndbox.setBottom(scene.height() - 1 + (bndbox.bottom() - scene.height() + 1) * alpha + 0.5);
}
void Mixture::posLatentSearch(const vector<Scene> & scenes, Object::Name name, int padx, int pady,
int interval, double overlap,
vector<pair<Model, int> > & positives) const
{
if (scenes.empty() || (padx < 1) || (pady < 1) || (interval < 1) || (overlap <= 0.0) ||
(overlap >= 1.0)) {
positives.clear();
cerr << "Invalid training paramters" << endl;
return;
}
positives.clear();
for (int i = 0; i < scenes.size(); ++i) {
// Skip negative scenes
bool negative = true;
for (int j = 0; j < scenes[i].objects().size(); ++j)
if ((scenes[i].objects()[j].name() == name) && !scenes[i].objects()[j].difficult())
negative = false;
if (negative)
continue;
const JPEGImage image(scenes[i].filename());
if (image.empty()) {
positives.clear();
return;
}
const HOGPyramid pyramid(image, padx, pady, interval);
if (pyramid.empty()) {
positives.clear();
return;
}
vector<HOGPyramid::Matrix> scores;
vector<Indices> argmaxes;
vector<vector<vector<Model::Positions> > > positions;
if (!zero_)
convolve(pyramid, scores, argmaxes, &positions);
// For each object, set as positive the best (highest score or else most intersecting)
// position
for (int j = 0; j < scenes[i].objects().size(); ++j) {
// Ignore objects with a different name or difficult objects
if ((scenes[i].objects()[j].name() != name) || scenes[i].objects()[j].difficult())
continue;
const Intersector intersector(scenes[i].objects()[j].bndbox(), overlap);
// The model, level, position, score, and intersection of the best example
int argModel = -1;
int argX = -1;
int argY = -1;
int argZ = -1;
double maxScore = -numeric_limits<double>::infinity();
double maxInter = 0.0;
for (int z = 0; z < pyramid.levels().size(); ++z) {
const double scale = pow(2.0, static_cast<double>(z) / interval + 2);
int rows = 0;
int cols = 0;
if (!zero_) {
rows = static_cast<int>(scores[z].rows());
cols = static_cast<int>(scores[z].cols());
}
else if (z >= interval) {
rows = static_cast<int>(pyramid.levels()[z].rows()) - maxSize().first + 1;
cols = static_cast<int>(pyramid.levels()[z].cols()) - maxSize().second + 1;
}
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
// Find the best matching model (highest score or else most intersecting)
int model = zero_ ? 0 : argmaxes[z](y, x);
double intersection = 0.0;
// Try all models and keep the most intersecting one
if (zero_) {
for (int k = 0; k < models_.size(); ++k) {
// The bounding box of the model at this position
Rectangle bndbox;
bndbox.setX((x - padx) * scale + 0.5);
bndbox.setY((y - pady) * scale + 0.5);
bndbox.setWidth(models_[k].rootSize().second * scale + 0.5);
bndbox.setHeight(models_[k].rootSize().first * scale + 0.5);
// Trade-off between clipping and penalizing
clipBndBox(bndbox, scenes[i], 0.5);
double inter = 0.0;
if (intersector(bndbox, &inter)) {
if (inter > intersection) {
model = k;
intersection = inter;
}
}
}
}
// Just take the model with the best score
else {
// The bounding box of the model at this position
Rectangle bndbox;
bndbox.setX((x - padx) * scale + 0.5);
bndbox.setY((y - pady) * scale + 0.5);
bndbox.setWidth(models_[model].rootSize().second * scale + 0.5);
bndbox.setHeight(models_[model].rootSize().first * scale + 0.5);
clipBndBox(bndbox, scenes[i]);
intersector(bndbox, &intersection);
}
if ((intersection > maxInter) && (zero_ || (scores[z](y, x) > maxScore))) {
argModel = model;
argX = x;
argY = y;
argZ = z;
if (!zero_)
maxScore = scores[z](y, x);
maxInter = intersection;
}
}
}
}
if (maxInter >= overlap) {
Model sample;
models_[argModel].initializeSample(pyramid, argX, argY, argZ, sample,
zero_ ? 0 : &positions[argModel]);
if (!sample.empty())
positives.push_back(make_pair(sample, argModel));
}
}
}
}
static inline bool operator==(const Model & a, const Model & b)
{
return (a.parts()[0].offset == b.parts()[0].offset) &&
(a.parts()[0].deformation(0) == b.parts()[0].deformation(0)) &&
(a.parts()[0].deformation(1) == b.parts()[0].deformation(1));
}
static inline bool operator<(const Model & a, const Model & b)
{
return (a.parts()[0].offset(0) < b.parts()[0].offset(0)) ||
((a.parts()[0].offset(0) == b.parts()[0].offset(0)) &&
((a.parts()[0].offset(1) < b.parts()[0].offset(1)) ||
((a.parts()[0].offset(1) == b.parts()[0].offset(1)) &&
((a.parts()[0].deformation(0) < b.parts()[0].deformation(0)) ||
((a.parts()[0].deformation(0) == b.parts()[0].deformation(0)) &&
((a.parts()[0].deformation(1) < b.parts()[0].deformation(1))))))));
}
void Mixture::negLatentSearch(const vector<Scene> & scenes, Object::Name name, int padx, int pady,
int interval, int maxNegatives,
vector<pair<Model, int> > & negatives) const
{
// Sample at most (maxNegatives - negatives.size()) negatives with a score above -1.0
if (scenes.empty() || (padx < 1) || (pady < 1) || (interval < 1) || (maxNegatives <= 0) ||
(negatives.size() >= maxNegatives)) {
negatives.clear();
cerr << "Invalid training paramters" << endl;
return;
}
// The number of negatives already in the cache
const int nbCached = static_cast<int>(negatives.size());
for (int i = 0, j = 0; i < scenes.size(); ++i) {
// Skip positive scenes
bool positive = false;
for (int k = 0; k < scenes[i].objects().size(); ++k)
if (scenes[i].objects()[k].name() == name)
positive = true;
if (positive)
continue;
const JPEGImage image(scenes[i].filename());
if (image.empty()) {
negatives.clear();
return;
}
const HOGPyramid pyramid(image, padx, pady, interval);
if (pyramid.empty()) {
negatives.clear();
return;
}
vector<HOGPyramid::Matrix> scores;
vector<Indices> argmaxes;
vector<vector<vector<Model::Positions> > > positions;
if (!zero_)
convolve(pyramid, scores, argmaxes, &positions);
for (int z = 0; z < pyramid.levels().size(); ++z) {
int rows = 0;
int cols = 0;
if (!zero_) {
rows = static_cast<int>(scores[z].rows());
cols = static_cast<int>(scores[z].cols());
}
else if (z >= interval) {
rows = static_cast<int>(pyramid.levels()[z].rows()) - maxSize().first + 1;
cols = static_cast<int>(pyramid.levels()[z].cols()) - maxSize().second + 1;
}
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
const int argmax = zero_ ? (rand() % models_.size()) : argmaxes[z](y, x);
if (zero_ || (scores[z](y, x) > -1)) {
Model sample;
models_[argmax].initializeSample(pyramid, x, y, z, sample,
zero_ ? 0 : &positions[argmax]);
if (!sample.empty()) {
// Store all the information about the sample in the offset and
// deformation of its root
sample.parts()[0].offset(0) = i;
sample.parts()[0].offset(1) = z;
sample.parts()[0].deformation(0) = y;
sample.parts()[0].deformation(1) = x;
sample.parts()[0].deformation(2) = argmax;
sample.parts()[0].deformation(3) = zero_ ? 0.0 : scores[z](y, x);
// Look if the same sample was already sampled
while ((j < nbCached) && (negatives[j].first < sample))
++j;
// Make sure not to put the same sample twice
if ((j >= nbCached) || !(negatives[j].first == sample)) {
negatives.push_back(make_pair(sample, argmax));
if (negatives.size() == maxNegatives)
return;
}
}
}
}
}
}
}
}
namespace FFLD
{
namespace detail
{
class Loss : public LBFGS::IFunction
{
public:
Loss(vector<Model> & models, const vector<pair<Model, int> > & positives,
const vector<pair<Model, int> > & negatives, double C, double J, int maxIterations) :
models_(models), positives_(positives), negatives_(negatives), C_(C), J_(J),
maxIterations_(maxIterations)
{
}
virtual int dim() const
{
int d = 0;
for (int i = 0; i < models_.size(); ++i) {
for (int j = 0; j < models_[i].parts().size(); ++j) {
d += models_[i].parts()[j].filter.size() * HOGPyramid::NbFeatures; // Filter
if (j)
d += 6; // Deformation
}
++d; // Bias
}
return d;
}
virtual double operator()(const double * x, double * g = 0) const
{
// Recopy the features into the models
ToModels(x, models_);
// Compute the loss and gradient over the samples
double loss = 0.0;
vector<Model> gradients;
if (g) {
gradients.resize(models_.size());
for (int i = 0; i < models_.size(); ++i)
gradients[i] = Model(models_[i].rootSize(),
static_cast<int>(models_[i].parts().size()) - 1,
models_[i].partSize());
}
vector<double> posMargins(positives_.size());
#pragma omp parallel for
for (int i = 0; i < positives_.size(); ++i)
posMargins[i] = models_[positives_[i].second].dot(positives_[i].first);
for (int i = 0; i < positives_.size(); ++i) {
if (posMargins[i] < 1.0) {
loss += 1.0 - posMargins[i];
if (g)
gradients[positives_[i].second] -= positives_[i].first;
}
}
// Reweight the positives
if (J_ != 1.0) {
loss *= J_;
if (g) {
for (int i = 0; i < models_.size(); ++i)
gradients[i] *= J_;
}
}
vector<double> negMargins(negatives_.size());
#pragma omp parallel for
for (int i = 0; i < negatives_.size(); ++i)
negMargins[i] = models_[negatives_[i].second].dot(negatives_[i].first);
for (int i = 0; i < negatives_.size(); ++i) {
if (negMargins[i] > -1.0) {
loss += 1.0 + negMargins[i];
if (g)
gradients[negatives_[i].second] += negatives_[i].first;
}
}
// Add the loss and gradient of the regularization term
double maxNorm = 0.0;
int argNorm = 0;
for (int i = 0; i < models_.size(); ++i) {
if (g)
gradients[i] *= C_;
const double norm = models_[i].norm();
if (norm > maxNorm) {
maxNorm = norm;
argNorm = i;
}
}
// Recopy the gradient if needed
if (g) {
// Regularization gradient
gradients[argNorm] += models_[argNorm];
// Regularize the deformation 10 times more
for (int i = 1; i < gradients[argNorm].parts().size(); ++i)
gradients[argNorm].parts()[i].deformation +=
9.0 * models_[argNorm].parts()[i].deformation;
// Do not regularize the bias
gradients[argNorm].bias() -= models_[argNorm].bias();
// In case minimum constraints were applied
for (int i = 0; i < models_.size(); ++i) {
for (int j = 1; j < models_[i].parts().size(); ++j) {
if (models_[i].parts()[j].deformation(0) >= -0.005)
gradients[i].parts()[j].deformation(0) =
max(gradients[i].parts()[j].deformation(0), 0.0);
if (models_[i].parts()[j].deformation(2) >= -0.005)
gradients[i].parts()[j].deformation(2) =
max(gradients[i].parts()[j].deformation(2), 0.0);
if (models_[i].parts()[j].deformation(4) >= -0.005)
gradients[i].parts()[j].deformation(4) =
max(gradients[i].parts()[j].deformation(4), 0.0);
}
}
FromModels(gradients, g);
}
return 0.5 * maxNorm * maxNorm + C_ * loss;
}
static void ToModels(const double * x, vector<Model> & models)
{
for (int i = 0, j = 0; i < models.size(); ++i) {
for (int k = 0; k < models[i].parts().size(); ++k) {
const int nbFeatures = static_cast<int>(models[i].parts()[k].filter.size()) *
HOGPyramid::NbFeatures;
copy(x + j, x + j + nbFeatures, models[i].parts()[k].filter.data()->data());
j += nbFeatures;
if (k) {
// Apply minimum constraints
models[i].parts()[k].deformation(0) = min((x + j)[0],-0.005);
models[i].parts()[k].deformation(1) = (x + j)[1];
models[i].parts()[k].deformation(2) = min((x + j)[2],-0.005);
models[i].parts()[k].deformation(3) = (x + j)[3];
models[i].parts()[k].deformation(4) = min((x + j)[4],-0.005);
models[i].parts()[k].deformation(5) = (x + j)[5];
j += 6;
}
}
models[i].bias() = x[j];
++j;
}
}
static void FromModels(const vector<Model> & models, double * x)
{
for (int i = 0, j = 0; i < models.size(); ++i) {
for (int k = 0; k < models[i].parts().size(); ++k) {
const int nbFeatures = static_cast<int>(models[i].parts()[k].filter.size()) *
HOGPyramid::NbFeatures;
copy(models[i].parts()[k].filter.data()->data(),
models[i].parts()[k].filter.data()->data() + nbFeatures, x + j);
j += nbFeatures;
if (k) {
copy(models[i].parts()[k].deformation.data(),
models[i].parts()[k].deformation.data() + 6, x + j);
j += 6;
}
}
x[j] = models[i].bias();
++j;
}
}
private:
vector<Model> & models_;
const vector<pair<Model, int> > & positives_;
const vector<pair<Model, int> > & negatives_;
double C_;
double J_;
int maxIterations_;
};}
}
double Mixture::train(const vector<pair<Model, int> > & positives,
const vector<pair<Model, int> > & negatives, double C, double J,
int maxIterations)
{
detail::Loss loss(models_, positives, negatives, C, J, maxIterations);
LBFGS lbfgs(&loss, 0.001, maxIterations, 20, 20);
// Start from the current models
VectorXd x(loss.dim());
detail::Loss::FromModels(models_, x.data());
const double l = lbfgs(x.data());
detail::Loss::ToModels(x.data(), models_);
return l;
}
void Mixture::convolve(const HOGPyramid & pyramid,
vector<vector<HOGPyramid::Matrix> > & scores,
vector<vector<vector<Model::Positions> > > * positions) const
{
if (empty() || pyramid.empty()) {
scores.clear();
if (positions)
positions->clear();
return;
}
const int nbModels = static_cast<int>(models_.size());
// Resize the scores and positions
scores.resize(nbModels);
if (positions)
positions->resize(nbModels);
// Transform the filters if needed
#ifndef FFLD_MIXTURE_STANDARD_CONVOLUTION
#pragma omp critical
if (!cached_)
cacheFilters();
while (!cached_);
// Create a patchwork
const Patchwork patchwork(pyramid);
// Convolve the patchwork with the filters
vector<vector<HOGPyramid::Matrix> > convolutions(filterCache_.size());
patchwork.convolve(filterCache_, convolutions);
// In case of error
if (convolutions.empty()) {
scores.clear();
if (positions)
positions->clear();
return;
}
// Save the offsets of each model in the filter list
vector<int> offsets(nbModels);
for (int i = 0, j = 0; i < nbModels; ++i) {
offsets[i] = j;
j += models_[i].parts().size();
}
// For each model
#pragma omp parallel for
for (int i = 0; i < nbModels; ++i) {
vector<vector<HOGPyramid::Matrix> > tmp(models_[i].parts().size());
for (int j = 0; j < tmp.size(); ++j)
tmp[j].swap(convolutions[offsets[i] + j]);
models_[i].convolve(pyramid, scores[i], positions ? &(*positions)[i] : 0, &tmp);
}
// In case of error
for (int i = 0; i < nbModels; ++i) {
if (scores[i].empty()) {
scores.clear();
if (positions)
positions->clear();
}
}
#else
#pragma omp parallel for
for (int i = 0; i < nbModels; ++i)
models_[i].convolve(pyramid, scores[i], positions ? &(*positions)[i] : 0);
#endif
}
vector<pair<int, int> > Mixture::FilterSizes(int nbComponents, const vector<Scene> & scenes,
Object::Name name)
{
const string Names[80] =
{
"airplane", "apple", "backpack", "banana", "baseball bat",
"baseball glove", "bear", "bed", "bench", "bicycle", "bird",
"boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
"car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
"cow", "cup", "dining table", "dog", "donut", "elephant",
"fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
"handbag", "horse", "hot_dog", "keyboard", "kite", "knife",
"laptop", "microwave", "motorcycle", "mouse", "orange",
"oven", "parking meter", "person", "pizza", "potted plant",
"refrigerator", "remote", "sandwich", "scissors", "sheep",
"sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
"stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
"tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
"truck", "tv", "umbrella", "vase", "wine", "zebra"
};
// Early return in case the filters or the dataset are empty
if ((nbComponents <= 0) || scenes.empty())
return vector<pair<int, int> >();
// Sort the aspect ratio of all the (non difficult) samples
vector<double> ratios;
for (int i = 0; i < scenes.size(); ++i) {
for (int j = 0; j < scenes[i].objects().size(); ++j) {
const Object & obj = scenes[i].objects()[j];
if ((obj.name() == name) && !obj.difficult()){
ratios.push_back(static_cast<double>(obj.bndbox().width()) / obj.bndbox().height());
}
}
}
// Early return if there is no object
if (ratios.empty())
return vector<pair<int, int> >();
// Sort the aspect ratio of all the samples
sort(ratios.begin(), ratios.end());
// For each mixture model
vector<double> references(nbComponents);
for (int i = 0; i < nbComponents; ++i)
references[i] = ratios[(i * ratios.size()) / nbComponents];
// Store the areas of the objects associated to each component
vector<vector<int> > areas(nbComponents);
for (int i = 0; i < scenes.size(); ++i) {
for (int j = 0; j < scenes[i].objects().size(); ++j) {
const Object & obj = scenes[i].objects()[j];
if ((obj.name() == name) && !obj.difficult()) {
double width = obj.bndbox().width();
double height = obj.bndbox().height();
if (width > 0 && height > 0){
const double r = static_cast<double>(width / height);
int k = 0;
while ((k + 1 < nbComponents) && (r >= references[k + 1]))
++k;
areas[k].push_back(width * height);
}
}
}
}
// For each component in reverse order
vector<pair<int, int> > sizes(nbComponents);
for (int i = nbComponents - 1; i >= 0; --i) {
if (!areas[i].empty()) {
sort(areas[i].begin(), areas[i].end());
const int area = min(max(areas[i][(areas[i].size() * 2) / 10], 3000), 5000);
const double ratio = ratios[(ratios.size() * (i * 2 + 1)) / (nbComponents * 2)];
std::cout << "Area" << area << std::endl;
std::cout << "Ratio" << ratio << std::endl;
sizes[i].first = sqrt(area / ratio) / 8.0 + 0.5;
sizes[i].second = sqrt(area * ratio) / 8.0 + 0.5;
}
else {
sizes[i] = sizes[i + 1];
}
}
return sizes;
}
void Mixture::Cluster(int nbComponents, vector<pair<Model, int> > & samples)
{
// Early return in case the filters or the dataset are empty
if ((nbComponents <= 0) || samples.empty())
return;
// For each model
for (int i = nbComponents - 1; i >= 0; --i) {
// Indices of the positives
vector<int> permutation;
// For each positive
for (int j = 0; j < samples.size(); ++j)
if (samples[j].second / 2 == i)
permutation.push_back(j);
// Next model if this one has no associated positives
if (permutation.empty())
continue;
// Score of the best split so far
double best = 0.0;
// Do 1000 clustering trials
for (int j = 0; j < 1000; ++j) {
random_shuffle(permutation.begin(), permutation.end());
vector<bool> assignment(permutation.size(), false);
Model left = samples[permutation[0]].first;
for (int k = 1; k < permutation.size(); ++k) {
const Model & positive = samples[permutation[k]].first;
if (positive.dot(left) > positive.dot(left.flip())) {
left += positive;
}
else {
left += positive.flip();
assignment[k] = true;
}
}
left *= 1.0 / permutation.size();
const Model right = left.flip();
double dots = 0.0;
for (int k = 0; k < permutation.size(); ++k)
dots += samples[permutation[k]].first.dot(assignment[k] ? right : left);
if (dots > best) {
for (int k = 0; k < permutation.size(); ++k)
samples[permutation[k]].second = 2 * i + assignment[k];
best = dots;
}
}
}
}
ostream & FFLD::operator<<(ostream & os, const Mixture & mixture)
{
// Save the number of models (mixture components)
os << mixture.models().size() << endl;
// Save the models themselves
for (int i = 0; i < mixture.models().size(); ++i)
os << mixture.models()[i] << endl;
return os;
}
istream & FFLD::operator>>(istream & is, Mixture & mixture)
{
int nbModels;
is >> nbModels;
if (!is || (nbModels <= 0)) {
mixture = Mixture();
return is;
}
vector<Model> models(nbModels);
for (int i = 0; i < nbModels; ++i) {
is >> models[i];
if (!is || models[i].empty()) {
mixture = Mixture();
return is;
}
}
mixture.models().swap(models);
return is;
}
|
#include <ros/ros.h>
#include <servo_controller/servo_control.h>
#include <servo_controller/servo_status.h>
#include <servo_controller/servo_array_status.h>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
#include <time.h> // time calls
#include <ros/console.h>
using namespace std;
using namespace ros::console::levels;
class ServoControllerCls
{
public:
ServoControllerCls();
void SetServoPosition(int channel_no, int target_position);
void InitializeSerialPort();
void InitializePubSub();
void InitializeServoProperties();
servo_controller::servo_array_status servo_array_status;
private:
void servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command);
ros::NodeHandle nh_;
ros::Publisher servo_array_status_pub_;
ros::Subscriber servo_0_control_sub_;
ros::Subscriber servo_1_control_sub_;
ros::Subscriber servo_2_control_sub_;
ros::Subscriber servo_3_control_sub_;
ros::Subscriber servo_4_control_sub_;
ros::Subscriber servo_5_control_sub_;
int serial_port;
};
void ServoControllerCls::InitializeSerialPort() {
serial_port = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
if (serial_port < 0)
{
ROS_WARN("Cannot open servo controller serial port on /dev/ttyACM0. Make sure you have correct permissions. Port no: %d", serial_port);
}
else
{
ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Opened servo controller serial port on /dev/ttyACM0. Port no: %d", serial_port);
//printf("Opened ACM0: %d\r\n", (int) (serial_port));
}
}
void ServoControllerCls::InitializePubSub() {
//nh_.param("axis_linear", linear_, linear_);
//nh_.param("axis_angular", angular_, angular_);
//nh_.param("scale_angular", a_scale_, a_scale_);
//nh_.param("scale_linear", l_scale_, l_scale_);
// Publish status for all servos
// Set latch to true, so the last message published on
// this topic will be saved and sent to new subscribers when they
// connect
servo_array_status_pub_ = nh_.advertise < servo_controller::servo_array_status
> ("servo_controller/servo_array_status", 1, true);
// Separate messages for independent control of each servo
servo_0_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_0_control", 10, &ServoControllerCls::servoControlCallback, this);
servo_1_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_1_control", 10, &ServoControllerCls::servoControlCallback, this);
servo_2_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_2_control", 10, &ServoControllerCls::servoControlCallback, this);
servo_3_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_3_control", 10, &ServoControllerCls::servoControlCallback, this);
servo_4_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_4_control", 10, &ServoControllerCls::servoControlCallback, this);
servo_5_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_5_control", 10, &ServoControllerCls::servoControlCallback, this);
// Publish initial, make sure values are initialized
servo_array_status_pub_.publish(servo_array_status);
}
void ServoControllerCls::InitializeServoProperties() {
const uint center = 6000;
const uint max_value = 8000;
const uint min_value = 4000;
const uint velocity_limit = 100;
const uint acceleration_limit = 20;
servo_array_status.servo[3].enabled = false;
servo_array_status.servo[4].enabled = false;
servo_array_status.servo[5].enabled = false;
servo_array_status.servo[3].enabled = false;
servo_array_status.servo[4].enabled = false;
servo_array_status.servo[5].enabled = false;
servo_array_status.servo[0].servo_no = 0;
servo_array_status.servo[1].servo_no = 1;
servo_array_status.servo[2].servo_no = 2;
servo_array_status.servo[3].servo_no = 3;
servo_array_status.servo[4].servo_no = 4;
servo_array_status.servo[5].servo_no = 5;
servo_array_status.servo[0].name = "";
servo_array_status.servo[1].name = "Right Wheel Encoder";
servo_array_status.servo[2].name = "Left Wheel Encoder";
servo_array_status.servo[3].name = "Right Steering Servo";
servo_array_status.servo[4].name = "Left Steering Servo";
servo_array_status.servo[5].name = "Main Motor";
servo_array_status.servo[0].mode = 0; // Not defined
servo_array_status.servo[1].mode = 2; // Digital input - wheel encoder
servo_array_status.servo[2].mode = 2; // Digital input - wheel encoder
servo_array_status.servo[3].mode = 1; // Servo control signal output - servo
servo_array_status.servo[4].mode = 1; // Servo control signal output - servo
servo_array_status.servo[5].mode = 1; // Servo control signal output - motor
servo_array_status.servo[3].target = center;
servo_array_status.servo[4].target = center;
servo_array_status.servo[5].target = center;
servo_array_status.servo[3].actual = center;
servo_array_status.servo[4].actual = center;
servo_array_status.servo[5].actual = center;
servo_array_status.servo[3].center = center;
servo_array_status.servo[4].center = center;
servo_array_status.servo[5].center = center;
servo_array_status.servo[3].max = max_value;
servo_array_status.servo[4].max = max_value;
servo_array_status.servo[5].max = max_value;
servo_array_status.servo[3].min = min_value;
servo_array_status.servo[4].min = min_value;
servo_array_status.servo[5].min = min_value;
servo_array_status.servo[3].velocity_limit = velocity_limit;
servo_array_status.servo[4].velocity_limit = velocity_limit;
servo_array_status.servo[5].velocity_limit = velocity_limit;
servo_array_status.servo[3].acceleration_limit = acceleration_limit;
servo_array_status.servo[4].acceleration_limit = acceleration_limit;
servo_array_status.servo[5].acceleration_limit = acceleration_limit;
servo_array_status.servo[3].enabled = true;
servo_array_status.servo[4].enabled = true;
servo_array_status.servo[5].enabled = true;
}
ServoControllerCls::ServoControllerCls()
{
InitializeSerialPort();
InitializeServoProperties();
InitializePubSub();
}
void ServoControllerCls::SetServoPosition(int channel_no, int target_position) {
char command_bytes[4] = { 0x84, channel_no, (char) ((target_position & 0x7F)),
(char) ((target_position >> 7 & 0x7F)) };
int n = write(serial_port, command_bytes, 4);
if (n < 0)
{
ROS_WARN("Could not write bytes to servo controller serial port for servo no: %d, target: %d", channel_no, target_position);
}
else
{
ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Set servo no: %d, target: %d", channel_no, target_position);
}
}
void ServoControllerCls::servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command)
{
int servo_no = control_command->servo_no;
if (servo_no < 0 || servo_no >= 6)
{
ROS_WARN("Wrong servo number passed: %d", servo_no);
return;
}
if (!servo_array_status.servo[servo_no].enabled)
{
ROS_WARN("Trying to control a not enabled servo: %d", servo_no);
return;
}
if (servo_array_status.servo[servo_no].mode != 1)
{
ROS_WARN("Trying to control servo: %d, in mode: %d. Mode has to be 1 for servos", servo_no, servo_array_status.servo[servo_no].mode);
return;
}
uint target = control_command->target;
const uint max_value = servo_array_status.servo[servo_no].max;
const uint min_value = servo_array_status.servo[servo_no].min;
if (target > max_value)
{
ROS_WARN("Trying to set servo: %d to target: %d more than maximum value: %d. Setting to maximum value", servo_no, target, max_value);
target = max_value;
}
if (target < min_value)
{
ROS_WARN("Trying to set servo: %d to target: %d less than minimum value: %d. Setting to maximum value", servo_no, target, min_value);
target = min_value;
}
SetServoPosition(servo_no, target);
// Publish update
servo_array_status.servo[servo_no].target = target;
servo_array_status_pub_.publish(servo_array_status);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "ServoController");
ServoControllerCls servo_controller;
ros::spin();
}
Enable Head servo
#include <ros/ros.h>
#include <servo_controller/servo_control.h>
#include <servo_controller/servo_status.h>
#include <servo_controller/servo_array_status.h>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
#include <time.h> // time calls
#include <ros/console.h>
using namespace std;
using namespace ros::console::levels;
class ServoControllerCls
{
public:
ServoControllerCls();
void SetServoPosition(int channel_no, int target_position);
void InitializeSerialPort();
void InitializePubSub();
void InitializeServoProperties();
servo_controller::servo_array_status servo_array_status;
private:
void servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command);
ros::NodeHandle nh_;
ros::Publisher servo_array_status_pub_;
ros::Subscriber servo_0_control_sub_;
ros::Subscriber servo_1_control_sub_;
ros::Subscriber servo_2_control_sub_;
ros::Subscriber servo_3_control_sub_;
ros::Subscriber servo_4_control_sub_;
ros::Subscriber servo_5_control_sub_;
int serial_port;
};
void ServoControllerCls::InitializeSerialPort() {
serial_port = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
if (serial_port < 0)
{
ROS_WARN("Cannot open servo controller serial port on /dev/ttyACM0. Make sure you have correct permissions. Port no: %d", serial_port);
}
else
{
ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Opened servo controller serial port on /dev/ttyACM0. Port no: %d", serial_port);
//printf("Opened ACM0: %d\r\n", (int) (serial_port));
}
}
void ServoControllerCls::InitializePubSub() {
//nh_.param("axis_linear", linear_, linear_);
//nh_.param("axis_angular", angular_, angular_);
//nh_.param("scale_angular", a_scale_, a_scale_);
//nh_.param("scale_linear", l_scale_, l_scale_);
// Publish status for all servos
// Set latch to true, so the last message published on
// this topic will be saved and sent to new subscribers when they
// connect
servo_array_status_pub_ = nh_.advertise < servo_controller::servo_array_status
> ("servo_controller/servo_array_status", 1, true);
// Separate messages for independent control of each servo
servo_0_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_0_control", 4, &ServoControllerCls::servoControlCallback, this);
servo_1_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_1_control", 4, &ServoControllerCls::servoControlCallback, this);
servo_2_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_2_control", 4, &ServoControllerCls::servoControlCallback, this);
servo_3_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_3_control", 4, &ServoControllerCls::servoControlCallback, this);
servo_4_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_4_control", 4, &ServoControllerCls::servoControlCallback, this);
servo_5_control_sub_ =
nh_.subscribe < servo_controller::servo_control
> ("servo_controller/servo_5_control", 4, &ServoControllerCls::servoControlCallback, this);
// Publish initial, make sure values are initialized
servo_array_status_pub_.publish(servo_array_status);
}
void ServoControllerCls::InitializeServoProperties() {
const uint center = 6000;
const uint max_value = 8000;
const uint min_value = 4000;
const uint velocity_limit = 100;
const uint acceleration_limit = 20;
servo_array_status.servo[0].enabled = false;
servo_array_status.servo[1].enabled = false;
servo_array_status.servo[2].enabled = false;
servo_array_status.servo[3].enabled = false;
servo_array_status.servo[4].enabled = false;
servo_array_status.servo[5].enabled = false;
servo_array_status.servo[0].servo_no = 0;
servo_array_status.servo[1].servo_no = 1;
servo_array_status.servo[2].servo_no = 2;
servo_array_status.servo[3].servo_no = 3;
servo_array_status.servo[4].servo_no = 4;
servo_array_status.servo[5].servo_no = 5;
servo_array_status.servo[0].name = "";
servo_array_status.servo[1].name = "--Right Wheel Encoder";
servo_array_status.servo[2].name = "Head Servo";
servo_array_status.servo[3].name = "Right Steering Servo";
servo_array_status.servo[4].name = "Left Steering Servo";
servo_array_status.servo[5].name = "Main Motor";
servo_array_status.servo[0].mode = 0; // Not defined
servo_array_status.servo[1].mode = 2; // Digital input - wheel encoder
servo_array_status.servo[2].mode = 1; // Servo control signal output - servo
servo_array_status.servo[3].mode = 1; // Servo control signal output - servo
servo_array_status.servo[4].mode = 1; // Servo control signal output - servo
servo_array_status.servo[5].mode = 1; // Servo control signal output - motor
servo_array_status.servo[2].target = center;
servo_array_status.servo[3].target = center;
servo_array_status.servo[4].target = center;
servo_array_status.servo[5].target = center;
servo_array_status.servo[2].actual = center;
servo_array_status.servo[3].actual = center;
servo_array_status.servo[4].actual = center;
servo_array_status.servo[5].actual = center;
servo_array_status.servo[2].center = center;
servo_array_status.servo[3].center = center;
servo_array_status.servo[4].center = center;
servo_array_status.servo[5].center = center;
servo_array_status.servo[2].max = max_value;
servo_array_status.servo[3].max = max_value;
servo_array_status.servo[4].max = max_value;
servo_array_status.servo[5].max = max_value;
servo_array_status.servo[2].min = min_value;
servo_array_status.servo[3].min = min_value;
servo_array_status.servo[4].min = min_value;
servo_array_status.servo[5].min = min_value;
servo_array_status.servo[2].velocity_limit = velocity_limit;
servo_array_status.servo[3].velocity_limit = velocity_limit;
servo_array_status.servo[4].velocity_limit = velocity_limit;
servo_array_status.servo[5].velocity_limit = velocity_limit;
servo_array_status.servo[2].acceleration_limit = acceleration_limit;
servo_array_status.servo[3].acceleration_limit = acceleration_limit;
servo_array_status.servo[4].acceleration_limit = acceleration_limit;
servo_array_status.servo[5].acceleration_limit = acceleration_limit;
servo_array_status.servo[0].enabled = false;
servo_array_status.servo[1].enabled = false;
servo_array_status.servo[2].enabled = true;
servo_array_status.servo[3].enabled = true;
servo_array_status.servo[4].enabled = true;
servo_array_status.servo[5].enabled = true;
}
ServoControllerCls::ServoControllerCls()
{
InitializeSerialPort();
InitializeServoProperties();
InitializePubSub();
}
void ServoControllerCls::SetServoPosition(int channel_no, int target_position) {
char command_bytes[4] = { 0x84, channel_no, (char) ((target_position & 0x7F)),
(char) ((target_position >> 7 & 0x7F)) };
int n = write(serial_port, command_bytes, 4);
if (n < 0)
{
ROS_WARN("Could not write bytes to servo controller serial port for servo no: %d, target: %d", channel_no, target_position);
}
else
{
ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Set servo no: %d, target: %d", channel_no, target_position);
}
}
void ServoControllerCls::servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command)
{
int servo_no = control_command->servo_no;
if (servo_no < 0 || servo_no >= 6)
{
ROS_WARN("Wrong servo number passed: %d", servo_no);
return;
}
if (!servo_array_status.servo[servo_no].enabled)
{
ROS_WARN("Trying to control a not enabled servo: %d", servo_no);
return;
}
if (servo_array_status.servo[servo_no].mode != 1)
{
ROS_WARN("Trying to control servo: %d, in mode: %d. Mode has to be 1 for servos", servo_no, servo_array_status.servo[servo_no].mode);
return;
}
uint target = control_command->target;
const uint max_value = servo_array_status.servo[servo_no].max;
const uint min_value = servo_array_status.servo[servo_no].min;
if (target > max_value)
{
ROS_WARN("Trying to set servo: %d to target: %d more than maximum value: %d. Setting to maximum value", servo_no, target, max_value);
target = max_value;
}
if (target < min_value)
{
ROS_WARN("Trying to set servo: %d to target: %d less than minimum value: %d. Setting to maximum value", servo_no, target, min_value);
target = min_value;
}
SetServoPosition(servo_no, target);
// Publish update
servo_array_status.servo[servo_no].target = target;
servo_array_status_pub_.publish(servo_array_status);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "ServoController");
ServoControllerCls servo_controller;
ros::spin();
}
|
/**
* \file SD1OverdriveFilter.cpp
*/
#include "SD1OverdriveFilter.h"
#include <boost/math/special_functions/sign.hpp>
#include "../Tools/exp.h"
#include "../Tools/ScalarNewtonRaphson.h"
namespace ATK
{
template<typename DataType_>
class SD1OverdriveFunction
{
public:
typedef DataType_ DataType;
protected:
DataType A;
DataType B;
DataType R1;
DataType Q;
DataType drive;
DataType is;
DataType vt;
DataType oldy0;
DataType oldexpy0;
DataType oldinvexpy0;
DataType oldy1;
DataType oldexpy1;
DataType oldinvexpy1;
Exp<DataType> exp;
public:
SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)
:R1(R1), Q(Q), drive(0.5), is(is), vt(vt), exp(32, 1024*1024)
{
A = dt / (2 * C) + R;
B = dt / (2 * C) - R;
oldy0 = oldy1 = 0;
oldexpy0 = oldinvexpy0 = oldexpy1 = oldinvexpy1 = 1;
}
void set_drive(DataType drive)
{
this->drive = (R1 + drive * Q);
}
std::pair<DataType, DataType> operator()(DataType x0, DataType x1, DataType y0, DataType y1)
{
y0 -= x0;
y1 -= x1;
DataType expdiode_y1_p = exp(y1 / vt);
DataType expdiode_y1_m = 1 / expdiode_y1_p;
DataType expdiode_y0_p;
DataType expdiode_y0_m;
if(y0 == oldy0)
{
expdiode_y0_p = oldexpy0;
expdiode_y0_m = oldinvexpy0;
}
else if(y0 == oldy1)
{
expdiode_y0_p = oldexpy1;
expdiode_y0_m = oldinvexpy1;
}
else
{
expdiode_y0_p = exp(y0 / vt);
expdiode_y0_m = 1 / expdiode_y0_p;
}
oldy0 = y0;
oldexpy0 = expdiode_y0_p;
oldinvexpy0 = expdiode_y0_m;
oldy1 = y1;
oldexpy1 = expdiode_y1_p;
oldinvexpy1 = expdiode_y1_m;
std::pair<DataType, DataType> diode1 = std::make_pair(is * (expdiode_y1_p - 2 * expdiode_y1_m + 1), is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt);
DataType diode0 = is * (expdiode_y0_p - 2 * expdiode_y0_m + 1);
return std::make_pair(x0 - x1 + y1 * (A / drive) + y0 * (B / drive) + A * diode1.first + B * diode0, (A / drive) + A * diode1.second);
}
};
template <typename DataType>
SD1OverdriveFilter<DataType>::SD1OverdriveFilter(int nb_channels)
:TypedBaseFilter<DataType>(nb_channels, nb_channels)
{
optimizer.reset(new ScalarNewtonRaphson<SD1OverdriveFunction<DataType> >(function));
}
template <typename DataType>
SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()
{
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::setup()
{
Parent::setup();
function.reset(new SD1OverdriveFunction<DataType>(static_cast<DataType>(1./input_sampling_rate), 100e3, 0.047e-6, 33e3, 1e6, 1e-12, 26e-3));
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::set_drive(DataType drive)
{
this->drive = drive;
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::process_impl(std::int64_t size)
{
assert(nb_input_ports == nb_output_ports);
for(int channel = 0; channel < nb_input_ports; ++channel)
{
for(std::int64_t i = 0; i < size; ++i)
{
outputs[channel][i] = optimizer->optimize(converted_inputs[channel][i]);
}
}
}
template class SD1OverdriveFilter<float>;
template class SD1OverdriveFilter<double>;
}
Init drive value (because you have to!)
/**
* \file SD1OverdriveFilter.cpp
*/
#include "SD1OverdriveFilter.h"
#include <boost/math/special_functions/sign.hpp>
#include "../Tools/exp.h"
#include "../Tools/ScalarNewtonRaphson.h"
namespace ATK
{
template<typename DataType_>
class SD1OverdriveFunction
{
public:
typedef DataType_ DataType;
protected:
DataType A;
DataType B;
DataType R1;
DataType Q;
DataType drive;
DataType is;
DataType vt;
DataType oldy0;
DataType oldexpy0;
DataType oldinvexpy0;
DataType oldy1;
DataType oldexpy1;
DataType oldinvexpy1;
Exp<DataType> exp;
public:
SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)
:R1(R1), Q(Q), drive(0.5), is(is), vt(vt), exp(32, 1024*1024)
{
A = dt / (2 * C) + R;
B = dt / (2 * C) - R;
oldy0 = oldy1 = 0;
oldexpy0 = oldinvexpy0 = oldexpy1 = oldinvexpy1 = 1;
}
void set_drive(DataType drive)
{
this->drive = (R1 + drive * Q);
}
std::pair<DataType, DataType> operator()(DataType x0, DataType x1, DataType y0, DataType y1)
{
y0 -= x0;
y1 -= x1;
DataType expdiode_y1_p = exp(y1 / vt);
DataType expdiode_y1_m = 1 / expdiode_y1_p;
DataType expdiode_y0_p;
DataType expdiode_y0_m;
if(y0 == oldy0)
{
expdiode_y0_p = oldexpy0;
expdiode_y0_m = oldinvexpy0;
}
else if(y0 == oldy1)
{
expdiode_y0_p = oldexpy1;
expdiode_y0_m = oldinvexpy1;
}
else
{
expdiode_y0_p = exp(y0 / vt);
expdiode_y0_m = 1 / expdiode_y0_p;
}
oldy0 = y0;
oldexpy0 = expdiode_y0_p;
oldinvexpy0 = expdiode_y0_m;
oldy1 = y1;
oldexpy1 = expdiode_y1_p;
oldinvexpy1 = expdiode_y1_m;
std::pair<DataType, DataType> diode1 = std::make_pair(is * (expdiode_y1_p - 2 * expdiode_y1_m + 1), is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt);
DataType diode0 = is * (expdiode_y0_p - 2 * expdiode_y0_m + 1);
return std::make_pair(x0 - x1 + y1 * (A / drive) + y0 * (B / drive) + A * diode1.first + B * diode0, (A / drive) + A * diode1.second);
}
};
template <typename DataType>
SD1OverdriveFilter<DataType>::SD1OverdriveFilter(int nb_channels)
:TypedBaseFilter<DataType>(nb_channels, nb_channels), drive(0)
{
optimizer.reset(new ScalarNewtonRaphson<SD1OverdriveFunction<DataType> >(function));
}
template <typename DataType>
SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()
{
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::setup()
{
Parent::setup();
function.reset(new SD1OverdriveFunction<DataType>(static_cast<DataType>(1./input_sampling_rate), 100e3, 0.047e-6, 33e3, 1e6, 1e-12, 26e-3));
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::set_drive(DataType drive)
{
this->drive = drive;
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::process_impl(std::int64_t size)
{
assert(nb_input_ports == nb_output_ports);
for(int channel = 0; channel < nb_input_ports; ++channel)
{
for(std::int64_t i = 0; i < size; ++i)
{
outputs[channel][i] = optimizer->optimize(converted_inputs[channel][i]);
}
}
}
template class SD1OverdriveFilter<float>;
template class SD1OverdriveFilter<double>;
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: querycontroller.hxx,v $
*
* $Revision: 1.32 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:00:38 $
*
* 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 DBAUI_QUERYCONTROLLER_HXX
#define DBAUI_QUERYCONTROLLER_HXX
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include <connectivity/sqliterator.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectInputStream.hpp>
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include "svx/ParseContext.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif
class VCLXWindow;
namespace dbaui
{
class OQueryView;
class OQueryContainerWindow;
class OTableConnectionData;
class OTableWindowData;
class OAddTableDlg;
class OTableFieldDesc;
class OQueryTableWindow;
class OQueryController : public OJoinController
{
OTableFields m_vTableFieldDesc;
OTableFields m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria
::svxform::OSystemParseContext* m_pParseContext;
::connectivity::OSQLParser* m_pSqlParser; // to parse sql statements
::connectivity::OSQLParseTreeIterator* m_pSqlIterator; // to iterate through them
::std::vector<sal_uInt32> m_vColumnWidth;
::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer > m_xComposer;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; // a number formatter working with the connection's NumberFormatsSupplier
::rtl::OUString m_sStatement; // contains the sql statement
::rtl::OUString m_sUpdateCatalogName; // catalog for update data
::rtl::OUString m_sUpdateSchemaName; // schema for update data
::rtl::OUString m_sUpdateTableName; // table for update data
::rtl::OUString m_sName; // name of the query
sal_Int32 m_nVisibleRows; // which rows the selection browse should show
sal_Int32 m_nSplitPos; // the position of the splitter
sal_Bool m_bDesign; // if design is true then we show the complete design otherwise only the text format
sal_Bool m_bDistinct; // true when you want "select distinct" otherwise false
sal_Bool m_bViewAlias; // show the alias row in the design view
sal_Bool m_bViewTable; // show the table row in the design view
sal_Bool m_bViewFunction; // show the function row in the design view
sal_Bool m_bEsacpeProcessing;// is true when we shouldn't parse the statement
sal_Bool m_bCreateView; // set to true when we should create a view otherwise we create a normal query
sal_Bool m_bIndependent; // are we creating an "independent" SQL command (which does *not* belong to a data source)?
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getElements() const;
sal_Bool askForNewName( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xElements,
sal_Bool _bSaveAs);
// creates the querycomposer
void setQueryComposer();
void deleteIterator();
void executeQuery();
void doSaveAsDoc(sal_Bool _bSaveAs);
void saveViewSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
void loadViewSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
::rtl::OUString translateStatement( bool _bFireStatementChange = true );
protected:
// all the features which should be handled by this class
virtual void describeSupportedFeatures();
// state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
virtual FeatureState GetState(sal_uInt16 nId) const;
// execute a feature
virtual void Execute(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs);
virtual void reconnect( sal_Bool _bUI );
virtual void updateTitle( );
OQueryContainerWindow* getContainer() const { return static_cast< OQueryContainerWindow* >( getView() ); }
public:
OQueryController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);
~OQueryController();
OTableFields& getTableFieldDesc() { return m_vTableFieldDesc; }
OTableFields& getUnUsedFields() { return m_vUnUsedFieldsDesc; }
void clearFields();
virtual void setModified(sal_Bool _bModified=sal_True);
// should the statement be parsed by our own sql parser
sal_Bool isEsacpeProcessing() const { return m_bEsacpeProcessing; }
sal_Bool isDesignMode() const { return m_bDesign; }
sal_Bool isDistinct() const { return m_bDistinct; }
::rtl::OUString getStatement() const { return m_sStatement; }
sal_Int32 getSplitPos() const { return m_nSplitPos;}
sal_Int32 getVisibleRows() const { return m_nVisibleRows; }
void setDistinct(sal_Bool _bDistinct) { m_bDistinct = _bDistinct;}
void setSplitPos(sal_Int32 _nSplitPos) { m_nSplitPos = _nSplitPos;}
void setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;}
::connectivity::OSQLParser* getParser() { return m_pSqlParser; }
::connectivity::OSQLParseTreeIterator& getParseIterator() { return *m_pSqlIterator; }
sal_uInt32 getColWidth(sal_uInt16 _nPos) const
{
return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0);
}
virtual sal_Bool Construct(Window* pParent);
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > getNumberFormatter()const { return m_xFormatter; }
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XComponent
virtual void SAL_CALL disposing();
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// need by registration
static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);
protected:
virtual void onLoadedMenu(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager >& _xLayoutManager);
virtual OTableWindowData* createTableWindowData();
virtual OJoinDesignView* getJoinView();
// ask the user if the design should be saved when it is modified
virtual short saveModified();
virtual void reset();
virtual void impl_initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );
void resetImpl();
/// sets m_sStatement, and notifies our respective property change listeners
void setStatement_fireEvent( const ::rtl::OUString& _rNewStatement, bool _bFireStatementChange = true );
private:
DECL_LINK( OnExecuteAddTable, void* );
};
}
#endif // DBAUI_QUERYCONTROLLER_HXX
INTEGRATION: CWS qiq (1.32.124); FILE MERGED
2006/05/17 04:30:48 fs 1.32.124.3: #i51143# changed signature of OSQLParseTreeIterator
2006/05/12 13:47:01 fs 1.32.124.2: #i51143# refactoring of controller initialization, which allows accessing the load arguments even during Construct (and not only in the - later - impl_initialize)
2006/05/12 11:09:55 fs 1.32.124.1: #i51143# +allowViews/+allowQueries
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: querycontroller.hxx,v $
*
* $Revision: 1.33 $
*
* last change: $Author: obo $ $Date: 2006-07-10 15:33:14 $
*
* 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 DBAUI_QUERYCONTROLLER_HXX
#define DBAUI_QUERYCONTROLLER_HXX
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include <connectivity/sqliterator.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectInputStream.hpp>
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include "svx/ParseContext.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif
class VCLXWindow;
namespace dbaui
{
class OQueryView;
class OQueryContainerWindow;
class OTableConnectionData;
class OTableWindowData;
class OAddTableDlg;
class OTableFieldDesc;
class OQueryTableWindow;
class OQueryController : public OJoinController
{
OTableFields m_vTableFieldDesc;
OTableFields m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria
::svxform::OSystemParseContext* m_pParseContext;
::connectivity::OSQLParser m_aSqlParser;
::connectivity::OSQLParseTreeIterator* m_pSqlIterator;
::std::vector<sal_uInt32> m_vColumnWidth;
::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer > m_xComposer;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; // a number formatter working with the connection's NumberFormatsSupplier
::rtl::OUString m_sStatement; // contains the sql statement
::rtl::OUString m_sUpdateCatalogName; // catalog for update data
::rtl::OUString m_sUpdateSchemaName; // schema for update data
::rtl::OUString m_sUpdateTableName; // table for update data
::rtl::OUString m_sName; // name of the query
sal_Int32 m_nVisibleRows; // which rows the selection browse should show
sal_Int32 m_nSplitPos; // the position of the splitter
sal_Bool m_bDesign; // if design is true then we show the complete design otherwise only the text format
sal_Bool m_bDistinct; // true when you want "select distinct" otherwise false
sal_Bool m_bViewAlias; // show the alias row in the design view
sal_Bool m_bViewTable; // show the table row in the design view
sal_Bool m_bViewFunction; // show the function row in the design view
sal_Bool m_bEsacpeProcessing;// is true when we shouldn't parse the statement
sal_Bool m_bCreateView; // set to true when we should create a view otherwise we create a normal query
sal_Bool m_bIndependent; // are we creating an "independent" SQL command (which does *not* belong to a data source)?
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getElements() const;
sal_Bool askForNewName( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xElements,
sal_Bool _bSaveAs);
// creates the querycomposer
void setQueryComposer();
void deleteIterator();
void executeQuery();
void doSaveAsDoc(sal_Bool _bSaveAs);
void saveViewSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
void loadViewSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
::rtl::OUString translateStatement( bool _bFireStatementChange = true );
protected:
// all the features which should be handled by this class
virtual void describeSupportedFeatures();
// state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
virtual FeatureState GetState(sal_uInt16 nId) const;
// execute a feature
virtual void Execute(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs);
virtual void reconnect( sal_Bool _bUI );
virtual void updateTitle( );
OQueryContainerWindow* getContainer() const { return static_cast< OQueryContainerWindow* >( getView() ); }
public:
OQueryController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);
~OQueryController();
OTableFields& getTableFieldDesc() { return m_vTableFieldDesc; }
OTableFields& getUnUsedFields() { return m_vUnUsedFieldsDesc; }
void clearFields();
virtual void setModified(sal_Bool _bModified=sal_True);
// should the statement be parsed by our own sql parser
sal_Bool isEsacpeProcessing() const { return m_bEsacpeProcessing; }
sal_Bool isDesignMode() const { return m_bDesign; }
sal_Bool isDistinct() const { return m_bDistinct; }
::rtl::OUString getStatement() const { return m_sStatement; }
sal_Int32 getSplitPos() const { return m_nSplitPos;}
sal_Int32 getVisibleRows() const { return m_nVisibleRows; }
void setDistinct(sal_Bool _bDistinct) { m_bDistinct = _bDistinct;}
void setSplitPos(sal_Int32 _nSplitPos) { m_nSplitPos = _nSplitPos;}
void setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;}
::connectivity::OSQLParser& getParser() { return m_aSqlParser; }
::connectivity::OSQLParseTreeIterator& getParseIterator() { return *m_pSqlIterator; }
sal_uInt32 getColWidth(sal_uInt16 _nPos) const
{
return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0);
}
virtual sal_Bool Construct(Window* pParent);
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > getNumberFormatter()const { return m_xFormatter; }
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XComponent
virtual void SAL_CALL disposing();
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// need by registration
static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);
protected:
virtual void onLoadedMenu(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager >& _xLayoutManager);
virtual OTableWindowData* createTableWindowData();
virtual OJoinDesignView* getJoinView();
// ask the user if the design should be saved when it is modified
virtual short saveModified();
virtual void reset();
virtual void impl_initialize();
void resetImpl();
/// sets m_sStatement, and notifies our respective property change listeners
void setStatement_fireEvent( const ::rtl::OUString& _rNewStatement, bool _bFireStatementChange = true );
// OJoinController overridables
virtual bool allowViews() const;
virtual bool allowQueries() const;
private:
DECL_LINK( OnExecuteAddTable, void* );
};
}
#endif // DBAUI_QUERYCONTROLLER_HXX
|
//---------------------------- vectors.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2001 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.
//
//---------------------------- vectors.cc ---------------------------
#include <base/function.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_constraints.h>
#include <fe/fe.h>
#include <fe/fe_values.h>
#include <base/quadrature.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <dofs/dof_tools.h>
#include <lac/vector.h>
#include <lac/block_vector.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition.h>
#include <lac/solver_cg.h>
#include <lac/vector_memory.h>
#include <fe/mapping_q1.h>
#include <numeric>
#include <algorithm>
#include <vector>
#include <cmath>
//TODO:[GK] Move templates containing vector arguments to vectors.templates.h
// if necessary try to work around a bug in the IBM xlC compiler
#ifdef XLC_WORK_AROUND_STD_BUG
using namespace std;
#endif
static inline double sqr (const double x)
{
return x*x;
};
template <int dim>
inline double sqr_point (const Tensor<1,dim> &p)
{
return p * p;
};
template <int dim, class VECTOR>
void VectorTools::interpolate (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const Function<dim> &function,
VECTOR &vec)
{
Assert (dof.get_fe().n_components() == function.n_components,
ExcComponentMismatch());
const FiniteElement<dim> &fe = dof.get_fe();
const unsigned int n_components = fe.n_components();
const bool fe_is_system = (n_components != 1);
typename DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(),
endc = dof.end();
// For FESystems many of the
// unit_support_points will
// appear multiply, as a point
// may be unit_support_point
// for several of the components
// of the system.
// The following is rather
// complicated as it is
// avoided to evaluate
// the vectorfunction multiply at
// the same point on a cell.
const typename std::vector<Point<dim> > &
unit_support_points = fe.get_unit_support_points();
Assert (unit_support_points.size() != 0,
ExcNonInterpolatingFE());
// Find the support points
// on a cell that
// are multiply mentioned in
// @p{unit_support_points}.
// Mark the first representative
// of each multiply mentioned
// support point by appending its
// dof index to @p{dofs_of_rep_points}.
// Each multiple point gets to know
// the dof index of its representative
// point by the @p{dof_to_rep_dof_table}.
// the following vector collects all dofs i,
// 0<=i<fe.dofs_per_cell, for that
// unit_support_points[i]
// is a representative one. i.e.
// the following vector collects all rep dofs.
// the position of a rep dof within this vector
// is called rep index.
std::vector<unsigned int> dofs_of_rep_points;
// the following table converts a dof i
// to the rep index.
std::vector<unsigned int> dof_to_rep_index_table;
unsigned int n_rep_points=0;
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
{
bool representative=true;
// the following loop is looped
// the other way round to get
// the minimal effort of
// O(fe.dofs_per_cell) for multiple
// support points that are placed
// one after the other.
for (unsigned int j=dofs_of_rep_points.size(); j>0; --j)
if (unit_support_points[i]
== unit_support_points[dofs_of_rep_points[j-1]])
{
dof_to_rep_index_table.push_back(j-1);
representative=false;
break;
}
if (representative)
{
// rep_index=dofs_of_rep_points.size()
dof_to_rep_index_table.push_back(dofs_of_rep_points.size());
// dofs_of_rep_points[rep_index]=i
dofs_of_rep_points.push_back(i);
++n_rep_points;
}
}
Assert(dofs_of_rep_points.size()==n_rep_points, ExcInternalError());
Assert(dof_to_rep_index_table.size()==fe.dofs_per_cell, ExcInternalError());
std::vector<unsigned int> dofs_on_cell (fe.dofs_per_cell);
std::vector<Point<dim> > rep_points (n_rep_points);
// get space for the values of the
// function at the rep support points.
//
// have two versions, one for system fe
// and one for scalar ones, to take the
// more efficient one respectively
std::vector<double> function_values_scalar (n_rep_points);
std::vector<Vector<double> > function_values_system (n_rep_points,
Vector<double>(fe.n_components()));
// Make a quadrature rule from support points
// to feed it into FEValues
Quadrature<dim> support_quadrature(unit_support_points);
// Transformed support points are computed by
// FEValues
FEValues<dim> fe_values (mapping, fe, support_quadrature, update_q_points);
for (; cell!=endc; ++cell)
{
// for each cell:
// get location of finite element
// support_points
fe_values.reinit(cell);
const std::vector<Point<dim> >& support_points =
fe_values.get_quadrature_points();
// pick out the representative
// support points
for (unsigned int j=0; j<dofs_of_rep_points.size(); ++j)
rep_points[j]=support_points[dofs_of_rep_points[j]];
// get indices of the dofs on this cell
cell->get_dof_indices (dofs_on_cell);
if (fe_is_system)
{
// get function values at
// these points. Here: get
// all components
function.vector_value_list (rep_points, function_values_system);
// distribute the function
// values to the global
// vector
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
{
const unsigned int component
= fe.system_to_component_index(i).first;
const unsigned int rep_dof=dof_to_rep_index_table[i];
vec(dofs_on_cell[i])
= function_values_system[rep_dof](component);
};
}
else
{
// get first component only,
// which is the only component
// in the function anyway
function.value_list (rep_points, function_values_scalar, 0);
// distribute the function
// values to the global
// vector
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
vec(dofs_on_cell[i])
= function_values_scalar[dof_to_rep_index_table[i]];
};
}
}
template <int dim, class VECTOR>
void VectorTools::interpolate (const DoFHandler<dim> &dof,
const Function<dim> &function,
VECTOR &vec)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
interpolate(mapping, dof, function, vec);
}
template <int dim, class InVector, class OutVector>
void
VectorTools::interpolate (const DoFHandler<dim> &dof_1,
const DoFHandler<dim> &dof_2,
const FullMatrix<double> &transfer,
const InVector &data_1,
OutVector &data_2)
{
Vector<double> cell_data_1(dof_1.get_fe().dofs_per_cell);
Vector<double> cell_data_2(dof_2.get_fe().dofs_per_cell);
std::vector<short unsigned int> touch_count (dof_2.n_dofs(), 0);
std::vector<unsigned int> local_dof_indices (dof_2.get_fe().dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator h = dof_1.begin_active();
typename DoFHandler<dim>::active_cell_iterator l = dof_2.begin_active();
const typename DoFHandler<dim>::cell_iterator endh = dof_1.end();
for(; h != endh; ++h, ++l)
{
h->get_dof_values(data_1, cell_data_1);
transfer.vmult(cell_data_2, cell_data_1);
l->get_dof_indices (local_dof_indices);
// distribute cell vector
for (unsigned int j=0; j<dof_2.get_fe().dofs_per_cell; ++j)
{
data_2(local_dof_indices[j]) += cell_data_2(j);
// count, how often we have
// added to this dof
Assert (touch_count[local_dof_indices[j]] < 255,
ExcInternalError());
++touch_count[local_dof_indices[j]];
};
};
// compute the mean value of the
// sum which we have placed in each
// entry of the output vector
for (unsigned int i=0; i<dof_2.n_dofs(); ++i)
{
Assert (touch_count[i] != 0,
ExcInternalError());
data_2(i) /= touch_count[i];
};
}
#if deal_II_dimension == 1
void VectorTools::project (const Mapping<1> &,
const DoFHandler<1> &,
const ConstraintMatrix &,
const Quadrature<1> &,
const Function<1> &,
Vector<double> &,
const bool ,
const Quadrature<0> &,
const bool )
{
// this function should easily be implemented
// using the template below. However some
// changes have to be made since faces don't
// exist in 1D. Maybe integrate the creation of
// zero boundary values into the
// project_boundary_values function?
Assert (false, ExcNotImplemented());
};
#endif
template <int dim>
void VectorTools::project (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const ConstraintMatrix &constraints,
const Quadrature<dim> &quadrature,
const Function<dim> &function,
Vector<double> &vec,
const bool enforce_zero_boundary,
const Quadrature<dim-1> &q_boundary,
const bool project_to_boundary_first)
{
Assert (dof.get_fe().n_components() == function.n_components,
ExcInvalidFE());
const FiniteElement<dim> &fe = dof.get_fe();
// make up boundary values
std::map<unsigned int,double> boundary_values;
if (enforce_zero_boundary == true)
// no need to project boundary
// values, but enforce
// homogeneous boundary values
// anyway
{
// loop over all boundary faces
// to get all dof indices of
// dofs on the boundary. note
// that in 3d there are cases
// where a face is not at the
// boundary, yet one of its
// lines is, and we should
// consider the degrees of
// freedom on it as boundary
// nodes. likewise, in 2d and
// 3d there are cases where a
// cell is only at the boundary
// by one vertex. nevertheless,
// since we do not support
// boundaries with dimension
// less or equal to dim-2, each
// such boundary dof is also
// found from some other face
// that is actually wholly on
// the boundary, not only by
// one line or one vertex
typename DoFHandler<dim>::active_face_iterator face = dof.begin_active_face(),
endf = dof.end_face();
std::vector<unsigned int> face_dof_indices (fe.dofs_per_face);
for (; face!=endf; ++face)
if (face->at_boundary())
{
face->get_dof_indices (face_dof_indices);
for (unsigned int i=0; i<fe.dofs_per_face; ++i)
// enter zero boundary values
// for all boundary nodes
//
// we need not care about
// vector valued elements here,
// since we set all components
boundary_values[face_dof_indices[i]] = 0.;
};
}
else
// no homogeneous boundary values
if (project_to_boundary_first == true)
// boundary projection required
{
// set up a list of boundary functions for
// the different boundary parts. We want the
// @p{function} to hold on all parts of the
// boundary
typename FunctionMap<dim>::type boundary_functions;
for (unsigned char c=0; c<255; ++c)
boundary_functions[c] = &function;
project_boundary_values (dof, boundary_functions, q_boundary,
boundary_values);
};
// set up mass matrix and right hand side
vec.reinit (dof.n_dofs());
SparsityPattern sparsity(dof.n_dofs(),
dof.n_dofs(),
dof.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof, sparsity);
constraints.condense (sparsity);
SparseMatrix<double> mass_matrix (sparsity);
Vector<double> tmp (mass_matrix.n());
MatrixCreator::create_mass_matrix (mapping, dof, quadrature, mass_matrix);
VectorTools::create_right_hand_side (mapping, dof, quadrature, function, tmp);
constraints.condense (mass_matrix);
constraints.condense (tmp);
if (boundary_values.size() != 0)
MatrixTools::apply_boundary_values (boundary_values,
mass_matrix, vec, tmp,
true);
SolverControl control(1000,1e-16);
PrimitiveVectorMemory<> memory;
SolverCG<> cg(control,memory);
PreconditionSSOR<> prec;
prec.initialize(mass_matrix, 1.2);
// solve
cg.solve (mass_matrix, vec, tmp, prec);
// distribute solution
constraints.distribute (vec);
};
template <int dim>
void VectorTools::project (const DoFHandler<dim> &dof,
const ConstraintMatrix &constraints,
const Quadrature<dim> &quadrature,
const Function<dim> &function,
Vector<double> &vec,
const bool enforce_zero_boundary,
const Quadrature<dim-1> &q_boundary,
const bool project_to_boundary_first)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
project(mapping, dof, constraints, quadrature, function, vec,
enforce_zero_boundary, q_boundary, project_to_boundary_first);
}
template <int dim>
void VectorTools::create_right_hand_side (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof_handler,
const Quadrature<dim> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector)
{
const FiniteElement<dim> &fe = dof_handler.get_fe();
Assert (fe.n_components() == rhs_function.n_components,
ExcComponentMismatch());
Assert (rhs_vector.size() == dof_handler.n_dofs(),
ExcDimensionMismatch(rhs_vector.size(), dof_handler.n_dofs()));
rhs_vector.clear();
UpdateFlags update_flags = UpdateFlags(update_values |
update_q_points |
update_JxW_values);
FEValues<dim> fe_values (mapping, fe, quadrature, update_flags);
const unsigned int dofs_per_cell = fe_values.dofs_per_cell,
n_q_points = fe_values.n_quadrature_points,
n_components = fe.n_components();
std::vector<unsigned int> dofs (dofs_per_cell);
Vector<double> cell_vector (dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
endc = dof_handler.end();
if (n_components==1)
{
std::vector<double> rhs_values(n_q_points);
for (; cell!=endc; ++cell)
{
fe_values.reinit(cell);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
cell_vector(i) += rhs_values[point] *
values(i,point) *
weights[point];
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
else
{
std::vector<Vector<double> > rhs_values(n_q_points, Vector<double>(n_components));
for (; cell!=endc; ++cell)
{
fe_values.reinit(cell);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.vector_value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
const unsigned int component
= fe.system_to_component_index(i).first;
cell_vector(i) += rhs_values[point](component) *
values(i,point) *
weights[point];
}
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
};
template <int dim>
void VectorTools::create_right_hand_side (const DoFHandler<dim> &dof_handler,
const Quadrature<dim> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
create_right_hand_side(mapping, dof_handler, quadrature,
rhs_function, rhs_vector);
}
#if deal_II_dimension != 1
template <int dim>
void
VectorTools::create_boundary_right_hand_side (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof_handler,
const Quadrature<dim-1> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector,
const std::set<unsigned char> &boundary_indicators)
{
const FiniteElement<dim> &fe = dof_handler.get_fe();
Assert (fe.n_components() == rhs_function.n_components,
ExcComponentMismatch());
Assert (rhs_vector.size() == dof_handler.n_dofs(),
ExcDimensionMismatch(rhs_vector.size(), dof_handler.n_dofs()));
rhs_vector.clear();
UpdateFlags update_flags = UpdateFlags(update_values |
update_q_points |
update_JxW_values);
FEFaceValues<dim> fe_values (mapping, fe, quadrature, update_flags);
const unsigned int dofs_per_cell = fe_values.dofs_per_cell,
n_q_points = fe_values.n_quadrature_points,
n_components = fe.n_components();
std::vector<unsigned int> dofs (dofs_per_cell);
Vector<double> cell_vector (dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
endc = dof_handler.end();
if (n_components==1)
{
std::vector<double> rhs_values(n_q_points);
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary () &&
(boundary_indicators.find (cell->face(face)->boundary_indicator())
!=
boundary_indicators.end()))
{
fe_values.reinit(cell, face);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
cell_vector(i) += rhs_values[point] *
values(i,point) *
weights[point];
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
else
{
std::vector<Vector<double> > rhs_values(n_q_points, Vector<double>(n_components));
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary () &&
(boundary_indicators.find (cell->face(face)->boundary_indicator())
!=
boundary_indicators.end()))
{
fe_values.reinit(cell, face);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.vector_value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
const unsigned int component
= fe.system_to_component_index(i).first;
cell_vector(i) += rhs_values[point](component) *
values(i,point) *
weights[point];
}
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
};
#else
void
VectorTools::create_boundary_right_hand_side (const Mapping<1> &,
const DoFHandler<1> &,
const Quadrature<0> &,
const Function<1> &,
Vector<double> &,
const std::set<unsigned char> &)
{
Assert (false, ExcImpossibleInDim(1));
};
#endif
template <int dim>
void
VectorTools::create_boundary_right_hand_side (const DoFHandler<dim> &dof_handler,
const Quadrature<dim-1> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector,
const std::set<unsigned char> &boundary_indicators)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
create_boundary_right_hand_side(mapping, dof_handler, quadrature,
rhs_function, rhs_vector,
boundary_indicators);
}
#if deal_II_dimension == 1
void
VectorTools::interpolate_boundary_values (const Mapping<1> &,
const DoFHandler<1> &dof,
const unsigned char boundary_component,
const Function<1> &boundary_function,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask_)
{
Assert (boundary_component != 255,
ExcInvalidBoundaryIndicator());
const FiniteElement<1> &fe = dof.get_fe();
Assert (fe.n_components() == boundary_function.n_components,
ExcComponentMismatch());
// set the component mask to either
// the original value or a vector
// of @p{true}s
const std::vector<bool> component_mask ((component_mask_.size() == 0) ?
std::vector<bool> (fe.n_components(), true) :
component_mask_);
Assert (std::count(component_mask.begin(), component_mask.end(), true) > 0,
ExcComponentMismatch());
// check whether boundary values at
// the left or right boundary of
// the line are
// requested. @p{direction} denotes
// the neighboring direction in
// which we seek the boundary,
// i.e. 0 is left boundary and 1 is
// right.
const unsigned int direction = boundary_component;
Assert (direction < 2, ExcInvalidBoundaryIndicator());
// first find the outermost active
// cell by first traversing the coarse
// grid to its end and then going
// to the children
DoFHandler<1>::cell_iterator outermost_cell = dof.begin(0);
while (outermost_cell->neighbor(direction).state() == valid)
outermost_cell = outermost_cell->neighbor(direction);
while (outermost_cell->has_children())
outermost_cell = outermost_cell->child(direction);
// now set the value of the
// outermost degree of
// freedom. setting also
// creates the entry in the map
// if it did not exist
// beforehand
//
// save some time by requesting
// values only once for each point,
// irrespective of the number of
// components of the function
Vector<double> function_values (fe.n_components());
if (fe.n_components() == 1)
function_values(0)
= boundary_function.value (outermost_cell->vertex(direction));
else
boundary_function.vector_value (outermost_cell->vertex(direction),
function_values);
for (unsigned int i=0; i<fe.dofs_per_vertex; ++i)
if (component_mask[fe.face_system_to_component_index(i).first])
boundary_values[outermost_cell->vertex_dof_index(direction,i)]
= function_values(fe.face_system_to_component_index(i).first);
};
void
VectorTools::interpolate_boundary_values (const Mapping<1> &mapping,
const DoFHandler<1> &dof,
const FunctionMap<1>::type &function_map,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
for (FunctionMap<1>::type::const_iterator i=function_map.begin();
i!=function_map.end(); ++i)
interpolate_boundary_values (mapping, dof, i->first, *i->second,
boundary_values, component_mask);
};
#endif
template <int dim>
void
VectorTools::interpolate_boundary_values (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &function_map,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask_)
{
// if for whatever we were passed
// an empty map, return immediately
if (function_map.size() == 0)
return;
Assert (function_map.find(255) == function_map.end(),
ExcInvalidBoundaryIndicator());
const FiniteElement<dim> &fe = dof.get_fe();
const unsigned int n_components = fe.n_components();
const bool fe_is_system = (n_components != 1);
Assert ((function_map.size() == 0) ||
(n_components == function_map.begin()->second->n_components),
ExcInvalidFE());
// set the component mask to either
// the original value or a vector
// of @p{true}s
const std::vector<bool> component_mask ((component_mask_.size() == 0) ?
std::vector<bool> (fe.n_components(), true) :
component_mask_);
Assert (std::count(component_mask.begin(), component_mask.end(), true) > 0,
ExcComponentMismatch());
// field to store the indices
std::vector<unsigned int> face_dofs (fe.dofs_per_face,
DoFHandler<dim>::invalid_dof_index);
std::vector<Point<dim> > dof_locations (face_dofs.size(), Point<dim>());
// array to store the values of
// the boundary function at the
// boundary points. have to arrays
// for scalar and vector functions
// to use the more efficient one
// respectively
std::vector<double> dof_values_scalar (fe.dofs_per_face);
std::vector<Vector<double> > dof_values_system (fe.dofs_per_face,
Vector<double>(fe.n_components()));
// next generate a quadrature rule
// on the face from the unit
// support points. this wil be used
// to obtain the quadrature points
// on the real cell's face
const typename std::vector<Point<dim-1> >
& unit_support_points = fe.get_unit_face_support_points();
// check whether there are support
// points on the face, if not, then
// this FE does not allow to be
// used in this function
Assert (unit_support_points.size() != 0, ExcNonInterpolatingFE());
Quadrature<dim-1> aux_quad (unit_support_points);
FEFaceValues<dim> fe_values (mapping, fe, aux_quad, update_q_points);
typename DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(),
endc = dof.end();
for (; cell!=endc; ++cell)
for (unsigned int face_no = 0; face_no < GeometryInfo<dim>::faces_per_cell;
++face_no)
{
typename DoFHandler<dim>::face_iterator face = cell->face(face_no);
const unsigned char boundary_component = face->boundary_indicator();
if (function_map.find(boundary_component) != function_map.end())
// face is of the right component
{
// get indices, physical location and
// boundary values of dofs on this
// face
face->get_dof_indices (face_dofs);
fe_values.reinit(cell, face_no);
const std::vector<Point<dim> > &dof_locations = fe_values.get_quadrature_points ();
if (fe_is_system)
{
function_map.find(boundary_component)->second->vector_value_list (dof_locations,
dof_values_system);
// enter into list
for (unsigned int i=0; i<face_dofs.size(); ++i)
if (component_mask[fe.face_system_to_component_index(i).first])
boundary_values[face_dofs[i]]
= dof_values_system[i](fe.face_system_to_component_index(i).first);
}
else
// fe has only one component,
// so save some computations
{
// get only the one component that
// this function has
function_map.find(boundary_component)->second->value_list (dof_locations,
dof_values_scalar,
0);
// enter into list
for (unsigned int i=0; i<face_dofs.size(); ++i)
boundary_values[face_dofs[i]] = dof_values_scalar[i];
}
}
}
}
template <int dim>
void
VectorTools::interpolate_boundary_values (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const unsigned char boundary_component,
const Function<dim> &boundary_function,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
typename FunctionMap<dim>::type function_map;
function_map[boundary_component] = &boundary_function;
interpolate_boundary_values (mapping, dof, function_map, boundary_values,
component_mask);
};
template <int dim>
void
VectorTools::interpolate_boundary_values (const DoFHandler<dim> &dof,
const unsigned char boundary_component,
const Function<dim> &boundary_function,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
interpolate_boundary_values(mapping, dof, boundary_component,
boundary_function, boundary_values, component_mask);
}
template <int dim>
void
VectorTools::interpolate_boundary_values (const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &function_map,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
interpolate_boundary_values(mapping, dof, function_map,
boundary_values, component_mask);
}
#if deal_II_dimension == 1
void
VectorTools::project_boundary_values (const Mapping<1> &mapping,
const DoFHandler<1> &dof,
const FunctionMap<1>::type &boundary_functions,
const Quadrature<0> &,
std::map<unsigned int,double> &boundary_values)
{
// projection in 1d is equivalent
// to interpolation
interpolate_boundary_values (mapping, dof, boundary_functions,
boundary_values, std::vector<bool>());
};
#endif
template <int dim>
void
VectorTools::project_boundary_values (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &boundary_functions,
const Quadrature<dim-1> &q,
std::map<unsigned int,double> &boundary_values)
{
//TODO:[?] In VectorTools::project_boundary_values, no condensation of sparsity
// structures, matrices and right hand sides or distribution of
// solution vectors is performed. This is ok for dim<3 because then
// there are no constrained nodes on the boundary, but is not
// acceptable for higher dimensions. Fix this.
Assert (dof.get_fe().n_components() == boundary_functions.begin()->second->n_components,
ExcComponentMismatch());
std::vector<unsigned int> dof_to_boundary_mapping;
std::set<unsigned char> selected_boundary_components;
for (typename FunctionMap<dim>::type::const_iterator i=boundary_functions.begin();
i!=boundary_functions.end(); ++i)
selected_boundary_components.insert (i->first);
DoFTools::map_dof_to_boundary_indices (dof, selected_boundary_components,
dof_to_boundary_mapping);
// set up sparsity structure
SparsityPattern sparsity(dof.n_boundary_dofs(boundary_functions),
dof.max_couplings_between_boundary_dofs());
DoFTools::make_boundary_sparsity_pattern (dof,
boundary_functions,
dof_to_boundary_mapping,
sparsity);
// note: for three or more dimensions, there
// may be constrained nodes on the boundary
// in this case the boundary mass matrix has
// to be condensed and the solution is to
// be distributed afterwards, which is not
// yet implemented. The reason for this is
// that we cannot simply use the @p{condense}
// family of functions, since the matrices
// and vectors do not use the global
// numbering but rather the boundary
// numbering, i.e. the condense function
// needs to use another indirection. There
// should be not many technical problems,
// but it needs to be implemented
if (dim<3)
sparsity.compress();
else
Assert (false, ExcNotImplemented());
// make mass matrix and right hand side
SparseMatrix<double> mass_matrix(sparsity);
Vector<double> rhs(sparsity.n_rows());
MatrixCreator::create_boundary_mass_matrix (mapping, dof, q,
mass_matrix, boundary_functions,
rhs, dof_to_boundary_mapping);
// same thing as above: if dim>=3 we need
// to consider constraints
Assert (dim<3, ExcNotImplemented());
Vector<double> boundary_projection (rhs.size());
SolverControl control(1000, 1e-16);
PrimitiveVectorMemory<> memory;
SolverCG<> cg(control,memory);
PreconditionSSOR<> prec;
prec.initialize(mass_matrix, 1.2);
// solve
cg.solve (mass_matrix, boundary_projection, rhs, prec);
// fill in boundary values
for (unsigned int i=0; i<dof_to_boundary_mapping.size(); ++i)
if (dof_to_boundary_mapping[i] != DoFHandler<dim>::invalid_dof_index)
// this dof is on one of the
// interesting boundary parts
//
// remember: @p{i} is the global dof
// number, @p{dof_to_boundary_mapping[i]}
// is the number on the boundary and
// thus in the solution vector
boundary_values[i] = boundary_projection(dof_to_boundary_mapping[i]);
};
template <int dim>
void
VectorTools::project_boundary_values (const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &boundary_functions,
const Quadrature<dim-1> &q,
std::map<unsigned int,double> &boundary_values)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
project_boundary_values(mapping, dof, boundary_functions, q, boundary_values);
}
template <int dim, class InVector, class OutVector>
void
VectorTools::integrate_difference (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const InVector &fe_function,
const Function<dim> &exact_solution,
OutVector &difference,
const Quadrature<dim> &q,
const NormType &norm,
const Function<dim> *weight)
{
const unsigned int n_q_points = q.n_quadrature_points;
const FiniteElement<dim> &fe = dof.get_fe();
const unsigned int n_components = fe.n_components();
const bool fe_is_system = (n_components != 1);
Assert( !((n_components == 1) && (norm == mean)),
ExcNotUseful());
if (weight!=0)
{
Assert ((weight->n_components==1) || (weight->n_components==n_components),
ExcDimensionMismatch(weight->n_components, n_components));
}
difference.reinit (dof.get_tria().n_active_cells());
UpdateFlags update_flags = UpdateFlags (update_q_points |
update_JxW_values);
if (norm != H1_seminorm)
update_flags = UpdateFlags(update_flags | update_values);
if ((norm==H1_seminorm) || (norm==H1_norm))
update_flags = UpdateFlags (update_flags | update_gradients);
FEValues<dim> fe_values(mapping, fe, q, update_flags);
std::vector< Vector<double> > function_values (n_q_points,
Vector<double>(n_components));
std::vector<std::vector<Tensor<1,dim> > > function_grads (n_q_points,
std::vector<Tensor<1,dim> >(n_components));
std::vector<double> weight_values (n_q_points);
std::vector<Vector<double> > weight_vectors (n_q_points,
Vector<double>(n_components));
std::vector<Vector<double> > psi_values (n_q_points,
Vector<double>(n_components));
std::vector<std::vector<Tensor<1,dim> > > psi_grads (n_q_points,
std::vector<Tensor<1,dim> >(n_components));
std::vector<double> psi_scalar (n_q_points);
// tmp vector when we use the
// Function<dim> functions for
// scalar functions
std::vector<double> tmp_values (fe_values.n_quadrature_points);
std::vector<Tensor<1,dim> > tmp_gradients (fe_values.n_quadrature_points);
// loop over all cells
typename DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(),
endc = dof.end();
for (unsigned int index=0; cell != endc; ++cell, ++index)
{
double diff=0;
// initialize for this cell
fe_values.reinit (cell);
if (weight!=0)
{
if (weight->n_components>1)
weight->vector_value_list (fe_values.get_quadrature_points(),
weight_vectors);
else
weight->value_list (fe_values.get_quadrature_points(),
weight_values);
}
switch (norm)
{
case mean:
case L1_norm:
case L2_norm:
case Linfty_norm:
case H1_norm:
{
// first compute the exact solution
// (vectors) at the quadrature points
// try to do this as efficient as
// possible by avoiding a second
// virtual function call in case
// the function really has only
// one component
if (fe_is_system)
exact_solution.vector_value_list (fe_values.get_quadrature_points(),
psi_values);
else
{
exact_solution.value_list (fe_values.get_quadrature_points(),
tmp_values);
for (unsigned int i=0; i<n_q_points; ++i)
psi_values[i](0) = tmp_values[i];
};
// then subtract finite element
// fe_function
fe_values.get_function_values (fe_function, function_values);
for (unsigned int q=0; q<n_q_points; ++q)
psi_values[q] -= function_values[q];
switch (norm)
{
case mean:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted mean value
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i)
* weight_vectors[q](i);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted mean value
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i)
* weight_values[q];
}
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// mean value
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i);
}
// Integration on one cell
diff = std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
break;
// Compute (weighted) squares
// in each quadrature point
case L2_norm:
case H1_norm:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted scalar product
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i)*psi_values[q](i)
* weight_vectors[q](i);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].norm_sqr()
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].norm_sqr();
// Integration on one cell
diff = std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
if (norm == L2_norm)
diff=std::sqrt(diff);
break;
case L1_norm:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted scalar product
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += std::fabs(psi_values[q](i))
* weight_vectors[q](i);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].l1_norm()
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].l1_norm();
// Integration on one cell
diff = std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
if (norm == L2_norm)
diff=std::sqrt(diff);
break;
case Linfty_norm:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
for (unsigned int i=0; i<n_components; ++i)
{
double newval = std::fabs(psi_values[q](i))
* weight_vectors[q](i);
if (psi_scalar[q]<newval)
psi_scalar[q] = newval;
}
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].linfty_norm()
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].linfty_norm();
// Maximum on one cell
diff = *std::max_element (psi_scalar.begin(), psi_scalar.end());
break;
default:
Assert (false, ExcNotImplemented());
}
// note: the H1_norm uses the result
// of the L2_norm and control goes
// over to the next case statement!
if (norm != H1_norm)
break;
};
case H1_seminorm:
{
// note: the computation of the
// H1_norm starts at the previous
// case statement, but continues
// here!
// Until now, @p{diff} includes the
// square of the L2_norm.
// in praxi: first compute
// exact fe_function vector
//
// try to be a little clever
// to avoid recursive virtual
// function calls when calling
// @p{gradient_list} for functions
// that are really scalar
// functions
if (fe_is_system)
exact_solution.vector_gradient_list (fe_values.get_quadrature_points(),
psi_grads);
else
{
exact_solution.gradient_list (fe_values.get_quadrature_points(),
tmp_gradients);
for (unsigned int i=0; i<n_q_points; ++i)
psi_grads[i][0] = tmp_gradients[i];
};
// then subtract finite element
// function_grads
fe_values.get_function_grads (fe_function, function_grads);
for (unsigned int k=0; k<n_components; ++k)
for (unsigned int q=0; q<n_q_points; ++q)
psi_grads[q][k] -= function_grads[q][k];
// take square of integrand
std::fill_n (psi_scalar.begin(), n_q_points, 0.0);
for (unsigned int k=0; k<n_components; ++k)
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
// weighted scalar product
psi_scalar[q] += sqr_point(psi_grads[q][k])
* weight_vectors[q](k);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = sqr_point(psi_grads[q][k])
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] += sqr_point(psi_grads[q][k]);
// add seminorm to L_2 norm or
// to zero
diff += std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
diff = std::sqrt(diff);
break;
};
default:
Assert (false, ExcNotImplemented());
};
// append result of this cell
// to the end of the vector
difference(index) = diff;
};
};
template <int dim, class InVector, class OutVector>
void
VectorTools::integrate_difference (const DoFHandler<dim> &dof,
const InVector &fe_function,
const Function<dim> &exact_solution,
OutVector &difference,
const Quadrature<dim> &q,
const NormType &norm,
const Function<dim> *weight)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
integrate_difference(mapping, dof, fe_function, exact_solution,
difference, q, norm, weight);
}
template <int dim>
double
VectorTools::compute_mean_value (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const Quadrature<dim> &quadrature,
Vector<double> &v,
const unsigned int component)
{
Assert (component < dof.get_fe().n_components(),
ExcIndexRange(component, 0, dof.get_fe().n_components()));
FEValues<dim> fe(mapping, dof.get_fe(), quadrature,
UpdateFlags(update_JxW_values
| update_values));
typename DoFHandler<dim>::active_cell_iterator c;
std::vector<Vector<double> > values(quadrature.n_quadrature_points,
Vector<double> (dof.get_fe().n_components()));
double mean = 0.;
double area = 0.;
// Compute mean value
for (c = dof.begin_active(); c != dof.end(); ++c)
{
fe.reinit (c);
fe.get_function_values(v, values);
for (unsigned int k=0; k< quadrature.n_quadrature_points; ++k)
{
mean += fe.JxW(k) * values[k](component);
area += fe.JxW(k);
};
};
return (mean/area);
};
template <int dim>
double
VectorTools::compute_mean_value (const DoFHandler<dim> &dof,
const Quadrature<dim> &quadrature,
Vector<double> &v,
const unsigned int component)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
return compute_mean_value(mapping, dof, quadrature, v, component);
}
// explicit instantiations
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<double>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<double>&);
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<float>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<float>&);
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<double>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<double>&);
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<float>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<float>&);
template
void VectorTools::interpolate(const DoFHandler<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const FullMatrix<double>&,
const Vector<double>&,
Vector<double>&);
template
void VectorTools::interpolate(const DoFHandler<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const FullMatrix<double>&,
const BlockVector<double>&,
BlockVector<double>&);
template
void VectorTools::project (const DoFHandler<deal_II_dimension> &,
const ConstraintMatrix &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const bool,
const Quadrature<deal_II_dimension-1> &,
const bool);
template
void VectorTools::create_right_hand_side (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &);
template
void VectorTools::create_right_hand_side (const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &);
#if deal_II_dimension != 1
template
void
VectorTools::create_boundary_right_hand_side (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension-1> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const std::set<unsigned char> &);
#endif
template
void
VectorTools::create_boundary_right_hand_side (const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension-1> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const std::set<unsigned char> &);
template
void VectorTools::interpolate_boundary_values (const DoFHandler<deal_II_dimension> &,
const unsigned char,
const Function<deal_II_dimension> &,
std::map<unsigned int,double> &,
const std::vector<bool> &);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
#if deal_II_dimension != 1
template
void VectorTools::project_boundary_values (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const FunctionMap<deal_II_dimension>::type &,
const Quadrature<deal_II_dimension-1>&,
std::map<unsigned int,double> &);
#endif
template
void VectorTools::project_boundary_values (const DoFHandler<deal_II_dimension> &,
const FunctionMap<deal_II_dimension>::type &,
const Quadrature<deal_II_dimension-1>&,
std::map<unsigned int,double> &);
template
double VectorTools::compute_mean_value (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
Vector<double> &,
const unsigned int);
template
double VectorTools::compute_mean_value (const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
Vector<double> &,
const unsigned int);
// the following two functions are not derived from a template in 1d
// and thus need no explicit instantiation
#if deal_II_dimension > 1
template
void VectorTools::interpolate_boundary_values (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const unsigned char,
const Function<deal_II_dimension> &,
std::map<unsigned int,double> &,
const std::vector<bool> &);
template
void VectorTools::project (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const ConstraintMatrix &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const bool,
const Quadrature<deal_II_dimension-1> &,
const bool);
#endif
None-useful assertion removed
git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@5155 0785d39b-7218-0410-832d-ea1e28bc413d
//---------------------------- vectors.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2001 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.
//
//---------------------------- vectors.cc ---------------------------
#include <base/function.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_constraints.h>
#include <fe/fe.h>
#include <fe/fe_values.h>
#include <base/quadrature.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <dofs/dof_tools.h>
#include <lac/vector.h>
#include <lac/block_vector.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition.h>
#include <lac/solver_cg.h>
#include <lac/vector_memory.h>
#include <fe/mapping_q1.h>
#include <numeric>
#include <algorithm>
#include <vector>
#include <cmath>
//TODO:[GK] Move templates containing vector arguments to vectors.templates.h
// if necessary try to work around a bug in the IBM xlC compiler
#ifdef XLC_WORK_AROUND_STD_BUG
using namespace std;
#endif
static inline double sqr (const double x)
{
return x*x;
};
template <int dim>
inline double sqr_point (const Tensor<1,dim> &p)
{
return p * p;
};
template <int dim, class VECTOR>
void VectorTools::interpolate (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const Function<dim> &function,
VECTOR &vec)
{
Assert (dof.get_fe().n_components() == function.n_components,
ExcComponentMismatch());
const FiniteElement<dim> &fe = dof.get_fe();
const unsigned int n_components = fe.n_components();
const bool fe_is_system = (n_components != 1);
typename DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(),
endc = dof.end();
// For FESystems many of the
// unit_support_points will
// appear multiply, as a point
// may be unit_support_point
// for several of the components
// of the system.
// The following is rather
// complicated as it is
// avoided to evaluate
// the vectorfunction multiply at
// the same point on a cell.
const typename std::vector<Point<dim> > &
unit_support_points = fe.get_unit_support_points();
Assert (unit_support_points.size() != 0,
ExcNonInterpolatingFE());
// Find the support points
// on a cell that
// are multiply mentioned in
// @p{unit_support_points}.
// Mark the first representative
// of each multiply mentioned
// support point by appending its
// dof index to @p{dofs_of_rep_points}.
// Each multiple point gets to know
// the dof index of its representative
// point by the @p{dof_to_rep_dof_table}.
// the following vector collects all dofs i,
// 0<=i<fe.dofs_per_cell, for that
// unit_support_points[i]
// is a representative one. i.e.
// the following vector collects all rep dofs.
// the position of a rep dof within this vector
// is called rep index.
std::vector<unsigned int> dofs_of_rep_points;
// the following table converts a dof i
// to the rep index.
std::vector<unsigned int> dof_to_rep_index_table;
unsigned int n_rep_points=0;
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
{
bool representative=true;
// the following loop is looped
// the other way round to get
// the minimal effort of
// O(fe.dofs_per_cell) for multiple
// support points that are placed
// one after the other.
for (unsigned int j=dofs_of_rep_points.size(); j>0; --j)
if (unit_support_points[i]
== unit_support_points[dofs_of_rep_points[j-1]])
{
dof_to_rep_index_table.push_back(j-1);
representative=false;
break;
}
if (representative)
{
// rep_index=dofs_of_rep_points.size()
dof_to_rep_index_table.push_back(dofs_of_rep_points.size());
// dofs_of_rep_points[rep_index]=i
dofs_of_rep_points.push_back(i);
++n_rep_points;
}
}
Assert(dofs_of_rep_points.size()==n_rep_points, ExcInternalError());
Assert(dof_to_rep_index_table.size()==fe.dofs_per_cell, ExcInternalError());
std::vector<unsigned int> dofs_on_cell (fe.dofs_per_cell);
std::vector<Point<dim> > rep_points (n_rep_points);
// get space for the values of the
// function at the rep support points.
//
// have two versions, one for system fe
// and one for scalar ones, to take the
// more efficient one respectively
std::vector<double> function_values_scalar (n_rep_points);
std::vector<Vector<double> > function_values_system (n_rep_points,
Vector<double>(fe.n_components()));
// Make a quadrature rule from support points
// to feed it into FEValues
Quadrature<dim> support_quadrature(unit_support_points);
// Transformed support points are computed by
// FEValues
FEValues<dim> fe_values (mapping, fe, support_quadrature, update_q_points);
for (; cell!=endc; ++cell)
{
// for each cell:
// get location of finite element
// support_points
fe_values.reinit(cell);
const std::vector<Point<dim> >& support_points =
fe_values.get_quadrature_points();
// pick out the representative
// support points
for (unsigned int j=0; j<dofs_of_rep_points.size(); ++j)
rep_points[j]=support_points[dofs_of_rep_points[j]];
// get indices of the dofs on this cell
cell->get_dof_indices (dofs_on_cell);
if (fe_is_system)
{
// get function values at
// these points. Here: get
// all components
function.vector_value_list (rep_points, function_values_system);
// distribute the function
// values to the global
// vector
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
{
const unsigned int component
= fe.system_to_component_index(i).first;
const unsigned int rep_dof=dof_to_rep_index_table[i];
vec(dofs_on_cell[i])
= function_values_system[rep_dof](component);
};
}
else
{
// get first component only,
// which is the only component
// in the function anyway
function.value_list (rep_points, function_values_scalar, 0);
// distribute the function
// values to the global
// vector
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
vec(dofs_on_cell[i])
= function_values_scalar[dof_to_rep_index_table[i]];
};
}
}
template <int dim, class VECTOR>
void VectorTools::interpolate (const DoFHandler<dim> &dof,
const Function<dim> &function,
VECTOR &vec)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
interpolate(mapping, dof, function, vec);
}
template <int dim, class InVector, class OutVector>
void
VectorTools::interpolate (const DoFHandler<dim> &dof_1,
const DoFHandler<dim> &dof_2,
const FullMatrix<double> &transfer,
const InVector &data_1,
OutVector &data_2)
{
Vector<double> cell_data_1(dof_1.get_fe().dofs_per_cell);
Vector<double> cell_data_2(dof_2.get_fe().dofs_per_cell);
std::vector<short unsigned int> touch_count (dof_2.n_dofs(), 0);
std::vector<unsigned int> local_dof_indices (dof_2.get_fe().dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator h = dof_1.begin_active();
typename DoFHandler<dim>::active_cell_iterator l = dof_2.begin_active();
const typename DoFHandler<dim>::cell_iterator endh = dof_1.end();
for(; h != endh; ++h, ++l)
{
h->get_dof_values(data_1, cell_data_1);
transfer.vmult(cell_data_2, cell_data_1);
l->get_dof_indices (local_dof_indices);
// distribute cell vector
for (unsigned int j=0; j<dof_2.get_fe().dofs_per_cell; ++j)
{
data_2(local_dof_indices[j]) += cell_data_2(j);
// count, how often we have
// added to this dof
Assert (touch_count[local_dof_indices[j]] < 255,
ExcInternalError());
++touch_count[local_dof_indices[j]];
};
};
// compute the mean value of the
// sum which we have placed in each
// entry of the output vector
for (unsigned int i=0; i<dof_2.n_dofs(); ++i)
{
Assert (touch_count[i] != 0,
ExcInternalError());
data_2(i) /= touch_count[i];
};
}
#if deal_II_dimension == 1
void VectorTools::project (const Mapping<1> &,
const DoFHandler<1> &,
const ConstraintMatrix &,
const Quadrature<1> &,
const Function<1> &,
Vector<double> &,
const bool ,
const Quadrature<0> &,
const bool )
{
// this function should easily be implemented
// using the template below. However some
// changes have to be made since faces don't
// exist in 1D. Maybe integrate the creation of
// zero boundary values into the
// project_boundary_values function?
Assert (false, ExcNotImplemented());
};
#endif
template <int dim>
void VectorTools::project (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const ConstraintMatrix &constraints,
const Quadrature<dim> &quadrature,
const Function<dim> &function,
Vector<double> &vec,
const bool enforce_zero_boundary,
const Quadrature<dim-1> &q_boundary,
const bool project_to_boundary_first)
{
Assert (dof.get_fe().n_components() == function.n_components,
ExcInvalidFE());
const FiniteElement<dim> &fe = dof.get_fe();
// make up boundary values
std::map<unsigned int,double> boundary_values;
if (enforce_zero_boundary == true)
// no need to project boundary
// values, but enforce
// homogeneous boundary values
// anyway
{
// loop over all boundary faces
// to get all dof indices of
// dofs on the boundary. note
// that in 3d there are cases
// where a face is not at the
// boundary, yet one of its
// lines is, and we should
// consider the degrees of
// freedom on it as boundary
// nodes. likewise, in 2d and
// 3d there are cases where a
// cell is only at the boundary
// by one vertex. nevertheless,
// since we do not support
// boundaries with dimension
// less or equal to dim-2, each
// such boundary dof is also
// found from some other face
// that is actually wholly on
// the boundary, not only by
// one line or one vertex
typename DoFHandler<dim>::active_face_iterator face = dof.begin_active_face(),
endf = dof.end_face();
std::vector<unsigned int> face_dof_indices (fe.dofs_per_face);
for (; face!=endf; ++face)
if (face->at_boundary())
{
face->get_dof_indices (face_dof_indices);
for (unsigned int i=0; i<fe.dofs_per_face; ++i)
// enter zero boundary values
// for all boundary nodes
//
// we need not care about
// vector valued elements here,
// since we set all components
boundary_values[face_dof_indices[i]] = 0.;
};
}
else
// no homogeneous boundary values
if (project_to_boundary_first == true)
// boundary projection required
{
// set up a list of boundary functions for
// the different boundary parts. We want the
// @p{function} to hold on all parts of the
// boundary
typename FunctionMap<dim>::type boundary_functions;
for (unsigned char c=0; c<255; ++c)
boundary_functions[c] = &function;
project_boundary_values (dof, boundary_functions, q_boundary,
boundary_values);
};
// set up mass matrix and right hand side
vec.reinit (dof.n_dofs());
SparsityPattern sparsity(dof.n_dofs(),
dof.n_dofs(),
dof.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof, sparsity);
constraints.condense (sparsity);
SparseMatrix<double> mass_matrix (sparsity);
Vector<double> tmp (mass_matrix.n());
MatrixCreator::create_mass_matrix (mapping, dof, quadrature, mass_matrix);
VectorTools::create_right_hand_side (mapping, dof, quadrature, function, tmp);
constraints.condense (mass_matrix);
constraints.condense (tmp);
if (boundary_values.size() != 0)
MatrixTools::apply_boundary_values (boundary_values,
mass_matrix, vec, tmp,
true);
SolverControl control(1000,1e-16);
PrimitiveVectorMemory<> memory;
SolverCG<> cg(control,memory);
PreconditionSSOR<> prec;
prec.initialize(mass_matrix, 1.2);
// solve
cg.solve (mass_matrix, vec, tmp, prec);
// distribute solution
constraints.distribute (vec);
};
template <int dim>
void VectorTools::project (const DoFHandler<dim> &dof,
const ConstraintMatrix &constraints,
const Quadrature<dim> &quadrature,
const Function<dim> &function,
Vector<double> &vec,
const bool enforce_zero_boundary,
const Quadrature<dim-1> &q_boundary,
const bool project_to_boundary_first)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
project(mapping, dof, constraints, quadrature, function, vec,
enforce_zero_boundary, q_boundary, project_to_boundary_first);
}
template <int dim>
void VectorTools::create_right_hand_side (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof_handler,
const Quadrature<dim> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector)
{
const FiniteElement<dim> &fe = dof_handler.get_fe();
Assert (fe.n_components() == rhs_function.n_components,
ExcComponentMismatch());
Assert (rhs_vector.size() == dof_handler.n_dofs(),
ExcDimensionMismatch(rhs_vector.size(), dof_handler.n_dofs()));
rhs_vector.clear();
UpdateFlags update_flags = UpdateFlags(update_values |
update_q_points |
update_JxW_values);
FEValues<dim> fe_values (mapping, fe, quadrature, update_flags);
const unsigned int dofs_per_cell = fe_values.dofs_per_cell,
n_q_points = fe_values.n_quadrature_points,
n_components = fe.n_components();
std::vector<unsigned int> dofs (dofs_per_cell);
Vector<double> cell_vector (dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
endc = dof_handler.end();
if (n_components==1)
{
std::vector<double> rhs_values(n_q_points);
for (; cell!=endc; ++cell)
{
fe_values.reinit(cell);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
cell_vector(i) += rhs_values[point] *
values(i,point) *
weights[point];
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
else
{
std::vector<Vector<double> > rhs_values(n_q_points, Vector<double>(n_components));
for (; cell!=endc; ++cell)
{
fe_values.reinit(cell);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.vector_value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
const unsigned int component
= fe.system_to_component_index(i).first;
cell_vector(i) += rhs_values[point](component) *
values(i,point) *
weights[point];
}
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
};
template <int dim>
void VectorTools::create_right_hand_side (const DoFHandler<dim> &dof_handler,
const Quadrature<dim> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
create_right_hand_side(mapping, dof_handler, quadrature,
rhs_function, rhs_vector);
}
#if deal_II_dimension != 1
template <int dim>
void
VectorTools::create_boundary_right_hand_side (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof_handler,
const Quadrature<dim-1> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector,
const std::set<unsigned char> &boundary_indicators)
{
const FiniteElement<dim> &fe = dof_handler.get_fe();
Assert (fe.n_components() == rhs_function.n_components,
ExcComponentMismatch());
Assert (rhs_vector.size() == dof_handler.n_dofs(),
ExcDimensionMismatch(rhs_vector.size(), dof_handler.n_dofs()));
rhs_vector.clear();
UpdateFlags update_flags = UpdateFlags(update_values |
update_q_points |
update_JxW_values);
FEFaceValues<dim> fe_values (mapping, fe, quadrature, update_flags);
const unsigned int dofs_per_cell = fe_values.dofs_per_cell,
n_q_points = fe_values.n_quadrature_points,
n_components = fe.n_components();
std::vector<unsigned int> dofs (dofs_per_cell);
Vector<double> cell_vector (dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
endc = dof_handler.end();
if (n_components==1)
{
std::vector<double> rhs_values(n_q_points);
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary () &&
(boundary_indicators.find (cell->face(face)->boundary_indicator())
!=
boundary_indicators.end()))
{
fe_values.reinit(cell, face);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
cell_vector(i) += rhs_values[point] *
values(i,point) *
weights[point];
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
else
{
std::vector<Vector<double> > rhs_values(n_q_points, Vector<double>(n_components));
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary () &&
(boundary_indicators.find (cell->face(face)->boundary_indicator())
!=
boundary_indicators.end()))
{
fe_values.reinit(cell, face);
const FullMatrix<double> &values = fe_values.get_shape_values ();
const std::vector<double> &weights = fe_values.get_JxW_values ();
rhs_function.vector_value_list (fe_values.get_quadrature_points(), rhs_values);
cell_vector.clear();
for (unsigned int point=0; point<n_q_points; ++point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
const unsigned int component
= fe.system_to_component_index(i).first;
cell_vector(i) += rhs_values[point](component) *
values(i,point) *
weights[point];
}
cell->get_dof_indices (dofs);
for (unsigned int i=0; i<dofs_per_cell; ++i)
rhs_vector(dofs[i]) += cell_vector(i);
}
}
};
#else
void
VectorTools::create_boundary_right_hand_side (const Mapping<1> &,
const DoFHandler<1> &,
const Quadrature<0> &,
const Function<1> &,
Vector<double> &,
const std::set<unsigned char> &)
{
Assert (false, ExcImpossibleInDim(1));
};
#endif
template <int dim>
void
VectorTools::create_boundary_right_hand_side (const DoFHandler<dim> &dof_handler,
const Quadrature<dim-1> &quadrature,
const Function<dim> &rhs_function,
Vector<double> &rhs_vector,
const std::set<unsigned char> &boundary_indicators)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
create_boundary_right_hand_side(mapping, dof_handler, quadrature,
rhs_function, rhs_vector,
boundary_indicators);
}
#if deal_II_dimension == 1
void
VectorTools::interpolate_boundary_values (const Mapping<1> &,
const DoFHandler<1> &dof,
const unsigned char boundary_component,
const Function<1> &boundary_function,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask_)
{
Assert (boundary_component != 255,
ExcInvalidBoundaryIndicator());
const FiniteElement<1> &fe = dof.get_fe();
Assert (fe.n_components() == boundary_function.n_components,
ExcComponentMismatch());
// set the component mask to either
// the original value or a vector
// of @p{true}s
const std::vector<bool> component_mask ((component_mask_.size() == 0) ?
std::vector<bool> (fe.n_components(), true) :
component_mask_);
Assert (std::count(component_mask.begin(), component_mask.end(), true) > 0,
ExcComponentMismatch());
// check whether boundary values at
// the left or right boundary of
// the line are
// requested. @p{direction} denotes
// the neighboring direction in
// which we seek the boundary,
// i.e. 0 is left boundary and 1 is
// right.
const unsigned int direction = boundary_component;
Assert (direction < 2, ExcInvalidBoundaryIndicator());
// first find the outermost active
// cell by first traversing the coarse
// grid to its end and then going
// to the children
DoFHandler<1>::cell_iterator outermost_cell = dof.begin(0);
while (outermost_cell->neighbor(direction).state() == valid)
outermost_cell = outermost_cell->neighbor(direction);
while (outermost_cell->has_children())
outermost_cell = outermost_cell->child(direction);
// now set the value of the
// outermost degree of
// freedom. setting also
// creates the entry in the map
// if it did not exist
// beforehand
//
// save some time by requesting
// values only once for each point,
// irrespective of the number of
// components of the function
Vector<double> function_values (fe.n_components());
if (fe.n_components() == 1)
function_values(0)
= boundary_function.value (outermost_cell->vertex(direction));
else
boundary_function.vector_value (outermost_cell->vertex(direction),
function_values);
for (unsigned int i=0; i<fe.dofs_per_vertex; ++i)
if (component_mask[fe.face_system_to_component_index(i).first])
boundary_values[outermost_cell->vertex_dof_index(direction,i)]
= function_values(fe.face_system_to_component_index(i).first);
};
void
VectorTools::interpolate_boundary_values (const Mapping<1> &mapping,
const DoFHandler<1> &dof,
const FunctionMap<1>::type &function_map,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
for (FunctionMap<1>::type::const_iterator i=function_map.begin();
i!=function_map.end(); ++i)
interpolate_boundary_values (mapping, dof, i->first, *i->second,
boundary_values, component_mask);
};
#endif
template <int dim>
void
VectorTools::interpolate_boundary_values (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &function_map,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask_)
{
// if for whatever we were passed
// an empty map, return immediately
if (function_map.size() == 0)
return;
Assert (function_map.find(255) == function_map.end(),
ExcInvalidBoundaryIndicator());
const FiniteElement<dim> &fe = dof.get_fe();
const unsigned int n_components = fe.n_components();
const bool fe_is_system = (n_components != 1);
Assert ((function_map.size() == 0) ||
(n_components == function_map.begin()->second->n_components),
ExcInvalidFE());
// set the component mask to either
// the original value or a vector
// of @p{true}s
const std::vector<bool> component_mask ((component_mask_.size() == 0) ?
std::vector<bool> (fe.n_components(), true) :
component_mask_);
Assert (std::count(component_mask.begin(), component_mask.end(), true) > 0,
ExcComponentMismatch());
// field to store the indices
std::vector<unsigned int> face_dofs (fe.dofs_per_face,
DoFHandler<dim>::invalid_dof_index);
std::vector<Point<dim> > dof_locations (face_dofs.size(), Point<dim>());
// array to store the values of
// the boundary function at the
// boundary points. have to arrays
// for scalar and vector functions
// to use the more efficient one
// respectively
std::vector<double> dof_values_scalar (fe.dofs_per_face);
std::vector<Vector<double> > dof_values_system (fe.dofs_per_face,
Vector<double>(fe.n_components()));
// next generate a quadrature rule
// on the face from the unit
// support points. this wil be used
// to obtain the quadrature points
// on the real cell's face
const typename std::vector<Point<dim-1> >
& unit_support_points = fe.get_unit_face_support_points();
// check whether there are support
// points on the face, if not, then
// this FE does not allow to be
// used in this function
Assert (unit_support_points.size() != 0, ExcNonInterpolatingFE());
Quadrature<dim-1> aux_quad (unit_support_points);
FEFaceValues<dim> fe_values (mapping, fe, aux_quad, update_q_points);
typename DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(),
endc = dof.end();
for (; cell!=endc; ++cell)
for (unsigned int face_no = 0; face_no < GeometryInfo<dim>::faces_per_cell;
++face_no)
{
typename DoFHandler<dim>::face_iterator face = cell->face(face_no);
const unsigned char boundary_component = face->boundary_indicator();
if (function_map.find(boundary_component) != function_map.end())
// face is of the right component
{
// get indices, physical location and
// boundary values of dofs on this
// face
face->get_dof_indices (face_dofs);
fe_values.reinit(cell, face_no);
const std::vector<Point<dim> > &dof_locations = fe_values.get_quadrature_points ();
if (fe_is_system)
{
function_map.find(boundary_component)->second->vector_value_list (dof_locations,
dof_values_system);
// enter into list
for (unsigned int i=0; i<face_dofs.size(); ++i)
if (component_mask[fe.face_system_to_component_index(i).first])
boundary_values[face_dofs[i]]
= dof_values_system[i](fe.face_system_to_component_index(i).first);
}
else
// fe has only one component,
// so save some computations
{
// get only the one component that
// this function has
function_map.find(boundary_component)->second->value_list (dof_locations,
dof_values_scalar,
0);
// enter into list
for (unsigned int i=0; i<face_dofs.size(); ++i)
boundary_values[face_dofs[i]] = dof_values_scalar[i];
}
}
}
}
template <int dim>
void
VectorTools::interpolate_boundary_values (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const unsigned char boundary_component,
const Function<dim> &boundary_function,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
typename FunctionMap<dim>::type function_map;
function_map[boundary_component] = &boundary_function;
interpolate_boundary_values (mapping, dof, function_map, boundary_values,
component_mask);
};
template <int dim>
void
VectorTools::interpolate_boundary_values (const DoFHandler<dim> &dof,
const unsigned char boundary_component,
const Function<dim> &boundary_function,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
interpolate_boundary_values(mapping, dof, boundary_component,
boundary_function, boundary_values, component_mask);
}
template <int dim>
void
VectorTools::interpolate_boundary_values (const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &function_map,
std::map<unsigned int,double> &boundary_values,
const std::vector<bool> &component_mask)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
interpolate_boundary_values(mapping, dof, function_map,
boundary_values, component_mask);
}
#if deal_II_dimension == 1
void
VectorTools::project_boundary_values (const Mapping<1> &mapping,
const DoFHandler<1> &dof,
const FunctionMap<1>::type &boundary_functions,
const Quadrature<0> &,
std::map<unsigned int,double> &boundary_values)
{
// projection in 1d is equivalent
// to interpolation
interpolate_boundary_values (mapping, dof, boundary_functions,
boundary_values, std::vector<bool>());
};
#endif
template <int dim>
void
VectorTools::project_boundary_values (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &boundary_functions,
const Quadrature<dim-1> &q,
std::map<unsigned int,double> &boundary_values)
{
//TODO:[?] In VectorTools::project_boundary_values, no condensation of sparsity
// structures, matrices and right hand sides or distribution of
// solution vectors is performed. This is ok for dim<3 because then
// there are no constrained nodes on the boundary, but is not
// acceptable for higher dimensions. Fix this.
Assert (dof.get_fe().n_components() == boundary_functions.begin()->second->n_components,
ExcComponentMismatch());
std::vector<unsigned int> dof_to_boundary_mapping;
std::set<unsigned char> selected_boundary_components;
for (typename FunctionMap<dim>::type::const_iterator i=boundary_functions.begin();
i!=boundary_functions.end(); ++i)
selected_boundary_components.insert (i->first);
DoFTools::map_dof_to_boundary_indices (dof, selected_boundary_components,
dof_to_boundary_mapping);
// set up sparsity structure
SparsityPattern sparsity(dof.n_boundary_dofs(boundary_functions),
dof.max_couplings_between_boundary_dofs());
DoFTools::make_boundary_sparsity_pattern (dof,
boundary_functions,
dof_to_boundary_mapping,
sparsity);
// note: for three or more dimensions, there
// may be constrained nodes on the boundary
// in this case the boundary mass matrix has
// to be condensed and the solution is to
// be distributed afterwards, which is not
// yet implemented. The reason for this is
// that we cannot simply use the @p{condense}
// family of functions, since the matrices
// and vectors do not use the global
// numbering but rather the boundary
// numbering, i.e. the condense function
// needs to use another indirection. There
// should be not many technical problems,
// but it needs to be implemented
if (dim<3)
sparsity.compress();
else
Assert (false, ExcNotImplemented());
// make mass matrix and right hand side
SparseMatrix<double> mass_matrix(sparsity);
Vector<double> rhs(sparsity.n_rows());
MatrixCreator::create_boundary_mass_matrix (mapping, dof, q,
mass_matrix, boundary_functions,
rhs, dof_to_boundary_mapping);
// same thing as above: if dim>=3 we need
// to consider constraints
Assert (dim<3, ExcNotImplemented());
Vector<double> boundary_projection (rhs.size());
SolverControl control(1000, 1e-16);
PrimitiveVectorMemory<> memory;
SolverCG<> cg(control,memory);
PreconditionSSOR<> prec;
prec.initialize(mass_matrix, 1.2);
// solve
cg.solve (mass_matrix, boundary_projection, rhs, prec);
// fill in boundary values
for (unsigned int i=0; i<dof_to_boundary_mapping.size(); ++i)
if (dof_to_boundary_mapping[i] != DoFHandler<dim>::invalid_dof_index)
// this dof is on one of the
// interesting boundary parts
//
// remember: @p{i} is the global dof
// number, @p{dof_to_boundary_mapping[i]}
// is the number on the boundary and
// thus in the solution vector
boundary_values[i] = boundary_projection(dof_to_boundary_mapping[i]);
};
template <int dim>
void
VectorTools::project_boundary_values (const DoFHandler<dim> &dof,
const typename FunctionMap<dim>::type &boundary_functions,
const Quadrature<dim-1> &q,
std::map<unsigned int,double> &boundary_values)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
project_boundary_values(mapping, dof, boundary_functions, q, boundary_values);
}
template <int dim, class InVector, class OutVector>
void
VectorTools::integrate_difference (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const InVector &fe_function,
const Function<dim> &exact_solution,
OutVector &difference,
const Quadrature<dim> &q,
const NormType &norm,
const Function<dim> *weight)
{
const unsigned int n_q_points = q.n_quadrature_points;
const FiniteElement<dim> &fe = dof.get_fe();
const unsigned int n_components = fe.n_components();
const bool fe_is_system = (n_components != 1);
if (weight!=0)
{
Assert ((weight->n_components==1) || (weight->n_components==n_components),
ExcDimensionMismatch(weight->n_components, n_components));
}
difference.reinit (dof.get_tria().n_active_cells());
UpdateFlags update_flags = UpdateFlags (update_q_points |
update_JxW_values);
if (norm != H1_seminorm)
update_flags = UpdateFlags(update_flags | update_values);
if ((norm==H1_seminorm) || (norm==H1_norm))
update_flags = UpdateFlags (update_flags | update_gradients);
FEValues<dim> fe_values(mapping, fe, q, update_flags);
std::vector< Vector<double> > function_values (n_q_points,
Vector<double>(n_components));
std::vector<std::vector<Tensor<1,dim> > > function_grads (n_q_points,
std::vector<Tensor<1,dim> >(n_components));
std::vector<double> weight_values (n_q_points);
std::vector<Vector<double> > weight_vectors (n_q_points,
Vector<double>(n_components));
std::vector<Vector<double> > psi_values (n_q_points,
Vector<double>(n_components));
std::vector<std::vector<Tensor<1,dim> > > psi_grads (n_q_points,
std::vector<Tensor<1,dim> >(n_components));
std::vector<double> psi_scalar (n_q_points);
// tmp vector when we use the
// Function<dim> functions for
// scalar functions
std::vector<double> tmp_values (fe_values.n_quadrature_points);
std::vector<Tensor<1,dim> > tmp_gradients (fe_values.n_quadrature_points);
// loop over all cells
typename DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(),
endc = dof.end();
for (unsigned int index=0; cell != endc; ++cell, ++index)
{
double diff=0;
// initialize for this cell
fe_values.reinit (cell);
if (weight!=0)
{
if (weight->n_components>1)
weight->vector_value_list (fe_values.get_quadrature_points(),
weight_vectors);
else
weight->value_list (fe_values.get_quadrature_points(),
weight_values);
}
switch (norm)
{
case mean:
case L1_norm:
case L2_norm:
case Linfty_norm:
case H1_norm:
{
// first compute the exact solution
// (vectors) at the quadrature points
// try to do this as efficient as
// possible by avoiding a second
// virtual function call in case
// the function really has only
// one component
if (fe_is_system)
exact_solution.vector_value_list (fe_values.get_quadrature_points(),
psi_values);
else
{
exact_solution.value_list (fe_values.get_quadrature_points(),
tmp_values);
for (unsigned int i=0; i<n_q_points; ++i)
psi_values[i](0) = tmp_values[i];
};
// then subtract finite element
// fe_function
fe_values.get_function_values (fe_function, function_values);
for (unsigned int q=0; q<n_q_points; ++q)
psi_values[q] -= function_values[q];
switch (norm)
{
case mean:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted mean value
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i)
* weight_vectors[q](i);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted mean value
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i)
* weight_values[q];
}
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// mean value
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i);
}
// Integration on one cell
diff = std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
break;
// Compute (weighted) squares
// in each quadrature point
case L2_norm:
case H1_norm:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted scalar product
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += psi_values[q](i)*psi_values[q](i)
* weight_vectors[q](i);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].norm_sqr()
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].norm_sqr();
// Integration on one cell
diff = std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
if (norm == L2_norm)
diff=std::sqrt(diff);
break;
case L1_norm:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
// weighted scalar product
for (unsigned int i=0; i<n_components; ++i)
psi_scalar[q] += std::fabs(psi_values[q](i))
* weight_vectors[q](i);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].l1_norm()
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].l1_norm();
// Integration on one cell
diff = std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
if (norm == L2_norm)
diff=std::sqrt(diff);
break;
case Linfty_norm:
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
psi_scalar[q] = 0;
for (unsigned int i=0; i<n_components; ++i)
{
double newval = std::fabs(psi_values[q](i))
* weight_vectors[q](i);
if (psi_scalar[q]<newval)
psi_scalar[q] = newval;
}
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].linfty_norm()
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = psi_values[q].linfty_norm();
// Maximum on one cell
diff = *std::max_element (psi_scalar.begin(), psi_scalar.end());
break;
default:
Assert (false, ExcNotImplemented());
}
// note: the H1_norm uses the result
// of the L2_norm and control goes
// over to the next case statement!
if (norm != H1_norm)
break;
};
case H1_seminorm:
{
// note: the computation of the
// H1_norm starts at the previous
// case statement, but continues
// here!
// Until now, @p{diff} includes the
// square of the L2_norm.
// in praxi: first compute
// exact fe_function vector
//
// try to be a little clever
// to avoid recursive virtual
// function calls when calling
// @p{gradient_list} for functions
// that are really scalar
// functions
if (fe_is_system)
exact_solution.vector_gradient_list (fe_values.get_quadrature_points(),
psi_grads);
else
{
exact_solution.gradient_list (fe_values.get_quadrature_points(),
tmp_gradients);
for (unsigned int i=0; i<n_q_points; ++i)
psi_grads[i][0] = tmp_gradients[i];
};
// then subtract finite element
// function_grads
fe_values.get_function_grads (fe_function, function_grads);
for (unsigned int k=0; k<n_components; ++k)
for (unsigned int q=0; q<n_q_points; ++q)
psi_grads[q][k] -= function_grads[q][k];
// take square of integrand
std::fill_n (psi_scalar.begin(), n_q_points, 0.0);
for (unsigned int k=0; k<n_components; ++k)
if (weight != 0)
{
// Different weights for
// each component?
if (weight->n_components > 1)
for (unsigned int q=0; q<n_q_points; ++q)
{
// weighted scalar product
psi_scalar[q] += sqr_point(psi_grads[q][k])
* weight_vectors[q](k);
}
else // weight->n_components == 1
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] = sqr_point(psi_grads[q][k])
* weight_values[q];
}
else // no weight function
for (unsigned int q=0; q<n_q_points; ++q)
psi_scalar[q] += sqr_point(psi_grads[q][k]);
// add seminorm to L_2 norm or
// to zero
diff += std::inner_product (psi_scalar.begin(), psi_scalar.end(),
fe_values.get_JxW_values().begin(),
0.0);
diff = std::sqrt(diff);
break;
};
default:
Assert (false, ExcNotImplemented());
};
// append result of this cell
// to the end of the vector
difference(index) = diff;
};
};
template <int dim, class InVector, class OutVector>
void
VectorTools::integrate_difference (const DoFHandler<dim> &dof,
const InVector &fe_function,
const Function<dim> &exact_solution,
OutVector &difference,
const Quadrature<dim> &q,
const NormType &norm,
const Function<dim> *weight)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
integrate_difference(mapping, dof, fe_function, exact_solution,
difference, q, norm, weight);
}
template <int dim>
double
VectorTools::compute_mean_value (const Mapping<dim> &mapping,
const DoFHandler<dim> &dof,
const Quadrature<dim> &quadrature,
Vector<double> &v,
const unsigned int component)
{
Assert (component < dof.get_fe().n_components(),
ExcIndexRange(component, 0, dof.get_fe().n_components()));
FEValues<dim> fe(mapping, dof.get_fe(), quadrature,
UpdateFlags(update_JxW_values
| update_values));
typename DoFHandler<dim>::active_cell_iterator c;
std::vector<Vector<double> > values(quadrature.n_quadrature_points,
Vector<double> (dof.get_fe().n_components()));
double mean = 0.;
double area = 0.;
// Compute mean value
for (c = dof.begin_active(); c != dof.end(); ++c)
{
fe.reinit (c);
fe.get_function_values(v, values);
for (unsigned int k=0; k< quadrature.n_quadrature_points; ++k)
{
mean += fe.JxW(k) * values[k](component);
area += fe.JxW(k);
};
};
return (mean/area);
};
template <int dim>
double
VectorTools::compute_mean_value (const DoFHandler<dim> &dof,
const Quadrature<dim> &quadrature,
Vector<double> &v,
const unsigned int component)
{
Assert (DEAL_II_COMPAT_MAPPING, ExcCompatibility("mapping"));
static const MappingQ1<dim> mapping;
return compute_mean_value(mapping, dof, quadrature, v, component);
}
// explicit instantiations
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<double>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<double>&);
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<float>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
Vector<float>&);
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<double>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<double>&);
template
void VectorTools::interpolate (const Mapping<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<float>&);
template
void VectorTools::interpolate (const DoFHandler<deal_II_dimension>&,
const Function<deal_II_dimension>&,
BlockVector<float>&);
template
void VectorTools::interpolate(const DoFHandler<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const FullMatrix<double>&,
const Vector<double>&,
Vector<double>&);
template
void VectorTools::interpolate(const DoFHandler<deal_II_dimension>&,
const DoFHandler<deal_II_dimension>&,
const FullMatrix<double>&,
const BlockVector<double>&,
BlockVector<double>&);
template
void VectorTools::project (const DoFHandler<deal_II_dimension> &,
const ConstraintMatrix &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const bool,
const Quadrature<deal_II_dimension-1> &,
const bool);
template
void VectorTools::create_right_hand_side (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &);
template
void VectorTools::create_right_hand_side (const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &);
#if deal_II_dimension != 1
template
void
VectorTools::create_boundary_right_hand_side (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension-1> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const std::set<unsigned char> &);
#endif
template
void
VectorTools::create_boundary_right_hand_side (const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension-1> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const std::set<unsigned char> &);
template
void VectorTools::interpolate_boundary_values (const DoFHandler<deal_II_dimension> &,
const unsigned char,
const Function<deal_II_dimension> &,
std::map<unsigned int,double> &,
const std::vector<bool> &);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const Vector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<double> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<float> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
template
void VectorTools::integrate_difference (const DoFHandler<deal_II_dimension> &,
const BlockVector<float> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const Quadrature<deal_II_dimension> &,
const NormType &,
const Function<deal_II_dimension> *);
#if deal_II_dimension != 1
template
void VectorTools::project_boundary_values (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const FunctionMap<deal_II_dimension>::type &,
const Quadrature<deal_II_dimension-1>&,
std::map<unsigned int,double> &);
#endif
template
void VectorTools::project_boundary_values (const DoFHandler<deal_II_dimension> &,
const FunctionMap<deal_II_dimension>::type &,
const Quadrature<deal_II_dimension-1>&,
std::map<unsigned int,double> &);
template
double VectorTools::compute_mean_value (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
Vector<double> &,
const unsigned int);
template
double VectorTools::compute_mean_value (const DoFHandler<deal_II_dimension> &,
const Quadrature<deal_II_dimension> &,
Vector<double> &,
const unsigned int);
// the following two functions are not derived from a template in 1d
// and thus need no explicit instantiation
#if deal_II_dimension > 1
template
void VectorTools::interpolate_boundary_values (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const unsigned char,
const Function<deal_II_dimension> &,
std::map<unsigned int,double> &,
const std::vector<bool> &);
template
void VectorTools::project (const Mapping<deal_II_dimension> &,
const DoFHandler<deal_II_dimension> &,
const ConstraintMatrix &,
const Quadrature<deal_II_dimension> &,
const Function<deal_II_dimension> &,
Vector<double> &,
const bool,
const Quadrature<deal_II_dimension-1> &,
const bool);
#endif
|
/**
* Daniel Sebastian Iliescu, http://dansil.net
* MIT License (MIT), http://opensource.org/licenses/MIT
*
* Tester for the various sorting algorithms.
*/
#include "sorts/bubble_sort.hpp"
#include "sorts/selection_sort.hpp"
#include "sorts/insertion_sort.hpp"
#include "sorts/merge_sort.hpp"
#include "sorts/quick_sort.hpp"
#include "utilities/generator.hpp"
#include <catch.hpp>
namespace
{
const std::string UNIT_NAME = "sort_";
}
namespace dsa
{
template< typename SortImplementation >
void sort_tester()
{
using value_type = std::int32_t;
constexpr auto ITERATIONS = 1000U;
std::array< value_type, ITERATIONS > container;
generator< value_type > generator;
generator.fill_buffer(
std::begin( container ),
std::end( container ) );
SortImplementation::sort(
std::begin( container ),
std::end( container ) );
REQUIRE(
std::is_sorted(
std::cbegin( container ),
std::cend( container ) ) );
}
TEST_CASE( ( UNIT_NAME + "bubble sort" ).c_str() )
{
sort_tester< bubble >();
}
TEST_CASE( ( UNIT_NAME + "selection sort (std implementation)" ).c_str() )
{
sort_tester< selection::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "selection sort (custom implementation)" ).c_str() )
{
sort_tester< selection::custom_implementation >();
}
TEST_CASE( ( UNIT_NAME + "insertion sort (std implementation)" ).c_str() )
{
sort_tester< insertion::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "insertion sort (custom implementation)" ).c_str() )
{
sort_tester< insertion::custom_implementation >();
}
TEST_CASE( ( UNIT_NAME + "merge sort (std implementation)" ).c_str() )
{
sort_tester< merge::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "merge sort (custom implementation)" ).c_str() )
{
sort_tester< merge::custom_implementation >();
}
TEST_CASE( ( UNIT_NAME + "quick sort" ).c_str() )
{
sort_tester< quick::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "quick sort (custom implementation)" ).c_str() )
{
sort_tester< quick::custom_implementation >();
}
}
Fix clang failures
/**
* Daniel Sebastian Iliescu, http://dansil.net
* MIT License (MIT), http://opensource.org/licenses/MIT
*
* Tester for the various sorting algorithms.
*/
#include "sorts/bubble_sort.hpp"
#include "sorts/selection_sort.hpp"
#include "sorts/insertion_sort.hpp"
#include "sorts/merge_sort.hpp"
#include "sorts/quick_sort.hpp"
#include "utilities/generator.hpp"
#include <catch.hpp>
#include <array>
namespace
{
const std::string UNIT_NAME = "sort_";
}
namespace dsa
{
template< typename SortImplementation >
void sort_tester()
{
using value_type = std::int32_t;
constexpr auto ITERATIONS = 1000U;
std::array< value_type, ITERATIONS > container;
generator< value_type > generator;
generator.fill_buffer(
std::begin( container ),
std::end( container ) );
SortImplementation::sort(
std::begin( container ),
std::end( container ) );
REQUIRE(
std::is_sorted(
std::cbegin( container ),
std::cend( container ) ) );
}
TEST_CASE( ( UNIT_NAME + "bubble sort" ).c_str() )
{
sort_tester< bubble >();
}
TEST_CASE( ( UNIT_NAME + "selection sort (std implementation)" ).c_str() )
{
sort_tester< selection::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "selection sort (custom implementation)" ).c_str() )
{
sort_tester< selection::custom_implementation >();
}
TEST_CASE( ( UNIT_NAME + "insertion sort (std implementation)" ).c_str() )
{
sort_tester< insertion::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "insertion sort (custom implementation)" ).c_str() )
{
sort_tester< insertion::custom_implementation >();
}
TEST_CASE( ( UNIT_NAME + "merge sort (std implementation)" ).c_str() )
{
sort_tester< merge::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "merge sort (custom implementation)" ).c_str() )
{
sort_tester< merge::custom_implementation >();
}
TEST_CASE( ( UNIT_NAME + "quick sort" ).c_str() )
{
sort_tester< quick::std_implementation >();
}
TEST_CASE( ( UNIT_NAME + "quick sort (custom implementation)" ).c_str() )
{
sort_tester< quick::custom_implementation >();
}
}
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_browser_view.h"
#include <vector>
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/gfx/geometry/rect.h"
namespace gin {
template <>
struct Converter<electron::AutoResizeFlags> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::AutoResizeFlags* auto_resize_flags) {
gin_helper::Dictionary params;
if (!ConvertFromV8(isolate, val, ¶ms)) {
return false;
}
uint8_t flags = 0;
bool width = false;
if (params.Get("width", &width) && width) {
flags |= electron::kAutoResizeWidth;
}
bool height = false;
if (params.Get("height", &height) && height) {
flags |= electron::kAutoResizeHeight;
}
bool horizontal = false;
if (params.Get("horizontal", &horizontal) && horizontal) {
flags |= electron::kAutoResizeHorizontal;
}
bool vertical = false;
if (params.Get("vertical", &vertical) && vertical) {
flags |= electron::kAutoResizeVertical;
}
*auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
return true;
}
};
} // namespace gin
namespace {
int32_t GetNextId() {
static int32_t next_id = 1;
return next_id++;
}
} // namespace
namespace electron {
namespace api {
gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};
BrowserView::BrowserView(gin::Arguments* args,
const gin_helper::Dictionary& options)
: id_(GetNextId()) {
v8::Isolate* isolate = args->isolate();
gin_helper::Dictionary web_preferences =
gin::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
v8::Local<v8::Value> value;
// Copy the webContents option to webPreferences. This is only used internally
// to implement nativeWindowOpen option.
if (options.Get("webContents", &value)) {
web_preferences.SetHidden("webContents", value);
}
auto web_contents =
WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
api_web_contents_->AddObserver(this);
Observe(web_contents->web_contents());
view_.reset(
NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}
void BrowserView::SetOwnerWindow(NativeWindow* window) {
// Ensure WebContents and BrowserView owner windows are in sync.
if (web_contents())
web_contents()->SetOwnerWindow(window);
owner_window_ = window ? window->GetWeakPtr() : nullptr;
}
BrowserView::~BrowserView() {
if (web_contents()) { // destroy() called without closing WebContents
web_contents()->RemoveObserver(this);
web_contents()->Destroy();
}
}
void BrowserView::WebContentsDestroyed() {
api_web_contents_ = nullptr;
web_contents_.Reset();
Unpin();
}
void BrowserView::OnDraggableRegionsUpdated(
const std::vector<mojom::DraggableRegionPtr>& regions) {
view_->UpdateDraggableRegions(regions);
}
// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create BrowserView before app is ready");
return gin::Handle<BrowserView>();
}
gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
auto handle =
gin::CreateHandle(args->isolate(), new BrowserView(args, options));
handle->Pin(args->isolate());
return handle;
}
void BrowserView::SetAutoResize(AutoResizeFlags flags) {
view_->SetAutoResizeFlags(flags);
}
void BrowserView::SetBounds(const gfx::Rect& bounds) {
view_->SetBounds(bounds);
}
gfx::Rect BrowserView::GetBounds() {
return view_->GetBounds();
}
void BrowserView::SetBackgroundColor(const std::string& color_name) {
if (!web_contents())
return;
auto* wc = web_contents()->web_contents();
wc->SetPageBaseBackgroundColor(ParseHexColor(color_name));
}
v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate);
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
// static
v8::Local<v8::ObjectTemplate> BrowserView::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
return gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("getBounds", &BrowserView::GetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.Build();
}
} // namespace api
} // namespace electron
namespace {
using electron::api::BrowserView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BrowserView", BrowserView::GetConstructor(context));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
fix: BrowserView setBackgroundColor needs two calls (#31863)
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_browser_view.h"
#include <vector>
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/gfx/geometry/rect.h"
namespace gin {
template <>
struct Converter<electron::AutoResizeFlags> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::AutoResizeFlags* auto_resize_flags) {
gin_helper::Dictionary params;
if (!ConvertFromV8(isolate, val, ¶ms)) {
return false;
}
uint8_t flags = 0;
bool width = false;
if (params.Get("width", &width) && width) {
flags |= electron::kAutoResizeWidth;
}
bool height = false;
if (params.Get("height", &height) && height) {
flags |= electron::kAutoResizeHeight;
}
bool horizontal = false;
if (params.Get("horizontal", &horizontal) && horizontal) {
flags |= electron::kAutoResizeHorizontal;
}
bool vertical = false;
if (params.Get("vertical", &vertical) && vertical) {
flags |= electron::kAutoResizeVertical;
}
*auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
return true;
}
};
} // namespace gin
namespace {
int32_t GetNextId() {
static int32_t next_id = 1;
return next_id++;
}
} // namespace
namespace electron {
namespace api {
gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};
BrowserView::BrowserView(gin::Arguments* args,
const gin_helper::Dictionary& options)
: id_(GetNextId()) {
v8::Isolate* isolate = args->isolate();
gin_helper::Dictionary web_preferences =
gin::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
v8::Local<v8::Value> value;
// Copy the webContents option to webPreferences. This is only used internally
// to implement nativeWindowOpen option.
if (options.Get("webContents", &value)) {
web_preferences.SetHidden("webContents", value);
}
auto web_contents =
WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
api_web_contents_->AddObserver(this);
Observe(web_contents->web_contents());
view_.reset(
NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}
void BrowserView::SetOwnerWindow(NativeWindow* window) {
// Ensure WebContents and BrowserView owner windows are in sync.
if (web_contents())
web_contents()->SetOwnerWindow(window);
owner_window_ = window ? window->GetWeakPtr() : nullptr;
}
BrowserView::~BrowserView() {
if (web_contents()) { // destroy() called without closing WebContents
web_contents()->RemoveObserver(this);
web_contents()->Destroy();
}
}
void BrowserView::WebContentsDestroyed() {
api_web_contents_ = nullptr;
web_contents_.Reset();
Unpin();
}
void BrowserView::OnDraggableRegionsUpdated(
const std::vector<mojom::DraggableRegionPtr>& regions) {
view_->UpdateDraggableRegions(regions);
}
// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create BrowserView before app is ready");
return gin::Handle<BrowserView>();
}
gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
auto handle =
gin::CreateHandle(args->isolate(), new BrowserView(args, options));
handle->Pin(args->isolate());
return handle;
}
void BrowserView::SetAutoResize(AutoResizeFlags flags) {
view_->SetAutoResizeFlags(flags);
}
void BrowserView::SetBounds(const gfx::Rect& bounds) {
view_->SetBounds(bounds);
}
gfx::Rect BrowserView::GetBounds() {
return view_->GetBounds();
}
void BrowserView::SetBackgroundColor(const std::string& color_name) {
view_->SetBackgroundColor(ParseHexColor(color_name));
if (web_contents()) {
auto* wc = web_contents()->web_contents();
wc->SetPageBaseBackgroundColor(ParseHexColor(color_name));
}
}
v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate);
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
// static
v8::Local<v8::ObjectTemplate> BrowserView::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
return gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("getBounds", &BrowserView::GetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.Build();
}
} // namespace api
} // namespace electron
namespace {
using electron::api::BrowserView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BrowserView", BrowserView::GetConstructor(context));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
|
// Copyright 2010 the V8 project authors. 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 Google Inc. 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 COPYRIGHT
// OWNER OR CONTRIBUTORS 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 "v8.h"
#if defined(V8_TARGET_ARCH_IA32)
#include "bootstrapper.h"
#include "codegen-inl.h"
#include "compiler.h"
#include "debug.h"
#include "ic-inl.h"
#include "jsregexp.h"
#include "parser.h"
#include "regexp-macro-assembler.h"
#include "regexp-stack.h"
#include "register-allocator-inl.h"
#include "runtime.h"
#include "scopes.h"
#include "virtual-frame-inl.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
// -------------------------------------------------------------------------
// Platform-specific FrameRegisterState functions.
void FrameRegisterState::Save(MacroAssembler* masm) const {
for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
int action = registers_[i];
if (action == kPush) {
__ push(RegisterAllocator::ToRegister(i));
} else if (action != kIgnore && (action & kSyncedFlag) == 0) {
__ mov(Operand(ebp, action), RegisterAllocator::ToRegister(i));
}
}
}
void FrameRegisterState::Restore(MacroAssembler* masm) const {
// Restore registers in reverse order due to the stack.
for (int i = RegisterAllocator::kNumRegisters - 1; i >= 0; i--) {
int action = registers_[i];
if (action == kPush) {
__ pop(RegisterAllocator::ToRegister(i));
} else if (action != kIgnore) {
action &= ~kSyncedFlag;
__ mov(RegisterAllocator::ToRegister(i), Operand(ebp, action));
}
}
}
#undef __
#define __ ACCESS_MASM(masm_)
// -------------------------------------------------------------------------
// Platform-specific DeferredCode functions.
void DeferredCode::SaveRegisters() {
frame_state_.Save(masm_);
}
void DeferredCode::RestoreRegisters() {
frame_state_.Restore(masm_);
}
// -------------------------------------------------------------------------
// Platform-specific RuntimeCallHelper functions.
void VirtualFrameRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
frame_state_->Save(masm);
}
void VirtualFrameRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
frame_state_->Restore(masm);
}
void ICRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
masm->EnterInternalFrame();
}
void ICRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
masm->LeaveInternalFrame();
}
// -------------------------------------------------------------------------
// CodeGenState implementation.
CodeGenState::CodeGenState(CodeGenerator* owner)
: owner_(owner),
destination_(NULL),
previous_(NULL) {
owner_->set_state(this);
}
CodeGenState::CodeGenState(CodeGenerator* owner,
ControlDestination* destination)
: owner_(owner),
destination_(destination),
previous_(owner->state()) {
owner_->set_state(this);
}
CodeGenState::~CodeGenState() {
ASSERT(owner_->state() == this);
owner_->set_state(previous_);
}
// -------------------------------------------------------------------------
// CodeGenerator implementation
CodeGenerator::CodeGenerator(MacroAssembler* masm)
: deferred_(8),
masm_(masm),
info_(NULL),
frame_(NULL),
allocator_(NULL),
state_(NULL),
loop_nesting_(0),
in_safe_int32_mode_(false),
safe_int32_mode_enabled_(true),
function_return_is_shadowed_(false),
in_spilled_code_(false) {
}
// Calling conventions:
// ebp: caller's frame pointer
// esp: stack pointer
// edi: called JS function
// esi: callee's context
void CodeGenerator::Generate(CompilationInfo* info) {
// Record the position for debugging purposes.
CodeForFunctionPosition(info->function());
Comment cmnt(masm_, "[ function compiled by virtual frame code generator");
// Initialize state.
info_ = info;
ASSERT(allocator_ == NULL);
RegisterAllocator register_allocator(this);
allocator_ = ®ister_allocator;
ASSERT(frame_ == NULL);
frame_ = new VirtualFrame();
set_in_spilled_code(false);
// Adjust for function-level loop nesting.
ASSERT_EQ(0, loop_nesting_);
loop_nesting_ = info->loop_nesting();
JumpTarget::set_compiling_deferred_code(false);
#ifdef DEBUG
if (strlen(FLAG_stop_at) > 0 &&
info->function()->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
frame_->SpillAll();
__ int3();
}
#endif
// New scope to get automatic timing calculation.
{ HistogramTimerScope codegen_timer(&Counters::code_generation);
CodeGenState state(this);
// Entry:
// Stack: receiver, arguments, return address.
// ebp: caller's frame pointer
// esp: stack pointer
// edi: called JS function
// esi: callee's context
allocator_->Initialize();
if (info->mode() == CompilationInfo::PRIMARY) {
frame_->Enter();
// Allocate space for locals and initialize them.
frame_->AllocateStackSlots();
// Allocate the local context if needed.
int heap_slots = scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
if (heap_slots > 0) {
Comment cmnt(masm_, "[ allocate local context");
// Allocate local context.
// Get outer context and create a new context based on it.
frame_->PushFunction();
Result context;
if (heap_slots <= FastNewContextStub::kMaximumSlots) {
FastNewContextStub stub(heap_slots);
context = frame_->CallStub(&stub, 1);
} else {
context = frame_->CallRuntime(Runtime::kNewContext, 1);
}
// Update context local.
frame_->SaveContextRegister();
// Verify that the runtime call result and esi agree.
if (FLAG_debug_code) {
__ cmp(context.reg(), Operand(esi));
__ Assert(equal, "Runtime::NewContext should end up in esi");
}
}
// TODO(1241774): Improve this code:
// 1) only needed if we have a context
// 2) no need to recompute context ptr every single time
// 3) don't copy parameter operand code from SlotOperand!
{
Comment cmnt2(masm_, "[ copy context parameters into .context");
// Note that iteration order is relevant here! If we have the same
// parameter twice (e.g., function (x, y, x)), and that parameter
// needs to be copied into the context, it must be the last argument
// passed to the parameter that needs to be copied. This is a rare
// case so we don't check for it, instead we rely on the copying
// order: such a parameter is copied repeatedly into the same
// context location and thus the last value is what is seen inside
// the function.
for (int i = 0; i < scope()->num_parameters(); i++) {
Variable* par = scope()->parameter(i);
Slot* slot = par->slot();
if (slot != NULL && slot->type() == Slot::CONTEXT) {
// The use of SlotOperand below is safe in unspilled code
// because the slot is guaranteed to be a context slot.
//
// There are no parameters in the global scope.
ASSERT(!scope()->is_global_scope());
frame_->PushParameterAt(i);
Result value = frame_->Pop();
value.ToRegister();
// SlotOperand loads context.reg() with the context object
// stored to, used below in RecordWrite.
Result context = allocator_->Allocate();
ASSERT(context.is_valid());
__ mov(SlotOperand(slot, context.reg()), value.reg());
int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_valid());
frame_->Spill(context.reg());
frame_->Spill(value.reg());
__ RecordWrite(context.reg(), offset, value.reg(), scratch.reg());
}
}
}
// Store the arguments object. This must happen after context
// initialization because the arguments object may be stored in
// the context.
if (ArgumentsMode() != NO_ARGUMENTS_ALLOCATION) {
StoreArgumentsObject(true);
}
// Initialize ThisFunction reference if present.
if (scope()->is_function_scope() && scope()->function() != NULL) {
frame_->Push(Factory::the_hole_value());
StoreToSlot(scope()->function()->slot(), NOT_CONST_INIT);
}
} else {
// When used as the secondary compiler for splitting, ebp, esi,
// and edi have been pushed on the stack. Adjust the virtual
// frame to match this state.
frame_->Adjust(3);
allocator_->Unuse(edi);
// Bind all the bailout labels to the beginning of the function.
List<CompilationInfo::Bailout*>* bailouts = info->bailouts();
for (int i = 0; i < bailouts->length(); i++) {
__ bind(bailouts->at(i)->label());
}
}
// Initialize the function return target after the locals are set
// up, because it needs the expected frame height from the frame.
function_return_.set_direction(JumpTarget::BIDIRECTIONAL);
function_return_is_shadowed_ = false;
// Generate code to 'execute' declarations and initialize functions
// (source elements). In case of an illegal redeclaration we need to
// handle that instead of processing the declarations.
if (scope()->HasIllegalRedeclaration()) {
Comment cmnt(masm_, "[ illegal redeclarations");
scope()->VisitIllegalRedeclaration(this);
} else {
Comment cmnt(masm_, "[ declarations");
ProcessDeclarations(scope()->declarations());
// Bail out if a stack-overflow exception occurred when processing
// declarations.
if (HasStackOverflow()) return;
}
if (FLAG_trace) {
frame_->CallRuntime(Runtime::kTraceEnter, 0);
// Ignore the return value.
}
CheckStack();
// Compile the body of the function in a vanilla state. Don't
// bother compiling all the code if the scope has an illegal
// redeclaration.
if (!scope()->HasIllegalRedeclaration()) {
Comment cmnt(masm_, "[ function body");
#ifdef DEBUG
bool is_builtin = Bootstrapper::IsActive();
bool should_trace =
is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
if (should_trace) {
frame_->CallRuntime(Runtime::kDebugTrace, 0);
// Ignore the return value.
}
#endif
VisitStatements(info->function()->body());
// Handle the return from the function.
if (has_valid_frame()) {
// If there is a valid frame, control flow can fall off the end of
// the body. In that case there is an implicit return statement.
ASSERT(!function_return_is_shadowed_);
CodeForReturnPosition(info->function());
frame_->PrepareForReturn();
Result undefined(Factory::undefined_value());
if (function_return_.is_bound()) {
function_return_.Jump(&undefined);
} else {
function_return_.Bind(&undefined);
GenerateReturnSequence(&undefined);
}
} else if (function_return_.is_linked()) {
// If the return target has dangling jumps to it, then we have not
// yet generated the return sequence. This can happen when (a)
// control does not flow off the end of the body so we did not
// compile an artificial return statement just above, and (b) there
// are return statements in the body but (c) they are all shadowed.
Result return_value;
function_return_.Bind(&return_value);
GenerateReturnSequence(&return_value);
}
}
}
// Adjust for function-level loop nesting.
ASSERT_EQ(info->loop_nesting(), loop_nesting_);
loop_nesting_ = 0;
// Code generation state must be reset.
ASSERT(state_ == NULL);
ASSERT(loop_nesting() == 0);
ASSERT(!function_return_is_shadowed_);
function_return_.Unuse();
DeleteFrame();
// Process any deferred code using the register allocator.
if (!HasStackOverflow()) {
HistogramTimerScope deferred_timer(&Counters::deferred_code_generation);
JumpTarget::set_compiling_deferred_code(true);
ProcessDeferred();
JumpTarget::set_compiling_deferred_code(false);
}
// There is no need to delete the register allocator, it is a
// stack-allocated local.
allocator_ = NULL;
}
Operand CodeGenerator::SlotOperand(Slot* slot, Register tmp) {
// Currently, this assertion will fail if we try to assign to
// a constant variable that is constant because it is read-only
// (such as the variable referring to a named function expression).
// We need to implement assignments to read-only variables.
// Ideally, we should do this during AST generation (by converting
// such assignments into expression statements); however, in general
// we may not be able to make the decision until past AST generation,
// that is when the entire program is known.
ASSERT(slot != NULL);
int index = slot->index();
switch (slot->type()) {
case Slot::PARAMETER:
return frame_->ParameterAt(index);
case Slot::LOCAL:
return frame_->LocalAt(index);
case Slot::CONTEXT: {
// Follow the context chain if necessary.
ASSERT(!tmp.is(esi)); // do not overwrite context register
Register context = esi;
int chain_length = scope()->ContextChainLength(slot->var()->scope());
for (int i = 0; i < chain_length; i++) {
// Load the closure.
// (All contexts, even 'with' contexts, have a closure,
// and it is the same for all contexts inside a function.
// There is no need to go to the function context first.)
__ mov(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
// Load the function context (which is the incoming, outer context).
__ mov(tmp, FieldOperand(tmp, JSFunction::kContextOffset));
context = tmp;
}
// We may have a 'with' context now. Get the function context.
// (In fact this mov may never be the needed, since the scope analysis
// may not permit a direct context access in this case and thus we are
// always at a function context. However it is safe to dereference be-
// cause the function context of a function context is itself. Before
// deleting this mov we should try to create a counter-example first,
// though...)
__ mov(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
return ContextOperand(tmp, index);
}
default:
UNREACHABLE();
return Operand(eax);
}
}
Operand CodeGenerator::ContextSlotOperandCheckExtensions(Slot* slot,
Result tmp,
JumpTarget* slow) {
ASSERT(slot->type() == Slot::CONTEXT);
ASSERT(tmp.is_register());
Register context = esi;
for (Scope* s = scope(); s != slot->var()->scope(); s = s->outer_scope()) {
if (s->num_heap_slots() > 0) {
if (s->calls_eval()) {
// Check that extension is NULL.
__ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
Immediate(0));
slow->Branch(not_equal, not_taken);
}
__ mov(tmp.reg(), ContextOperand(context, Context::CLOSURE_INDEX));
__ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
context = tmp.reg();
}
}
// Check that last extension is NULL.
__ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
slow->Branch(not_equal, not_taken);
__ mov(tmp.reg(), ContextOperand(context, Context::FCONTEXT_INDEX));
return ContextOperand(tmp.reg(), slot->index());
}
// Emit code to load the value of an expression to the top of the
// frame. If the expression is boolean-valued it may be compiled (or
// partially compiled) into control flow to the control destination.
// If force_control is true, control flow is forced.
void CodeGenerator::LoadCondition(Expression* expr,
ControlDestination* dest,
bool force_control) {
ASSERT(!in_spilled_code());
int original_height = frame_->height();
{ CodeGenState new_state(this, dest);
Visit(expr);
// If we hit a stack overflow, we may not have actually visited
// the expression. In that case, we ensure that we have a
// valid-looking frame state because we will continue to generate
// code as we unwind the C++ stack.
//
// It's possible to have both a stack overflow and a valid frame
// state (eg, a subexpression overflowed, visiting it returned
// with a dummied frame state, and visiting this expression
// returned with a normal-looking state).
if (HasStackOverflow() &&
!dest->is_used() &&
frame_->height() == original_height) {
dest->Goto(true);
}
}
if (force_control && !dest->is_used()) {
// Convert the TOS value into flow to the control destination.
ToBoolean(dest);
}
ASSERT(!(force_control && !dest->is_used()));
ASSERT(dest->is_used() || frame_->height() == original_height + 1);
}
void CodeGenerator::LoadAndSpill(Expression* expression) {
ASSERT(in_spilled_code());
set_in_spilled_code(false);
Load(expression);
frame_->SpillAll();
set_in_spilled_code(true);
}
void CodeGenerator::LoadInSafeInt32Mode(Expression* expr,
BreakTarget* unsafe_bailout) {
set_unsafe_bailout(unsafe_bailout);
set_in_safe_int32_mode(true);
Load(expr);
Result value = frame_->Pop();
ASSERT(frame_->HasNoUntaggedInt32Elements());
if (expr->GuaranteedSmiResult()) {
ConvertInt32ResultToSmi(&value);
} else {
ConvertInt32ResultToNumber(&value);
}
set_in_safe_int32_mode(false);
set_unsafe_bailout(NULL);
frame_->Push(&value);
}
void CodeGenerator::LoadWithSafeInt32ModeDisabled(Expression* expr) {
set_safe_int32_mode_enabled(false);
Load(expr);
set_safe_int32_mode_enabled(true);
}
void CodeGenerator::ConvertInt32ResultToSmi(Result* value) {
ASSERT(value->is_untagged_int32());
if (value->is_register()) {
__ add(value->reg(), Operand(value->reg()));
} else {
ASSERT(value->is_constant());
ASSERT(value->handle()->IsSmi());
}
value->set_untagged_int32(false);
value->set_type_info(TypeInfo::Smi());
}
void CodeGenerator::ConvertInt32ResultToNumber(Result* value) {
ASSERT(value->is_untagged_int32());
if (value->is_register()) {
Register val = value->reg();
JumpTarget done;
__ add(val, Operand(val));
done.Branch(no_overflow, value);
__ sar(val, 1);
// If there was an overflow, bits 30 and 31 of the original number disagree.
__ xor_(val, 0x80000000u);
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ cvtsi2sd(xmm0, Operand(val));
} else {
// Move val to ST[0] in the FPU
// Push and pop are safe with respect to the virtual frame because
// all synced elements are below the actual stack pointer.
__ push(val);
__ fild_s(Operand(esp, 0));
__ pop(val);
}
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_register());
Label allocation_failed;
__ AllocateHeapNumber(val, scratch.reg(),
no_reg, &allocation_failed);
VirtualFrame* clone = new VirtualFrame(frame_);
scratch.Unuse();
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ movdbl(FieldOperand(val, HeapNumber::kValueOffset), xmm0);
} else {
__ fstp_d(FieldOperand(val, HeapNumber::kValueOffset));
}
done.Jump(value);
// Establish the virtual frame, cloned from where AllocateHeapNumber
// jumped to allocation_failed.
RegisterFile empty_regs;
SetFrame(clone, &empty_regs);
__ bind(&allocation_failed);
unsafe_bailout_->Jump();
done.Bind(value);
} else {
ASSERT(value->is_constant());
}
value->set_untagged_int32(false);
value->set_type_info(TypeInfo::Integer32());
}
void CodeGenerator::Load(Expression* expr) {
#ifdef DEBUG
int original_height = frame_->height();
#endif
ASSERT(!in_spilled_code());
// If the expression should be a side-effect-free 32-bit int computation,
// compile that SafeInt32 path, and a bailout path.
if (!in_safe_int32_mode() &&
safe_int32_mode_enabled() &&
expr->side_effect_free() &&
expr->num_bit_ops() > 2 &&
CpuFeatures::IsSupported(SSE2)) {
BreakTarget unsafe_bailout;
JumpTarget done;
unsafe_bailout.set_expected_height(frame_->height());
LoadInSafeInt32Mode(expr, &unsafe_bailout);
done.Jump();
if (unsafe_bailout.is_linked()) {
unsafe_bailout.Bind();
LoadWithSafeInt32ModeDisabled(expr);
}
done.Bind();
} else {
JumpTarget true_target;
JumpTarget false_target;
ControlDestination dest(&true_target, &false_target, true);
LoadCondition(expr, &dest, false);
if (dest.false_was_fall_through()) {
// The false target was just bound.
JumpTarget loaded;
frame_->Push(Factory::false_value());
// There may be dangling jumps to the true target.
if (true_target.is_linked()) {
loaded.Jump();
true_target.Bind();
frame_->Push(Factory::true_value());
loaded.Bind();
}
} else if (dest.is_used()) {
// There is true, and possibly false, control flow (with true as
// the fall through).
JumpTarget loaded;
frame_->Push(Factory::true_value());
if (false_target.is_linked()) {
loaded.Jump();
false_target.Bind();
frame_->Push(Factory::false_value());
loaded.Bind();
}
} else {
// We have a valid value on top of the frame, but we still may
// have dangling jumps to the true and false targets from nested
// subexpressions (eg, the left subexpressions of the
// short-circuited boolean operators).
ASSERT(has_valid_frame());
if (true_target.is_linked() || false_target.is_linked()) {
JumpTarget loaded;
loaded.Jump(); // Don't lose the current TOS.
if (true_target.is_linked()) {
true_target.Bind();
frame_->Push(Factory::true_value());
if (false_target.is_linked()) {
loaded.Jump();
}
}
if (false_target.is_linked()) {
false_target.Bind();
frame_->Push(Factory::false_value());
}
loaded.Bind();
}
}
}
ASSERT(has_valid_frame());
ASSERT(frame_->height() == original_height + 1);
}
void CodeGenerator::LoadGlobal() {
if (in_spilled_code()) {
frame_->EmitPush(GlobalObject());
} else {
Result temp = allocator_->Allocate();
__ mov(temp.reg(), GlobalObject());
frame_->Push(&temp);
}
}
void CodeGenerator::LoadGlobalReceiver() {
Result temp = allocator_->Allocate();
Register reg = temp.reg();
__ mov(reg, GlobalObject());
__ mov(reg, FieldOperand(reg, GlobalObject::kGlobalReceiverOffset));
frame_->Push(&temp);
}
void CodeGenerator::LoadTypeofExpression(Expression* expr) {
// Special handling of identifiers as subexpressions of typeof.
Variable* variable = expr->AsVariableProxy()->AsVariable();
if (variable != NULL && !variable->is_this() && variable->is_global()) {
// For a global variable we build the property reference
// <global>.<variable> and perform a (regular non-contextual) property
// load to make sure we do not get reference errors.
Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
Literal key(variable->name());
Property property(&global, &key, RelocInfo::kNoPosition);
Reference ref(this, &property);
ref.GetValue();
} else if (variable != NULL && variable->slot() != NULL) {
// For a variable that rewrites to a slot, we signal it is the immediate
// subexpression of a typeof.
LoadFromSlotCheckForArguments(variable->slot(), INSIDE_TYPEOF);
} else {
// Anything else can be handled normally.
Load(expr);
}
}
ArgumentsAllocationMode CodeGenerator::ArgumentsMode() {
if (scope()->arguments() == NULL) return NO_ARGUMENTS_ALLOCATION;
ASSERT(scope()->arguments_shadow() != NULL);
// We don't want to do lazy arguments allocation for functions that
// have heap-allocated contexts, because it interfers with the
// uninitialized const tracking in the context objects.
return (scope()->num_heap_slots() > 0)
? EAGER_ARGUMENTS_ALLOCATION
: LAZY_ARGUMENTS_ALLOCATION;
}
Result CodeGenerator::StoreArgumentsObject(bool initial) {
ArgumentsAllocationMode mode = ArgumentsMode();
ASSERT(mode != NO_ARGUMENTS_ALLOCATION);
Comment cmnt(masm_, "[ store arguments object");
if (mode == LAZY_ARGUMENTS_ALLOCATION && initial) {
// When using lazy arguments allocation, we store the hole value
// as a sentinel indicating that the arguments object hasn't been
// allocated yet.
frame_->Push(Factory::the_hole_value());
} else {
ArgumentsAccessStub stub(ArgumentsAccessStub::NEW_OBJECT);
frame_->PushFunction();
frame_->PushReceiverSlotAddress();
frame_->Push(Smi::FromInt(scope()->num_parameters()));
Result result = frame_->CallStub(&stub, 3);
frame_->Push(&result);
}
Variable* arguments = scope()->arguments()->var();
Variable* shadow = scope()->arguments_shadow()->var();
ASSERT(arguments != NULL && arguments->slot() != NULL);
ASSERT(shadow != NULL && shadow->slot() != NULL);
JumpTarget done;
bool skip_arguments = false;
if (mode == LAZY_ARGUMENTS_ALLOCATION && !initial) {
// We have to skip storing into the arguments slot if it has already
// been written to. This can happen if the a function has a local
// variable named 'arguments'.
LoadFromSlot(arguments->slot(), NOT_INSIDE_TYPEOF);
Result probe = frame_->Pop();
if (probe.is_constant()) {
// We have to skip updating the arguments object if it has
// been assigned a proper value.
skip_arguments = !probe.handle()->IsTheHole();
} else {
__ cmp(Operand(probe.reg()), Immediate(Factory::the_hole_value()));
probe.Unuse();
done.Branch(not_equal);
}
}
if (!skip_arguments) {
StoreToSlot(arguments->slot(), NOT_CONST_INIT);
if (mode == LAZY_ARGUMENTS_ALLOCATION) done.Bind();
}
StoreToSlot(shadow->slot(), NOT_CONST_INIT);
return frame_->Pop();
}
//------------------------------------------------------------------------------
// CodeGenerator implementation of variables, lookups, and stores.
Reference::Reference(CodeGenerator* cgen,
Expression* expression,
bool persist_after_get)
: cgen_(cgen),
expression_(expression),
type_(ILLEGAL),
persist_after_get_(persist_after_get) {
cgen->LoadReference(this);
}
Reference::~Reference() {
ASSERT(is_unloaded() || is_illegal());
}
void CodeGenerator::LoadReference(Reference* ref) {
// References are loaded from both spilled and unspilled code. Set the
// state to unspilled to allow that (and explicitly spill after
// construction at the construction sites).
bool was_in_spilled_code = in_spilled_code_;
in_spilled_code_ = false;
Comment cmnt(masm_, "[ LoadReference");
Expression* e = ref->expression();
Property* property = e->AsProperty();
Variable* var = e->AsVariableProxy()->AsVariable();
if (property != NULL) {
// The expression is either a property or a variable proxy that rewrites
// to a property.
Load(property->obj());
if (property->key()->IsPropertyName()) {
ref->set_type(Reference::NAMED);
} else {
Load(property->key());
ref->set_type(Reference::KEYED);
}
} else if (var != NULL) {
// The expression is a variable proxy that does not rewrite to a
// property. Global variables are treated as named property references.
if (var->is_global()) {
// If eax is free, the register allocator prefers it. Thus the code
// generator will load the global object into eax, which is where
// LoadIC wants it. Most uses of Reference call LoadIC directly
// after the reference is created.
frame_->Spill(eax);
LoadGlobal();
ref->set_type(Reference::NAMED);
} else {
ASSERT(var->slot() != NULL);
ref->set_type(Reference::SLOT);
}
} else {
// Anything else is a runtime error.
Load(e);
frame_->CallRuntime(Runtime::kThrowReferenceError, 1);
}
in_spilled_code_ = was_in_spilled_code;
}
// ECMA-262, section 9.2, page 30: ToBoolean(). Pop the top of stack and
// convert it to a boolean in the condition code register or jump to
// 'false_target'/'true_target' as appropriate.
void CodeGenerator::ToBoolean(ControlDestination* dest) {
Comment cmnt(masm_, "[ ToBoolean");
// The value to convert should be popped from the frame.
Result value = frame_->Pop();
value.ToRegister();
if (value.is_integer32()) { // Also takes Smi case.
Comment cmnt(masm_, "ONLY_INTEGER_32");
if (FLAG_debug_code) {
Label ok;
__ AbortIfNotNumber(value.reg());
__ test(value.reg(), Immediate(kSmiTagMask));
__ j(zero, &ok);
__ fldz();
__ fld_d(FieldOperand(value.reg(), HeapNumber::kValueOffset));
__ FCmp();
__ j(not_zero, &ok);
__ Abort("Smi was wrapped in HeapNumber in output from bitop");
__ bind(&ok);
}
// In the integer32 case there are no Smis hidden in heap numbers, so we
// need only test for Smi zero.
__ test(value.reg(), Operand(value.reg()));
dest->false_target()->Branch(zero);
value.Unuse();
dest->Split(not_zero);
} else if (value.is_number()) {
Comment cmnt(masm_, "ONLY_NUMBER");
// Fast case if TypeInfo indicates only numbers.
if (FLAG_debug_code) {
__ AbortIfNotNumber(value.reg());
}
// Smi => false iff zero.
ASSERT(kSmiTag == 0);
__ test(value.reg(), Operand(value.reg()));
dest->false_target()->Branch(zero);
__ test(value.reg(), Immediate(kSmiTagMask));
dest->true_target()->Branch(zero);
__ fldz();
__ fld_d(FieldOperand(value.reg(), HeapNumber::kValueOffset));
__ FCmp();
value.Unuse();
dest->Split(not_zero);
} else {
// Fast case checks.
// 'false' => false.
__ cmp(value.reg(), Factory::false_value());
dest->false_target()->Branch(equal);
// 'true' => true.
__ cmp(value.reg(), Factory::true_value());
dest->true_target()->Branch(equal);
// 'undefined' => false.
__ cmp(value.reg(), Factory::undefined_value());
dest->false_target()->Branch(equal);
// Smi => false iff zero.
ASSERT(kSmiTag == 0);
__ test(value.reg(), Operand(value.reg()));
dest->false_target()->Branch(zero);
__ test(value.reg(), Immediate(kSmiTagMask));
dest->true_target()->Branch(zero);
// Call the stub for all other cases.
frame_->Push(&value); // Undo the Pop() from above.
ToBooleanStub stub;
Result temp = frame_->CallStub(&stub, 1);
// Convert the result to a condition code.
__ test(temp.reg(), Operand(temp.reg()));
temp.Unuse();
dest->Split(not_equal);
}
}
class FloatingPointHelper : public AllStatic {
public:
enum ArgLocation {
ARGS_ON_STACK,
ARGS_IN_REGISTERS
};
// Code pattern for loading a floating point value. Input value must
// be either a smi or a heap number object (fp value). Requirements:
// operand in register number. Returns operand as floating point number
// on FPU stack.
static void LoadFloatOperand(MacroAssembler* masm, Register number);
// Code pattern for loading floating point values. Input values must
// be either smi or heap number objects (fp values). Requirements:
// operand_1 on TOS+1 or in edx, operand_2 on TOS+2 or in eax.
// Returns operands as floating point numbers on FPU stack.
static void LoadFloatOperands(MacroAssembler* masm,
Register scratch,
ArgLocation arg_location = ARGS_ON_STACK);
// Similar to LoadFloatOperand but assumes that both operands are smis.
// Expects operands in edx, eax.
static void LoadFloatSmis(MacroAssembler* masm, Register scratch);
// Test if operands are smi or number objects (fp). Requirements:
// operand_1 in eax, operand_2 in edx; falls through on float
// operands, jumps to the non_float label otherwise.
static void CheckFloatOperands(MacroAssembler* masm,
Label* non_float,
Register scratch);
// Takes the operands in edx and eax and loads them as integers in eax
// and ecx.
static void LoadAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* operand_conversion_failure);
static void LoadNumbersAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* operand_conversion_failure);
static void LoadUnknownsAsIntegers(MacroAssembler* masm,
bool use_sse3,
Label* operand_conversion_failure);
// Test if operands are smis or heap numbers and load them
// into xmm0 and xmm1 if they are. Operands are in edx and eax.
// Leaves operands unchanged.
static void LoadSSE2Operands(MacroAssembler* masm);
// Test if operands are numbers (smi or HeapNumber objects), and load
// them into xmm0 and xmm1 if they are. Jump to label not_numbers if
// either operand is not a number. Operands are in edx and eax.
// Leaves operands unchanged.
static void LoadSSE2Operands(MacroAssembler* masm, Label* not_numbers);
// Similar to LoadSSE2Operands but assumes that both operands are smis.
// Expects operands in edx, eax.
static void LoadSSE2Smis(MacroAssembler* masm, Register scratch);
};
const char* GenericBinaryOpStub::GetName() {
if (name_ != NULL) return name_;
const int kMaxNameLength = 100;
name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
if (name_ == NULL) return "OOM";
const char* op_name = Token::Name(op_);
const char* overwrite_name;
switch (mode_) {
case NO_OVERWRITE: overwrite_name = "Alloc"; break;
case OVERWRITE_RIGHT: overwrite_name = "OverwriteRight"; break;
case OVERWRITE_LEFT: overwrite_name = "OverwriteLeft"; break;
default: overwrite_name = "UnknownOverwrite"; break;
}
OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
"GenericBinaryOpStub_%s_%s%s_%s%s_%s_%s",
op_name,
overwrite_name,
(flags_ & NO_SMI_CODE_IN_STUB) ? "_NoSmiInStub" : "",
args_in_registers_ ? "RegArgs" : "StackArgs",
args_reversed_ ? "_R" : "",
static_operands_type_.ToString(),
BinaryOpIC::GetName(runtime_operands_type_));
return name_;
}
// Call the specialized stub for a binary operation.
class DeferredInlineBinaryOperation: public DeferredCode {
public:
DeferredInlineBinaryOperation(Token::Value op,
Register dst,
Register left,
Register right,
TypeInfo left_info,
TypeInfo right_info,
OverwriteMode mode)
: op_(op), dst_(dst), left_(left), right_(right),
left_info_(left_info), right_info_(right_info), mode_(mode) {
set_comment("[ DeferredInlineBinaryOperation");
}
virtual void Generate();
private:
Token::Value op_;
Register dst_;
Register left_;
Register right_;
TypeInfo left_info_;
TypeInfo right_info_;
OverwriteMode mode_;
};
void DeferredInlineBinaryOperation::Generate() {
Label done;
if (CpuFeatures::IsSupported(SSE2) && ((op_ == Token::ADD) ||
(op_ ==Token::SUB) ||
(op_ == Token::MUL) ||
(op_ == Token::DIV))) {
CpuFeatures::Scope use_sse2(SSE2);
Label call_runtime, after_alloc_failure;
Label left_smi, right_smi, load_right, do_op;
if (!left_info_.IsSmi()) {
__ test(left_, Immediate(kSmiTagMask));
__ j(zero, &left_smi);
if (!left_info_.IsNumber()) {
__ cmp(FieldOperand(left_, HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, &call_runtime);
}
__ movdbl(xmm0, FieldOperand(left_, HeapNumber::kValueOffset));
if (mode_ == OVERWRITE_LEFT) {
__ mov(dst_, left_);
}
__ jmp(&load_right);
__ bind(&left_smi);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left_);
}
__ SmiUntag(left_);
__ cvtsi2sd(xmm0, Operand(left_));
__ SmiTag(left_);
if (mode_ == OVERWRITE_LEFT) {
Label alloc_failure;
__ push(left_);
__ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
__ pop(left_);
}
__ bind(&load_right);
if (!right_info_.IsSmi()) {
__ test(right_, Immediate(kSmiTagMask));
__ j(zero, &right_smi);
if (!right_info_.IsNumber()) {
__ cmp(FieldOperand(right_, HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, &call_runtime);
}
__ movdbl(xmm1, FieldOperand(right_, HeapNumber::kValueOffset));
if (mode_ == OVERWRITE_RIGHT) {
__ mov(dst_, right_);
} else if (mode_ == NO_OVERWRITE) {
Label alloc_failure;
__ push(left_);
__ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
__ pop(left_);
}
__ jmp(&do_op);
__ bind(&right_smi);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(right_);
}
__ SmiUntag(right_);
__ cvtsi2sd(xmm1, Operand(right_));
__ SmiTag(right_);
if (mode_ == OVERWRITE_RIGHT || mode_ == NO_OVERWRITE) {
Label alloc_failure;
__ push(left_);
__ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
__ pop(left_);
}
__ bind(&do_op);
switch (op_) {
case Token::ADD: __ addsd(xmm0, xmm1); break;
case Token::SUB: __ subsd(xmm0, xmm1); break;
case Token::MUL: __ mulsd(xmm0, xmm1); break;
case Token::DIV: __ divsd(xmm0, xmm1); break;
default: UNREACHABLE();
}
__ movdbl(FieldOperand(dst_, HeapNumber::kValueOffset), xmm0);
__ jmp(&done);
__ bind(&after_alloc_failure);
__ pop(left_);
__ bind(&call_runtime);
}
GenericBinaryOpStub stub(op_,
mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(left_info_, right_info_));
stub.GenerateCall(masm_, left_, right_);
if (!dst_.is(eax)) __ mov(dst_, eax);
__ bind(&done);
}
static TypeInfo CalculateTypeInfo(TypeInfo operands_type,
Token::Value op,
const Result& right,
const Result& left) {
// Set TypeInfo of result according to the operation performed.
// Rely on the fact that smis have a 31 bit payload on ia32.
ASSERT(kSmiValueSize == 31);
switch (op) {
case Token::COMMA:
return right.type_info();
case Token::OR:
case Token::AND:
// Result type can be either of the two input types.
return operands_type;
case Token::BIT_AND: {
// Anding with positive Smis will give you a Smi.
if (right.is_constant() && right.handle()->IsSmi() &&
Smi::cast(*right.handle())->value() >= 0) {
return TypeInfo::Smi();
} else if (left.is_constant() && left.handle()->IsSmi() &&
Smi::cast(*left.handle())->value() >= 0) {
return TypeInfo::Smi();
}
return (operands_type.IsSmi())
? TypeInfo::Smi()
: TypeInfo::Integer32();
}
case Token::BIT_OR: {
// Oring with negative Smis will give you a Smi.
if (right.is_constant() && right.handle()->IsSmi() &&
Smi::cast(*right.handle())->value() < 0) {
return TypeInfo::Smi();
} else if (left.is_constant() && left.handle()->IsSmi() &&
Smi::cast(*left.handle())->value() < 0) {
return TypeInfo::Smi();
}
return (operands_type.IsSmi())
? TypeInfo::Smi()
: TypeInfo::Integer32();
}
case Token::BIT_XOR:
// Result is always a 32 bit integer. Smi property of inputs is preserved.
return (operands_type.IsSmi())
? TypeInfo::Smi()
: TypeInfo::Integer32();
case Token::SAR:
if (left.is_smi()) return TypeInfo::Smi();
// Result is a smi if we shift by a constant >= 1, otherwise an integer32.
// Shift amount is masked with 0x1F (ECMA standard 11.7.2).
return (right.is_constant() && right.handle()->IsSmi()
&& (Smi::cast(*right.handle())->value() & 0x1F) >= 1)
? TypeInfo::Smi()
: TypeInfo::Integer32();
case Token::SHR:
// Result is a smi if we shift by a constant >= 2, an integer32 if
// we shift by 1, and an unsigned 32-bit integer if we shift by 0.
if (right.is_constant() && right.handle()->IsSmi()) {
int shift_amount = Smi::cast(*right.handle())->value() & 0x1F;
if (shift_amount > 1) {
return TypeInfo::Smi();
} else if (shift_amount > 0) {
return TypeInfo::Integer32();
}
}
return TypeInfo::Number();
case Token::ADD:
if (operands_type.IsSmi()) {
// The Integer32 range is big enough to take the sum of any two Smis.
return TypeInfo::Integer32();
} else if (operands_type.IsNumber()) {
return TypeInfo::Number();
} else if (left.type_info().IsString() || right.type_info().IsString()) {
return TypeInfo::String();
} else {
return TypeInfo::Unknown();
}
case Token::SHL:
return TypeInfo::Integer32();
case Token::SUB:
// The Integer32 range is big enough to take the difference of any two
// Smis.
return (operands_type.IsSmi()) ?
TypeInfo::Integer32() :
TypeInfo::Number();
case Token::MUL:
case Token::DIV:
case Token::MOD:
// Result is always a number.
return TypeInfo::Number();
default:
UNREACHABLE();
}
UNREACHABLE();
return TypeInfo::Unknown();
}
void CodeGenerator::GenericBinaryOperation(BinaryOperation* expr,
OverwriteMode overwrite_mode) {
Comment cmnt(masm_, "[ BinaryOperation");
Token::Value op = expr->op();
Comment cmnt_token(masm_, Token::String(op));
if (op == Token::COMMA) {
// Simply discard left value.
frame_->Nip(1);
return;
}
Result right = frame_->Pop();
Result left = frame_->Pop();
if (op == Token::ADD) {
const bool left_is_string = left.type_info().IsString();
const bool right_is_string = right.type_info().IsString();
// Make sure constant strings have string type info.
ASSERT(!(left.is_constant() && left.handle()->IsString()) ||
left_is_string);
ASSERT(!(right.is_constant() && right.handle()->IsString()) ||
right_is_string);
if (left_is_string || right_is_string) {
frame_->Push(&left);
frame_->Push(&right);
Result answer;
if (left_is_string) {
if (right_is_string) {
StringAddStub stub(NO_STRING_CHECK_IN_STUB);
answer = frame_->CallStub(&stub, 2);
} else {
answer =
frame_->InvokeBuiltin(Builtins::STRING_ADD_LEFT, CALL_FUNCTION, 2);
}
} else if (right_is_string) {
answer =
frame_->InvokeBuiltin(Builtins::STRING_ADD_RIGHT, CALL_FUNCTION, 2);
}
answer.set_type_info(TypeInfo::String());
frame_->Push(&answer);
return;
}
// Neither operand is known to be a string.
}
bool left_is_smi_constant = left.is_constant() && left.handle()->IsSmi();
bool left_is_non_smi_constant = left.is_constant() && !left.handle()->IsSmi();
bool right_is_smi_constant = right.is_constant() && right.handle()->IsSmi();
bool right_is_non_smi_constant =
right.is_constant() && !right.handle()->IsSmi();
if (left_is_smi_constant && right_is_smi_constant) {
// Compute the constant result at compile time, and leave it on the frame.
int left_int = Smi::cast(*left.handle())->value();
int right_int = Smi::cast(*right.handle())->value();
if (FoldConstantSmis(op, left_int, right_int)) return;
}
// Get number type of left and right sub-expressions.
TypeInfo operands_type =
TypeInfo::Combine(left.type_info(), right.type_info());
TypeInfo result_type = CalculateTypeInfo(operands_type, op, right, left);
Result answer;
if (left_is_non_smi_constant || right_is_non_smi_constant) {
// Go straight to the slow case, with no smi code.
GenericBinaryOpStub stub(op,
overwrite_mode,
NO_SMI_CODE_IN_STUB,
operands_type);
answer = stub.GenerateCall(masm_, frame_, &left, &right);
} else if (right_is_smi_constant) {
answer = ConstantSmiBinaryOperation(expr, &left, right.handle(),
false, overwrite_mode);
} else if (left_is_smi_constant) {
answer = ConstantSmiBinaryOperation(expr, &right, left.handle(),
true, overwrite_mode);
} else {
// Set the flags based on the operation, type and loop nesting level.
// Bit operations always assume they likely operate on Smis. Still only
// generate the inline Smi check code if this operation is part of a loop.
// For all other operations only inline the Smi check code for likely smis
// if the operation is part of a loop.
if (loop_nesting() > 0 &&
(Token::IsBitOp(op) ||
operands_type.IsInteger32() ||
expr->type()->IsLikelySmi())) {
answer = LikelySmiBinaryOperation(expr, &left, &right, overwrite_mode);
} else {
GenericBinaryOpStub stub(op,
overwrite_mode,
NO_GENERIC_BINARY_FLAGS,
operands_type);
answer = stub.GenerateCall(masm_, frame_, &left, &right);
}
}
answer.set_type_info(result_type);
frame_->Push(&answer);
}
bool CodeGenerator::FoldConstantSmis(Token::Value op, int left, int right) {
Object* answer_object = Heap::undefined_value();
switch (op) {
case Token::ADD:
if (Smi::IsValid(left + right)) {
answer_object = Smi::FromInt(left + right);
}
break;
case Token::SUB:
if (Smi::IsValid(left - right)) {
answer_object = Smi::FromInt(left - right);
}
break;
case Token::MUL: {
double answer = static_cast<double>(left) * right;
if (answer >= Smi::kMinValue && answer <= Smi::kMaxValue) {
// If the product is zero and the non-zero factor is negative,
// the spec requires us to return floating point negative zero.
if (answer != 0 || (left >= 0 && right >= 0)) {
answer_object = Smi::FromInt(static_cast<int>(answer));
}
}
}
break;
case Token::DIV:
case Token::MOD:
break;
case Token::BIT_OR:
answer_object = Smi::FromInt(left | right);
break;
case Token::BIT_AND:
answer_object = Smi::FromInt(left & right);
break;
case Token::BIT_XOR:
answer_object = Smi::FromInt(left ^ right);
break;
case Token::SHL: {
int shift_amount = right & 0x1F;
if (Smi::IsValid(left << shift_amount)) {
answer_object = Smi::FromInt(left << shift_amount);
}
break;
}
case Token::SHR: {
int shift_amount = right & 0x1F;
unsigned int unsigned_left = left;
unsigned_left >>= shift_amount;
if (unsigned_left <= static_cast<unsigned int>(Smi::kMaxValue)) {
answer_object = Smi::FromInt(unsigned_left);
}
break;
}
case Token::SAR: {
int shift_amount = right & 0x1F;
unsigned int unsigned_left = left;
if (left < 0) {
// Perform arithmetic shift of a negative number by
// complementing number, logical shifting, complementing again.
unsigned_left = ~unsigned_left;
unsigned_left >>= shift_amount;
unsigned_left = ~unsigned_left;
} else {
unsigned_left >>= shift_amount;
}
ASSERT(Smi::IsValid(unsigned_left)); // Converted to signed.
answer_object = Smi::FromInt(unsigned_left); // Converted to signed.
break;
}
default:
UNREACHABLE();
break;
}
if (answer_object == Heap::undefined_value()) {
return false;
}
frame_->Push(Handle<Object>(answer_object));
return true;
}
static void CheckTwoForSminess(MacroAssembler* masm,
Register left, Register right, Register scratch,
TypeInfo left_info, TypeInfo right_info,
DeferredInlineBinaryOperation* deferred);
// Implements a binary operation using a deferred code object and some
// inline code to operate on smis quickly.
Result CodeGenerator::LikelySmiBinaryOperation(BinaryOperation* expr,
Result* left,
Result* right,
OverwriteMode overwrite_mode) {
// Copy the type info because left and right may be overwritten.
TypeInfo left_type_info = left->type_info();
TypeInfo right_type_info = right->type_info();
Token::Value op = expr->op();
Result answer;
// Special handling of div and mod because they use fixed registers.
if (op == Token::DIV || op == Token::MOD) {
// We need eax as the quotient register, edx as the remainder
// register, neither left nor right in eax or edx, and left copied
// to eax.
Result quotient;
Result remainder;
bool left_is_in_eax = false;
// Step 1: get eax for quotient.
if ((left->is_register() && left->reg().is(eax)) ||
(right->is_register() && right->reg().is(eax))) {
// One or both is in eax. Use a fresh non-edx register for
// them.
Result fresh = allocator_->Allocate();
ASSERT(fresh.is_valid());
if (fresh.reg().is(edx)) {
remainder = fresh;
fresh = allocator_->Allocate();
ASSERT(fresh.is_valid());
}
if (left->is_register() && left->reg().is(eax)) {
quotient = *left;
*left = fresh;
left_is_in_eax = true;
}
if (right->is_register() && right->reg().is(eax)) {
quotient = *right;
*right = fresh;
}
__ mov(fresh.reg(), eax);
} else {
// Neither left nor right is in eax.
quotient = allocator_->Allocate(eax);
}
ASSERT(quotient.is_register() && quotient.reg().is(eax));
ASSERT(!(left->is_register() && left->reg().is(eax)));
ASSERT(!(right->is_register() && right->reg().is(eax)));
// Step 2: get edx for remainder if necessary.
if (!remainder.is_valid()) {
if ((left->is_register() && left->reg().is(edx)) ||
(right->is_register() && right->reg().is(edx))) {
Result fresh = allocator_->Allocate();
ASSERT(fresh.is_valid());
if (left->is_register() && left->reg().is(edx)) {
remainder = *left;
*left = fresh;
}
if (right->is_register() && right->reg().is(edx)) {
remainder = *right;
*right = fresh;
}
__ mov(fresh.reg(), edx);
} else {
// Neither left nor right is in edx.
remainder = allocator_->Allocate(edx);
}
}
ASSERT(remainder.is_register() && remainder.reg().is(edx));
ASSERT(!(left->is_register() && left->reg().is(edx)));
ASSERT(!(right->is_register() && right->reg().is(edx)));
left->ToRegister();
right->ToRegister();
frame_->Spill(eax);
frame_->Spill(edx);
// Check that left and right are smi tagged.
DeferredInlineBinaryOperation* deferred =
new DeferredInlineBinaryOperation(op,
(op == Token::DIV) ? eax : edx,
left->reg(),
right->reg(),
left_type_info,
right_type_info,
overwrite_mode);
if (left->reg().is(right->reg())) {
__ test(left->reg(), Immediate(kSmiTagMask));
} else {
// Use the quotient register as a scratch for the tag check.
if (!left_is_in_eax) __ mov(eax, left->reg());
left_is_in_eax = false; // About to destroy the value in eax.
__ or_(eax, Operand(right->reg()));
ASSERT(kSmiTag == 0); // Adjust test if not the case.
__ test(eax, Immediate(kSmiTagMask));
}
deferred->Branch(not_zero);
if (!left_is_in_eax) __ mov(eax, left->reg());
// Sign extend eax into edx:eax.
__ cdq();
// Check for 0 divisor.
__ test(right->reg(), Operand(right->reg()));
deferred->Branch(zero);
// Divide edx:eax by the right operand.
__ idiv(right->reg());
// Complete the operation.
if (op == Token::DIV) {
// Check for negative zero result. If result is zero, and divisor
// is negative, return a floating point negative zero. The
// virtual frame is unchanged in this block, so local control flow
// can use a Label rather than a JumpTarget. If the context of this
// expression will treat -0 like 0, do not do this test.
if (!expr->no_negative_zero()) {
Label non_zero_result;
__ test(left->reg(), Operand(left->reg()));
__ j(not_zero, &non_zero_result);
__ test(right->reg(), Operand(right->reg()));
deferred->Branch(negative);
__ bind(&non_zero_result);
}
// Check for the corner case of dividing the most negative smi by
// -1. We cannot use the overflow flag, since it is not set by
// idiv instruction.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ cmp(eax, 0x40000000);
deferred->Branch(equal);
// Check that the remainder is zero.
__ test(edx, Operand(edx));
deferred->Branch(not_zero);
// Tag the result and store it in the quotient register.
__ SmiTag(eax);
deferred->BindExit();
left->Unuse();
right->Unuse();
answer = quotient;
} else {
ASSERT(op == Token::MOD);
// Check for a negative zero result. If the result is zero, and
// the dividend is negative, return a floating point negative
// zero. The frame is unchanged in this block, so local control
// flow can use a Label rather than a JumpTarget.
if (!expr->no_negative_zero()) {
Label non_zero_result;
__ test(edx, Operand(edx));
__ j(not_zero, &non_zero_result, taken);
__ test(left->reg(), Operand(left->reg()));
deferred->Branch(negative);
__ bind(&non_zero_result);
}
deferred->BindExit();
left->Unuse();
right->Unuse();
answer = remainder;
}
ASSERT(answer.is_valid());
return answer;
}
// Special handling of shift operations because they use fixed
// registers.
if (op == Token::SHL || op == Token::SHR || op == Token::SAR) {
// Move left out of ecx if necessary.
if (left->is_register() && left->reg().is(ecx)) {
*left = allocator_->Allocate();
ASSERT(left->is_valid());
__ mov(left->reg(), ecx);
}
right->ToRegister(ecx);
left->ToRegister();
ASSERT(left->is_register() && !left->reg().is(ecx));
ASSERT(right->is_register() && right->reg().is(ecx));
// We will modify right, it must be spilled.
frame_->Spill(ecx);
// Use a fresh answer register to avoid spilling the left operand.
answer = allocator_->Allocate();
ASSERT(answer.is_valid());
// Check that both operands are smis using the answer register as a
// temporary.
DeferredInlineBinaryOperation* deferred =
new DeferredInlineBinaryOperation(op,
answer.reg(),
left->reg(),
ecx,
left_type_info,
right_type_info,
overwrite_mode);
Label do_op, left_nonsmi;
// If right is a smi we make a fast case if left is either a smi
// or a heapnumber.
if (CpuFeatures::IsSupported(SSE2) && right_type_info.IsSmi()) {
CpuFeatures::Scope use_sse2(SSE2);
__ mov(answer.reg(), left->reg());
// Fast case - both are actually smis.
if (!left_type_info.IsSmi()) {
__ test(answer.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &left_nonsmi);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left->reg());
}
if (FLAG_debug_code) __ AbortIfNotSmi(right->reg());
__ SmiUntag(answer.reg());
__ jmp(&do_op);
__ bind(&left_nonsmi);
// Branch if not a heapnumber.
__ cmp(FieldOperand(answer.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
deferred->Branch(not_equal);
// Load integer value into answer register using truncation.
__ cvttsd2si(answer.reg(),
FieldOperand(answer.reg(), HeapNumber::kValueOffset));
// Branch if we do not fit in a smi.
__ cmp(answer.reg(), 0xc0000000);
deferred->Branch(negative);
} else {
CheckTwoForSminess(masm_, left->reg(), right->reg(), answer.reg(),
left_type_info, right_type_info, deferred);
// Untag both operands.
__ mov(answer.reg(), left->reg());
__ SmiUntag(answer.reg());
}
__ bind(&do_op);
__ SmiUntag(ecx);
// Perform the operation.
switch (op) {
case Token::SAR:
__ sar_cl(answer.reg());
// No checks of result necessary
break;
case Token::SHR: {
Label result_ok;
__ shr_cl(answer.reg());
// Check that the *unsigned* result fits in a smi. Neither of
// the two high-order bits can be set:
// * 0x80000000: high bit would be lost when smi tagging.
// * 0x40000000: this number would convert to negative when smi
// tagging.
// These two cases can only happen with shifts by 0 or 1 when
// handed a valid smi. If the answer cannot be represented by a
// smi, restore the left and right arguments, and jump to slow
// case. The low bit of the left argument may be lost, but only
// in a case where it is dropped anyway.
__ test(answer.reg(), Immediate(0xc0000000));
__ j(zero, &result_ok);
__ SmiTag(ecx);
deferred->Jump();
__ bind(&result_ok);
break;
}
case Token::SHL: {
Label result_ok;
__ shl_cl(answer.reg());
// Check that the *signed* result fits in a smi.
__ cmp(answer.reg(), 0xc0000000);
__ j(positive, &result_ok);
__ SmiTag(ecx);
deferred->Jump();
__ bind(&result_ok);
break;
}
default:
UNREACHABLE();
}
// Smi-tag the result in answer.
__ SmiTag(answer.reg());
deferred->BindExit();
left->Unuse();
right->Unuse();
ASSERT(answer.is_valid());
return answer;
}
// Handle the other binary operations.
left->ToRegister();
right->ToRegister();
// A newly allocated register answer is used to hold the answer. The
// registers containing left and right are not modified so they don't
// need to be spilled in the fast case.
answer = allocator_->Allocate();
ASSERT(answer.is_valid());
// Perform the smi tag check.
DeferredInlineBinaryOperation* deferred =
new DeferredInlineBinaryOperation(op,
answer.reg(),
left->reg(),
right->reg(),
left_type_info,
right_type_info,
overwrite_mode);
CheckTwoForSminess(masm_, left->reg(), right->reg(), answer.reg(),
left_type_info, right_type_info, deferred);
__ mov(answer.reg(), left->reg());
switch (op) {
case Token::ADD:
__ add(answer.reg(), Operand(right->reg()));
deferred->Branch(overflow);
break;
case Token::SUB:
__ sub(answer.reg(), Operand(right->reg()));
deferred->Branch(overflow);
break;
case Token::MUL: {
// If the smi tag is 0 we can just leave the tag on one operand.
ASSERT(kSmiTag == 0); // Adjust code below if not the case.
// Remove smi tag from the left operand (but keep sign).
// Left-hand operand has been copied into answer.
__ SmiUntag(answer.reg());
// Do multiplication of smis, leaving result in answer.
__ imul(answer.reg(), Operand(right->reg()));
// Go slow on overflows.
deferred->Branch(overflow);
// Check for negative zero result. If product is zero, and one
// argument is negative, go to slow case. The frame is unchanged
// in this block, so local control flow can use a Label rather
// than a JumpTarget.
if (!expr->no_negative_zero()) {
Label non_zero_result;
__ test(answer.reg(), Operand(answer.reg()));
__ j(not_zero, &non_zero_result, taken);
__ mov(answer.reg(), left->reg());
__ or_(answer.reg(), Operand(right->reg()));
deferred->Branch(negative);
__ xor_(answer.reg(), Operand(answer.reg())); // Positive 0 is correct.
__ bind(&non_zero_result);
}
break;
}
case Token::BIT_OR:
__ or_(answer.reg(), Operand(right->reg()));
break;
case Token::BIT_AND:
__ and_(answer.reg(), Operand(right->reg()));
break;
case Token::BIT_XOR:
__ xor_(answer.reg(), Operand(right->reg()));
break;
default:
UNREACHABLE();
break;
}
deferred->BindExit();
left->Unuse();
right->Unuse();
ASSERT(answer.is_valid());
return answer;
}
// Call the appropriate binary operation stub to compute src op value
// and leave the result in dst.
class DeferredInlineSmiOperation: public DeferredCode {
public:
DeferredInlineSmiOperation(Token::Value op,
Register dst,
Register src,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: op_(op),
dst_(dst),
src_(src),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
if (type_info.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
set_comment("[ DeferredInlineSmiOperation");
}
virtual void Generate();
private:
Token::Value op_;
Register dst_;
Register src_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiOperation::Generate() {
// For mod we don't generate all the Smi code inline.
GenericBinaryOpStub stub(
op_,
overwrite_mode_,
(op_ == Token::MOD) ? NO_GENERIC_BINARY_FLAGS : NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
stub.GenerateCall(masm_, src_, value_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// Call the appropriate binary operation stub to compute value op src
// and leave the result in dst.
class DeferredInlineSmiOperationReversed: public DeferredCode {
public:
DeferredInlineSmiOperationReversed(Token::Value op,
Register dst,
Smi* value,
Register src,
TypeInfo type_info,
OverwriteMode overwrite_mode)
: op_(op),
dst_(dst),
type_info_(type_info),
value_(value),
src_(src),
overwrite_mode_(overwrite_mode) {
set_comment("[ DeferredInlineSmiOperationReversed");
}
virtual void Generate();
private:
Token::Value op_;
Register dst_;
TypeInfo type_info_;
Smi* value_;
Register src_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiOperationReversed::Generate() {
GenericBinaryOpStub igostub(
op_,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, value_, src_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The result of src + value is in dst. It either overflowed or was not
// smi tagged. Undo the speculative addition and call the appropriate
// specialized stub for add. The result is left in dst.
class DeferredInlineSmiAdd: public DeferredCode {
public:
DeferredInlineSmiAdd(Register dst,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: dst_(dst),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
if (type_info_.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
set_comment("[ DeferredInlineSmiAdd");
}
virtual void Generate();
private:
Register dst_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiAdd::Generate() {
// Undo the optimistic add operation and call the shared stub.
__ sub(Operand(dst_), Immediate(value_));
GenericBinaryOpStub igostub(
Token::ADD,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, dst_, value_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The result of value + src is in dst. It either overflowed or was not
// smi tagged. Undo the speculative addition and call the appropriate
// specialized stub for add. The result is left in dst.
class DeferredInlineSmiAddReversed: public DeferredCode {
public:
DeferredInlineSmiAddReversed(Register dst,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: dst_(dst),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
set_comment("[ DeferredInlineSmiAddReversed");
}
virtual void Generate();
private:
Register dst_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiAddReversed::Generate() {
// Undo the optimistic add operation and call the shared stub.
__ sub(Operand(dst_), Immediate(value_));
GenericBinaryOpStub igostub(
Token::ADD,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, value_, dst_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The result of src - value is in dst. It either overflowed or was not
// smi tagged. Undo the speculative subtraction and call the
// appropriate specialized stub for subtract. The result is left in
// dst.
class DeferredInlineSmiSub: public DeferredCode {
public:
DeferredInlineSmiSub(Register dst,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: dst_(dst),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
if (type_info.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
set_comment("[ DeferredInlineSmiSub");
}
virtual void Generate();
private:
Register dst_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiSub::Generate() {
// Undo the optimistic sub operation and call the shared stub.
__ add(Operand(dst_), Immediate(value_));
GenericBinaryOpStub igostub(
Token::SUB,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, dst_, value_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
Result CodeGenerator::ConstantSmiBinaryOperation(BinaryOperation* expr,
Result* operand,
Handle<Object> value,
bool reversed,
OverwriteMode overwrite_mode) {
// Generate inline code for a binary operation when one of the
// operands is a constant smi. Consumes the argument "operand".
if (IsUnsafeSmi(value)) {
Result unsafe_operand(value);
if (reversed) {
return LikelySmiBinaryOperation(expr, &unsafe_operand, operand,
overwrite_mode);
} else {
return LikelySmiBinaryOperation(expr, operand, &unsafe_operand,
overwrite_mode);
}
}
// Get the literal value.
Smi* smi_value = Smi::cast(*value);
int int_value = smi_value->value();
Token::Value op = expr->op();
Result answer;
switch (op) {
case Token::ADD: {
operand->ToRegister();
frame_->Spill(operand->reg());
// Optimistically add. Call the specialized add stub if the
// result is not a smi or overflows.
DeferredCode* deferred = NULL;
if (reversed) {
deferred = new DeferredInlineSmiAddReversed(operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
} else {
deferred = new DeferredInlineSmiAdd(operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
}
__ add(Operand(operand->reg()), Immediate(value));
deferred->Branch(overflow);
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
deferred->BindExit();
answer = *operand;
break;
}
case Token::SUB: {
DeferredCode* deferred = NULL;
if (reversed) {
// The reversed case is only hit when the right operand is not a
// constant.
ASSERT(operand->is_register());
answer = allocator()->Allocate();
ASSERT(answer.is_valid());
__ Set(answer.reg(), Immediate(value));
deferred =
new DeferredInlineSmiOperationReversed(op,
answer.reg(),
smi_value,
operand->reg(),
operand->type_info(),
overwrite_mode);
__ sub(answer.reg(), Operand(operand->reg()));
} else {
operand->ToRegister();
frame_->Spill(operand->reg());
answer = *operand;
deferred = new DeferredInlineSmiSub(operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
__ sub(Operand(operand->reg()), Immediate(value));
}
deferred->Branch(overflow);
if (!operand->type_info().IsSmi()) {
__ test(answer.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
deferred->BindExit();
operand->Unuse();
break;
}
case Token::SAR:
if (reversed) {
Result constant_operand(value);
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
// Only the least significant 5 bits of the shift value are used.
// In the slow case, this masking is done inside the runtime call.
int shift_value = int_value & 0x1f;
operand->ToRegister();
frame_->Spill(operand->reg());
if (!operand->type_info().IsSmi()) {
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
if (shift_value > 0) {
__ sar(operand->reg(), shift_value);
__ and_(operand->reg(), ~kSmiTagMask);
}
deferred->BindExit();
} else {
if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
if (shift_value > 0) {
__ sar(operand->reg(), shift_value);
__ and_(operand->reg(), ~kSmiTagMask);
}
}
answer = *operand;
}
break;
case Token::SHR:
if (reversed) {
Result constant_operand(value);
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
// Only the least significant 5 bits of the shift value are used.
// In the slow case, this masking is done inside the runtime call.
int shift_value = int_value & 0x1f;
operand->ToRegister();
answer = allocator()->Allocate();
ASSERT(answer.is_valid());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
answer.reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
__ mov(answer.reg(), operand->reg());
__ SmiUntag(answer.reg());
__ shr(answer.reg(), shift_value);
// A negative Smi shifted right two is in the positive Smi range.
if (shift_value < 2) {
__ test(answer.reg(), Immediate(0xc0000000));
deferred->Branch(not_zero);
}
operand->Unuse();
__ SmiTag(answer.reg());
deferred->BindExit();
}
break;
case Token::SHL:
if (reversed) {
// Move operand into ecx and also into a second register.
// If operand is already in a register, take advantage of that.
// This lets us modify ecx, but still bail out to deferred code.
Result right;
Result right_copy_in_ecx;
TypeInfo right_type_info = operand->type_info();
operand->ToRegister();
if (operand->reg().is(ecx)) {
right = allocator()->Allocate();
__ mov(right.reg(), ecx);
frame_->Spill(ecx);
right_copy_in_ecx = *operand;
} else {
right_copy_in_ecx = allocator()->Allocate(ecx);
__ mov(ecx, operand->reg());
right = *operand;
}
operand->Unuse();
answer = allocator()->Allocate();
DeferredInlineSmiOperationReversed* deferred =
new DeferredInlineSmiOperationReversed(op,
answer.reg(),
smi_value,
right.reg(),
right_type_info,
overwrite_mode);
__ mov(answer.reg(), Immediate(int_value));
__ sar(ecx, kSmiTagSize);
if (!right_type_info.IsSmi()) {
deferred->Branch(carry);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(right.reg());
}
__ shl_cl(answer.reg());
__ cmp(answer.reg(), 0xc0000000);
deferred->Branch(sign);
__ SmiTag(answer.reg());
deferred->BindExit();
} else {
// Only the least significant 5 bits of the shift value are used.
// In the slow case, this masking is done inside the runtime call.
int shift_value = int_value & 0x1f;
operand->ToRegister();
if (shift_value == 0) {
// Spill operand so it can be overwritten in the slow case.
frame_->Spill(operand->reg());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
deferred->BindExit();
answer = *operand;
} else {
// Use a fresh temporary for nonzero shift values.
answer = allocator()->Allocate();
ASSERT(answer.is_valid());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
answer.reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
__ mov(answer.reg(), operand->reg());
ASSERT(kSmiTag == 0); // adjust code if not the case
// We do no shifts, only the Smi conversion, if shift_value is 1.
if (shift_value > 1) {
__ shl(answer.reg(), shift_value - 1);
}
// Convert int result to Smi, checking that it is in int range.
ASSERT(kSmiTagSize == 1); // adjust code if not the case
__ add(answer.reg(), Operand(answer.reg()));
deferred->Branch(overflow);
deferred->BindExit();
operand->Unuse();
}
}
break;
case Token::BIT_OR:
case Token::BIT_XOR:
case Token::BIT_AND: {
operand->ToRegister();
frame_->Spill(operand->reg());
DeferredCode* deferred = NULL;
if (reversed) {
deferred =
new DeferredInlineSmiOperationReversed(op,
operand->reg(),
smi_value,
operand->reg(),
operand->type_info(),
overwrite_mode);
} else {
deferred = new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
}
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
if (op == Token::BIT_AND) {
__ and_(Operand(operand->reg()), Immediate(value));
} else if (op == Token::BIT_XOR) {
if (int_value != 0) {
__ xor_(Operand(operand->reg()), Immediate(value));
}
} else {
ASSERT(op == Token::BIT_OR);
if (int_value != 0) {
__ or_(Operand(operand->reg()), Immediate(value));
}
}
deferred->BindExit();
answer = *operand;
break;
}
case Token::DIV:
if (!reversed && int_value == 2) {
operand->ToRegister();
frame_->Spill(operand->reg());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
// Check that lowest log2(value) bits of operand are zero, and test
// smi tag at the same time.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize);
__ test(operand->reg(), Immediate(3));
deferred->Branch(not_zero); // Branch if non-smi or odd smi.
__ sar(operand->reg(), 1);
deferred->BindExit();
answer = *operand;
} else {
// Cannot fall through MOD to default case, so we duplicate the
// default case here.
Result constant_operand(value);
if (reversed) {
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
answer = LikelySmiBinaryOperation(expr, operand, &constant_operand,
overwrite_mode);
}
}
break;
// Generate inline code for mod of powers of 2 and negative powers of 2.
case Token::MOD:
if (!reversed &&
int_value != 0 &&
(IsPowerOf2(int_value) || IsPowerOf2(-int_value))) {
operand->ToRegister();
frame_->Spill(operand->reg());
DeferredCode* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
// Check for negative or non-Smi left hand side.
__ test(operand->reg(), Immediate(kSmiTagMask | kSmiSignMask));
deferred->Branch(not_zero);
if (int_value < 0) int_value = -int_value;
if (int_value == 1) {
__ mov(operand->reg(), Immediate(Smi::FromInt(0)));
} else {
__ and_(operand->reg(), (int_value << kSmiTagSize) - 1);
}
deferred->BindExit();
answer = *operand;
break;
}
// Fall through if we did not find a power of 2 on the right hand side!
default: {
Result constant_operand(value);
if (reversed) {
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
answer = LikelySmiBinaryOperation(expr, operand, &constant_operand,
overwrite_mode);
}
break;
}
}
ASSERT(answer.is_valid());
return answer;
}
static bool CouldBeNaN(const Result& result) {
if (result.type_info().IsSmi()) return false;
if (result.type_info().IsInteger32()) return false;
if (!result.is_constant()) return true;
if (!result.handle()->IsHeapNumber()) return false;
return isnan(HeapNumber::cast(*result.handle())->value());
}
// Convert from signed to unsigned comparison to match the way EFLAGS are set
// by FPU and XMM compare instructions.
static Condition DoubleCondition(Condition cc) {
switch (cc) {
case less: return below;
case equal: return equal;
case less_equal: return below_equal;
case greater: return above;
case greater_equal: return above_equal;
default: UNREACHABLE();
}
UNREACHABLE();
return equal;
}
void CodeGenerator::Comparison(AstNode* node,
Condition cc,
bool strict,
ControlDestination* dest) {
// Strict only makes sense for equality comparisons.
ASSERT(!strict || cc == equal);
Result left_side;
Result right_side;
// Implement '>' and '<=' by reversal to obtain ECMA-262 conversion order.
if (cc == greater || cc == less_equal) {
cc = ReverseCondition(cc);
left_side = frame_->Pop();
right_side = frame_->Pop();
} else {
right_side = frame_->Pop();
left_side = frame_->Pop();
}
ASSERT(cc == less || cc == equal || cc == greater_equal);
// If either side is a constant of some sort, we can probably optimize the
// comparison.
bool left_side_constant_smi = false;
bool left_side_constant_null = false;
bool left_side_constant_1_char_string = false;
if (left_side.is_constant()) {
left_side_constant_smi = left_side.handle()->IsSmi();
left_side_constant_null = left_side.handle()->IsNull();
left_side_constant_1_char_string =
(left_side.handle()->IsString() &&
String::cast(*left_side.handle())->length() == 1 &&
String::cast(*left_side.handle())->IsAsciiRepresentation());
}
bool right_side_constant_smi = false;
bool right_side_constant_null = false;
bool right_side_constant_1_char_string = false;
if (right_side.is_constant()) {
right_side_constant_smi = right_side.handle()->IsSmi();
right_side_constant_null = right_side.handle()->IsNull();
right_side_constant_1_char_string =
(right_side.handle()->IsString() &&
String::cast(*right_side.handle())->length() == 1 &&
String::cast(*right_side.handle())->IsAsciiRepresentation());
}
if (left_side_constant_smi || right_side_constant_smi) {
if (left_side_constant_smi && right_side_constant_smi) {
// Trivial case, comparing two constants.
int left_value = Smi::cast(*left_side.handle())->value();
int right_value = Smi::cast(*right_side.handle())->value();
switch (cc) {
case less:
dest->Goto(left_value < right_value);
break;
case equal:
dest->Goto(left_value == right_value);
break;
case greater_equal:
dest->Goto(left_value >= right_value);
break;
default:
UNREACHABLE();
}
} else {
// Only one side is a constant Smi.
// If left side is a constant Smi, reverse the operands.
// Since one side is a constant Smi, conversion order does not matter.
if (left_side_constant_smi) {
Result temp = left_side;
left_side = right_side;
right_side = temp;
cc = ReverseCondition(cc);
// This may re-introduce greater or less_equal as the value of cc.
// CompareStub and the inline code both support all values of cc.
}
// Implement comparison against a constant Smi, inlining the case
// where both sides are Smis.
left_side.ToRegister();
Register left_reg = left_side.reg();
Handle<Object> right_val = right_side.handle();
// Here we split control flow to the stub call and inlined cases
// before finally splitting it to the control destination. We use
// a jump target and branching to duplicate the virtual frame at
// the first split. We manually handle the off-frame references
// by reconstituting them on the non-fall-through path.
if (left_side.is_smi()) {
if (FLAG_debug_code) {
__ AbortIfNotSmi(left_side.reg());
}
} else {
JumpTarget is_smi;
__ test(left_side.reg(), Immediate(kSmiTagMask));
is_smi.Branch(zero, taken);
bool is_loop_condition = (node->AsExpression() != NULL) &&
node->AsExpression()->is_loop_condition();
if (!is_loop_condition &&
CpuFeatures::IsSupported(SSE2) &&
right_val->IsSmi()) {
// Right side is a constant smi and left side has been checked
// not to be a smi.
CpuFeatures::Scope use_sse2(SSE2);
JumpTarget not_number;
__ cmp(FieldOperand(left_reg, HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
not_number.Branch(not_equal, &left_side);
__ movdbl(xmm1,
FieldOperand(left_reg, HeapNumber::kValueOffset));
int value = Smi::cast(*right_val)->value();
if (value == 0) {
__ xorpd(xmm0, xmm0);
} else {
Result temp = allocator()->Allocate();
__ mov(temp.reg(), Immediate(value));
__ cvtsi2sd(xmm0, Operand(temp.reg()));
temp.Unuse();
}
__ ucomisd(xmm1, xmm0);
// Jump to builtin for NaN.
not_number.Branch(parity_even, &left_side);
left_side.Unuse();
dest->true_target()->Branch(DoubleCondition(cc));
dest->false_target()->Jump();
not_number.Bind(&left_side);
}
// Setup and call the compare stub.
CompareStub stub(cc, strict, kCantBothBeNaN);
Result result = frame_->CallStub(&stub, &left_side, &right_side);
result.ToRegister();
__ cmp(result.reg(), 0);
result.Unuse();
dest->true_target()->Branch(cc);
dest->false_target()->Jump();
is_smi.Bind();
}
left_side = Result(left_reg);
right_side = Result(right_val);
// Test smi equality and comparison by signed int comparison.
if (IsUnsafeSmi(right_side.handle())) {
right_side.ToRegister();
__ cmp(left_side.reg(), Operand(right_side.reg()));
} else {
__ cmp(Operand(left_side.reg()), Immediate(right_side.handle()));
}
left_side.Unuse();
right_side.Unuse();
dest->Split(cc);
}
} else if (cc == equal &&
(left_side_constant_null || right_side_constant_null)) {
// To make null checks efficient, we check if either the left side or
// the right side is the constant 'null'.
// If so, we optimize the code by inlining a null check instead of
// calling the (very) general runtime routine for checking equality.
Result operand = left_side_constant_null ? right_side : left_side;
right_side.Unuse();
left_side.Unuse();
operand.ToRegister();
__ cmp(operand.reg(), Factory::null_value());
if (strict) {
operand.Unuse();
dest->Split(equal);
} else {
// The 'null' value is only equal to 'undefined' if using non-strict
// comparisons.
dest->true_target()->Branch(equal);
__ cmp(operand.reg(), Factory::undefined_value());
dest->true_target()->Branch(equal);
__ test(operand.reg(), Immediate(kSmiTagMask));
dest->false_target()->Branch(equal);
// It can be an undetectable object.
// Use a scratch register in preference to spilling operand.reg().
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(),
FieldOperand(operand.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
temp.Unuse();
operand.Unuse();
dest->Split(not_zero);
}
} else if (left_side_constant_1_char_string ||
right_side_constant_1_char_string) {
if (left_side_constant_1_char_string && right_side_constant_1_char_string) {
// Trivial case, comparing two constants.
int left_value = String::cast(*left_side.handle())->Get(0);
int right_value = String::cast(*right_side.handle())->Get(0);
switch (cc) {
case less:
dest->Goto(left_value < right_value);
break;
case equal:
dest->Goto(left_value == right_value);
break;
case greater_equal:
dest->Goto(left_value >= right_value);
break;
default:
UNREACHABLE();
}
} else {
// Only one side is a constant 1 character string.
// If left side is a constant 1-character string, reverse the operands.
// Since one side is a constant string, conversion order does not matter.
if (left_side_constant_1_char_string) {
Result temp = left_side;
left_side = right_side;
right_side = temp;
cc = ReverseCondition(cc);
// This may reintroduce greater or less_equal as the value of cc.
// CompareStub and the inline code both support all values of cc.
}
// Implement comparison against a constant string, inlining the case
// where both sides are strings.
left_side.ToRegister();
// Here we split control flow to the stub call and inlined cases
// before finally splitting it to the control destination. We use
// a jump target and branching to duplicate the virtual frame at
// the first split. We manually handle the off-frame references
// by reconstituting them on the non-fall-through path.
JumpTarget is_not_string, is_string;
Register left_reg = left_side.reg();
Handle<Object> right_val = right_side.handle();
ASSERT(StringShape(String::cast(*right_val)).IsSymbol());
__ test(left_side.reg(), Immediate(kSmiTagMask));
is_not_string.Branch(zero, &left_side);
Result temp = allocator_->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(),
FieldOperand(left_side.reg(), HeapObject::kMapOffset));
__ movzx_b(temp.reg(),
FieldOperand(temp.reg(), Map::kInstanceTypeOffset));
// If we are testing for equality then make use of the symbol shortcut.
// Check if the right left hand side has the same type as the left hand
// side (which is always a symbol).
if (cc == equal) {
Label not_a_symbol;
ASSERT(kSymbolTag != 0);
// Ensure that no non-strings have the symbol bit set.
ASSERT(kNotStringTag + kIsSymbolMask > LAST_TYPE);
__ test(temp.reg(), Immediate(kIsSymbolMask)); // Test the symbol bit.
__ j(zero, ¬_a_symbol);
// They are symbols, so do identity compare.
__ cmp(left_side.reg(), right_side.handle());
dest->true_target()->Branch(equal);
dest->false_target()->Branch(not_equal);
__ bind(¬_a_symbol);
}
// Call the compare stub if the left side is not a flat ascii string.
__ and_(temp.reg(),
kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
__ cmp(temp.reg(), kStringTag | kSeqStringTag | kAsciiStringTag);
temp.Unuse();
is_string.Branch(equal, &left_side);
// Setup and call the compare stub.
is_not_string.Bind(&left_side);
CompareStub stub(cc, strict, kCantBothBeNaN);
Result result = frame_->CallStub(&stub, &left_side, &right_side);
result.ToRegister();
__ cmp(result.reg(), 0);
result.Unuse();
dest->true_target()->Branch(cc);
dest->false_target()->Jump();
is_string.Bind(&left_side);
// left_side is a sequential ASCII string.
left_side = Result(left_reg);
right_side = Result(right_val);
// Test string equality and comparison.
Label comparison_done;
if (cc == equal) {
__ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Immediate(Smi::FromInt(1)));
__ j(not_equal, &comparison_done);
uint8_t char_value =
static_cast<uint8_t>(String::cast(*right_val)->Get(0));
__ cmpb(FieldOperand(left_side.reg(), SeqAsciiString::kHeaderSize),
char_value);
} else {
__ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Immediate(Smi::FromInt(1)));
// If the length is 0 then the jump is taken and the flags
// correctly represent being less than the one-character string.
__ j(below, &comparison_done);
// Compare the first character of the string with the
// constant 1-character string.
uint8_t char_value =
static_cast<uint8_t>(String::cast(*right_val)->Get(0));
__ cmpb(FieldOperand(left_side.reg(), SeqAsciiString::kHeaderSize),
char_value);
__ j(not_equal, &comparison_done);
// If the first character is the same then the long string sorts after
// the short one.
__ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Immediate(Smi::FromInt(1)));
}
__ bind(&comparison_done);
left_side.Unuse();
right_side.Unuse();
dest->Split(cc);
}
} else {
// Neither side is a constant Smi, constant 1-char string or constant null.
// If either side is a non-smi constant, or known to be a heap number skip
// the smi check.
bool known_non_smi =
(left_side.is_constant() && !left_side.handle()->IsSmi()) ||
(right_side.is_constant() && !right_side.handle()->IsSmi()) ||
left_side.type_info().IsDouble() ||
right_side.type_info().IsDouble();
NaNInformation nan_info =
(CouldBeNaN(left_side) && CouldBeNaN(right_side)) ?
kBothCouldBeNaN :
kCantBothBeNaN;
// Inline number comparison handling any combination of smi's and heap
// numbers if:
// code is in a loop
// the compare operation is different from equal
// compare is not a for-loop comparison
// The reason for excluding equal is that it will most likely be done
// with smi's (not heap numbers) and the code to comparing smi's is inlined
// separately. The same reason applies for for-loop comparison which will
// also most likely be smi comparisons.
bool is_loop_condition = (node->AsExpression() != NULL)
&& node->AsExpression()->is_loop_condition();
bool inline_number_compare =
loop_nesting() > 0 && cc != equal && !is_loop_condition;
// Left and right needed in registers for the following code.
left_side.ToRegister();
right_side.ToRegister();
if (known_non_smi) {
// Inline the equality check if both operands can't be a NaN. If both
// objects are the same they are equal.
if (nan_info == kCantBothBeNaN && cc == equal) {
__ cmp(left_side.reg(), Operand(right_side.reg()));
dest->true_target()->Branch(equal);
}
// Inline number comparison.
if (inline_number_compare) {
GenerateInlineNumberComparison(&left_side, &right_side, cc, dest);
}
// End of in-line compare, call out to the compare stub. Don't include
// number comparison in the stub if it was inlined.
CompareStub stub(cc, strict, nan_info, !inline_number_compare);
Result answer = frame_->CallStub(&stub, &left_side, &right_side);
__ test(answer.reg(), Operand(answer.reg()));
answer.Unuse();
dest->Split(cc);
} else {
// Here we split control flow to the stub call and inlined cases
// before finally splitting it to the control destination. We use
// a jump target and branching to duplicate the virtual frame at
// the first split. We manually handle the off-frame references
// by reconstituting them on the non-fall-through path.
JumpTarget is_smi;
Register left_reg = left_side.reg();
Register right_reg = right_side.reg();
// In-line check for comparing two smis.
Result temp = allocator_->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), left_side.reg());
__ or_(temp.reg(), Operand(right_side.reg()));
__ test(temp.reg(), Immediate(kSmiTagMask));
temp.Unuse();
is_smi.Branch(zero, taken);
// Inline the equality check if both operands can't be a NaN. If both
// objects are the same they are equal.
if (nan_info == kCantBothBeNaN && cc == equal) {
__ cmp(left_side.reg(), Operand(right_side.reg()));
dest->true_target()->Branch(equal);
}
// Inline number comparison.
if (inline_number_compare) {
GenerateInlineNumberComparison(&left_side, &right_side, cc, dest);
}
// End of in-line compare, call out to the compare stub. Don't include
// number comparison in the stub if it was inlined.
CompareStub stub(cc, strict, nan_info, !inline_number_compare);
Result answer = frame_->CallStub(&stub, &left_side, &right_side);
__ test(answer.reg(), Operand(answer.reg()));
answer.Unuse();
dest->true_target()->Branch(cc);
dest->false_target()->Jump();
is_smi.Bind();
left_side = Result(left_reg);
right_side = Result(right_reg);
__ cmp(left_side.reg(), Operand(right_side.reg()));
right_side.Unuse();
left_side.Unuse();
dest->Split(cc);
}
}
}
// Check that the comparison operand is a number. Jump to not_numbers jump
// target passing the left and right result if the operand is not a number.
static void CheckComparisonOperand(MacroAssembler* masm_,
Result* operand,
Result* left_side,
Result* right_side,
JumpTarget* not_numbers) {
// Perform check if operand is not known to be a number.
if (!operand->type_info().IsNumber()) {
Label done;
__ test(operand->reg(), Immediate(kSmiTagMask));
__ j(zero, &done);
__ cmp(FieldOperand(operand->reg(), HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
not_numbers->Branch(not_equal, left_side, right_side, not_taken);
__ bind(&done);
}
}
// Load a comparison operand to the FPU stack. This assumes that the operand has
// already been checked and is a number.
static void LoadComparisonOperand(MacroAssembler* masm_,
Result* operand) {
Label done;
if (operand->type_info().IsDouble()) {
// Operand is known to be a heap number, just load it.
__ fld_d(FieldOperand(operand->reg(), HeapNumber::kValueOffset));
} else if (operand->type_info().IsSmi()) {
// Operand is known to be a smi. Convert it to double and keep the original
// smi.
__ SmiUntag(operand->reg());
__ push(operand->reg());
__ fild_s(Operand(esp, 0));
__ pop(operand->reg());
__ SmiTag(operand->reg());
} else {
// Operand type not known, check for smi otherwise assume heap number.
Label smi;
__ test(operand->reg(), Immediate(kSmiTagMask));
__ j(zero, &smi);
__ fld_d(FieldOperand(operand->reg(), HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&smi);
__ SmiUntag(operand->reg());
__ push(operand->reg());
__ fild_s(Operand(esp, 0));
__ pop(operand->reg());
__ SmiTag(operand->reg());
__ jmp(&done);
}
__ bind(&done);
}
// Load a comparison operand into into a XMM register. Jump to not_numbers jump
// target passing the left and right result if the operand is not a number.
static void LoadComparisonOperandSSE2(MacroAssembler* masm_,
Result* operand,
XMMRegister reg,
Result* left_side,
Result* right_side,
JumpTarget* not_numbers) {
Label done;
if (operand->type_info().IsDouble()) {
// Operand is known to be a heap number, just load it.
__ movdbl(reg, FieldOperand(operand->reg(), HeapNumber::kValueOffset));
} else if (operand->type_info().IsSmi()) {
// Operand is known to be a smi. Convert it to double and keep the original
// smi.
__ SmiUntag(operand->reg());
__ cvtsi2sd(reg, Operand(operand->reg()));
__ SmiTag(operand->reg());
} else {
// Operand type not known, check for smi or heap number.
Label smi;
__ test(operand->reg(), Immediate(kSmiTagMask));
__ j(zero, &smi);
if (!operand->type_info().IsNumber()) {
__ cmp(FieldOperand(operand->reg(), HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
not_numbers->Branch(not_equal, left_side, right_side, taken);
}
__ movdbl(reg, FieldOperand(operand->reg(), HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&smi);
// Comvert smi to float and keep the original smi.
__ SmiUntag(operand->reg());
__ cvtsi2sd(reg, Operand(operand->reg()));
__ SmiTag(operand->reg());
__ jmp(&done);
}
__ bind(&done);
}
void CodeGenerator::GenerateInlineNumberComparison(Result* left_side,
Result* right_side,
Condition cc,
ControlDestination* dest) {
ASSERT(left_side->is_register());
ASSERT(right_side->is_register());
JumpTarget not_numbers;
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
// Load left and right operand into registers xmm0 and xmm1 and compare.
LoadComparisonOperandSSE2(masm_, left_side, xmm0, left_side, right_side,
¬_numbers);
LoadComparisonOperandSSE2(masm_, right_side, xmm1, left_side, right_side,
¬_numbers);
__ comisd(xmm0, xmm1);
} else {
Label check_right, compare;
// Make sure that both comparison operands are numbers.
CheckComparisonOperand(masm_, left_side, left_side, right_side,
¬_numbers);
CheckComparisonOperand(masm_, right_side, left_side, right_side,
¬_numbers);
// Load right and left operand to FPU stack and compare.
LoadComparisonOperand(masm_, right_side);
LoadComparisonOperand(masm_, left_side);
__ FCmp();
}
// Bail out if a NaN is involved.
not_numbers.Branch(parity_even, left_side, right_side, not_taken);
// Split to destination targets based on comparison.
left_side->Unuse();
right_side->Unuse();
dest->true_target()->Branch(DoubleCondition(cc));
dest->false_target()->Jump();
not_numbers.Bind(left_side, right_side);
}
// Call the function just below TOS on the stack with the given
// arguments. The receiver is the TOS.
void CodeGenerator::CallWithArguments(ZoneList<Expression*>* args,
CallFunctionFlags flags,
int position) {
// Push the arguments ("left-to-right") on the stack.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Record the position for debugging purposes.
CodeForSourcePosition(position);
// Use the shared code stub to call the function.
InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
CallFunctionStub call_function(arg_count, in_loop, flags);
Result answer = frame_->CallStub(&call_function, arg_count + 1);
// Restore context and replace function on the stack with the
// result of the stub invocation.
frame_->RestoreContextRegister();
frame_->SetElementAt(0, &answer);
}
void CodeGenerator::CallApplyLazy(Expression* applicand,
Expression* receiver,
VariableProxy* arguments,
int position) {
// An optimized implementation of expressions of the form
// x.apply(y, arguments).
// If the arguments object of the scope has not been allocated,
// and x.apply is Function.prototype.apply, this optimization
// just copies y and the arguments of the current function on the
// stack, as receiver and arguments, and calls x.
// In the implementation comments, we call x the applicand
// and y the receiver.
ASSERT(ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION);
ASSERT(arguments->IsArguments());
// Load applicand.apply onto the stack. This will usually
// give us a megamorphic load site. Not super, but it works.
Load(applicand);
frame()->Dup();
Handle<String> name = Factory::LookupAsciiSymbol("apply");
frame()->Push(name);
Result answer = frame()->CallLoadIC(RelocInfo::CODE_TARGET);
__ nop();
frame()->Push(&answer);
// Load the receiver and the existing arguments object onto the
// expression stack. Avoid allocating the arguments object here.
Load(receiver);
LoadFromSlot(scope()->arguments()->var()->slot(), NOT_INSIDE_TYPEOF);
// Emit the source position information after having loaded the
// receiver and the arguments.
CodeForSourcePosition(position);
// Contents of frame at this point:
// Frame[0]: arguments object of the current function or the hole.
// Frame[1]: receiver
// Frame[2]: applicand.apply
// Frame[3]: applicand.
// Check if the arguments object has been lazily allocated
// already. If so, just use that instead of copying the arguments
// from the stack. This also deals with cases where a local variable
// named 'arguments' has been introduced.
frame_->Dup();
Result probe = frame_->Pop();
{ VirtualFrame::SpilledScope spilled_scope;
Label slow, done;
bool try_lazy = true;
if (probe.is_constant()) {
try_lazy = probe.handle()->IsTheHole();
} else {
__ cmp(Operand(probe.reg()), Immediate(Factory::the_hole_value()));
probe.Unuse();
__ j(not_equal, &slow);
}
if (try_lazy) {
Label build_args;
// Get rid of the arguments object probe.
frame_->Drop(); // Can be called on a spilled frame.
// Stack now has 3 elements on it.
// Contents of stack at this point:
// esp[0]: receiver
// esp[1]: applicand.apply
// esp[2]: applicand.
// Check that the receiver really is a JavaScript object.
__ mov(eax, Operand(esp, 0));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &build_args);
// We allow all JSObjects including JSFunctions. As long as
// JS_FUNCTION_TYPE is the last instance type and it is right
// after LAST_JS_OBJECT_TYPE, we do not have to check the upper
// bound.
ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
__ j(below, &build_args);
// Check that applicand.apply is Function.prototype.apply.
__ mov(eax, Operand(esp, kPointerSize));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &build_args);
__ CmpObjectType(eax, JS_FUNCTION_TYPE, ecx);
__ j(not_equal, &build_args);
__ mov(ecx, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
Handle<Code> apply_code(Builtins::builtin(Builtins::FunctionApply));
__ cmp(FieldOperand(ecx, SharedFunctionInfo::kCodeOffset),
Immediate(apply_code));
__ j(not_equal, &build_args);
// Check that applicand is a function.
__ mov(edi, Operand(esp, 2 * kPointerSize));
__ test(edi, Immediate(kSmiTagMask));
__ j(zero, &build_args);
__ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
__ j(not_equal, &build_args);
// Copy the arguments to this function possibly from the
// adaptor frame below it.
Label invoke, adapted;
__ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
__ cmp(Operand(ecx),
Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &adapted);
// No arguments adaptor frame. Copy fixed number of arguments.
__ mov(eax, Immediate(scope()->num_parameters()));
for (int i = 0; i < scope()->num_parameters(); i++) {
__ push(frame_->ParameterAt(i));
}
__ jmp(&invoke);
// Arguments adaptor frame present. Copy arguments from there, but
// avoid copying too many arguments to avoid stack overflows.
__ bind(&adapted);
static const uint32_t kArgumentsLimit = 1 * KB;
__ mov(eax, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ SmiUntag(eax);
__ mov(ecx, Operand(eax));
__ cmp(eax, kArgumentsLimit);
__ j(above, &build_args);
// Loop through the arguments pushing them onto the execution
// stack. We don't inform the virtual frame of the push, so we don't
// have to worry about getting rid of the elements from the virtual
// frame.
Label loop;
// ecx is a small non-negative integer, due to the test above.
__ test(ecx, Operand(ecx));
__ j(zero, &invoke);
__ bind(&loop);
__ push(Operand(edx, ecx, times_pointer_size, 1 * kPointerSize));
__ dec(ecx);
__ j(not_zero, &loop);
// Invoke the function.
__ bind(&invoke);
ParameterCount actual(eax);
__ InvokeFunction(edi, actual, CALL_FUNCTION);
// Drop applicand.apply and applicand from the stack, and push
// the result of the function call, but leave the spilled frame
// unchanged, with 3 elements, so it is correct when we compile the
// slow-case code.
__ add(Operand(esp), Immediate(2 * kPointerSize));
__ push(eax);
// Stack now has 1 element:
// esp[0]: result
__ jmp(&done);
// Slow-case: Allocate the arguments object since we know it isn't
// there, and fall-through to the slow-case where we call
// applicand.apply.
__ bind(&build_args);
// Stack now has 3 elements, because we have jumped from where:
// esp[0]: receiver
// esp[1]: applicand.apply
// esp[2]: applicand.
// StoreArgumentsObject requires a correct frame, and may modify it.
Result arguments_object = StoreArgumentsObject(false);
frame_->SpillAll();
arguments_object.ToRegister();
frame_->EmitPush(arguments_object.reg());
arguments_object.Unuse();
// Stack and frame now have 4 elements.
__ bind(&slow);
}
// Generic computation of x.apply(y, args) with no special optimization.
// Flip applicand.apply and applicand on the stack, so
// applicand looks like the receiver of the applicand.apply call.
// Then process it as a normal function call.
__ mov(eax, Operand(esp, 3 * kPointerSize));
__ mov(ebx, Operand(esp, 2 * kPointerSize));
__ mov(Operand(esp, 2 * kPointerSize), eax);
__ mov(Operand(esp, 3 * kPointerSize), ebx);
CallFunctionStub call_function(2, NOT_IN_LOOP, NO_CALL_FUNCTION_FLAGS);
Result res = frame_->CallStub(&call_function, 3);
// The function and its two arguments have been dropped.
frame_->Drop(1); // Drop the receiver as well.
res.ToRegister();
frame_->EmitPush(res.reg());
// Stack now has 1 element:
// esp[0]: result
if (try_lazy) __ bind(&done);
} // End of spilled scope.
// Restore the context register after a call.
frame_->RestoreContextRegister();
}
class DeferredStackCheck: public DeferredCode {
public:
DeferredStackCheck() {
set_comment("[ DeferredStackCheck");
}
virtual void Generate();
};
void DeferredStackCheck::Generate() {
StackCheckStub stub;
__ CallStub(&stub);
}
void CodeGenerator::CheckStack() {
DeferredStackCheck* deferred = new DeferredStackCheck;
ExternalReference stack_limit =
ExternalReference::address_of_stack_limit();
__ cmp(esp, Operand::StaticVariable(stack_limit));
deferred->Branch(below);
deferred->BindExit();
}
void CodeGenerator::VisitAndSpill(Statement* statement) {
ASSERT(in_spilled_code());
set_in_spilled_code(false);
Visit(statement);
if (frame_ != NULL) {
frame_->SpillAll();
}
set_in_spilled_code(true);
}
void CodeGenerator::VisitStatementsAndSpill(ZoneList<Statement*>* statements) {
ASSERT(in_spilled_code());
set_in_spilled_code(false);
VisitStatements(statements);
if (frame_ != NULL) {
frame_->SpillAll();
}
set_in_spilled_code(true);
}
void CodeGenerator::VisitStatements(ZoneList<Statement*>* statements) {
ASSERT(!in_spilled_code());
for (int i = 0; has_valid_frame() && i < statements->length(); i++) {
Visit(statements->at(i));
}
}
void CodeGenerator::VisitBlock(Block* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ Block");
CodeForStatementPosition(node);
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
VisitStatements(node->statements());
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
node->break_target()->Unuse();
}
void CodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
// Call the runtime to declare the globals. The inevitable call
// will sync frame elements to memory anyway, so we do it eagerly to
// allow us to push the arguments directly into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi); // The context is the first argument.
frame_->EmitPush(Immediate(pairs));
frame_->EmitPush(Immediate(Smi::FromInt(is_eval() ? 1 : 0)));
Result ignored = frame_->CallRuntime(Runtime::kDeclareGlobals, 3);
// Return value is ignored.
}
void CodeGenerator::VisitDeclaration(Declaration* node) {
Comment cmnt(masm_, "[ Declaration");
Variable* var = node->proxy()->var();
ASSERT(var != NULL); // must have been resolved
Slot* slot = var->slot();
// If it was not possible to allocate the variable at compile time,
// we need to "declare" it at runtime to make sure it actually
// exists in the local context.
if (slot != NULL && slot->type() == Slot::LOOKUP) {
// Variables with a "LOOKUP" slot were introduced as non-locals
// during variable resolution and must have mode DYNAMIC.
ASSERT(var->is_dynamic());
// For now, just do a runtime call. Sync the virtual frame eagerly
// so we can simply push the arguments into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(var->name()));
// Declaration nodes are always introduced in one of two modes.
ASSERT(node->mode() == Variable::VAR || node->mode() == Variable::CONST);
PropertyAttributes attr = node->mode() == Variable::VAR ? NONE : READ_ONLY;
frame_->EmitPush(Immediate(Smi::FromInt(attr)));
// Push initial value, if any.
// Note: For variables we must not push an initial value (such as
// 'undefined') because we may have a (legal) redeclaration and we
// must not destroy the current value.
if (node->mode() == Variable::CONST) {
frame_->EmitPush(Immediate(Factory::the_hole_value()));
} else if (node->fun() != NULL) {
Load(node->fun());
} else {
frame_->EmitPush(Immediate(Smi::FromInt(0))); // no initial value!
}
Result ignored = frame_->CallRuntime(Runtime::kDeclareContextSlot, 4);
// Ignore the return value (declarations are statements).
return;
}
ASSERT(!var->is_global());
// If we have a function or a constant, we need to initialize the variable.
Expression* val = NULL;
if (node->mode() == Variable::CONST) {
val = new Literal(Factory::the_hole_value());
} else {
val = node->fun(); // NULL if we don't have a function
}
if (val != NULL) {
{
// Set the initial value.
Reference target(this, node->proxy());
Load(val);
target.SetValue(NOT_CONST_INIT);
// The reference is removed from the stack (preserving TOS) when
// it goes out of scope.
}
// Get rid of the assigned value (declarations are statements).
frame_->Drop();
}
}
void CodeGenerator::VisitExpressionStatement(ExpressionStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ExpressionStatement");
CodeForStatementPosition(node);
Expression* expression = node->expression();
expression->MarkAsStatement();
Load(expression);
// Remove the lingering expression result from the top of stack.
frame_->Drop();
}
void CodeGenerator::VisitEmptyStatement(EmptyStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "// EmptyStatement");
CodeForStatementPosition(node);
// nothing to do
}
void CodeGenerator::VisitIfStatement(IfStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ IfStatement");
// Generate different code depending on which parts of the if statement
// are present or not.
bool has_then_stm = node->HasThenStatement();
bool has_else_stm = node->HasElseStatement();
CodeForStatementPosition(node);
JumpTarget exit;
if (has_then_stm && has_else_stm) {
JumpTarget then;
JumpTarget else_;
ControlDestination dest(&then, &else_, true);
LoadCondition(node->condition(), &dest, true);
if (dest.false_was_fall_through()) {
// The else target was bound, so we compile the else part first.
Visit(node->else_statement());
// We may have dangling jumps to the then part.
if (then.is_linked()) {
if (has_valid_frame()) exit.Jump();
then.Bind();
Visit(node->then_statement());
}
} else {
// The then target was bound, so we compile the then part first.
Visit(node->then_statement());
if (else_.is_linked()) {
if (has_valid_frame()) exit.Jump();
else_.Bind();
Visit(node->else_statement());
}
}
} else if (has_then_stm) {
ASSERT(!has_else_stm);
JumpTarget then;
ControlDestination dest(&then, &exit, true);
LoadCondition(node->condition(), &dest, true);
if (dest.false_was_fall_through()) {
// The exit label was bound. We may have dangling jumps to the
// then part.
if (then.is_linked()) {
exit.Unuse();
exit.Jump();
then.Bind();
Visit(node->then_statement());
}
} else {
// The then label was bound.
Visit(node->then_statement());
}
} else if (has_else_stm) {
ASSERT(!has_then_stm);
JumpTarget else_;
ControlDestination dest(&exit, &else_, false);
LoadCondition(node->condition(), &dest, true);
if (dest.true_was_fall_through()) {
// The exit label was bound. We may have dangling jumps to the
// else part.
if (else_.is_linked()) {
exit.Unuse();
exit.Jump();
else_.Bind();
Visit(node->else_statement());
}
} else {
// The else label was bound.
Visit(node->else_statement());
}
} else {
ASSERT(!has_then_stm && !has_else_stm);
// We only care about the condition's side effects (not its value
// or control flow effect). LoadCondition is called without
// forcing control flow.
ControlDestination dest(&exit, &exit, true);
LoadCondition(node->condition(), &dest, false);
if (!dest.is_used()) {
// We got a value on the frame rather than (or in addition to)
// control flow.
frame_->Drop();
}
}
if (exit.is_linked()) {
exit.Bind();
}
}
void CodeGenerator::VisitContinueStatement(ContinueStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ContinueStatement");
CodeForStatementPosition(node);
node->target()->continue_target()->Jump();
}
void CodeGenerator::VisitBreakStatement(BreakStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ BreakStatement");
CodeForStatementPosition(node);
node->target()->break_target()->Jump();
}
void CodeGenerator::VisitReturnStatement(ReturnStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ReturnStatement");
CodeForStatementPosition(node);
Load(node->expression());
Result return_value = frame_->Pop();
masm()->WriteRecordedPositions();
if (function_return_is_shadowed_) {
function_return_.Jump(&return_value);
} else {
frame_->PrepareForReturn();
if (function_return_.is_bound()) {
// If the function return label is already bound we reuse the
// code by jumping to the return site.
function_return_.Jump(&return_value);
} else {
function_return_.Bind(&return_value);
GenerateReturnSequence(&return_value);
}
}
}
void CodeGenerator::GenerateReturnSequence(Result* return_value) {
// The return value is a live (but not currently reference counted)
// reference to eax. This is safe because the current frame does not
// contain a reference to eax (it is prepared for the return by spilling
// all registers).
if (FLAG_trace) {
frame_->Push(return_value);
*return_value = frame_->CallRuntime(Runtime::kTraceExit, 1);
}
return_value->ToRegister(eax);
// Add a label for checking the size of the code used for returning.
Label check_exit_codesize;
masm_->bind(&check_exit_codesize);
// Leave the frame and return popping the arguments and the
// receiver.
frame_->Exit();
masm_->ret((scope()->num_parameters() + 1) * kPointerSize);
DeleteFrame();
#ifdef ENABLE_DEBUGGER_SUPPORT
// Check that the size of the code used for returning matches what is
// expected by the debugger.
ASSERT_EQ(Assembler::kJSReturnSequenceLength,
masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
#endif
}
void CodeGenerator::VisitWithEnterStatement(WithEnterStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ WithEnterStatement");
CodeForStatementPosition(node);
Load(node->expression());
Result context;
if (node->is_catch_block()) {
context = frame_->CallRuntime(Runtime::kPushCatchContext, 1);
} else {
context = frame_->CallRuntime(Runtime::kPushContext, 1);
}
// Update context local.
frame_->SaveContextRegister();
// Verify that the runtime call result and esi agree.
if (FLAG_debug_code) {
__ cmp(context.reg(), Operand(esi));
__ Assert(equal, "Runtime::NewContext should end up in esi");
}
}
void CodeGenerator::VisitWithExitStatement(WithExitStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ WithExitStatement");
CodeForStatementPosition(node);
// Pop context.
__ mov(esi, ContextOperand(esi, Context::PREVIOUS_INDEX));
// Update context local.
frame_->SaveContextRegister();
}
void CodeGenerator::VisitSwitchStatement(SwitchStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ SwitchStatement");
CodeForStatementPosition(node);
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
// Compile the switch value.
Load(node->tag());
ZoneList<CaseClause*>* cases = node->cases();
int length = cases->length();
CaseClause* default_clause = NULL;
JumpTarget next_test;
// Compile the case label expressions and comparisons. Exit early
// if a comparison is unconditionally true. The target next_test is
// bound before the loop in order to indicate control flow to the
// first comparison.
next_test.Bind();
for (int i = 0; i < length && !next_test.is_unused(); i++) {
CaseClause* clause = cases->at(i);
// The default is not a test, but remember it for later.
if (clause->is_default()) {
default_clause = clause;
continue;
}
Comment cmnt(masm_, "[ Case comparison");
// We recycle the same target next_test for each test. Bind it if
// the previous test has not done so and then unuse it for the
// loop.
if (next_test.is_linked()) {
next_test.Bind();
}
next_test.Unuse();
// Duplicate the switch value.
frame_->Dup();
// Compile the label expression.
Load(clause->label());
// Compare and branch to the body if true or the next test if
// false. Prefer the next test as a fall through.
ControlDestination dest(clause->body_target(), &next_test, false);
Comparison(node, equal, true, &dest);
// If the comparison fell through to the true target, jump to the
// actual body.
if (dest.true_was_fall_through()) {
clause->body_target()->Unuse();
clause->body_target()->Jump();
}
}
// If there was control flow to a next test from the last one
// compiled, compile a jump to the default or break target.
if (!next_test.is_unused()) {
if (next_test.is_linked()) {
next_test.Bind();
}
// Drop the switch value.
frame_->Drop();
if (default_clause != NULL) {
default_clause->body_target()->Jump();
} else {
node->break_target()->Jump();
}
}
// The last instruction emitted was a jump, either to the default
// clause or the break target, or else to a case body from the loop
// that compiles the tests.
ASSERT(!has_valid_frame());
// Compile case bodies as needed.
for (int i = 0; i < length; i++) {
CaseClause* clause = cases->at(i);
// There are two ways to reach the body: from the corresponding
// test or as the fall through of the previous body.
if (clause->body_target()->is_linked() || has_valid_frame()) {
if (clause->body_target()->is_linked()) {
if (has_valid_frame()) {
// If we have both a jump to the test and a fall through, put
// a jump on the fall through path to avoid the dropping of
// the switch value on the test path. The exception is the
// default which has already had the switch value dropped.
if (clause->is_default()) {
clause->body_target()->Bind();
} else {
JumpTarget body;
body.Jump();
clause->body_target()->Bind();
frame_->Drop();
body.Bind();
}
} else {
// No fall through to worry about.
clause->body_target()->Bind();
if (!clause->is_default()) {
frame_->Drop();
}
}
} else {
// Otherwise, we have only fall through.
ASSERT(has_valid_frame());
}
// We are now prepared to compile the body.
Comment cmnt(masm_, "[ Case body");
VisitStatements(clause->statements());
}
clause->body_target()->Unuse();
}
// We may not have a valid frame here so bind the break target only
// if needed.
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
node->break_target()->Unuse();
}
void CodeGenerator::VisitDoWhileStatement(DoWhileStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ DoWhileStatement");
CodeForStatementPosition(node);
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
JumpTarget body(JumpTarget::BIDIRECTIONAL);
IncrementLoopNesting();
ConditionAnalysis info = AnalyzeCondition(node->cond());
// Label the top of the loop for the backward jump if necessary.
switch (info) {
case ALWAYS_TRUE:
// Use the continue target.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
break;
case ALWAYS_FALSE:
// No need to label it.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
break;
case DONT_KNOW:
// Continue is the test, so use the backward body target.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
body.Bind();
break;
}
CheckStack(); // TODO(1222600): ignore if body contains calls.
Visit(node->body());
// Compile the test.
switch (info) {
case ALWAYS_TRUE:
// If control flow can fall off the end of the body, jump back to
// the top and bind the break target at the exit.
if (has_valid_frame()) {
node->continue_target()->Jump();
}
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
break;
case ALWAYS_FALSE:
// We may have had continues or breaks in the body.
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
break;
case DONT_KNOW:
// We have to compile the test expression if it can be reached by
// control flow falling out of the body or via continue.
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
if (has_valid_frame()) {
Comment cmnt(masm_, "[ DoWhileCondition");
CodeForDoWhileConditionPosition(node);
ControlDestination dest(&body, node->break_target(), false);
LoadCondition(node->cond(), &dest, true);
}
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
break;
}
DecrementLoopNesting();
}
void CodeGenerator::VisitWhileStatement(WhileStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ WhileStatement");
CodeForStatementPosition(node);
// If the condition is always false and has no side effects, we do not
// need to compile anything.
ConditionAnalysis info = AnalyzeCondition(node->cond());
if (info == ALWAYS_FALSE) return;
// Do not duplicate conditions that may have function literal
// subexpressions. This can cause us to compile the function literal
// twice.
bool test_at_bottom = !node->may_have_function_literal();
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
IncrementLoopNesting();
JumpTarget body;
if (test_at_bottom) {
body.set_direction(JumpTarget::BIDIRECTIONAL);
}
// Based on the condition analysis, compile the test as necessary.
switch (info) {
case ALWAYS_TRUE:
// We will not compile the test expression. Label the top of the
// loop with the continue target.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
break;
case DONT_KNOW: {
if (test_at_bottom) {
// Continue is the test at the bottom, no need to label the test
// at the top. The body is a backward target.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
} else {
// Label the test at the top as the continue target. The body
// is a forward-only target.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
}
// Compile the test with the body as the true target and preferred
// fall-through and with the break target as the false target.
ControlDestination dest(&body, node->break_target(), true);
LoadCondition(node->cond(), &dest, true);
if (dest.false_was_fall_through()) {
// If we got the break target as fall-through, the test may have
// been unconditionally false (if there are no jumps to the
// body).
if (!body.is_linked()) {
DecrementLoopNesting();
return;
}
// Otherwise, jump around the body on the fall through and then
// bind the body target.
node->break_target()->Unuse();
node->break_target()->Jump();
body.Bind();
}
break;
}
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
CheckStack(); // TODO(1222600): ignore if body contains calls.
Visit(node->body());
// Based on the condition analysis, compile the backward jump as
// necessary.
switch (info) {
case ALWAYS_TRUE:
// The loop body has been labeled with the continue target.
if (has_valid_frame()) {
node->continue_target()->Jump();
}
break;
case DONT_KNOW:
if (test_at_bottom) {
// If we have chosen to recompile the test at the bottom, then
// it is the continue target.
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
if (has_valid_frame()) {
// The break target is the fall-through (body is a backward
// jump from here and thus an invalid fall-through).
ControlDestination dest(&body, node->break_target(), false);
LoadCondition(node->cond(), &dest, true);
}
} else {
// If we have chosen not to recompile the test at the bottom,
// jump back to the one at the top.
if (has_valid_frame()) {
node->continue_target()->Jump();
}
}
break;
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
// The break target may be already bound (by the condition), or there
// may not be a valid frame. Bind it only if needed.
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
DecrementLoopNesting();
}
void CodeGenerator::SetTypeForStackSlot(Slot* slot, TypeInfo info) {
ASSERT(slot->type() == Slot::LOCAL || slot->type() == Slot::PARAMETER);
if (slot->type() == Slot::LOCAL) {
frame_->SetTypeForLocalAt(slot->index(), info);
} else {
frame_->SetTypeForParamAt(slot->index(), info);
}
if (FLAG_debug_code && info.IsSmi()) {
if (slot->type() == Slot::LOCAL) {
frame_->PushLocalAt(slot->index());
} else {
frame_->PushParameterAt(slot->index());
}
Result var = frame_->Pop();
var.ToRegister();
__ AbortIfNotSmi(var.reg());
}
}
void CodeGenerator::VisitForStatement(ForStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ForStatement");
CodeForStatementPosition(node);
// Compile the init expression if present.
if (node->init() != NULL) {
Visit(node->init());
}
// If the condition is always false and has no side effects, we do not
// need to compile anything else.
ConditionAnalysis info = AnalyzeCondition(node->cond());
if (info == ALWAYS_FALSE) return;
// Do not duplicate conditions that may have function literal
// subexpressions. This can cause us to compile the function literal
// twice.
bool test_at_bottom = !node->may_have_function_literal();
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
IncrementLoopNesting();
// Target for backward edge if no test at the bottom, otherwise
// unused.
JumpTarget loop(JumpTarget::BIDIRECTIONAL);
// Target for backward edge if there is a test at the bottom,
// otherwise used as target for test at the top.
JumpTarget body;
if (test_at_bottom) {
body.set_direction(JumpTarget::BIDIRECTIONAL);
}
// Based on the condition analysis, compile the test as necessary.
switch (info) {
case ALWAYS_TRUE:
// We will not compile the test expression. Label the top of the
// loop.
if (node->next() == NULL) {
// Use the continue target if there is no update expression.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
} else {
// Otherwise use the backward loop target.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
loop.Bind();
}
break;
case DONT_KNOW: {
if (test_at_bottom) {
// Continue is either the update expression or the test at the
// bottom, no need to label the test at the top.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
} else if (node->next() == NULL) {
// We are not recompiling the test at the bottom and there is no
// update expression.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
} else {
// We are not recompiling the test at the bottom and there is an
// update expression.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
loop.Bind();
}
// Compile the test with the body as the true target and preferred
// fall-through and with the break target as the false target.
ControlDestination dest(&body, node->break_target(), true);
LoadCondition(node->cond(), &dest, true);
if (dest.false_was_fall_through()) {
// If we got the break target as fall-through, the test may have
// been unconditionally false (if there are no jumps to the
// body).
if (!body.is_linked()) {
DecrementLoopNesting();
return;
}
// Otherwise, jump around the body on the fall through and then
// bind the body target.
node->break_target()->Unuse();
node->break_target()->Jump();
body.Bind();
}
break;
}
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
CheckStack(); // TODO(1222600): ignore if body contains calls.
// We know that the loop index is a smi if it is not modified in the
// loop body and it is checked against a constant limit in the loop
// condition. In this case, we reset the static type information of the
// loop index to smi before compiling the body, the update expression, and
// the bottom check of the loop condition.
if (node->is_fast_smi_loop()) {
// Set number type of the loop variable to smi.
SetTypeForStackSlot(node->loop_variable()->slot(), TypeInfo::Smi());
}
Visit(node->body());
// If there is an update expression, compile it if necessary.
if (node->next() != NULL) {
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
// Control can reach the update by falling out of the body or by a
// continue.
if (has_valid_frame()) {
// Record the source position of the statement as this code which
// is after the code for the body actually belongs to the loop
// statement and not the body.
CodeForStatementPosition(node);
Visit(node->next());
}
}
// Set the type of the loop variable to smi before compiling the test
// expression if we are in a fast smi loop condition.
if (node->is_fast_smi_loop() && has_valid_frame()) {
// Set number type of the loop variable to smi.
SetTypeForStackSlot(node->loop_variable()->slot(), TypeInfo::Smi());
}
// Based on the condition analysis, compile the backward jump as
// necessary.
switch (info) {
case ALWAYS_TRUE:
if (has_valid_frame()) {
if (node->next() == NULL) {
node->continue_target()->Jump();
} else {
loop.Jump();
}
}
break;
case DONT_KNOW:
if (test_at_bottom) {
if (node->continue_target()->is_linked()) {
// We can have dangling jumps to the continue target if there
// was no update expression.
node->continue_target()->Bind();
}
// Control can reach the test at the bottom by falling out of
// the body, by a continue in the body, or from the update
// expression.
if (has_valid_frame()) {
// The break target is the fall-through (body is a backward
// jump from here).
ControlDestination dest(&body, node->break_target(), false);
LoadCondition(node->cond(), &dest, true);
}
} else {
// Otherwise, jump back to the test at the top.
if (has_valid_frame()) {
if (node->next() == NULL) {
node->continue_target()->Jump();
} else {
loop.Jump();
}
}
}
break;
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
// The break target may be already bound (by the condition), or
// there may not be a valid frame. Bind it only if needed.
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
DecrementLoopNesting();
}
void CodeGenerator::VisitForInStatement(ForInStatement* node) {
ASSERT(!in_spilled_code());
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ ForInStatement");
CodeForStatementPosition(node);
JumpTarget primitive;
JumpTarget jsobject;
JumpTarget fixed_array;
JumpTarget entry(JumpTarget::BIDIRECTIONAL);
JumpTarget end_del_check;
JumpTarget exit;
// Get the object to enumerate over (converted to JSObject).
LoadAndSpill(node->enumerable());
// Both SpiderMonkey and kjs ignore null and undefined in contrast
// to the specification. 12.6.4 mandates a call to ToObject.
frame_->EmitPop(eax);
// eax: value to be iterated over
__ cmp(eax, Factory::undefined_value());
exit.Branch(equal);
__ cmp(eax, Factory::null_value());
exit.Branch(equal);
// Stack layout in body:
// [iteration counter (smi)] <- slot 0
// [length of array] <- slot 1
// [FixedArray] <- slot 2
// [Map or 0] <- slot 3
// [Object] <- slot 4
// Check if enumerable is already a JSObject
// eax: value to be iterated over
__ test(eax, Immediate(kSmiTagMask));
primitive.Branch(zero);
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
jsobject.Branch(above_equal);
primitive.Bind();
frame_->EmitPush(eax);
frame_->InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION, 1);
// function call returns the value in eax, which is where we want it below
jsobject.Bind();
// Get the set of properties (as a FixedArray or Map).
// eax: value to be iterated over
frame_->EmitPush(eax); // Push the object being iterated over.
// Check cache validity in generated code. This is a fast case for
// the JSObject::IsSimpleEnum cache validity checks. If we cannot
// guarantee cache validity, call the runtime system to check cache
// validity or get the property names in a fixed array.
JumpTarget call_runtime;
JumpTarget loop(JumpTarget::BIDIRECTIONAL);
JumpTarget check_prototype;
JumpTarget use_cache;
__ mov(ecx, eax);
loop.Bind();
// Check that there are no elements.
__ mov(edx, FieldOperand(ecx, JSObject::kElementsOffset));
__ cmp(Operand(edx), Immediate(Factory::empty_fixed_array()));
call_runtime.Branch(not_equal);
// Check that instance descriptors are not empty so that we can
// check for an enum cache. Leave the map in ebx for the subsequent
// prototype load.
__ mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));
__ mov(edx, FieldOperand(ebx, Map::kInstanceDescriptorsOffset));
__ cmp(Operand(edx), Immediate(Factory::empty_descriptor_array()));
call_runtime.Branch(equal);
// Check that there in an enum cache in the non-empty instance
// descriptors. This is the case if the next enumeration index
// field does not contain a smi.
__ mov(edx, FieldOperand(edx, DescriptorArray::kEnumerationIndexOffset));
__ test(edx, Immediate(kSmiTagMask));
call_runtime.Branch(zero);
// For all objects but the receiver, check that the cache is empty.
__ cmp(ecx, Operand(eax));
check_prototype.Branch(equal);
__ mov(edx, FieldOperand(edx, DescriptorArray::kEnumCacheBridgeCacheOffset));
__ cmp(Operand(edx), Immediate(Factory::empty_fixed_array()));
call_runtime.Branch(not_equal);
check_prototype.Bind();
// Load the prototype from the map and loop if non-null.
__ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
__ cmp(Operand(ecx), Immediate(Factory::null_value()));
loop.Branch(not_equal);
// The enum cache is valid. Load the map of the object being
// iterated over and use the cache for the iteration.
__ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
use_cache.Jump();
call_runtime.Bind();
// Call the runtime to get the property names for the object.
frame_->EmitPush(eax); // push the Object (slot 4) for the runtime call
frame_->CallRuntime(Runtime::kGetPropertyNamesFast, 1);
// If we got a map from the runtime call, we can do a fast
// modification check. Otherwise, we got a fixed array, and we have
// to do a slow check.
// eax: map or fixed array (result from call to
// Runtime::kGetPropertyNamesFast)
__ mov(edx, Operand(eax));
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ cmp(ecx, Factory::meta_map());
fixed_array.Branch(not_equal);
use_cache.Bind();
// Get enum cache
// eax: map (either the result from a call to
// Runtime::kGetPropertyNamesFast or has been fetched directly from
// the object)
__ mov(ecx, Operand(eax));
__ mov(ecx, FieldOperand(ecx, Map::kInstanceDescriptorsOffset));
// Get the bridge array held in the enumeration index field.
__ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumerationIndexOffset));
// Get the cache from the bridge array.
__ mov(edx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
frame_->EmitPush(eax); // <- slot 3
frame_->EmitPush(edx); // <- slot 2
__ mov(eax, FieldOperand(edx, FixedArray::kLengthOffset));
frame_->EmitPush(eax); // <- slot 1
frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 0
entry.Jump();
fixed_array.Bind();
// eax: fixed array (result from call to Runtime::kGetPropertyNamesFast)
frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 3
frame_->EmitPush(eax); // <- slot 2
// Push the length of the array and the initial index onto the stack.
__ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
frame_->EmitPush(eax); // <- slot 1
frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 0
// Condition.
entry.Bind();
// Grab the current frame's height for the break and continue
// targets only after all the state is pushed on the frame.
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
__ mov(eax, frame_->ElementAt(0)); // load the current count
__ cmp(eax, frame_->ElementAt(1)); // compare to the array length
node->break_target()->Branch(above_equal);
// Get the i'th entry of the array.
__ mov(edx, frame_->ElementAt(2));
__ mov(ebx, FixedArrayElementOperand(edx, eax));
// Get the expected map from the stack or a zero map in the
// permanent slow case eax: current iteration count ebx: i'th entry
// of the enum cache
__ mov(edx, frame_->ElementAt(3));
// Check if the expected map still matches that of the enumerable.
// If not, we have to filter the key.
// eax: current iteration count
// ebx: i'th entry of the enum cache
// edx: expected map value
__ mov(ecx, frame_->ElementAt(4));
__ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
__ cmp(ecx, Operand(edx));
end_del_check.Branch(equal);
// Convert the entry to a string (or null if it isn't a property anymore).
frame_->EmitPush(frame_->ElementAt(4)); // push enumerable
frame_->EmitPush(ebx); // push entry
frame_->InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION, 2);
__ mov(ebx, Operand(eax));
// If the property has been removed while iterating, we just skip it.
__ cmp(ebx, Factory::null_value());
node->continue_target()->Branch(equal);
end_del_check.Bind();
// Store the entry in the 'each' expression and take another spin in the
// loop. edx: i'th entry of the enum cache (or string there of)
frame_->EmitPush(ebx);
{ Reference each(this, node->each());
// Loading a reference may leave the frame in an unspilled state.
frame_->SpillAll();
if (!each.is_illegal()) {
if (each.size() > 0) {
frame_->EmitPush(frame_->ElementAt(each.size()));
each.SetValue(NOT_CONST_INIT);
frame_->Drop(2);
} else {
// If the reference was to a slot we rely on the convenient property
// that it doesn't matter whether a value (eg, ebx pushed above) is
// right on top of or right underneath a zero-sized reference.
each.SetValue(NOT_CONST_INIT);
frame_->Drop();
}
}
}
// Unloading a reference may leave the frame in an unspilled state.
frame_->SpillAll();
// Body.
CheckStack(); // TODO(1222600): ignore if body contains calls.
VisitAndSpill(node->body());
// Next. Reestablish a spilled frame in case we are coming here via
// a continue in the body.
node->continue_target()->Bind();
frame_->SpillAll();
frame_->EmitPop(eax);
__ add(Operand(eax), Immediate(Smi::FromInt(1)));
frame_->EmitPush(eax);
entry.Jump();
// Cleanup. No need to spill because VirtualFrame::Drop is safe for
// any frame.
node->break_target()->Bind();
frame_->Drop(5);
// Exit.
exit.Bind();
node->continue_target()->Unuse();
node->break_target()->Unuse();
}
void CodeGenerator::VisitTryCatchStatement(TryCatchStatement* node) {
ASSERT(!in_spilled_code());
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ TryCatchStatement");
CodeForStatementPosition(node);
JumpTarget try_block;
JumpTarget exit;
try_block.Call();
// --- Catch block ---
frame_->EmitPush(eax);
// Store the caught exception in the catch variable.
Variable* catch_var = node->catch_var()->var();
ASSERT(catch_var != NULL && catch_var->slot() != NULL);
StoreToSlot(catch_var->slot(), NOT_CONST_INIT);
// Remove the exception from the stack.
frame_->Drop();
VisitStatementsAndSpill(node->catch_block()->statements());
if (has_valid_frame()) {
exit.Jump();
}
// --- Try block ---
try_block.Bind();
frame_->PushTryHandler(TRY_CATCH_HANDLER);
int handler_height = frame_->height();
// Shadow the jump targets for all escapes from the try block, including
// returns. During shadowing, the original target is hidden as the
// ShadowTarget and operations on the original actually affect the
// shadowing target.
//
// We should probably try to unify the escaping targets and the return
// target.
int nof_escapes = node->escaping_targets()->length();
List<ShadowTarget*> shadows(1 + nof_escapes);
// Add the shadow target for the function return.
static const int kReturnShadowIndex = 0;
shadows.Add(new ShadowTarget(&function_return_));
bool function_return_was_shadowed = function_return_is_shadowed_;
function_return_is_shadowed_ = true;
ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
// Add the remaining shadow targets.
for (int i = 0; i < nof_escapes; i++) {
shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
}
// Generate code for the statements in the try block.
VisitStatementsAndSpill(node->try_block()->statements());
// Stop the introduced shadowing and count the number of required unlinks.
// After shadowing stops, the original targets are unshadowed and the
// ShadowTargets represent the formerly shadowing targets.
bool has_unlinks = false;
for (int i = 0; i < shadows.length(); i++) {
shadows[i]->StopShadowing();
has_unlinks = has_unlinks || shadows[i]->is_linked();
}
function_return_is_shadowed_ = function_return_was_shadowed;
// Get an external reference to the handler address.
ExternalReference handler_address(Top::k_handler_address);
// Make sure that there's nothing left on the stack above the
// handler structure.
if (FLAG_debug_code) {
__ mov(eax, Operand::StaticVariable(handler_address));
__ cmp(esp, Operand(eax));
__ Assert(equal, "stack pointer should point to top handler");
}
// If we can fall off the end of the try block, unlink from try chain.
if (has_valid_frame()) {
// The next handler address is on top of the frame. Unlink from
// the handler list and drop the rest of this handler from the
// frame.
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
if (has_unlinks) {
exit.Jump();
}
}
// Generate unlink code for the (formerly) shadowing targets that
// have been jumped to. Deallocate each shadow target.
Result return_value;
for (int i = 0; i < shadows.length(); i++) {
if (shadows[i]->is_linked()) {
// Unlink from try chain; be careful not to destroy the TOS if
// there is one.
if (i == kReturnShadowIndex) {
shadows[i]->Bind(&return_value);
return_value.ToRegister(eax);
} else {
shadows[i]->Bind();
}
// Because we can be jumping here (to spilled code) from
// unspilled code, we need to reestablish a spilled frame at
// this block.
frame_->SpillAll();
// Reload sp from the top handler, because some statements that we
// break from (eg, for...in) may have left stuff on the stack.
__ mov(esp, Operand::StaticVariable(handler_address));
frame_->Forget(frame_->height() - handler_height);
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
if (i == kReturnShadowIndex) {
if (!function_return_is_shadowed_) frame_->PrepareForReturn();
shadows[i]->other_target()->Jump(&return_value);
} else {
shadows[i]->other_target()->Jump();
}
}
}
exit.Bind();
}
void CodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* node) {
ASSERT(!in_spilled_code());
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ TryFinallyStatement");
CodeForStatementPosition(node);
// State: Used to keep track of reason for entering the finally
// block. Should probably be extended to hold information for
// break/continue from within the try block.
enum { FALLING, THROWING, JUMPING };
JumpTarget try_block;
JumpTarget finally_block;
try_block.Call();
frame_->EmitPush(eax);
// In case of thrown exceptions, this is where we continue.
__ Set(ecx, Immediate(Smi::FromInt(THROWING)));
finally_block.Jump();
// --- Try block ---
try_block.Bind();
frame_->PushTryHandler(TRY_FINALLY_HANDLER);
int handler_height = frame_->height();
// Shadow the jump targets for all escapes from the try block, including
// returns. During shadowing, the original target is hidden as the
// ShadowTarget and operations on the original actually affect the
// shadowing target.
//
// We should probably try to unify the escaping targets and the return
// target.
int nof_escapes = node->escaping_targets()->length();
List<ShadowTarget*> shadows(1 + nof_escapes);
// Add the shadow target for the function return.
static const int kReturnShadowIndex = 0;
shadows.Add(new ShadowTarget(&function_return_));
bool function_return_was_shadowed = function_return_is_shadowed_;
function_return_is_shadowed_ = true;
ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
// Add the remaining shadow targets.
for (int i = 0; i < nof_escapes; i++) {
shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
}
// Generate code for the statements in the try block.
VisitStatementsAndSpill(node->try_block()->statements());
// Stop the introduced shadowing and count the number of required unlinks.
// After shadowing stops, the original targets are unshadowed and the
// ShadowTargets represent the formerly shadowing targets.
int nof_unlinks = 0;
for (int i = 0; i < shadows.length(); i++) {
shadows[i]->StopShadowing();
if (shadows[i]->is_linked()) nof_unlinks++;
}
function_return_is_shadowed_ = function_return_was_shadowed;
// Get an external reference to the handler address.
ExternalReference handler_address(Top::k_handler_address);
// If we can fall off the end of the try block, unlink from the try
// chain and set the state on the frame to FALLING.
if (has_valid_frame()) {
// The next handler address is on top of the frame.
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
// Fake a top of stack value (unneeded when FALLING) and set the
// state in ecx, then jump around the unlink blocks if any.
frame_->EmitPush(Immediate(Factory::undefined_value()));
__ Set(ecx, Immediate(Smi::FromInt(FALLING)));
if (nof_unlinks > 0) {
finally_block.Jump();
}
}
// Generate code to unlink and set the state for the (formerly)
// shadowing targets that have been jumped to.
for (int i = 0; i < shadows.length(); i++) {
if (shadows[i]->is_linked()) {
// If we have come from the shadowed return, the return value is
// on the virtual frame. We must preserve it until it is
// pushed.
if (i == kReturnShadowIndex) {
Result return_value;
shadows[i]->Bind(&return_value);
return_value.ToRegister(eax);
} else {
shadows[i]->Bind();
}
// Because we can be jumping here (to spilled code) from
// unspilled code, we need to reestablish a spilled frame at
// this block.
frame_->SpillAll();
// Reload sp from the top handler, because some statements that
// we break from (eg, for...in) may have left stuff on the
// stack.
__ mov(esp, Operand::StaticVariable(handler_address));
frame_->Forget(frame_->height() - handler_height);
// Unlink this handler and drop it from the frame.
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
if (i == kReturnShadowIndex) {
// If this target shadowed the function return, materialize
// the return value on the stack.
frame_->EmitPush(eax);
} else {
// Fake TOS for targets that shadowed breaks and continues.
frame_->EmitPush(Immediate(Factory::undefined_value()));
}
__ Set(ecx, Immediate(Smi::FromInt(JUMPING + i)));
if (--nof_unlinks > 0) {
// If this is not the last unlink block, jump around the next.
finally_block.Jump();
}
}
}
// --- Finally block ---
finally_block.Bind();
// Push the state on the stack.
frame_->EmitPush(ecx);
// We keep two elements on the stack - the (possibly faked) result
// and the state - while evaluating the finally block.
//
// Generate code for the statements in the finally block.
VisitStatementsAndSpill(node->finally_block()->statements());
if (has_valid_frame()) {
// Restore state and return value or faked TOS.
frame_->EmitPop(ecx);
frame_->EmitPop(eax);
}
// Generate code to jump to the right destination for all used
// formerly shadowing targets. Deallocate each shadow target.
for (int i = 0; i < shadows.length(); i++) {
if (has_valid_frame() && shadows[i]->is_bound()) {
BreakTarget* original = shadows[i]->other_target();
__ cmp(Operand(ecx), Immediate(Smi::FromInt(JUMPING + i)));
if (i == kReturnShadowIndex) {
// The return value is (already) in eax.
Result return_value = allocator_->Allocate(eax);
ASSERT(return_value.is_valid());
if (function_return_is_shadowed_) {
original->Branch(equal, &return_value);
} else {
// Branch around the preparation for return which may emit
// code.
JumpTarget skip;
skip.Branch(not_equal);
frame_->PrepareForReturn();
original->Jump(&return_value);
skip.Bind();
}
} else {
original->Branch(equal);
}
}
}
if (has_valid_frame()) {
// Check if we need to rethrow the exception.
JumpTarget exit;
__ cmp(Operand(ecx), Immediate(Smi::FromInt(THROWING)));
exit.Branch(not_equal);
// Rethrow exception.
frame_->EmitPush(eax); // undo pop from above
frame_->CallRuntime(Runtime::kReThrow, 1);
// Done.
exit.Bind();
}
}
void CodeGenerator::VisitDebuggerStatement(DebuggerStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ DebuggerStatement");
CodeForStatementPosition(node);
#ifdef ENABLE_DEBUGGER_SUPPORT
// Spill everything, even constants, to the frame.
frame_->SpillAll();
frame_->DebugBreak();
// Ignore the return value.
#endif
}
Result CodeGenerator::InstantiateFunction(
Handle<SharedFunctionInfo> function_info) {
// The inevitable call will sync frame elements to memory anyway, so
// we do it eagerly to allow us to push the arguments directly into
// place.
frame()->SyncRange(0, frame()->element_count() - 1);
// Use the fast case closure allocation code that allocates in new
// space for nested functions that don't need literals cloning.
if (scope()->is_function_scope() && function_info->num_literals() == 0) {
FastNewClosureStub stub;
frame()->EmitPush(Immediate(function_info));
return frame()->CallStub(&stub, 1);
} else {
// Call the runtime to instantiate the function based on the
// shared function info.
frame()->EmitPush(esi);
frame()->EmitPush(Immediate(function_info));
return frame()->CallRuntime(Runtime::kNewClosure, 2);
}
}
void CodeGenerator::VisitFunctionLiteral(FunctionLiteral* node) {
Comment cmnt(masm_, "[ FunctionLiteral");
ASSERT(!in_safe_int32_mode());
// Build the function info and instantiate it.
Handle<SharedFunctionInfo> function_info =
Compiler::BuildFunctionInfo(node, script(), this);
// Check for stack-overflow exception.
if (HasStackOverflow()) return;
Result result = InstantiateFunction(function_info);
frame()->Push(&result);
}
void CodeGenerator::VisitSharedFunctionInfoLiteral(
SharedFunctionInfoLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ SharedFunctionInfoLiteral");
Result result = InstantiateFunction(node->shared_function_info());
frame()->Push(&result);
}
void CodeGenerator::VisitConditional(Conditional* node) {
Comment cmnt(masm_, "[ Conditional");
ASSERT(!in_safe_int32_mode());
JumpTarget then;
JumpTarget else_;
JumpTarget exit;
ControlDestination dest(&then, &else_, true);
LoadCondition(node->condition(), &dest, true);
if (dest.false_was_fall_through()) {
// The else target was bound, so we compile the else part first.
Load(node->else_expression());
if (then.is_linked()) {
exit.Jump();
then.Bind();
Load(node->then_expression());
}
} else {
// The then target was bound, so we compile the then part first.
Load(node->then_expression());
if (else_.is_linked()) {
exit.Jump();
else_.Bind();
Load(node->else_expression());
}
}
exit.Bind();
}
void CodeGenerator::LoadFromSlot(Slot* slot, TypeofState typeof_state) {
if (slot->type() == Slot::LOOKUP) {
ASSERT(slot->var()->is_dynamic());
JumpTarget slow;
JumpTarget done;
Result value;
// Generate fast case for loading from slots that correspond to
// local/global variables or arguments unless they are shadowed by
// eval-introduced bindings.
EmitDynamicLoadFromSlotFastCase(slot,
typeof_state,
&value,
&slow,
&done);
slow.Bind();
// A runtime call is inevitable. We eagerly sync frame elements
// to memory so that we can push the arguments directly into place
// on top of the frame.
frame()->SyncRange(0, frame()->element_count() - 1);
frame()->EmitPush(esi);
frame()->EmitPush(Immediate(slot->var()->name()));
if (typeof_state == INSIDE_TYPEOF) {
value =
frame()->CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2);
} else {
value = frame()->CallRuntime(Runtime::kLoadContextSlot, 2);
}
done.Bind(&value);
frame_->Push(&value);
} else if (slot->var()->mode() == Variable::CONST) {
// Const slots may contain 'the hole' value (the constant hasn't been
// initialized yet) which needs to be converted into the 'undefined'
// value.
//
// We currently spill the virtual frame because constants use the
// potentially unsafe direct-frame access of SlotOperand.
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ Load const");
Label exit;
__ mov(ecx, SlotOperand(slot, ecx));
__ cmp(ecx, Factory::the_hole_value());
__ j(not_equal, &exit);
__ mov(ecx, Factory::undefined_value());
__ bind(&exit);
frame()->EmitPush(ecx);
} else if (slot->type() == Slot::PARAMETER) {
frame()->PushParameterAt(slot->index());
} else if (slot->type() == Slot::LOCAL) {
frame()->PushLocalAt(slot->index());
} else {
// The other remaining slot types (LOOKUP and GLOBAL) cannot reach
// here.
//
// The use of SlotOperand below is safe for an unspilled frame
// because it will always be a context slot.
ASSERT(slot->type() == Slot::CONTEXT);
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), SlotOperand(slot, temp.reg()));
frame()->Push(&temp);
}
}
void CodeGenerator::LoadFromSlotCheckForArguments(Slot* slot,
TypeofState state) {
LoadFromSlot(slot, state);
// Bail out quickly if we're not using lazy arguments allocation.
if (ArgumentsMode() != LAZY_ARGUMENTS_ALLOCATION) return;
// ... or if the slot isn't a non-parameter arguments slot.
if (slot->type() == Slot::PARAMETER || !slot->is_arguments()) return;
// If the loaded value is a constant, we know if the arguments
// object has been lazily loaded yet.
Result result = frame()->Pop();
if (result.is_constant()) {
if (result.handle()->IsTheHole()) {
result = StoreArgumentsObject(false);
}
frame()->Push(&result);
return;
}
ASSERT(result.is_register());
// The loaded value is in a register. If it is the sentinel that
// indicates that we haven't loaded the arguments object yet, we
// need to do it now.
JumpTarget exit;
__ cmp(Operand(result.reg()), Immediate(Factory::the_hole_value()));
frame()->Push(&result);
exit.Branch(not_equal);
result = StoreArgumentsObject(false);
frame()->SetElementAt(0, &result);
result.Unuse();
exit.Bind();
return;
}
Result CodeGenerator::LoadFromGlobalSlotCheckExtensions(
Slot* slot,
TypeofState typeof_state,
JumpTarget* slow) {
ASSERT(!in_safe_int32_mode());
// Check that no extension objects have been created by calls to
// eval from the current scope to the global scope.
Register context = esi;
Result tmp = allocator_->Allocate();
ASSERT(tmp.is_valid()); // All non-reserved registers were available.
Scope* s = scope();
while (s != NULL) {
if (s->num_heap_slots() > 0) {
if (s->calls_eval()) {
// Check that extension is NULL.
__ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
Immediate(0));
slow->Branch(not_equal, not_taken);
}
// Load next context in chain.
__ mov(tmp.reg(), ContextOperand(context, Context::CLOSURE_INDEX));
__ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
context = tmp.reg();
}
// If no outer scope calls eval, we do not need to check more
// context extensions. If we have reached an eval scope, we check
// all extensions from this point.
if (!s->outer_scope_calls_eval() || s->is_eval_scope()) break;
s = s->outer_scope();
}
if (s != NULL && s->is_eval_scope()) {
// Loop up the context chain. There is no frame effect so it is
// safe to use raw labels here.
Label next, fast;
if (!context.is(tmp.reg())) {
__ mov(tmp.reg(), context);
}
__ bind(&next);
// Terminate at global context.
__ cmp(FieldOperand(tmp.reg(), HeapObject::kMapOffset),
Immediate(Factory::global_context_map()));
__ j(equal, &fast);
// Check that extension is NULL.
__ cmp(ContextOperand(tmp.reg(), Context::EXTENSION_INDEX), Immediate(0));
slow->Branch(not_equal, not_taken);
// Load next context in chain.
__ mov(tmp.reg(), ContextOperand(tmp.reg(), Context::CLOSURE_INDEX));
__ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
__ jmp(&next);
__ bind(&fast);
}
tmp.Unuse();
// All extension objects were empty and it is safe to use a global
// load IC call.
// The register allocator prefers eax if it is free, so the code generator
// will load the global object directly into eax, which is where the LoadIC
// expects it.
frame_->Spill(eax);
LoadGlobal();
frame_->Push(slot->var()->name());
RelocInfo::Mode mode = (typeof_state == INSIDE_TYPEOF)
? RelocInfo::CODE_TARGET
: RelocInfo::CODE_TARGET_CONTEXT;
Result answer = frame_->CallLoadIC(mode);
// A test eax instruction following the call signals that the inobject
// property case was inlined. Ensure that there is not a test eax
// instruction here.
__ nop();
return answer;
}
void CodeGenerator::EmitDynamicLoadFromSlotFastCase(Slot* slot,
TypeofState typeof_state,
Result* result,
JumpTarget* slow,
JumpTarget* done) {
// Generate fast-case code for variables that might be shadowed by
// eval-introduced variables. Eval is used a lot without
// introducing variables. In those cases, we do not want to
// perform a runtime call for all variables in the scope
// containing the eval.
if (slot->var()->mode() == Variable::DYNAMIC_GLOBAL) {
*result = LoadFromGlobalSlotCheckExtensions(slot, typeof_state, slow);
done->Jump(result);
} else if (slot->var()->mode() == Variable::DYNAMIC_LOCAL) {
Slot* potential_slot = slot->var()->local_if_not_shadowed()->slot();
Expression* rewrite = slot->var()->local_if_not_shadowed()->rewrite();
if (potential_slot != NULL) {
// Generate fast case for locals that rewrite to slots.
// Allocate a fresh register to use as a temp in
// ContextSlotOperandCheckExtensions and to hold the result
// value.
*result = allocator()->Allocate();
ASSERT(result->is_valid());
__ mov(result->reg(),
ContextSlotOperandCheckExtensions(potential_slot, *result, slow));
if (potential_slot->var()->mode() == Variable::CONST) {
__ cmp(result->reg(), Factory::the_hole_value());
done->Branch(not_equal, result);
__ mov(result->reg(), Factory::undefined_value());
}
done->Jump(result);
} else if (rewrite != NULL) {
// Generate fast case for calls of an argument function.
Property* property = rewrite->AsProperty();
if (property != NULL) {
VariableProxy* obj_proxy = property->obj()->AsVariableProxy();
Literal* key_literal = property->key()->AsLiteral();
if (obj_proxy != NULL &&
key_literal != NULL &&
obj_proxy->IsArguments() &&
key_literal->handle()->IsSmi()) {
// Load arguments object if there are no eval-introduced
// variables. Then load the argument from the arguments
// object using keyed load.
Result arguments = allocator()->Allocate();
ASSERT(arguments.is_valid());
__ mov(arguments.reg(),
ContextSlotOperandCheckExtensions(obj_proxy->var()->slot(),
arguments,
slow));
frame_->Push(&arguments);
frame_->Push(key_literal->handle());
*result = EmitKeyedLoad();
done->Jump(result);
}
}
}
}
}
void CodeGenerator::StoreToSlot(Slot* slot, InitState init_state) {
if (slot->type() == Slot::LOOKUP) {
ASSERT(slot->var()->is_dynamic());
// For now, just do a runtime call. Since the call is inevitable,
// we eagerly sync the virtual frame so we can directly push the
// arguments into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(slot->var()->name()));
Result value;
if (init_state == CONST_INIT) {
// Same as the case for a normal store, but ignores attribute
// (e.g. READ_ONLY) of context slot so that we can initialize const
// properties (introduced via eval("const foo = (some expr);")). Also,
// uses the current function context instead of the top context.
//
// Note that we must declare the foo upon entry of eval(), via a
// context slot declaration, but we cannot initialize it at the same
// time, because the const declaration may be at the end of the eval
// code (sigh...) and the const variable may have been used before
// (where its value is 'undefined'). Thus, we can only do the
// initialization when we actually encounter the expression and when
// the expression operands are defined and valid, and thus we need the
// split into 2 operations: declaration of the context slot followed
// by initialization.
value = frame_->CallRuntime(Runtime::kInitializeConstContextSlot, 3);
} else {
value = frame_->CallRuntime(Runtime::kStoreContextSlot, 3);
}
// Storing a variable must keep the (new) value on the expression
// stack. This is necessary for compiling chained assignment
// expressions.
frame_->Push(&value);
} else {
ASSERT(!slot->var()->is_dynamic());
JumpTarget exit;
if (init_state == CONST_INIT) {
ASSERT(slot->var()->mode() == Variable::CONST);
// Only the first const initialization must be executed (the slot
// still contains 'the hole' value). When the assignment is executed,
// the code is identical to a normal store (see below).
//
// We spill the frame in the code below because the direct-frame
// access of SlotOperand is potentially unsafe with an unspilled
// frame.
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ Init const");
__ mov(ecx, SlotOperand(slot, ecx));
__ cmp(ecx, Factory::the_hole_value());
exit.Branch(not_equal);
}
// We must execute the store. Storing a variable must keep the (new)
// value on the stack. This is necessary for compiling assignment
// expressions.
//
// Note: We will reach here even with slot->var()->mode() ==
// Variable::CONST because of const declarations which will initialize
// consts to 'the hole' value and by doing so, end up calling this code.
if (slot->type() == Slot::PARAMETER) {
frame_->StoreToParameterAt(slot->index());
} else if (slot->type() == Slot::LOCAL) {
frame_->StoreToLocalAt(slot->index());
} else {
// The other slot types (LOOKUP and GLOBAL) cannot reach here.
//
// The use of SlotOperand below is safe for an unspilled frame
// because the slot is a context slot.
ASSERT(slot->type() == Slot::CONTEXT);
frame_->Dup();
Result value = frame_->Pop();
value.ToRegister();
Result start = allocator_->Allocate();
ASSERT(start.is_valid());
__ mov(SlotOperand(slot, start.reg()), value.reg());
// RecordWrite may destroy the value registers.
//
// TODO(204): Avoid actually spilling when the value is not
// needed (probably the common case).
frame_->Spill(value.reg());
int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
Result temp = allocator_->Allocate();
ASSERT(temp.is_valid());
__ RecordWrite(start.reg(), offset, value.reg(), temp.reg());
// The results start, value, and temp are unused by going out of
// scope.
}
exit.Bind();
}
}
void CodeGenerator::VisitSlot(Slot* slot) {
Comment cmnt(masm_, "[ Slot");
if (in_safe_int32_mode()) {
if ((slot->type() == Slot::LOCAL && !slot->is_arguments())) {
frame()->UntaggedPushLocalAt(slot->index());
} else if (slot->type() == Slot::PARAMETER) {
frame()->UntaggedPushParameterAt(slot->index());
} else {
UNREACHABLE();
}
} else {
LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
}
}
void CodeGenerator::VisitVariableProxy(VariableProxy* node) {
Comment cmnt(masm_, "[ VariableProxy");
Variable* var = node->var();
Expression* expr = var->rewrite();
if (expr != NULL) {
Visit(expr);
} else {
ASSERT(var->is_global());
ASSERT(!in_safe_int32_mode());
Reference ref(this, node);
ref.GetValue();
}
}
void CodeGenerator::VisitLiteral(Literal* node) {
Comment cmnt(masm_, "[ Literal");
if (in_safe_int32_mode()) {
frame_->PushUntaggedElement(node->handle());
} else {
frame_->Push(node->handle());
}
}
void CodeGenerator::PushUnsafeSmi(Handle<Object> value) {
ASSERT(value->IsSmi());
int bits = reinterpret_cast<int>(*value);
__ push(Immediate(bits & 0x0000FFFF));
__ or_(Operand(esp, 0), Immediate(bits & 0xFFFF0000));
}
void CodeGenerator::StoreUnsafeSmiToLocal(int offset, Handle<Object> value) {
ASSERT(value->IsSmi());
int bits = reinterpret_cast<int>(*value);
__ mov(Operand(ebp, offset), Immediate(bits & 0x0000FFFF));
__ or_(Operand(ebp, offset), Immediate(bits & 0xFFFF0000));
}
void CodeGenerator::MoveUnsafeSmi(Register target, Handle<Object> value) {
ASSERT(target.is_valid());
ASSERT(value->IsSmi());
int bits = reinterpret_cast<int>(*value);
__ Set(target, Immediate(bits & 0x0000FFFF));
__ or_(target, bits & 0xFFFF0000);
}
bool CodeGenerator::IsUnsafeSmi(Handle<Object> value) {
if (!value->IsSmi()) return false;
int int_value = Smi::cast(*value)->value();
return !is_intn(int_value, kMaxSmiInlinedBits);
}
// Materialize the regexp literal 'node' in the literals array
// 'literals' of the function. Leave the regexp boilerplate in
// 'boilerplate'.
class DeferredRegExpLiteral: public DeferredCode {
public:
DeferredRegExpLiteral(Register boilerplate,
Register literals,
RegExpLiteral* node)
: boilerplate_(boilerplate), literals_(literals), node_(node) {
set_comment("[ DeferredRegExpLiteral");
}
void Generate();
private:
Register boilerplate_;
Register literals_;
RegExpLiteral* node_;
};
void DeferredRegExpLiteral::Generate() {
// Since the entry is undefined we call the runtime system to
// compute the literal.
// Literal array (0).
__ push(literals_);
// Literal index (1).
__ push(Immediate(Smi::FromInt(node_->literal_index())));
// RegExp pattern (2).
__ push(Immediate(node_->pattern()));
// RegExp flags (3).
__ push(Immediate(node_->flags()));
__ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
if (!boilerplate_.is(eax)) __ mov(boilerplate_, eax);
}
void CodeGenerator::VisitRegExpLiteral(RegExpLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ RegExp Literal");
// Retrieve the literals array and check the allocated entry. Begin
// with a writable copy of the function of this activation in a
// register.
frame_->PushFunction();
Result literals = frame_->Pop();
literals.ToRegister();
frame_->Spill(literals.reg());
// Load the literals array of the function.
__ mov(literals.reg(),
FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
// Load the literal at the ast saved index.
Result boilerplate = allocator_->Allocate();
ASSERT(boilerplate.is_valid());
int literal_offset =
FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
__ mov(boilerplate.reg(), FieldOperand(literals.reg(), literal_offset));
// Check whether we need to materialize the RegExp object. If so,
// jump to the deferred code passing the literals array.
DeferredRegExpLiteral* deferred =
new DeferredRegExpLiteral(boilerplate.reg(), literals.reg(), node);
__ cmp(boilerplate.reg(), Factory::undefined_value());
deferred->Branch(equal);
deferred->BindExit();
literals.Unuse();
// Push the boilerplate object.
frame_->Push(&boilerplate);
}
void CodeGenerator::VisitObjectLiteral(ObjectLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ ObjectLiteral");
// Load a writable copy of the function of this activation in a
// register.
frame_->PushFunction();
Result literals = frame_->Pop();
literals.ToRegister();
frame_->Spill(literals.reg());
// Load the literals array of the function.
__ mov(literals.reg(),
FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
// Literal array.
frame_->Push(&literals);
// Literal index.
frame_->Push(Smi::FromInt(node->literal_index()));
// Constant properties.
frame_->Push(node->constant_properties());
// Should the object literal have fast elements?
frame_->Push(Smi::FromInt(node->fast_elements() ? 1 : 0));
Result clone;
if (node->depth() > 1) {
clone = frame_->CallRuntime(Runtime::kCreateObjectLiteral, 4);
} else {
clone = frame_->CallRuntime(Runtime::kCreateObjectLiteralShallow, 4);
}
frame_->Push(&clone);
for (int i = 0; i < node->properties()->length(); i++) {
ObjectLiteral::Property* property = node->properties()->at(i);
switch (property->kind()) {
case ObjectLiteral::Property::CONSTANT:
break;
case ObjectLiteral::Property::MATERIALIZED_LITERAL:
if (CompileTimeValue::IsCompileTimeValue(property->value())) break;
// else fall through.
case ObjectLiteral::Property::COMPUTED: {
Handle<Object> key(property->key()->handle());
if (key->IsSymbol()) {
// Duplicate the object as the IC receiver.
frame_->Dup();
Load(property->value());
Result dummy = frame_->CallStoreIC(Handle<String>::cast(key), false);
dummy.Unuse();
break;
}
// Fall through
}
case ObjectLiteral::Property::PROTOTYPE: {
// Duplicate the object as an argument to the runtime call.
frame_->Dup();
Load(property->key());
Load(property->value());
Result ignored = frame_->CallRuntime(Runtime::kSetProperty, 3);
// Ignore the result.
break;
}
case ObjectLiteral::Property::SETTER: {
// Duplicate the object as an argument to the runtime call.
frame_->Dup();
Load(property->key());
frame_->Push(Smi::FromInt(1));
Load(property->value());
Result ignored = frame_->CallRuntime(Runtime::kDefineAccessor, 4);
// Ignore the result.
break;
}
case ObjectLiteral::Property::GETTER: {
// Duplicate the object as an argument to the runtime call.
frame_->Dup();
Load(property->key());
frame_->Push(Smi::FromInt(0));
Load(property->value());
Result ignored = frame_->CallRuntime(Runtime::kDefineAccessor, 4);
// Ignore the result.
break;
}
default: UNREACHABLE();
}
}
}
void CodeGenerator::VisitArrayLiteral(ArrayLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ ArrayLiteral");
// Load a writable copy of the function of this activation in a
// register.
frame_->PushFunction();
Result literals = frame_->Pop();
literals.ToRegister();
frame_->Spill(literals.reg());
// Load the literals array of the function.
__ mov(literals.reg(),
FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
frame_->Push(&literals);
frame_->Push(Smi::FromInt(node->literal_index()));
frame_->Push(node->constant_elements());
int length = node->values()->length();
Result clone;
if (node->depth() > 1) {
clone = frame_->CallRuntime(Runtime::kCreateArrayLiteral, 3);
} else if (length > FastCloneShallowArrayStub::kMaximumLength) {
clone = frame_->CallRuntime(Runtime::kCreateArrayLiteralShallow, 3);
} else {
FastCloneShallowArrayStub stub(length);
clone = frame_->CallStub(&stub, 3);
}
frame_->Push(&clone);
// Generate code to set the elements in the array that are not
// literals.
for (int i = 0; i < length; i++) {
Expression* value = node->values()->at(i);
// If value is a literal the property value is already set in the
// boilerplate object.
if (value->AsLiteral() != NULL) continue;
// If value is a materialized literal the property value is already set
// in the boilerplate object if it is simple.
if (CompileTimeValue::IsCompileTimeValue(value)) continue;
// The property must be set by generated code.
Load(value);
// Get the property value off the stack.
Result prop_value = frame_->Pop();
prop_value.ToRegister();
// Fetch the array literal while leaving a copy on the stack and
// use it to get the elements array.
frame_->Dup();
Result elements = frame_->Pop();
elements.ToRegister();
frame_->Spill(elements.reg());
// Get the elements array.
__ mov(elements.reg(),
FieldOperand(elements.reg(), JSObject::kElementsOffset));
// Write to the indexed properties array.
int offset = i * kPointerSize + FixedArray::kHeaderSize;
__ mov(FieldOperand(elements.reg(), offset), prop_value.reg());
// Update the write barrier for the array address.
frame_->Spill(prop_value.reg()); // Overwritten by the write barrier.
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_valid());
__ RecordWrite(elements.reg(), offset, prop_value.reg(), scratch.reg());
}
}
void CodeGenerator::VisitCatchExtensionObject(CatchExtensionObject* node) {
ASSERT(!in_safe_int32_mode());
ASSERT(!in_spilled_code());
// Call runtime routine to allocate the catch extension object and
// assign the exception value to the catch variable.
Comment cmnt(masm_, "[ CatchExtensionObject");
Load(node->key());
Load(node->value());
Result result =
frame_->CallRuntime(Runtime::kCreateCatchExtensionObject, 2);
frame_->Push(&result);
}
void CodeGenerator::EmitSlotAssignment(Assignment* node) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Comment cmnt(masm(), "[ Variable Assignment");
Variable* var = node->target()->AsVariableProxy()->AsVariable();
ASSERT(var != NULL);
Slot* slot = var->slot();
ASSERT(slot != NULL);
// Evaluate the right-hand side.
if (node->is_compound()) {
// For a compound assignment the right-hand side is a binary operation
// between the current property value and the actual right-hand side.
LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
Load(node->value());
// Perform the binary operation.
bool overwrite_value =
(node->value()->AsBinaryOperation() != NULL &&
node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
// Construct the implicit binary operation.
BinaryOperation expr(node, node->binary_op(), node->target(),
node->value());
GenericBinaryOperation(&expr,
overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
} else {
// For non-compound assignment just load the right-hand side.
Load(node->value());
}
// Perform the assignment.
if (var->mode() != Variable::CONST || node->op() == Token::INIT_CONST) {
CodeForSourcePosition(node->position());
StoreToSlot(slot,
node->op() == Token::INIT_CONST ? CONST_INIT : NOT_CONST_INIT);
}
ASSERT(frame()->height() == original_height + 1);
}
void CodeGenerator::EmitNamedPropertyAssignment(Assignment* node) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Comment cmnt(masm(), "[ Named Property Assignment");
Variable* var = node->target()->AsVariableProxy()->AsVariable();
Property* prop = node->target()->AsProperty();
ASSERT(var == NULL || (prop == NULL && var->is_global()));
// Initialize name and evaluate the receiver sub-expression if necessary. If
// the receiver is trivial it is not placed on the stack at this point, but
// loaded whenever actually needed.
Handle<String> name;
bool is_trivial_receiver = false;
if (var != NULL) {
name = var->name();
} else {
Literal* lit = prop->key()->AsLiteral();
ASSERT_NOT_NULL(lit);
name = Handle<String>::cast(lit->handle());
// Do not materialize the receiver on the frame if it is trivial.
is_trivial_receiver = prop->obj()->IsTrivial();
if (!is_trivial_receiver) Load(prop->obj());
}
// Change to slow case in the beginning of an initialization block to
// avoid the quadratic behavior of repeatedly adding fast properties.
if (node->starts_initialization_block()) {
// Initialization block consists of assignments of the form expr.x = ..., so
// this will never be an assignment to a variable, so there must be a
// receiver object.
ASSERT_EQ(NULL, var);
if (is_trivial_receiver) {
frame()->Push(prop->obj());
} else {
frame()->Dup();
}
Result ignored = frame()->CallRuntime(Runtime::kToSlowProperties, 1);
}
// Change to fast case at the end of an initialization block. To prepare for
// that add an extra copy of the receiver to the frame, so that it can be
// converted back to fast case after the assignment.
if (node->ends_initialization_block() && !is_trivial_receiver) {
frame()->Dup();
}
// Stack layout:
// [tos] : receiver (only materialized if non-trivial)
// [tos+1] : receiver if at the end of an initialization block
// Evaluate the right-hand side.
if (node->is_compound()) {
// For a compound assignment the right-hand side is a binary operation
// between the current property value and the actual right-hand side.
if (is_trivial_receiver) {
frame()->Push(prop->obj());
} else if (var != NULL) {
// The LoadIC stub expects the object in eax.
// Freeing eax causes the code generator to load the global into it.
frame_->Spill(eax);
LoadGlobal();
} else {
frame()->Dup();
}
Result value = EmitNamedLoad(name, var != NULL);
frame()->Push(&value);
Load(node->value());
bool overwrite_value =
(node->value()->AsBinaryOperation() != NULL &&
node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
// Construct the implicit binary operation.
BinaryOperation expr(node, node->binary_op(), node->target(),
node->value());
GenericBinaryOperation(&expr,
overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
} else {
// For non-compound assignment just load the right-hand side.
Load(node->value());
}
// Stack layout:
// [tos] : value
// [tos+1] : receiver (only materialized if non-trivial)
// [tos+2] : receiver if at the end of an initialization block
// Perform the assignment. It is safe to ignore constants here.
ASSERT(var == NULL || var->mode() != Variable::CONST);
ASSERT_NE(Token::INIT_CONST, node->op());
if (is_trivial_receiver) {
Result value = frame()->Pop();
frame()->Push(prop->obj());
frame()->Push(&value);
}
CodeForSourcePosition(node->position());
bool is_contextual = (var != NULL);
Result answer = EmitNamedStore(name, is_contextual);
frame()->Push(&answer);
// Stack layout:
// [tos] : result
// [tos+1] : receiver if at the end of an initialization block
if (node->ends_initialization_block()) {
ASSERT_EQ(NULL, var);
// The argument to the runtime call is the receiver.
if (is_trivial_receiver) {
frame()->Push(prop->obj());
} else {
// A copy of the receiver is below the value of the assignment. Swap
// the receiver and the value of the assignment expression.
Result result = frame()->Pop();
Result receiver = frame()->Pop();
frame()->Push(&result);
frame()->Push(&receiver);
}
Result ignored = frame_->CallRuntime(Runtime::kToFastProperties, 1);
}
// Stack layout:
// [tos] : result
ASSERT_EQ(frame()->height(), original_height + 1);
}
void CodeGenerator::EmitKeyedPropertyAssignment(Assignment* node) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Comment cmnt(masm_, "[ Keyed Property Assignment");
Property* prop = node->target()->AsProperty();
ASSERT_NOT_NULL(prop);
// Evaluate the receiver subexpression.
Load(prop->obj());
// Change to slow case in the beginning of an initialization block to
// avoid the quadratic behavior of repeatedly adding fast properties.
if (node->starts_initialization_block()) {
frame_->Dup();
Result ignored = frame_->CallRuntime(Runtime::kToSlowProperties, 1);
}
// Change to fast case at the end of an initialization block. To prepare for
// that add an extra copy of the receiver to the frame, so that it can be
// converted back to fast case after the assignment.
if (node->ends_initialization_block()) {
frame_->Dup();
}
// Evaluate the key subexpression.
Load(prop->key());
// Stack layout:
// [tos] : key
// [tos+1] : receiver
// [tos+2] : receiver if at the end of an initialization block
// Evaluate the right-hand side.
if (node->is_compound()) {
// For a compound assignment the right-hand side is a binary operation
// between the current property value and the actual right-hand side.
// Duplicate receiver and key for loading the current property value.
frame()->PushElementAt(1);
frame()->PushElementAt(1);
Result value = EmitKeyedLoad();
frame()->Push(&value);
Load(node->value());
// Perform the binary operation.
bool overwrite_value =
(node->value()->AsBinaryOperation() != NULL &&
node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
BinaryOperation expr(node, node->binary_op(), node->target(),
node->value());
GenericBinaryOperation(&expr,
overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
} else {
// For non-compound assignment just load the right-hand side.
Load(node->value());
}
// Stack layout:
// [tos] : value
// [tos+1] : key
// [tos+2] : receiver
// [tos+3] : receiver if at the end of an initialization block
// Perform the assignment. It is safe to ignore constants here.
ASSERT(node->op() != Token::INIT_CONST);
CodeForSourcePosition(node->position());
Result answer = EmitKeyedStore(prop->key()->type());
frame()->Push(&answer);
// Stack layout:
// [tos] : result
// [tos+1] : receiver if at the end of an initialization block
// Change to fast case at the end of an initialization block.
if (node->ends_initialization_block()) {
// The argument to the runtime call is the extra copy of the receiver,
// which is below the value of the assignment. Swap the receiver and
// the value of the assignment expression.
Result result = frame()->Pop();
Result receiver = frame()->Pop();
frame()->Push(&result);
frame()->Push(&receiver);
Result ignored = frame_->CallRuntime(Runtime::kToFastProperties, 1);
}
// Stack layout:
// [tos] : result
ASSERT(frame()->height() == original_height + 1);
}
void CodeGenerator::VisitAssignment(Assignment* node) {
ASSERT(!in_safe_int32_mode());
#ifdef DEBUG
int original_height = frame()->height();
#endif
Variable* var = node->target()->AsVariableProxy()->AsVariable();
Property* prop = node->target()->AsProperty();
if (var != NULL && !var->is_global()) {
EmitSlotAssignment(node);
} else if ((prop != NULL && prop->key()->IsPropertyName()) ||
(var != NULL && var->is_global())) {
// Properties whose keys are property names and global variables are
// treated as named property references. We do not need to consider
// global 'this' because it is not a valid left-hand side.
EmitNamedPropertyAssignment(node);
} else if (prop != NULL) {
// Other properties (including rewritten parameters for a function that
// uses arguments) are keyed property assignments.
EmitKeyedPropertyAssignment(node);
} else {
// Invalid left-hand side.
Load(node->target());
Result result = frame()->CallRuntime(Runtime::kThrowReferenceError, 1);
// The runtime call doesn't actually return but the code generator will
// still generate code and expects a certain frame height.
frame()->Push(&result);
}
ASSERT(frame()->height() == original_height + 1);
}
void CodeGenerator::VisitThrow(Throw* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ Throw");
Load(node->exception());
Result result = frame_->CallRuntime(Runtime::kThrow, 1);
frame_->Push(&result);
}
void CodeGenerator::VisitProperty(Property* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ Property");
Reference property(this, node);
property.GetValue();
}
void CodeGenerator::VisitCall(Call* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ Call");
Expression* function = node->expression();
ZoneList<Expression*>* args = node->arguments();
// Check if the function is a variable or a property.
Variable* var = function->AsVariableProxy()->AsVariable();
Property* property = function->AsProperty();
// ------------------------------------------------------------------------
// Fast-case: Use inline caching.
// ---
// According to ECMA-262, section 11.2.3, page 44, the function to call
// must be resolved after the arguments have been evaluated. The IC code
// automatically handles this by loading the arguments before the function
// is resolved in cache misses (this also holds for megamorphic calls).
// ------------------------------------------------------------------------
if (var != NULL && var->is_possibly_eval()) {
// ----------------------------------
// JavaScript example: 'eval(arg)' // eval is not known to be shadowed
// ----------------------------------
// In a call to eval, we first call %ResolvePossiblyDirectEval to
// resolve the function we need to call and the receiver of the
// call. Then we call the resolved function using the given
// arguments.
// Prepare the stack for the call to the resolved function.
Load(function);
// Allocate a frame slot for the receiver.
frame_->Push(Factory::undefined_value());
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Result to hold the result of the function resolution and the
// final result of the eval call.
Result result;
// If we know that eval can only be shadowed by eval-introduced
// variables we attempt to load the global eval function directly
// in generated code. If we succeed, there is no need to perform a
// context lookup in the runtime system.
JumpTarget done;
if (var->slot() != NULL && var->mode() == Variable::DYNAMIC_GLOBAL) {
ASSERT(var->slot()->type() == Slot::LOOKUP);
JumpTarget slow;
// Prepare the stack for the call to
// ResolvePossiblyDirectEvalNoLookup by pushing the loaded
// function, the first argument to the eval call and the
// receiver.
Result fun = LoadFromGlobalSlotCheckExtensions(var->slot(),
NOT_INSIDE_TYPEOF,
&slow);
frame_->Push(&fun);
if (arg_count > 0) {
frame_->PushElementAt(arg_count);
} else {
frame_->Push(Factory::undefined_value());
}
frame_->PushParameterAt(-1);
// Resolve the call.
result =
frame_->CallRuntime(Runtime::kResolvePossiblyDirectEvalNoLookup, 3);
done.Jump(&result);
slow.Bind();
}
// Prepare the stack for the call to ResolvePossiblyDirectEval by
// pushing the loaded function, the first argument to the eval
// call and the receiver.
frame_->PushElementAt(arg_count + 1);
if (arg_count > 0) {
frame_->PushElementAt(arg_count);
} else {
frame_->Push(Factory::undefined_value());
}
frame_->PushParameterAt(-1);
// Resolve the call.
result = frame_->CallRuntime(Runtime::kResolvePossiblyDirectEval, 3);
// If we generated fast-case code bind the jump-target where fast
// and slow case merge.
if (done.is_linked()) done.Bind(&result);
// The runtime call returns a pair of values in eax (function) and
// edx (receiver). Touch up the stack with the right values.
Result receiver = allocator_->Allocate(edx);
frame_->SetElementAt(arg_count + 1, &result);
frame_->SetElementAt(arg_count, &receiver);
receiver.Unuse();
// Call the function.
CodeForSourcePosition(node->position());
InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
CallFunctionStub call_function(arg_count, in_loop, RECEIVER_MIGHT_BE_VALUE);
result = frame_->CallStub(&call_function, arg_count + 1);
// Restore the context and overwrite the function on the stack with
// the result.
frame_->RestoreContextRegister();
frame_->SetElementAt(0, &result);
} else if (var != NULL && !var->is_this() && var->is_global()) {
// ----------------------------------
// JavaScript example: 'foo(1, 2, 3)' // foo is global
// ----------------------------------
// Pass the global object as the receiver and let the IC stub
// patch the stack to use the global proxy as 'this' in the
// invoked function.
LoadGlobal();
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Push the name of the function onto the frame.
frame_->Push(var->name());
// Call the IC initialization code.
CodeForSourcePosition(node->position());
Result result = frame_->CallCallIC(RelocInfo::CODE_TARGET_CONTEXT,
arg_count,
loop_nesting());
frame_->RestoreContextRegister();
frame_->Push(&result);
} else if (var != NULL && var->slot() != NULL &&
var->slot()->type() == Slot::LOOKUP) {
// ----------------------------------
// JavaScript examples:
//
// with (obj) foo(1, 2, 3) // foo may be in obj.
//
// function f() {};
// function g() {
// eval(...);
// f(); // f could be in extension object.
// }
// ----------------------------------
JumpTarget slow, done;
Result function;
// Generate fast case for loading functions from slots that
// correspond to local/global variables or arguments unless they
// are shadowed by eval-introduced bindings.
EmitDynamicLoadFromSlotFastCase(var->slot(),
NOT_INSIDE_TYPEOF,
&function,
&slow,
&done);
slow.Bind();
// Enter the runtime system to load the function from the context.
// Sync the frame so we can push the arguments directly into
// place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(var->name()));
frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
// The runtime call returns a pair of values in eax and edx. The
// looked-up function is in eax and the receiver is in edx. These
// register references are not ref counted here. We spill them
// eagerly since they are arguments to an inevitable call (and are
// not sharable by the arguments).
ASSERT(!allocator()->is_used(eax));
frame_->EmitPush(eax);
// Load the receiver.
ASSERT(!allocator()->is_used(edx));
frame_->EmitPush(edx);
// If fast case code has been generated, emit code to push the
// function and receiver and have the slow path jump around this
// code.
if (done.is_linked()) {
JumpTarget call;
call.Jump();
done.Bind(&function);
frame_->Push(&function);
LoadGlobalReceiver();
call.Bind();
}
// Call the function.
CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
} else if (property != NULL) {
// Check if the key is a literal string.
Literal* literal = property->key()->AsLiteral();
if (literal != NULL && literal->handle()->IsSymbol()) {
// ------------------------------------------------------------------
// JavaScript example: 'object.foo(1, 2, 3)' or 'map["key"](1, 2, 3)'
// ------------------------------------------------------------------
Handle<String> name = Handle<String>::cast(literal->handle());
if (ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION &&
name->IsEqualTo(CStrVector("apply")) &&
args->length() == 2 &&
args->at(1)->AsVariableProxy() != NULL &&
args->at(1)->AsVariableProxy()->IsArguments()) {
// Use the optimized Function.prototype.apply that avoids
// allocating lazily allocated arguments objects.
CallApplyLazy(property->obj(),
args->at(0),
args->at(1)->AsVariableProxy(),
node->position());
} else {
// Push the receiver onto the frame.
Load(property->obj());
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Push the name of the function onto the frame.
frame_->Push(name);
// Call the IC initialization code.
CodeForSourcePosition(node->position());
Result result =
frame_->CallCallIC(RelocInfo::CODE_TARGET, arg_count,
loop_nesting());
frame_->RestoreContextRegister();
frame_->Push(&result);
}
} else {
// -------------------------------------------
// JavaScript example: 'array[index](1, 2, 3)'
// -------------------------------------------
// Load the function to call from the property through a reference.
// Pass receiver to called function.
if (property->is_synthetic()) {
Reference ref(this, property);
ref.GetValue();
// Use global object as receiver.
LoadGlobalReceiver();
// Call the function.
CallWithArguments(args, RECEIVER_MIGHT_BE_VALUE, node->position());
} else {
// Push the receiver onto the frame.
Load(property->obj());
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Load the name of the function.
Load(property->key());
// Call the IC initialization code.
CodeForSourcePosition(node->position());
Result result =
frame_->CallKeyedCallIC(RelocInfo::CODE_TARGET,
arg_count,
loop_nesting());
frame_->RestoreContextRegister();
frame_->Push(&result);
}
}
} else {
// ----------------------------------
// JavaScript example: 'foo(1, 2, 3)' // foo is not global
// ----------------------------------
// Load the function.
Load(function);
// Pass the global proxy as the receiver.
LoadGlobalReceiver();
// Call the function.
CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
}
}
void CodeGenerator::VisitCallNew(CallNew* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ CallNew");
// According to ECMA-262, section 11.2.2, page 44, the function
// expression in new calls must be evaluated before the
// arguments. This is different from ordinary calls, where the
// actual function to call is resolved after the arguments have been
// evaluated.
// Compute function to call and use the global object as the
// receiver. There is no need to use the global proxy here because
// it will always be replaced with a newly allocated object.
Load(node->expression());
LoadGlobal();
// Push the arguments ("left-to-right") on the stack.
ZoneList<Expression*>* args = node->arguments();
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
}
// Call the construct call builtin that handles allocation and
// constructor invocation.
CodeForSourcePosition(node->position());
Result result = frame_->CallConstructor(arg_count);
// Replace the function on the stack with the result.
frame_->SetElementAt(0, &result);
}
void CodeGenerator::GenerateIsSmi(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask));
value.Unuse();
destination()->Split(zero);
}
void CodeGenerator::GenerateLog(ZoneList<Expression*>* args) {
// Conditionally generate a log call.
// Args:
// 0 (literal string): The type of logging (corresponds to the flags).
// This is used to determine whether or not to generate the log call.
// 1 (string): Format string. Access the string at argument index 2
// with '%2s' (see Logger::LogRuntime for all the formats).
// 2 (array): Arguments to the format string.
ASSERT_EQ(args->length(), 3);
#ifdef ENABLE_LOGGING_AND_PROFILING
if (ShouldGenerateLog(args->at(0))) {
Load(args->at(1));
Load(args->at(2));
frame_->CallRuntime(Runtime::kLog, 2);
}
#endif
// Finally, we're expected to leave a value on the top of the stack.
frame_->Push(Factory::undefined_value());
}
void CodeGenerator::GenerateIsNonNegativeSmi(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask | kSmiSignMask));
value.Unuse();
destination()->Split(zero);
}
class DeferredStringCharCodeAt : public DeferredCode {
public:
DeferredStringCharCodeAt(Register object,
Register index,
Register scratch,
Register result)
: result_(result),
char_code_at_generator_(object,
index,
scratch,
result,
&need_conversion_,
&need_conversion_,
&index_out_of_range_,
STRING_INDEX_IS_NUMBER) {}
StringCharCodeAtGenerator* fast_case_generator() {
return &char_code_at_generator_;
}
virtual void Generate() {
VirtualFrameRuntimeCallHelper call_helper(frame_state());
char_code_at_generator_.GenerateSlow(masm(), call_helper);
__ bind(&need_conversion_);
// Move the undefined value into the result register, which will
// trigger conversion.
__ Set(result_, Immediate(Factory::undefined_value()));
__ jmp(exit_label());
__ bind(&index_out_of_range_);
// When the index is out of range, the spec requires us to return
// NaN.
__ Set(result_, Immediate(Factory::nan_value()));
__ jmp(exit_label());
}
private:
Register result_;
Label need_conversion_;
Label index_out_of_range_;
StringCharCodeAtGenerator char_code_at_generator_;
};
// This generates code that performs a String.prototype.charCodeAt() call
// or returns a smi in order to trigger conversion.
void CodeGenerator::GenerateStringCharCodeAt(ZoneList<Expression*>* args) {
Comment(masm_, "[ GenerateStringCharCodeAt");
ASSERT(args->length() == 2);
Load(args->at(0));
Load(args->at(1));
Result index = frame_->Pop();
Result object = frame_->Pop();
object.ToRegister();
index.ToRegister();
// We might mutate the object register.
frame_->Spill(object.reg());
// We need two extra registers.
Result result = allocator()->Allocate();
ASSERT(result.is_valid());
Result scratch = allocator()->Allocate();
ASSERT(scratch.is_valid());
DeferredStringCharCodeAt* deferred =
new DeferredStringCharCodeAt(object.reg(),
index.reg(),
scratch.reg(),
result.reg());
deferred->fast_case_generator()->GenerateFast(masm_);
deferred->BindExit();
frame_->Push(&result);
}
class DeferredStringCharFromCode : public DeferredCode {
public:
DeferredStringCharFromCode(Register code,
Register result)
: char_from_code_generator_(code, result) {}
StringCharFromCodeGenerator* fast_case_generator() {
return &char_from_code_generator_;
}
virtual void Generate() {
VirtualFrameRuntimeCallHelper call_helper(frame_state());
char_from_code_generator_.GenerateSlow(masm(), call_helper);
}
private:
StringCharFromCodeGenerator char_from_code_generator_;
};
// Generates code for creating a one-char string from a char code.
void CodeGenerator::GenerateStringCharFromCode(ZoneList<Expression*>* args) {
Comment(masm_, "[ GenerateStringCharFromCode");
ASSERT(args->length() == 1);
Load(args->at(0));
Result code = frame_->Pop();
code.ToRegister();
ASSERT(code.is_valid());
Result result = allocator()->Allocate();
ASSERT(result.is_valid());
DeferredStringCharFromCode* deferred = new DeferredStringCharFromCode(
code.reg(), result.reg());
deferred->fast_case_generator()->GenerateFast(masm_);
deferred->BindExit();
frame_->Push(&result);
}
class DeferredStringCharAt : public DeferredCode {
public:
DeferredStringCharAt(Register object,
Register index,
Register scratch1,
Register scratch2,
Register result)
: result_(result),
char_at_generator_(object,
index,
scratch1,
scratch2,
result,
&need_conversion_,
&need_conversion_,
&index_out_of_range_,
STRING_INDEX_IS_NUMBER) {}
StringCharAtGenerator* fast_case_generator() {
return &char_at_generator_;
}
virtual void Generate() {
VirtualFrameRuntimeCallHelper call_helper(frame_state());
char_at_generator_.GenerateSlow(masm(), call_helper);
__ bind(&need_conversion_);
// Move smi zero into the result register, which will trigger
// conversion.
__ Set(result_, Immediate(Smi::FromInt(0)));
__ jmp(exit_label());
__ bind(&index_out_of_range_);
// When the index is out of range, the spec requires us to return
// the empty string.
__ Set(result_, Immediate(Factory::empty_string()));
__ jmp(exit_label());
}
private:
Register result_;
Label need_conversion_;
Label index_out_of_range_;
StringCharAtGenerator char_at_generator_;
};
// This generates code that performs a String.prototype.charAt() call
// or returns a smi in order to trigger conversion.
void CodeGenerator::GenerateStringCharAt(ZoneList<Expression*>* args) {
Comment(masm_, "[ GenerateStringCharAt");
ASSERT(args->length() == 2);
Load(args->at(0));
Load(args->at(1));
Result index = frame_->Pop();
Result object = frame_->Pop();
object.ToRegister();
index.ToRegister();
// We might mutate the object register.
frame_->Spill(object.reg());
// We need three extra registers.
Result result = allocator()->Allocate();
ASSERT(result.is_valid());
Result scratch1 = allocator()->Allocate();
ASSERT(scratch1.is_valid());
Result scratch2 = allocator()->Allocate();
ASSERT(scratch2.is_valid());
DeferredStringCharAt* deferred =
new DeferredStringCharAt(object.reg(),
index.reg(),
scratch1.reg(),
scratch2.reg(),
result.reg());
deferred->fast_case_generator()->GenerateFast(masm_);
deferred->BindExit();
frame_->Push(&result);
}
void CodeGenerator::GenerateIsArray(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(equal);
// It is a heap object - get map.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
// Check if the object is a JS array or not.
__ CmpObjectType(value.reg(), JS_ARRAY_TYPE, temp.reg());
value.Unuse();
temp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateIsRegExp(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(equal);
// It is a heap object - get map.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
// Check if the object is a regexp.
__ CmpObjectType(value.reg(), JS_REGEXP_TYPE, temp.reg());
value.Unuse();
temp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateIsObject(ZoneList<Expression*>* args) {
// This generates a fast version of:
// (typeof(arg) === 'object' || %_ClassOf(arg) == 'RegExp')
ASSERT(args->length() == 1);
Load(args->at(0));
Result obj = frame_->Pop();
obj.ToRegister();
__ test(obj.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
__ cmp(obj.reg(), Factory::null_value());
destination()->true_target()->Branch(equal);
Result map = allocator()->Allocate();
ASSERT(map.is_valid());
__ mov(map.reg(), FieldOperand(obj.reg(), HeapObject::kMapOffset));
// Undetectable objects behave like undefined when tested with typeof.
__ test_b(FieldOperand(map.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
destination()->false_target()->Branch(not_zero);
// Do a range test for JSObject type. We can't use
// MacroAssembler::IsInstanceJSObjectType, because we are using a
// ControlDestination, so we copy its implementation here.
__ movzx_b(map.reg(), FieldOperand(map.reg(), Map::kInstanceTypeOffset));
__ sub(Operand(map.reg()), Immediate(FIRST_JS_OBJECT_TYPE));
__ cmp(map.reg(), LAST_JS_OBJECT_TYPE - FIRST_JS_OBJECT_TYPE);
obj.Unuse();
map.Unuse();
destination()->Split(below_equal);
}
void CodeGenerator::GenerateIsFunction(ZoneList<Expression*>* args) {
// This generates a fast version of:
// (%_ClassOf(arg) === 'Function')
ASSERT(args->length() == 1);
Load(args->at(0));
Result obj = frame_->Pop();
obj.ToRegister();
__ test(obj.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ CmpObjectType(obj.reg(), JS_FUNCTION_TYPE, temp.reg());
obj.Unuse();
temp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateIsUndetectableObject(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result obj = frame_->Pop();
obj.ToRegister();
__ test(obj.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(),
FieldOperand(obj.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
obj.Unuse();
temp.Unuse();
destination()->Split(not_zero);
}
void CodeGenerator::GenerateIsConstructCall(ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
// Get the frame pointer for the calling frame.
Result fp = allocator()->Allocate();
__ mov(fp.reg(), Operand(ebp, StandardFrameConstants::kCallerFPOffset));
// Skip the arguments adaptor frame if it exists.
Label check_frame_marker;
__ cmp(Operand(fp.reg(), StandardFrameConstants::kContextOffset),
Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(not_equal, &check_frame_marker);
__ mov(fp.reg(), Operand(fp.reg(), StandardFrameConstants::kCallerFPOffset));
// Check the marker in the calling frame.
__ bind(&check_frame_marker);
__ cmp(Operand(fp.reg(), StandardFrameConstants::kMarkerOffset),
Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
fp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateArgumentsLength(ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
Result fp = allocator_->Allocate();
Result result = allocator_->Allocate();
ASSERT(fp.is_valid() && result.is_valid());
Label exit;
// Get the number of formal parameters.
__ Set(result.reg(), Immediate(Smi::FromInt(scope()->num_parameters())));
// Check if the calling frame is an arguments adaptor frame.
__ mov(fp.reg(), Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ cmp(Operand(fp.reg(), StandardFrameConstants::kContextOffset),
Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(not_equal, &exit);
// Arguments adaptor case: Read the arguments length from the
// adaptor frame.
__ mov(result.reg(),
Operand(fp.reg(), ArgumentsAdaptorFrameConstants::kLengthOffset));
__ bind(&exit);
result.set_type_info(TypeInfo::Smi());
if (FLAG_debug_code) __ AbortIfNotSmi(result.reg());
frame_->Push(&result);
}
void CodeGenerator::GenerateClassOf(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
JumpTarget leave, null, function, non_function_constructor;
Load(args->at(0)); // Load the object.
Result obj = frame_->Pop();
obj.ToRegister();
frame_->Spill(obj.reg());
// If the object is a smi, we return null.
__ test(obj.reg(), Immediate(kSmiTagMask));
null.Branch(zero);
// Check that the object is a JS object but take special care of JS
// functions to make sure they have 'Function' as their class.
__ CmpObjectType(obj.reg(), FIRST_JS_OBJECT_TYPE, obj.reg());
null.Branch(below);
// As long as JS_FUNCTION_TYPE is the last instance type and it is
// right after LAST_JS_OBJECT_TYPE, we can avoid checking for
// LAST_JS_OBJECT_TYPE.
ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
__ CmpInstanceType(obj.reg(), JS_FUNCTION_TYPE);
function.Branch(equal);
// Check if the constructor in the map is a function.
{ Result tmp = allocator()->Allocate();
__ mov(obj.reg(), FieldOperand(obj.reg(), Map::kConstructorOffset));
__ CmpObjectType(obj.reg(), JS_FUNCTION_TYPE, tmp.reg());
non_function_constructor.Branch(not_equal);
}
// The map register now contains the constructor function. Grab the
// instance class name from there.
__ mov(obj.reg(),
FieldOperand(obj.reg(), JSFunction::kSharedFunctionInfoOffset));
__ mov(obj.reg(),
FieldOperand(obj.reg(), SharedFunctionInfo::kInstanceClassNameOffset));
frame_->Push(&obj);
leave.Jump();
// Functions have class 'Function'.
function.Bind();
frame_->Push(Factory::function_class_symbol());
leave.Jump();
// Objects with a non-function constructor have class 'Object'.
non_function_constructor.Bind();
frame_->Push(Factory::Object_symbol());
leave.Jump();
// Non-JS objects have class null.
null.Bind();
frame_->Push(Factory::null_value());
// All done.
leave.Bind();
}
void CodeGenerator::GenerateValueOf(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
JumpTarget leave;
Load(args->at(0)); // Load the object.
frame_->Dup();
Result object = frame_->Pop();
object.ToRegister();
ASSERT(object.is_valid());
// if (object->IsSmi()) return object.
__ test(object.reg(), Immediate(kSmiTagMask));
leave.Branch(zero, taken);
// It is a heap object - get map.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
// if (!object->IsJSValue()) return object.
__ CmpObjectType(object.reg(), JS_VALUE_TYPE, temp.reg());
leave.Branch(not_equal, not_taken);
__ mov(temp.reg(), FieldOperand(object.reg(), JSValue::kValueOffset));
object.Unuse();
frame_->SetElementAt(0, &temp);
leave.Bind();
}
void CodeGenerator::GenerateSetValueOf(ZoneList<Expression*>* args) {
ASSERT(args->length() == 2);
JumpTarget leave;
Load(args->at(0)); // Load the object.
Load(args->at(1)); // Load the value.
Result value = frame_->Pop();
Result object = frame_->Pop();
value.ToRegister();
object.ToRegister();
// if (object->IsSmi()) return value.
__ test(object.reg(), Immediate(kSmiTagMask));
leave.Branch(zero, &value, taken);
// It is a heap object - get its map.
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_valid());
// if (!object->IsJSValue()) return value.
__ CmpObjectType(object.reg(), JS_VALUE_TYPE, scratch.reg());
leave.Branch(not_equal, &value, not_taken);
// Store the value.
__ mov(FieldOperand(object.reg(), JSValue::kValueOffset), value.reg());
// Update the write barrier. Save the value as it will be
// overwritten by the write barrier code and is needed afterward.
Result duplicate_value = allocator_->Allocate();
ASSERT(duplicate_value.is_valid());
__ mov(duplicate_value.reg(), value.reg());
// The object register is also overwritten by the write barrier and
// possibly aliased in the frame.
frame_->Spill(object.reg());
__ RecordWrite(object.reg(), JSValue::kValueOffset, duplicate_value.reg(),
scratch.reg());
object.Unuse();
scratch.Unuse();
duplicate_value.Unuse();
// Leave.
leave.Bind(&value);
frame_->Push(&value);
}
void CodeGenerator::GenerateArguments(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
// ArgumentsAccessStub expects the key in edx and the formal
// parameter count in eax.
Load(args->at(0));
Result key = frame_->Pop();
// Explicitly create a constant result.
Result count(Handle<Smi>(Smi::FromInt(scope()->num_parameters())));
// Call the shared stub to get to arguments[key].
ArgumentsAccessStub stub(ArgumentsAccessStub::READ_ELEMENT);
Result result = frame_->CallStub(&stub, &key, &count);
frame_->Push(&result);
}
void CodeGenerator::GenerateObjectEquals(ZoneList<Expression*>* args) {
ASSERT(args->length() == 2);
// Load the two objects into registers and perform the comparison.
Load(args->at(0));
Load(args->at(1));
Result right = frame_->Pop();
Result left = frame_->Pop();
right.ToRegister();
left.ToRegister();
__ cmp(right.reg(), Operand(left.reg()));
right.Unuse();
left.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateGetFramePointer(ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
ASSERT(kSmiTag == 0); // EBP value is aligned, so it should look like Smi.
Result ebp_as_smi = allocator_->Allocate();
ASSERT(ebp_as_smi.is_valid());
__ mov(ebp_as_smi.reg(), Operand(ebp));
frame_->Push(&ebp_as_smi);
}
void CodeGenerator::GenerateRandomHeapNumber(
ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
frame_->SpillAll();
Label slow_allocate_heapnumber;
Label heapnumber_allocated;
__ AllocateHeapNumber(edi, ebx, ecx, &slow_allocate_heapnumber);
__ jmp(&heapnumber_allocated);
__ bind(&slow_allocate_heapnumber);
// To allocate a heap number, and ensure that it is not a smi, we
// call the runtime function FUnaryMinus on 0, returning the double
// -0.0. A new, distinct heap number is returned each time.
__ push(Immediate(Smi::FromInt(0)));
__ CallRuntime(Runtime::kNumberUnaryMinus, 1);
__ mov(edi, eax);
__ bind(&heapnumber_allocated);
__ PrepareCallCFunction(0, ebx);
__ CallCFunction(ExternalReference::random_uint32_function(), 0);
// Convert 32 random bits in eax to 0.(32 random bits) in a double
// by computing:
// ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
// This is implemented on both SSE2 and FPU.
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ mov(ebx, Immediate(0x49800000)); // 1.0 x 2^20 as single.
__ movd(xmm1, Operand(ebx));
__ movd(xmm0, Operand(eax));
__ cvtss2sd(xmm1, xmm1);
__ pxor(xmm0, xmm1);
__ subsd(xmm0, xmm1);
__ movdbl(FieldOperand(edi, HeapNumber::kValueOffset), xmm0);
} else {
// 0x4130000000000000 is 1.0 x 2^20 as a double.
__ mov(FieldOperand(edi, HeapNumber::kExponentOffset),
Immediate(0x41300000));
__ mov(FieldOperand(edi, HeapNumber::kMantissaOffset), eax);
__ fld_d(FieldOperand(edi, HeapNumber::kValueOffset));
__ mov(FieldOperand(edi, HeapNumber::kMantissaOffset), Immediate(0));
__ fld_d(FieldOperand(edi, HeapNumber::kValueOffset));
__ fsubp(1);
__ fstp_d(FieldOperand(edi, HeapNumber::kValueOffset));
}
__ mov(eax, edi);
Result result = allocator_->Allocate(eax);
frame_->Push(&result);
}
void CodeGenerator::GenerateStringAdd(ZoneList<Expression*>* args) {
ASSERT_EQ(2, args->length());
Load(args->at(0));
Load(args->at(1));
StringAddStub stub(NO_STRING_ADD_FLAGS);
Result answer = frame_->CallStub(&stub, 2);
frame_->Push(&answer);
}
void CodeGenerator::GenerateSubString(ZoneList<Expression*>* args) {
ASSERT_EQ(3, args->length());
Load(args->at(0));
Load(args->at(1));
Load(args->at(2));
SubStringStub stub;
Result answer = frame_->CallStub(&stub, 3);
frame_->Push(&answer);
}
void CodeGenerator::GenerateStringCompare(ZoneList<Expression*>* args) {
ASSERT_EQ(2, args->length());
Load(args->at(0));
Load(args->at(1));
StringCompareStub stub;
Result answer = frame_->CallStub(&stub, 2);
frame_->Push(&answer);
}
void CodeGenerator::GenerateRegExpExec(ZoneList<Expression*>* args) {
ASSERT_EQ(4, args->length());
// Load the arguments on the stack and call the stub.
Load(args->at(0));
Load(args->at(1));
Load(args->at(2));
Load(args->at(3));
RegExpExecStub stub;
Result result = frame_->CallStub(&stub, 4);
frame_->Push(&result);
}
void CodeGenerator::GenerateRegExpConstructResult(ZoneList<Expression*>* args) {
// No stub. This code only occurs a few times in regexp.js.
const int kMaxInlineLength = 100;
ASSERT_EQ(3, args->length());
Load(args->at(0)); // Size of array, smi.
Load(args->at(1)); // "index" property value.
Load(args->at(2)); // "input" property value.
{
VirtualFrame::SpilledScope spilled_scope;
Label slowcase;
Label done;
__ mov(ebx, Operand(esp, kPointerSize * 2));
__ test(ebx, Immediate(kSmiTagMask));
__ j(not_zero, &slowcase);
__ cmp(Operand(ebx), Immediate(Smi::FromInt(kMaxInlineLength)));
__ j(above, &slowcase);
// Smi-tagging is equivalent to multiplying by 2.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
// Allocate RegExpResult followed by FixedArray with size in ebx.
// JSArray: [Map][empty properties][Elements][Length-smi][index][input]
// Elements: [Map][Length][..elements..]
__ AllocateInNewSpace(JSRegExpResult::kSize + FixedArray::kHeaderSize,
times_half_pointer_size,
ebx, // In: Number of elements (times 2, being a smi)
eax, // Out: Start of allocation (tagged).
ecx, // Out: End of allocation.
edx, // Scratch register
&slowcase,
TAG_OBJECT);
// eax: Start of allocated area, object-tagged.
// Set JSArray map to global.regexp_result_map().
// Set empty properties FixedArray.
// Set elements to point to FixedArray allocated right after the JSArray.
// Interleave operations for better latency.
__ mov(edx, ContextOperand(esi, Context::GLOBAL_INDEX));
__ mov(ecx, Immediate(Factory::empty_fixed_array()));
__ lea(ebx, Operand(eax, JSRegExpResult::kSize));
__ mov(edx, FieldOperand(edx, GlobalObject::kGlobalContextOffset));
__ mov(FieldOperand(eax, JSObject::kElementsOffset), ebx);
__ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ecx);
__ mov(edx, ContextOperand(edx, Context::REGEXP_RESULT_MAP_INDEX));
__ mov(FieldOperand(eax, HeapObject::kMapOffset), edx);
// Set input, index and length fields from arguments.
__ pop(FieldOperand(eax, JSRegExpResult::kInputOffset));
__ pop(FieldOperand(eax, JSRegExpResult::kIndexOffset));
__ pop(ecx);
__ mov(FieldOperand(eax, JSArray::kLengthOffset), ecx);
// Fill out the elements FixedArray.
// eax: JSArray.
// ebx: FixedArray.
// ecx: Number of elements in array, as smi.
// Set map.
__ mov(FieldOperand(ebx, HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
// Set length.
__ mov(FieldOperand(ebx, FixedArray::kLengthOffset), ecx);
// Fill contents of fixed-array with the-hole.
__ SmiUntag(ecx);
__ mov(edx, Immediate(Factory::the_hole_value()));
__ lea(ebx, FieldOperand(ebx, FixedArray::kHeaderSize));
// Fill fixed array elements with hole.
// eax: JSArray.
// ecx: Number of elements to fill.
// ebx: Start of elements in FixedArray.
// edx: the hole.
Label loop;
__ test(ecx, Operand(ecx));
__ bind(&loop);
__ j(less_equal, &done); // Jump if ecx is negative or zero.
__ sub(Operand(ecx), Immediate(1));
__ mov(Operand(ebx, ecx, times_pointer_size, 0), edx);
__ jmp(&loop);
__ bind(&slowcase);
__ CallRuntime(Runtime::kRegExpConstructResult, 3);
__ bind(&done);
}
frame_->Forget(3);
frame_->Push(eax);
}
class DeferredSearchCache: public DeferredCode {
public:
DeferredSearchCache(Register dst, Register cache, Register key)
: dst_(dst), cache_(cache), key_(key) {
set_comment("[ DeferredSearchCache");
}
virtual void Generate();
private:
Register dst_; // on invocation Smi index of finger, on exit
// holds value being looked up.
Register cache_; // instance of JSFunctionResultCache.
Register key_; // key being looked up.
};
void DeferredSearchCache::Generate() {
Label first_loop, search_further, second_loop, cache_miss;
// Smi-tagging is equivalent to multiplying by 2.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
Smi* kEntrySizeSmi = Smi::FromInt(JSFunctionResultCache::kEntrySize);
Smi* kEntriesIndexSmi = Smi::FromInt(JSFunctionResultCache::kEntriesIndex);
// Check the cache from finger to start of the cache.
__ bind(&first_loop);
__ sub(Operand(dst_), Immediate(kEntrySizeSmi));
__ cmp(Operand(dst_), Immediate(kEntriesIndexSmi));
__ j(less, &search_further);
__ cmp(key_, CodeGenerator::FixedArrayElementOperand(cache_, dst_));
__ j(not_equal, &first_loop);
__ mov(FieldOperand(cache_, JSFunctionResultCache::kFingerOffset), dst_);
__ mov(dst_, CodeGenerator::FixedArrayElementOperand(cache_, dst_, 1));
__ jmp(exit_label());
__ bind(&search_further);
// Check the cache from end of cache up to finger.
__ mov(dst_, FieldOperand(cache_, JSFunctionResultCache::kCacheSizeOffset));
__ bind(&second_loop);
__ sub(Operand(dst_), Immediate(kEntrySizeSmi));
// Consider prefetching into some reg.
__ cmp(dst_, FieldOperand(cache_, JSFunctionResultCache::kFingerOffset));
__ j(less_equal, &cache_miss);
__ cmp(key_, CodeGenerator::FixedArrayElementOperand(cache_, dst_));
__ j(not_equal, &second_loop);
__ mov(FieldOperand(cache_, JSFunctionResultCache::kFingerOffset), dst_);
__ mov(dst_, CodeGenerator::FixedArrayElementOperand(cache_, dst_, 1));
__ jmp(exit_label());
__ bind(&cache_miss);
__ push(cache_); // store a reference to cache
__ push(key_); // store a key
Handle<Object> receiver(Top::global_context()->global());
__ push(Immediate(receiver));
__ push(key_);
// On ia32 function must be in edi.
__ mov(edi, FieldOperand(cache_, JSFunctionResultCache::kFactoryOffset));
ParameterCount expected(1);
__ InvokeFunction(edi, expected, CALL_FUNCTION);
// Find a place to put new cached value into.
Label add_new_entry, update_cache;
__ mov(ecx, Operand(esp, kPointerSize)); // restore the cache
// Possible optimization: cache size is constant for the given cache
// so technically we could use a constant here. However, if we have
// cache miss this optimization would hardly matter much.
// Check if we could add new entry to cache.
__ mov(ebx, FieldOperand(ecx, FixedArray::kLengthOffset));
__ cmp(ebx, FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset));
__ j(greater, &add_new_entry);
// Check if we could evict entry after finger.
__ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kFingerOffset));
__ add(Operand(edx), Immediate(kEntrySizeSmi));
__ cmp(ebx, Operand(edx));
__ j(greater, &update_cache);
// Need to wrap over the cache.
__ mov(edx, Immediate(kEntriesIndexSmi));
__ jmp(&update_cache);
__ bind(&add_new_entry);
__ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset));
__ lea(ebx, Operand(edx, JSFunctionResultCache::kEntrySize << 1));
__ mov(FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset), ebx);
// Update the cache itself.
// edx holds the index.
__ bind(&update_cache);
__ pop(ebx); // restore the key
__ mov(FieldOperand(ecx, JSFunctionResultCache::kFingerOffset), edx);
// Store key.
__ mov(CodeGenerator::FixedArrayElementOperand(ecx, edx), ebx);
__ RecordWrite(ecx, 0, ebx, edx);
// Store value.
__ pop(ecx); // restore the cache.
__ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kFingerOffset));
__ add(Operand(edx), Immediate(Smi::FromInt(1)));
__ mov(ebx, eax);
__ mov(CodeGenerator::FixedArrayElementOperand(ecx, edx), ebx);
__ RecordWrite(ecx, 0, ebx, edx);
if (!dst_.is(eax)) {
__ mov(dst_, eax);
}
}
void CodeGenerator::GenerateGetFromCache(ZoneList<Expression*>* args) {
ASSERT_EQ(2, args->length());
ASSERT_NE(NULL, args->at(0)->AsLiteral());
int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->handle()))->value();
Handle<FixedArray> jsfunction_result_caches(
Top::global_context()->jsfunction_result_caches());
if (jsfunction_result_caches->length() <= cache_id) {
__ Abort("Attempt to use undefined cache.");
frame_->Push(Factory::undefined_value());
return;
}
Load(args->at(1));
Result key = frame_->Pop();
key.ToRegister();
Result cache = allocator()->Allocate();
ASSERT(cache.is_valid());
__ mov(cache.reg(), ContextOperand(esi, Context::GLOBAL_INDEX));
__ mov(cache.reg(),
FieldOperand(cache.reg(), GlobalObject::kGlobalContextOffset));
__ mov(cache.reg(),
ContextOperand(cache.reg(), Context::JSFUNCTION_RESULT_CACHES_INDEX));
__ mov(cache.reg(),
FieldOperand(cache.reg(), FixedArray::OffsetOfElementAt(cache_id)));
Result tmp = allocator()->Allocate();
ASSERT(tmp.is_valid());
DeferredSearchCache* deferred = new DeferredSearchCache(tmp.reg(),
cache.reg(),
key.reg());
// tmp.reg() now holds finger offset as a smi.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ mov(tmp.reg(), FieldOperand(cache.reg(),
JSFunctionResultCache::kFingerOffset));
__ cmp(key.reg(), FixedArrayElementOperand(cache.reg(), tmp.reg()));
deferred->Branch(not_equal);
__ mov(tmp.reg(), FixedArrayElementOperand(cache.reg(), tmp.reg(), 1));
deferred->BindExit();
frame_->Push(&tmp);
}
void CodeGenerator::GenerateNumberToString(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
// Load the argument on the stack and call the stub.
Load(args->at(0));
NumberToStringStub stub;
Result result = frame_->CallStub(&stub, 1);
frame_->Push(&result);
}
class DeferredSwapElements: public DeferredCode {
public:
DeferredSwapElements(Register object, Register index1, Register index2)
: object_(object), index1_(index1), index2_(index2) {
set_comment("[ DeferredSwapElements");
}
virtual void Generate();
private:
Register object_, index1_, index2_;
};
void DeferredSwapElements::Generate() {
__ push(object_);
__ push(index1_);
__ push(index2_);
__ CallRuntime(Runtime::kSwapElements, 3);
}
void CodeGenerator::GenerateSwapElements(ZoneList<Expression*>* args) {
// Note: this code assumes that indices are passed are within
// elements' bounds and refer to valid (not holes) values.
Comment cmnt(masm_, "[ GenerateSwapElements");
ASSERT_EQ(3, args->length());
Load(args->at(0));
Load(args->at(1));
Load(args->at(2));
Result index2 = frame_->Pop();
index2.ToRegister();
Result index1 = frame_->Pop();
index1.ToRegister();
Result object = frame_->Pop();
object.ToRegister();
Result tmp1 = allocator()->Allocate();
tmp1.ToRegister();
Result tmp2 = allocator()->Allocate();
tmp2.ToRegister();
frame_->Spill(object.reg());
frame_->Spill(index1.reg());
frame_->Spill(index2.reg());
DeferredSwapElements* deferred = new DeferredSwapElements(object.reg(),
index1.reg(),
index2.reg());
// Fetch the map and check if array is in fast case.
// Check that object doesn't require security checks and
// has no indexed interceptor.
__ CmpObjectType(object.reg(), FIRST_JS_OBJECT_TYPE, tmp1.reg());
deferred->Branch(below);
__ test_b(FieldOperand(tmp1.reg(), Map::kBitFieldOffset),
KeyedLoadIC::kSlowCaseBitFieldMask);
deferred->Branch(not_zero);
// Check the object's elements are in fast case.
__ mov(tmp1.reg(), FieldOperand(object.reg(), JSObject::kElementsOffset));
__ cmp(FieldOperand(tmp1.reg(), HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
deferred->Branch(not_equal);
// Smi-tagging is equivalent to multiplying by 2.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
// Check that both indices are smis.
__ mov(tmp2.reg(), index1.reg());
__ or_(tmp2.reg(), Operand(index2.reg()));
__ test(tmp2.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
// Bring addresses into index1 and index2.
__ lea(index1.reg(), FixedArrayElementOperand(tmp1.reg(), index1.reg()));
__ lea(index2.reg(), FixedArrayElementOperand(tmp1.reg(), index2.reg()));
// Swap elements.
__ mov(object.reg(), Operand(index1.reg(), 0));
__ mov(tmp2.reg(), Operand(index2.reg(), 0));
__ mov(Operand(index2.reg(), 0), object.reg());
__ mov(Operand(index1.reg(), 0), tmp2.reg());
Label done;
__ InNewSpace(tmp1.reg(), tmp2.reg(), equal, &done);
// Possible optimization: do a check that both values are Smis
// (or them and test against Smi mask.)
__ mov(tmp2.reg(), tmp1.reg());
__ RecordWriteHelper(tmp2.reg(), index1.reg(), object.reg());
__ RecordWriteHelper(tmp1.reg(), index2.reg(), object.reg());
__ bind(&done);
deferred->BindExit();
frame_->Push(Factory::undefined_value());
}
void CodeGenerator::GenerateCallFunction(ZoneList<Expression*>* args) {
Comment cmnt(masm_, "[ GenerateCallFunction");
ASSERT(args->length() >= 2);
int n_args = args->length() - 2; // for receiver and function.
Load(args->at(0)); // receiver
for (int i = 0; i < n_args; i++) {
Load(args->at(i + 1));
}
Load(args->at(n_args + 1)); // function
Result result = frame_->CallJSFunction(n_args);
frame_->Push(&result);
}
// Generates the Math.pow method. Only handles special cases and
// branches to the runtime system for everything else. Please note
// that this function assumes that the callsite has executed ToNumber
// on both arguments.
void CodeGenerator::GenerateMathPow(ZoneList<Expression*>* args) {
ASSERT(args->length() == 2);
Load(args->at(0));
Load(args->at(1));
if (!CpuFeatures::IsSupported(SSE2)) {
Result res = frame_->CallRuntime(Runtime::kMath_pow, 2);
frame_->Push(&res);
} else {
CpuFeatures::Scope use_sse2(SSE2);
Label allocate_return;
// Load the two operands while leaving the values on the frame.
frame()->Dup();
Result exponent = frame()->Pop();
exponent.ToRegister();
frame()->Spill(exponent.reg());
frame()->PushElementAt(1);
Result base = frame()->Pop();
base.ToRegister();
frame()->Spill(base.reg());
Result answer = allocator()->Allocate();
ASSERT(answer.is_valid());
ASSERT(!exponent.reg().is(base.reg()));
JumpTarget call_runtime;
// Save 1 in xmm3 - we need this several times later on.
__ mov(answer.reg(), Immediate(1));
__ cvtsi2sd(xmm3, Operand(answer.reg()));
Label exponent_nonsmi;
Label base_nonsmi;
// If the exponent is a heap number go to that specific case.
__ test(exponent.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &exponent_nonsmi);
__ test(base.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &base_nonsmi);
// Optimized version when y is an integer.
Label powi;
__ SmiUntag(base.reg());
__ cvtsi2sd(xmm0, Operand(base.reg()));
__ jmp(&powi);
// exponent is smi and base is a heapnumber.
__ bind(&base_nonsmi);
__ cmp(FieldOperand(base.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
call_runtime.Branch(not_equal);
__ movdbl(xmm0, FieldOperand(base.reg(), HeapNumber::kValueOffset));
// Optimized version of pow if y is an integer.
__ bind(&powi);
__ SmiUntag(exponent.reg());
// Save exponent in base as we need to check if exponent is negative later.
// We know that base and exponent are in different registers.
__ mov(base.reg(), exponent.reg());
// Get absolute value of exponent.
Label no_neg;
__ cmp(exponent.reg(), 0);
__ j(greater_equal, &no_neg);
__ neg(exponent.reg());
__ bind(&no_neg);
// Load xmm1 with 1.
__ movsd(xmm1, xmm3);
Label while_true;
Label no_multiply;
__ bind(&while_true);
__ shr(exponent.reg(), 1);
__ j(not_carry, &no_multiply);
__ mulsd(xmm1, xmm0);
__ bind(&no_multiply);
__ test(exponent.reg(), Operand(exponent.reg()));
__ mulsd(xmm0, xmm0);
__ j(not_zero, &while_true);
// x has the original value of y - if y is negative return 1/result.
__ test(base.reg(), Operand(base.reg()));
__ j(positive, &allocate_return);
// Special case if xmm1 has reached infinity.
__ mov(answer.reg(), Immediate(0x7FB00000));
__ movd(xmm0, Operand(answer.reg()));
__ cvtss2sd(xmm0, xmm0);
__ ucomisd(xmm0, xmm1);
call_runtime.Branch(equal);
__ divsd(xmm3, xmm1);
__ movsd(xmm1, xmm3);
__ jmp(&allocate_return);
// exponent (or both) is a heapnumber - no matter what we should now work
// on doubles.
__ bind(&exponent_nonsmi);
__ cmp(FieldOperand(exponent.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
call_runtime.Branch(not_equal);
__ movdbl(xmm1, FieldOperand(exponent.reg(), HeapNumber::kValueOffset));
// Test if exponent is nan.
__ ucomisd(xmm1, xmm1);
call_runtime.Branch(parity_even);
Label base_not_smi;
Label handle_special_cases;
__ test(base.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &base_not_smi);
__ SmiUntag(base.reg());
__ cvtsi2sd(xmm0, Operand(base.reg()));
__ jmp(&handle_special_cases);
__ bind(&base_not_smi);
__ cmp(FieldOperand(base.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
call_runtime.Branch(not_equal);
__ mov(answer.reg(), FieldOperand(base.reg(), HeapNumber::kExponentOffset));
__ and_(answer.reg(), HeapNumber::kExponentMask);
__ cmp(Operand(answer.reg()), Immediate(HeapNumber::kExponentMask));
// base is NaN or +/-Infinity
call_runtime.Branch(greater_equal);
__ movdbl(xmm0, FieldOperand(base.reg(), HeapNumber::kValueOffset));
// base is in xmm0 and exponent is in xmm1.
__ bind(&handle_special_cases);
Label not_minus_half;
// Test for -0.5.
// Load xmm2 with -0.5.
__ mov(answer.reg(), Immediate(0xBF000000));
__ movd(xmm2, Operand(answer.reg()));
__ cvtss2sd(xmm2, xmm2);
// xmm2 now has -0.5.
__ ucomisd(xmm2, xmm1);
__ j(not_equal, ¬_minus_half);
// Calculates reciprocal of square root.
// Note that 1/sqrt(x) = sqrt(1/x))
__ divsd(xmm3, xmm0);
__ movsd(xmm1, xmm3);
__ sqrtsd(xmm1, xmm1);
__ jmp(&allocate_return);
// Test for 0.5.
__ bind(¬_minus_half);
// Load xmm2 with 0.5.
// Since xmm3 is 1 and xmm2 is -0.5 this is simply xmm2 + xmm3.
__ addsd(xmm2, xmm3);
// xmm2 now has 0.5.
__ comisd(xmm2, xmm1);
call_runtime.Branch(not_equal);
// Calculates square root.
__ movsd(xmm1, xmm0);
__ sqrtsd(xmm1, xmm1);
JumpTarget done;
Label failure, success;
__ bind(&allocate_return);
// Make a copy of the frame to enable us to handle allocation
// failure after the JumpTarget jump.
VirtualFrame* clone = new VirtualFrame(frame());
__ AllocateHeapNumber(answer.reg(), exponent.reg(),
base.reg(), &failure);
__ movdbl(FieldOperand(answer.reg(), HeapNumber::kValueOffset), xmm1);
// Remove the two original values from the frame - we only need those
// in the case where we branch to runtime.
frame()->Drop(2);
exponent.Unuse();
base.Unuse();
done.Jump(&answer);
// Use the copy of the original frame as our current frame.
RegisterFile empty_regs;
SetFrame(clone, &empty_regs);
// If we experience an allocation failure we branch to runtime.
__ bind(&failure);
call_runtime.Bind();
answer = frame()->CallRuntime(Runtime::kMath_pow_cfunction, 2);
done.Bind(&answer);
frame()->Push(&answer);
}
}
void CodeGenerator::GenerateMathSin(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
Load(args->at(0));
TranscendentalCacheStub stub(TranscendentalCache::SIN);
Result result = frame_->CallStub(&stub, 1);
frame_->Push(&result);
}
void CodeGenerator::GenerateMathCos(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
Load(args->at(0));
TranscendentalCacheStub stub(TranscendentalCache::COS);
Result result = frame_->CallStub(&stub, 1);
frame_->Push(&result);
}
// Generates the Math.sqrt method. Please note - this function assumes that
// the callsite has executed ToNumber on the argument.
void CodeGenerator::GenerateMathSqrt(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
Load(args->at(0));
if (!CpuFeatures::IsSupported(SSE2)) {
Result result = frame()->CallRuntime(Runtime::kMath_sqrt, 1);
frame()->Push(&result);
} else {
CpuFeatures::Scope use_sse2(SSE2);
// Leave original value on the frame if we need to call runtime.
frame()->Dup();
Result result = frame()->Pop();
result.ToRegister();
frame()->Spill(result.reg());
Label runtime;
Label non_smi;
Label load_done;
JumpTarget end;
__ test(result.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &non_smi);
__ SmiUntag(result.reg());
__ cvtsi2sd(xmm0, Operand(result.reg()));
__ jmp(&load_done);
__ bind(&non_smi);
__ cmp(FieldOperand(result.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, &runtime);
__ movdbl(xmm0, FieldOperand(result.reg(), HeapNumber::kValueOffset));
__ bind(&load_done);
__ sqrtsd(xmm0, xmm0);
// A copy of the virtual frame to allow us to go to runtime after the
// JumpTarget jump.
Result scratch = allocator()->Allocate();
VirtualFrame* clone = new VirtualFrame(frame());
__ AllocateHeapNumber(result.reg(), scratch.reg(), no_reg, &runtime);
__ movdbl(FieldOperand(result.reg(), HeapNumber::kValueOffset), xmm0);
frame()->Drop(1);
scratch.Unuse();
end.Jump(&result);
// We only branch to runtime if we have an allocation error.
// Use the copy of the original frame as our current frame.
RegisterFile empty_regs;
SetFrame(clone, &empty_regs);
__ bind(&runtime);
result = frame()->CallRuntime(Runtime::kMath_sqrt, 1);
end.Bind(&result);
frame()->Push(&result);
}
}
void CodeGenerator::VisitCallRuntime(CallRuntime* node) {
ASSERT(!in_safe_int32_mode());
if (CheckForInlineRuntimeCall(node)) {
return;
}
ZoneList<Expression*>* args = node->arguments();
Comment cmnt(masm_, "[ CallRuntime");
Runtime::Function* function = node->function();
if (function == NULL) {
// Push the builtins object found in the current global object.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), GlobalObject());
__ mov(temp.reg(), FieldOperand(temp.reg(), GlobalObject::kBuiltinsOffset));
frame_->Push(&temp);
}
// Push the arguments ("left-to-right").
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
}
if (function == NULL) {
// Call the JS runtime function.
frame_->Push(node->name());
Result answer = frame_->CallCallIC(RelocInfo::CODE_TARGET,
arg_count,
loop_nesting_);
frame_->RestoreContextRegister();
frame_->Push(&answer);
} else {
// Call the C runtime function.
Result answer = frame_->CallRuntime(function, arg_count);
frame_->Push(&answer);
}
}
void CodeGenerator::VisitUnaryOperation(UnaryOperation* node) {
Comment cmnt(masm_, "[ UnaryOperation");
Token::Value op = node->op();
if (op == Token::NOT) {
// Swap the true and false targets but keep the same actual label
// as the fall through.
destination()->Invert();
LoadCondition(node->expression(), destination(), true);
// Swap the labels back.
destination()->Invert();
} else if (op == Token::DELETE) {
Property* property = node->expression()->AsProperty();
if (property != NULL) {
Load(property->obj());
Load(property->key());
Result answer = frame_->InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, 2);
frame_->Push(&answer);
return;
}
Variable* variable = node->expression()->AsVariableProxy()->AsVariable();
if (variable != NULL) {
Slot* slot = variable->slot();
if (variable->is_global()) {
LoadGlobal();
frame_->Push(variable->name());
Result answer = frame_->InvokeBuiltin(Builtins::DELETE,
CALL_FUNCTION, 2);
frame_->Push(&answer);
return;
} else if (slot != NULL && slot->type() == Slot::LOOKUP) {
// Call the runtime to look up the context holding the named
// variable. Sync the virtual frame eagerly so we can push the
// arguments directly into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(variable->name()));
Result context = frame_->CallRuntime(Runtime::kLookupContext, 2);
ASSERT(context.is_register());
frame_->EmitPush(context.reg());
context.Unuse();
frame_->EmitPush(Immediate(variable->name()));
Result answer = frame_->InvokeBuiltin(Builtins::DELETE,
CALL_FUNCTION, 2);
frame_->Push(&answer);
return;
}
// Default: Result of deleting non-global, not dynamically
// introduced variables is false.
frame_->Push(Factory::false_value());
} else {
// Default: Result of deleting expressions is true.
Load(node->expression()); // may have side-effects
frame_->SetElementAt(0, Factory::true_value());
}
} else if (op == Token::TYPEOF) {
// Special case for loading the typeof expression; see comment on
// LoadTypeofExpression().
LoadTypeofExpression(node->expression());
Result answer = frame_->CallRuntime(Runtime::kTypeof, 1);
frame_->Push(&answer);
} else if (op == Token::VOID) {
Expression* expression = node->expression();
if (expression && expression->AsLiteral() && (
expression->AsLiteral()->IsTrue() ||
expression->AsLiteral()->IsFalse() ||
expression->AsLiteral()->handle()->IsNumber() ||
expression->AsLiteral()->handle()->IsString() ||
expression->AsLiteral()->handle()->IsJSRegExp() ||
expression->AsLiteral()->IsNull())) {
// Omit evaluating the value of the primitive literal.
// It will be discarded anyway, and can have no side effect.
frame_->Push(Factory::undefined_value());
} else {
Load(node->expression());
frame_->SetElementAt(0, Factory::undefined_value());
}
} else {
if (in_safe_int32_mode()) {
Visit(node->expression());
Result value = frame_->Pop();
ASSERT(value.is_untagged_int32());
// Registers containing an int32 value are not multiply used.
ASSERT(!value.is_register() || !frame_->is_used(value.reg()));
value.ToRegister();
switch (op) {
case Token::SUB: {
__ neg(value.reg());
if (node->no_negative_zero()) {
// -MIN_INT is MIN_INT with the overflow flag set.
unsafe_bailout_->Branch(overflow);
} else {
// MIN_INT and 0 both have bad negations. They both have 31 zeros.
__ test(value.reg(), Immediate(0x7FFFFFFF));
unsafe_bailout_->Branch(zero);
}
break;
}
case Token::BIT_NOT: {
__ not_(value.reg());
break;
}
case Token::ADD: {
// Unary plus has no effect on int32 values.
break;
}
default:
UNREACHABLE();
break;
}
frame_->Push(&value);
} else {
Load(node->expression());
bool overwrite =
(node->expression()->AsBinaryOperation() != NULL &&
node->expression()->AsBinaryOperation()->ResultOverwriteAllowed());
switch (op) {
case Token::NOT:
case Token::DELETE:
case Token::TYPEOF:
UNREACHABLE(); // handled above
break;
case Token::SUB: {
GenericUnaryOpStub stub(Token::SUB, overwrite);
Result operand = frame_->Pop();
Result answer = frame_->CallStub(&stub, &operand);
answer.set_type_info(TypeInfo::Number());
frame_->Push(&answer);
break;
}
case Token::BIT_NOT: {
// Smi check.
JumpTarget smi_label;
JumpTarget continue_label;
Result operand = frame_->Pop();
TypeInfo operand_info = operand.type_info();
operand.ToRegister();
if (operand_info.IsSmi()) {
if (FLAG_debug_code) __ AbortIfNotSmi(operand.reg());
frame_->Spill(operand.reg());
// Set smi tag bit. It will be reset by the not operation.
__ lea(operand.reg(), Operand(operand.reg(), kSmiTagMask));
__ not_(operand.reg());
Result answer = operand;
answer.set_type_info(TypeInfo::Smi());
frame_->Push(&answer);
} else {
__ test(operand.reg(), Immediate(kSmiTagMask));
smi_label.Branch(zero, &operand, taken);
GenericUnaryOpStub stub(Token::BIT_NOT, overwrite);
Result answer = frame_->CallStub(&stub, &operand);
continue_label.Jump(&answer);
smi_label.Bind(&answer);
answer.ToRegister();
frame_->Spill(answer.reg());
// Set smi tag bit. It will be reset by the not operation.
__ lea(answer.reg(), Operand(answer.reg(), kSmiTagMask));
__ not_(answer.reg());
continue_label.Bind(&answer);
answer.set_type_info(TypeInfo::Integer32());
frame_->Push(&answer);
}
break;
}
case Token::ADD: {
// Smi check.
JumpTarget continue_label;
Result operand = frame_->Pop();
TypeInfo operand_info = operand.type_info();
operand.ToRegister();
__ test(operand.reg(), Immediate(kSmiTagMask));
continue_label.Branch(zero, &operand, taken);
frame_->Push(&operand);
Result answer = frame_->InvokeBuiltin(Builtins::TO_NUMBER,
CALL_FUNCTION, 1);
continue_label.Bind(&answer);
if (operand_info.IsSmi()) {
answer.set_type_info(TypeInfo::Smi());
} else if (operand_info.IsInteger32()) {
answer.set_type_info(TypeInfo::Integer32());
} else {
answer.set_type_info(TypeInfo::Number());
}
frame_->Push(&answer);
break;
}
default:
UNREACHABLE();
}
}
}
}
// The value in dst was optimistically incremented or decremented. The
// result overflowed or was not smi tagged. Undo the operation, call
// into the runtime to convert the argument to a number, and call the
// specialized add or subtract stub. The result is left in dst.
class DeferredPrefixCountOperation: public DeferredCode {
public:
DeferredPrefixCountOperation(Register dst,
bool is_increment,
TypeInfo input_type)
: dst_(dst), is_increment_(is_increment), input_type_(input_type) {
set_comment("[ DeferredCountOperation");
}
virtual void Generate();
private:
Register dst_;
bool is_increment_;
TypeInfo input_type_;
};
void DeferredPrefixCountOperation::Generate() {
// Undo the optimistic smi operation.
if (is_increment_) {
__ sub(Operand(dst_), Immediate(Smi::FromInt(1)));
} else {
__ add(Operand(dst_), Immediate(Smi::FromInt(1)));
}
Register left;
if (input_type_.IsNumber()) {
left = dst_;
} else {
__ push(dst_);
__ InvokeBuiltin(Builtins::TO_NUMBER, CALL_FUNCTION);
left = eax;
}
GenericBinaryOpStub stub(is_increment_ ? Token::ADD : Token::SUB,
NO_OVERWRITE,
NO_GENERIC_BINARY_FLAGS,
TypeInfo::Number());
stub.GenerateCall(masm_, left, Smi::FromInt(1));
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The value in dst was optimistically incremented or decremented. The
// result overflowed or was not smi tagged. Undo the operation and call
// into the runtime to convert the argument to a number. Update the
// original value in old. Call the specialized add or subtract stub.
// The result is left in dst.
class DeferredPostfixCountOperation: public DeferredCode {
public:
DeferredPostfixCountOperation(Register dst,
Register old,
bool is_increment,
TypeInfo input_type)
: dst_(dst),
old_(old),
is_increment_(is_increment),
input_type_(input_type) {
set_comment("[ DeferredCountOperation");
}
virtual void Generate();
private:
Register dst_;
Register old_;
bool is_increment_;
TypeInfo input_type_;
};
void DeferredPostfixCountOperation::Generate() {
// Undo the optimistic smi operation.
if (is_increment_) {
__ sub(Operand(dst_), Immediate(Smi::FromInt(1)));
} else {
__ add(Operand(dst_), Immediate(Smi::FromInt(1)));
}
Register left;
if (input_type_.IsNumber()) {
__ push(dst_); // Save the input to use as the old value.
left = dst_;
} else {
__ push(dst_);
__ InvokeBuiltin(Builtins::TO_NUMBER, CALL_FUNCTION);
__ push(eax); // Save the result of ToNumber to use as the old value.
left = eax;
}
GenericBinaryOpStub stub(is_increment_ ? Token::ADD : Token::SUB,
NO_OVERWRITE,
NO_GENERIC_BINARY_FLAGS,
TypeInfo::Number());
stub.GenerateCall(masm_, left, Smi::FromInt(1));
if (!dst_.is(eax)) __ mov(dst_, eax);
__ pop(old_);
}
void CodeGenerator::VisitCountOperation(CountOperation* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ CountOperation");
bool is_postfix = node->is_postfix();
bool is_increment = node->op() == Token::INC;
Variable* var = node->expression()->AsVariableProxy()->AsVariable();
bool is_const = (var != NULL && var->mode() == Variable::CONST);
// Postfix operations need a stack slot under the reference to hold
// the old value while the new value is being stored. This is so that
// in the case that storing the new value requires a call, the old
// value will be in the frame to be spilled.
if (is_postfix) frame_->Push(Smi::FromInt(0));
// A constant reference is not saved to, so a constant reference is not a
// compound assignment reference.
{ Reference target(this, node->expression(), !is_const);
if (target.is_illegal()) {
// Spoof the virtual frame to have the expected height (one higher
// than on entry).
if (!is_postfix) frame_->Push(Smi::FromInt(0));
return;
}
target.TakeValue();
Result new_value = frame_->Pop();
new_value.ToRegister();
Result old_value; // Only allocated in the postfix case.
if (is_postfix) {
// Allocate a temporary to preserve the old value.
old_value = allocator_->Allocate();
ASSERT(old_value.is_valid());
__ mov(old_value.reg(), new_value.reg());
// The return value for postfix operations is ToNumber(input).
// Keep more precise type info if the input is some kind of
// number already. If the input is not a number we have to wait
// for the deferred code to convert it.
if (new_value.type_info().IsNumber()) {
old_value.set_type_info(new_value.type_info());
}
}
// Ensure the new value is writable.
frame_->Spill(new_value.reg());
Result tmp;
if (new_value.is_smi()) {
if (FLAG_debug_code) __ AbortIfNotSmi(new_value.reg());
} else {
// We don't know statically if the input is a smi.
// In order to combine the overflow and the smi tag check, we need
// to be able to allocate a byte register. We attempt to do so
// without spilling. If we fail, we will generate separate overflow
// and smi tag checks.
// We allocate and clear a temporary byte register before performing
// the count operation since clearing the register using xor will clear
// the overflow flag.
tmp = allocator_->AllocateByteRegisterWithoutSpilling();
if (tmp.is_valid()) {
__ Set(tmp.reg(), Immediate(0));
}
}
if (is_increment) {
__ add(Operand(new_value.reg()), Immediate(Smi::FromInt(1)));
} else {
__ sub(Operand(new_value.reg()), Immediate(Smi::FromInt(1)));
}
DeferredCode* deferred = NULL;
if (is_postfix) {
deferred = new DeferredPostfixCountOperation(new_value.reg(),
old_value.reg(),
is_increment,
new_value.type_info());
} else {
deferred = new DeferredPrefixCountOperation(new_value.reg(),
is_increment,
new_value.type_info());
}
if (new_value.is_smi()) {
// In case we have a smi as input just check for overflow.
deferred->Branch(overflow);
} else {
// If the count operation didn't overflow and the result is a valid
// smi, we're done. Otherwise, we jump to the deferred slow-case
// code.
// We combine the overflow and the smi tag check if we could
// successfully allocate a temporary byte register.
if (tmp.is_valid()) {
__ setcc(overflow, tmp.reg());
__ or_(Operand(tmp.reg()), new_value.reg());
__ test(tmp.reg(), Immediate(kSmiTagMask));
tmp.Unuse();
deferred->Branch(not_zero);
} else {
// Otherwise we test separately for overflow and smi tag.
deferred->Branch(overflow);
__ test(new_value.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
}
}
deferred->BindExit();
// Postfix count operations return their input converted to
// number. The case when the input is already a number is covered
// above in the allocation code for old_value.
if (is_postfix && !new_value.type_info().IsNumber()) {
old_value.set_type_info(TypeInfo::Number());
}
// The result of ++ or -- is an Integer32 if the
// input is a smi. Otherwise it is a number.
if (new_value.is_smi()) {
new_value.set_type_info(TypeInfo::Integer32());
} else {
new_value.set_type_info(TypeInfo::Number());
}
// Postfix: store the old value in the allocated slot under the
// reference.
if (is_postfix) frame_->SetElementAt(target.size(), &old_value);
frame_->Push(&new_value);
// Non-constant: update the reference.
if (!is_const) target.SetValue(NOT_CONST_INIT);
}
// Postfix: drop the new value and use the old.
if (is_postfix) frame_->Drop();
}
void CodeGenerator::Int32BinaryOperation(BinaryOperation* node) {
Token::Value op = node->op();
Comment cmnt(masm_, "[ Int32BinaryOperation");
ASSERT(in_safe_int32_mode());
ASSERT(safe_int32_mode_enabled());
ASSERT(FLAG_safe_int32_compiler);
if (op == Token::COMMA) {
// Discard left value.
frame_->Nip(1);
return;
}
Result right = frame_->Pop();
Result left = frame_->Pop();
ASSERT(right.is_untagged_int32());
ASSERT(left.is_untagged_int32());
// Registers containing an int32 value are not multiply used.
ASSERT(!left.is_register() || !frame_->is_used(left.reg()));
ASSERT(!right.is_register() || !frame_->is_used(right.reg()));
switch (op) {
case Token::COMMA:
case Token::OR:
case Token::AND:
UNREACHABLE();
break;
case Token::BIT_OR:
case Token::BIT_XOR:
case Token::BIT_AND:
if (left.is_constant() || right.is_constant()) {
int32_t value; // Put constant in value, non-constant in left.
// Constants are known to be int32 values, from static analysis,
// or else will be converted to int32 by implicit ECMA [[ToInt32]].
if (left.is_constant()) {
ASSERT(left.handle()->IsSmi() || left.handle()->IsHeapNumber());
value = NumberToInt32(*left.handle());
left = right;
} else {
ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
value = NumberToInt32(*right.handle());
}
left.ToRegister();
if (op == Token::BIT_OR) {
__ or_(Operand(left.reg()), Immediate(value));
} else if (op == Token::BIT_XOR) {
__ xor_(Operand(left.reg()), Immediate(value));
} else {
ASSERT(op == Token::BIT_AND);
__ and_(Operand(left.reg()), Immediate(value));
}
} else {
ASSERT(left.is_register());
ASSERT(right.is_register());
if (op == Token::BIT_OR) {
__ or_(left.reg(), Operand(right.reg()));
} else if (op == Token::BIT_XOR) {
__ xor_(left.reg(), Operand(right.reg()));
} else {
ASSERT(op == Token::BIT_AND);
__ and_(left.reg(), Operand(right.reg()));
}
}
frame_->Push(&left);
right.Unuse();
break;
case Token::SAR:
case Token::SHL:
case Token::SHR: {
bool test_shr_overflow = false;
left.ToRegister();
if (right.is_constant()) {
ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
int shift_amount = NumberToInt32(*right.handle()) & 0x1F;
if (op == Token::SAR) {
__ sar(left.reg(), shift_amount);
} else if (op == Token::SHL) {
__ shl(left.reg(), shift_amount);
} else {
ASSERT(op == Token::SHR);
__ shr(left.reg(), shift_amount);
if (shift_amount == 0) test_shr_overflow = true;
}
} else {
// Move right to ecx
if (left.is_register() && left.reg().is(ecx)) {
right.ToRegister();
__ xchg(left.reg(), right.reg());
left = right; // Left is unused here, copy of right unused by Push.
} else {
right.ToRegister(ecx);
left.ToRegister();
}
if (op == Token::SAR) {
__ sar_cl(left.reg());
} else if (op == Token::SHL) {
__ shl_cl(left.reg());
} else {
ASSERT(op == Token::SHR);
__ shr_cl(left.reg());
test_shr_overflow = true;
}
}
{
Register left_reg = left.reg();
frame_->Push(&left);
right.Unuse();
if (test_shr_overflow && !node->to_int32()) {
// Uint32 results with top bit set are not Int32 values.
// If they will be forced to Int32, skip the test.
// Test is needed because shr with shift amount 0 does not set flags.
__ test(left_reg, Operand(left_reg));
unsafe_bailout_->Branch(sign);
}
}
break;
}
case Token::ADD:
case Token::SUB:
case Token::MUL:
if ((left.is_constant() && op != Token::SUB) || right.is_constant()) {
int32_t value; // Put constant in value, non-constant in left.
if (right.is_constant()) {
ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
value = NumberToInt32(*right.handle());
} else {
ASSERT(left.handle()->IsSmi() || left.handle()->IsHeapNumber());
value = NumberToInt32(*left.handle());
left = right;
}
left.ToRegister();
if (op == Token::ADD) {
__ add(Operand(left.reg()), Immediate(value));
} else if (op == Token::SUB) {
__ sub(Operand(left.reg()), Immediate(value));
} else {
ASSERT(op == Token::MUL);
__ imul(left.reg(), left.reg(), value);
}
} else {
left.ToRegister();
ASSERT(left.is_register());
ASSERT(right.is_register());
if (op == Token::ADD) {
__ add(left.reg(), Operand(right.reg()));
} else if (op == Token::SUB) {
__ sub(left.reg(), Operand(right.reg()));
} else {
ASSERT(op == Token::MUL);
// We have statically verified that a negative zero can be ignored.
__ imul(left.reg(), Operand(right.reg()));
}
}
right.Unuse();
frame_->Push(&left);
if (!node->to_int32()) {
// If ToInt32 is called on the result of ADD, SUB, or MUL, we don't
// care about overflows.
unsafe_bailout_->Branch(overflow);
}
break;
case Token::DIV:
case Token::MOD: {
if (right.is_register() && (right.reg().is(eax) || right.reg().is(edx))) {
if (left.is_register() && left.reg().is(edi)) {
right.ToRegister(ebx);
} else {
right.ToRegister(edi);
}
}
left.ToRegister(eax);
Result edx_reg = allocator_->Allocate(edx);
right.ToRegister();
// The results are unused here because BreakTarget::Branch cannot handle
// live results.
Register right_reg = right.reg();
left.Unuse();
right.Unuse();
edx_reg.Unuse();
__ cmp(right_reg, 0);
// Ensure divisor is positive: no chance of non-int32 or -0 result.
unsafe_bailout_->Branch(less_equal);
__ cdq(); // Sign-extend eax into edx:eax
__ idiv(right_reg);
if (op == Token::MOD) {
// Negative zero can arise as a negative divident with a zero result.
if (!node->no_negative_zero()) {
Label not_negative_zero;
__ test(edx, Operand(edx));
__ j(not_zero, ¬_negative_zero);
__ test(eax, Operand(eax));
unsafe_bailout_->Branch(negative);
__ bind(¬_negative_zero);
}
Result edx_result(edx, TypeInfo::Integer32());
edx_result.set_untagged_int32(true);
frame_->Push(&edx_result);
} else {
ASSERT(op == Token::DIV);
__ test(edx, Operand(edx));
unsafe_bailout_->Branch(not_equal);
Result eax_result(eax, TypeInfo::Integer32());
eax_result.set_untagged_int32(true);
frame_->Push(&eax_result);
}
break;
}
default:
UNREACHABLE();
break;
}
}
void CodeGenerator::GenerateLogicalBooleanOperation(BinaryOperation* node) {
// According to ECMA-262 section 11.11, page 58, the binary logical
// operators must yield the result of one of the two expressions
// before any ToBoolean() conversions. This means that the value
// produced by a && or || operator is not necessarily a boolean.
// NOTE: If the left hand side produces a materialized value (not
// control flow), we force the right hand side to do the same. This
// is necessary because we assume that if we get control flow on the
// last path out of an expression we got it on all paths.
if (node->op() == Token::AND) {
ASSERT(!in_safe_int32_mode());
JumpTarget is_true;
ControlDestination dest(&is_true, destination()->false_target(), true);
LoadCondition(node->left(), &dest, false);
if (dest.false_was_fall_through()) {
// The current false target was used as the fall-through. If
// there are no dangling jumps to is_true then the left
// subexpression was unconditionally false. Otherwise we have
// paths where we do have to evaluate the right subexpression.
if (is_true.is_linked()) {
// We need to compile the right subexpression. If the jump to
// the current false target was a forward jump then we have a
// valid frame, we have just bound the false target, and we
// have to jump around the code for the right subexpression.
if (has_valid_frame()) {
destination()->false_target()->Unuse();
destination()->false_target()->Jump();
}
is_true.Bind();
// The left subexpression compiled to control flow, so the
// right one is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have actually just jumped to or bound the current false
// target but the current control destination is not marked as
// used.
destination()->Use(false);
}
} else if (dest.is_used()) {
// The left subexpression compiled to control flow (and is_true
// was just bound), so the right is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have a materialized value on the frame, so we exit with
// one on all paths. There are possibly also jumps to is_true
// from nested subexpressions.
JumpTarget pop_and_continue;
JumpTarget exit;
// Avoid popping the result if it converts to 'false' using the
// standard ToBoolean() conversion as described in ECMA-262,
// section 9.2, page 30.
//
// Duplicate the TOS value. The duplicate will be popped by
// ToBoolean.
frame_->Dup();
ControlDestination dest(&pop_and_continue, &exit, true);
ToBoolean(&dest);
// Pop the result of evaluating the first part.
frame_->Drop();
// Compile right side expression.
is_true.Bind();
Load(node->right());
// Exit (always with a materialized value).
exit.Bind();
}
} else {
ASSERT(node->op() == Token::OR);
ASSERT(!in_safe_int32_mode());
JumpTarget is_false;
ControlDestination dest(destination()->true_target(), &is_false, false);
LoadCondition(node->left(), &dest, false);
if (dest.true_was_fall_through()) {
// The current true target was used as the fall-through. If
// there are no dangling jumps to is_false then the left
// subexpression was unconditionally true. Otherwise we have
// paths where we do have to evaluate the right subexpression.
if (is_false.is_linked()) {
// We need to compile the right subexpression. If the jump to
// the current true target was a forward jump then we have a
// valid frame, we have just bound the true target, and we
// have to jump around the code for the right subexpression.
if (has_valid_frame()) {
destination()->true_target()->Unuse();
destination()->true_target()->Jump();
}
is_false.Bind();
// The left subexpression compiled to control flow, so the
// right one is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have just jumped to or bound the current true target but
// the current control destination is not marked as used.
destination()->Use(true);
}
} else if (dest.is_used()) {
// The left subexpression compiled to control flow (and is_false
// was just bound), so the right is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have a materialized value on the frame, so we exit with
// one on all paths. There are possibly also jumps to is_false
// from nested subexpressions.
JumpTarget pop_and_continue;
JumpTarget exit;
// Avoid popping the result if it converts to 'true' using the
// standard ToBoolean() conversion as described in ECMA-262,
// section 9.2, page 30.
//
// Duplicate the TOS value. The duplicate will be popped by
// ToBoolean.
frame_->Dup();
ControlDestination dest(&exit, &pop_and_continue, false);
ToBoolean(&dest);
// Pop the result of evaluating the first part.
frame_->Drop();
// Compile right side expression.
is_false.Bind();
Load(node->right());
// Exit (always with a materialized value).
exit.Bind();
}
}
}
void CodeGenerator::VisitBinaryOperation(BinaryOperation* node) {
Comment cmnt(masm_, "[ BinaryOperation");
if (node->op() == Token::AND || node->op() == Token::OR) {
GenerateLogicalBooleanOperation(node);
} else if (in_safe_int32_mode()) {
Visit(node->left());
Visit(node->right());
Int32BinaryOperation(node);
} else {
// NOTE: The code below assumes that the slow cases (calls to runtime)
// never return a constant/immutable object.
OverwriteMode overwrite_mode = NO_OVERWRITE;
if (node->left()->AsBinaryOperation() != NULL &&
node->left()->AsBinaryOperation()->ResultOverwriteAllowed()) {
overwrite_mode = OVERWRITE_LEFT;
} else if (node->right()->AsBinaryOperation() != NULL &&
node->right()->AsBinaryOperation()->ResultOverwriteAllowed()) {
overwrite_mode = OVERWRITE_RIGHT;
}
if (node->left()->IsTrivial()) {
Load(node->right());
Result right = frame_->Pop();
frame_->Push(node->left());
frame_->Push(&right);
} else {
Load(node->left());
Load(node->right());
}
GenericBinaryOperation(node, overwrite_mode);
}
}
void CodeGenerator::VisitThisFunction(ThisFunction* node) {
ASSERT(!in_safe_int32_mode());
frame_->PushFunction();
}
void CodeGenerator::VisitCompareOperation(CompareOperation* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ CompareOperation");
bool left_already_loaded = false;
// Get the expressions from the node.
Expression* left = node->left();
Expression* right = node->right();
Token::Value op = node->op();
// To make typeof testing for natives implemented in JavaScript really
// efficient, we generate special code for expressions of the form:
// 'typeof <expression> == <string>'.
UnaryOperation* operation = left->AsUnaryOperation();
if ((op == Token::EQ || op == Token::EQ_STRICT) &&
(operation != NULL && operation->op() == Token::TYPEOF) &&
(right->AsLiteral() != NULL &&
right->AsLiteral()->handle()->IsString())) {
Handle<String> check(String::cast(*right->AsLiteral()->handle()));
// Load the operand and move it to a register.
LoadTypeofExpression(operation->expression());
Result answer = frame_->Pop();
answer.ToRegister();
if (check->Equals(Heap::number_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->true_target()->Branch(zero);
frame_->Spill(answer.reg());
__ mov(answer.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
__ cmp(answer.reg(), Factory::heap_number_map());
answer.Unuse();
destination()->Split(equal);
} else if (check->Equals(Heap::string_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
// It can be an undetectable string object.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
destination()->false_target()->Branch(not_zero);
__ CmpInstanceType(temp.reg(), FIRST_NONSTRING_TYPE);
temp.Unuse();
answer.Unuse();
destination()->Split(below);
} else if (check->Equals(Heap::boolean_symbol())) {
__ cmp(answer.reg(), Factory::true_value());
destination()->true_target()->Branch(equal);
__ cmp(answer.reg(), Factory::false_value());
answer.Unuse();
destination()->Split(equal);
} else if (check->Equals(Heap::undefined_symbol())) {
__ cmp(answer.reg(), Factory::undefined_value());
destination()->true_target()->Branch(equal);
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
// It can be an undetectable object.
frame_->Spill(answer.reg());
__ mov(answer.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(answer.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
answer.Unuse();
destination()->Split(not_zero);
} else if (check->Equals(Heap::function_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
frame_->Spill(answer.reg());
__ CmpObjectType(answer.reg(), JS_FUNCTION_TYPE, answer.reg());
destination()->true_target()->Branch(equal);
// Regular expressions are callable so typeof == 'function'.
__ CmpInstanceType(answer.reg(), JS_REGEXP_TYPE);
answer.Unuse();
destination()->Split(equal);
} else if (check->Equals(Heap::object_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
__ cmp(answer.reg(), Factory::null_value());
destination()->true_target()->Branch(equal);
Result map = allocator()->Allocate();
ASSERT(map.is_valid());
// Regular expressions are typeof == 'function', not 'object'.
__ CmpObjectType(answer.reg(), JS_REGEXP_TYPE, map.reg());
destination()->false_target()->Branch(equal);
// It can be an undetectable object.
__ test_b(FieldOperand(map.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
destination()->false_target()->Branch(not_zero);
// Do a range test for JSObject type. We can't use
// MacroAssembler::IsInstanceJSObjectType, because we are using a
// ControlDestination, so we copy its implementation here.
__ movzx_b(map.reg(), FieldOperand(map.reg(), Map::kInstanceTypeOffset));
__ sub(Operand(map.reg()), Immediate(FIRST_JS_OBJECT_TYPE));
__ cmp(map.reg(), LAST_JS_OBJECT_TYPE - FIRST_JS_OBJECT_TYPE);
answer.Unuse();
map.Unuse();
destination()->Split(below_equal);
} else {
// Uncommon case: typeof testing against a string literal that is
// never returned from the typeof operator.
answer.Unuse();
destination()->Goto(false);
}
return;
} else if (op == Token::LT &&
right->AsLiteral() != NULL &&
right->AsLiteral()->handle()->IsHeapNumber()) {
Handle<HeapNumber> check(HeapNumber::cast(*right->AsLiteral()->handle()));
if (check->value() == 2147483648.0) { // 0x80000000.
Load(left);
left_already_loaded = true;
Result lhs = frame_->Pop();
lhs.ToRegister();
__ test(lhs.reg(), Immediate(kSmiTagMask));
destination()->true_target()->Branch(zero); // All Smis are less.
Result scratch = allocator()->Allocate();
ASSERT(scratch.is_valid());
__ mov(scratch.reg(), FieldOperand(lhs.reg(), HeapObject::kMapOffset));
__ cmp(scratch.reg(), Factory::heap_number_map());
JumpTarget not_a_number;
not_a_number.Branch(not_equal, &lhs);
__ mov(scratch.reg(),
FieldOperand(lhs.reg(), HeapNumber::kExponentOffset));
__ cmp(Operand(scratch.reg()), Immediate(0xfff00000));
not_a_number.Branch(above_equal, &lhs); // It's a negative NaN or -Inf.
const uint32_t borderline_exponent =
(HeapNumber::kExponentBias + 31) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch.reg()), Immediate(borderline_exponent));
scratch.Unuse();
lhs.Unuse();
destination()->true_target()->Branch(less);
destination()->false_target()->Jump();
not_a_number.Bind(&lhs);
frame_->Push(&lhs);
}
}
Condition cc = no_condition;
bool strict = false;
switch (op) {
case Token::EQ_STRICT:
strict = true;
// Fall through
case Token::EQ:
cc = equal;
break;
case Token::LT:
cc = less;
break;
case Token::GT:
cc = greater;
break;
case Token::LTE:
cc = less_equal;
break;
case Token::GTE:
cc = greater_equal;
break;
case Token::IN: {
if (!left_already_loaded) Load(left);
Load(right);
Result answer = frame_->InvokeBuiltin(Builtins::IN, CALL_FUNCTION, 2);
frame_->Push(&answer); // push the result
return;
}
case Token::INSTANCEOF: {
if (!left_already_loaded) Load(left);
Load(right);
InstanceofStub stub;
Result answer = frame_->CallStub(&stub, 2);
answer.ToRegister();
__ test(answer.reg(), Operand(answer.reg()));
answer.Unuse();
destination()->Split(zero);
return;
}
default:
UNREACHABLE();
}
if (left->IsTrivial()) {
if (!left_already_loaded) {
Load(right);
Result right_result = frame_->Pop();
frame_->Push(left);
frame_->Push(&right_result);
} else {
Load(right);
}
} else {
if (!left_already_loaded) Load(left);
Load(right);
}
Comparison(node, cc, strict, destination());
}
#ifdef DEBUG
bool CodeGenerator::HasValidEntryRegisters() {
return (allocator()->count(eax) == (frame()->is_used(eax) ? 1 : 0))
&& (allocator()->count(ebx) == (frame()->is_used(ebx) ? 1 : 0))
&& (allocator()->count(ecx) == (frame()->is_used(ecx) ? 1 : 0))
&& (allocator()->count(edx) == (frame()->is_used(edx) ? 1 : 0))
&& (allocator()->count(edi) == (frame()->is_used(edi) ? 1 : 0));
}
#endif
// Emit a LoadIC call to get the value from receiver and leave it in
// dst.
class DeferredReferenceGetNamedValue: public DeferredCode {
public:
DeferredReferenceGetNamedValue(Register dst,
Register receiver,
Handle<String> name)
: dst_(dst), receiver_(receiver), name_(name) {
set_comment("[ DeferredReferenceGetNamedValue");
}
virtual void Generate();
Label* patch_site() { return &patch_site_; }
private:
Label patch_site_;
Register dst_;
Register receiver_;
Handle<String> name_;
};
void DeferredReferenceGetNamedValue::Generate() {
if (!receiver_.is(eax)) {
__ mov(eax, receiver_);
}
__ Set(ecx, Immediate(name_));
Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
__ call(ic, RelocInfo::CODE_TARGET);
// The call must be followed by a test eax instruction to indicate
// that the inobject property case was inlined.
//
// Store the delta to the map check instruction here in the test
// instruction. Use masm_-> instead of the __ macro since the
// latter can't return a value.
int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
// Here we use masm_-> instead of the __ macro because this is the
// instruction that gets patched and coverage code gets in the way.
masm_->test(eax, Immediate(-delta_to_patch_site));
__ IncrementCounter(&Counters::named_load_inline_miss, 1);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
class DeferredReferenceGetKeyedValue: public DeferredCode {
public:
explicit DeferredReferenceGetKeyedValue(Register dst,
Register receiver,
Register key)
: dst_(dst), receiver_(receiver), key_(key) {
set_comment("[ DeferredReferenceGetKeyedValue");
}
virtual void Generate();
Label* patch_site() { return &patch_site_; }
private:
Label patch_site_;
Register dst_;
Register receiver_;
Register key_;
};
void DeferredReferenceGetKeyedValue::Generate() {
if (!receiver_.is(eax)) {
// Register eax is available for key.
if (!key_.is(eax)) {
__ mov(eax, key_);
}
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
} else if (!key_.is(edx)) {
// Register edx is available for receiver.
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
if (!key_.is(eax)) {
__ mov(eax, key_);
}
} else {
__ xchg(edx, eax);
}
// Calculate the delta from the IC call instruction to the map check
// cmp instruction in the inlined version. This delta is stored in
// a test(eax, delta) instruction after the call so that we can find
// it in the IC initialization code and patch the cmp instruction.
// This means that we cannot allow test instructions after calls to
// KeyedLoadIC stubs in other places.
Handle<Code> ic(Builtins::builtin(Builtins::KeyedLoadIC_Initialize));
__ call(ic, RelocInfo::CODE_TARGET);
// The delta from the start of the map-compare instruction to the
// test instruction. We use masm_-> directly here instead of the __
// macro because the macro sometimes uses macro expansion to turn
// into something that can't return a value. This is encountered
// when doing generated code coverage tests.
int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
// Here we use masm_-> instead of the __ macro because this is the
// instruction that gets patched and coverage code gets in the way.
masm_->test(eax, Immediate(-delta_to_patch_site));
__ IncrementCounter(&Counters::keyed_load_inline_miss, 1);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
class DeferredReferenceSetKeyedValue: public DeferredCode {
public:
DeferredReferenceSetKeyedValue(Register value,
Register key,
Register receiver,
Register scratch)
: value_(value),
key_(key),
receiver_(receiver),
scratch_(scratch) {
set_comment("[ DeferredReferenceSetKeyedValue");
}
virtual void Generate();
Label* patch_site() { return &patch_site_; }
private:
Register value_;
Register key_;
Register receiver_;
Register scratch_;
Label patch_site_;
};
void DeferredReferenceSetKeyedValue::Generate() {
__ IncrementCounter(&Counters::keyed_store_inline_miss, 1);
// Move value_ to eax, key_ to ecx, and receiver_ to edx.
Register old_value = value_;
// First, move value to eax.
if (!value_.is(eax)) {
if (key_.is(eax)) {
// Move key_ out of eax, preferably to ecx.
if (!value_.is(ecx) && !receiver_.is(ecx)) {
__ mov(ecx, key_);
key_ = ecx;
} else {
__ mov(scratch_, key_);
key_ = scratch_;
}
}
if (receiver_.is(eax)) {
// Move receiver_ out of eax, preferably to edx.
if (!value_.is(edx) && !key_.is(edx)) {
__ mov(edx, receiver_);
receiver_ = edx;
} else {
// Both moves to scratch are from eax, also, no valid path hits both.
__ mov(scratch_, receiver_);
receiver_ = scratch_;
}
}
__ mov(eax, value_);
value_ = eax;
}
// Now value_ is in eax. Move the other two to the right positions.
// We do not update the variables key_ and receiver_ to ecx and edx.
if (key_.is(ecx)) {
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
} else if (key_.is(edx)) {
if (receiver_.is(ecx)) {
__ xchg(edx, ecx);
} else {
__ mov(ecx, key_);
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
}
} else { // Key is not in edx or ecx.
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
__ mov(ecx, key_);
}
// Call the IC stub.
Handle<Code> ic(Builtins::builtin(Builtins::KeyedStoreIC_Initialize));
__ call(ic, RelocInfo::CODE_TARGET);
// The delta from the start of the map-compare instruction to the
// test instruction. We use masm_-> directly here instead of the
// __ macro because the macro sometimes uses macro expansion to turn
// into something that can't return a value. This is encountered
// when doing generated code coverage tests.
int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
// Here we use masm_-> instead of the __ macro because this is the
// instruction that gets patched and coverage code gets in the way.
masm_->test(eax, Immediate(-delta_to_patch_site));
// Restore value (returned from store IC) register.
if (!old_value.is(eax)) __ mov(old_value, eax);
}
Result CodeGenerator::EmitNamedLoad(Handle<String> name, bool is_contextual) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Result result;
// Do not inline the inobject property case for loads from the global
// object. Also do not inline for unoptimized code. This saves time in
// the code generator. Unoptimized code is toplevel code or code that is
// not in a loop.
if (is_contextual || scope()->is_global_scope() || loop_nesting() == 0) {
Comment cmnt(masm(), "[ Load from named Property");
frame()->Push(name);
RelocInfo::Mode mode = is_contextual
? RelocInfo::CODE_TARGET_CONTEXT
: RelocInfo::CODE_TARGET;
result = frame()->CallLoadIC(mode);
// A test eax instruction following the call signals that the inobject
// property case was inlined. Ensure that there is not a test eax
// instruction here.
__ nop();
} else {
// Inline the inobject property case.
Comment cmnt(masm(), "[ Inlined named property load");
Result receiver = frame()->Pop();
receiver.ToRegister();
result = allocator()->Allocate();
ASSERT(result.is_valid());
DeferredReferenceGetNamedValue* deferred =
new DeferredReferenceGetNamedValue(result.reg(), receiver.reg(), name);
// Check that the receiver is a heap object.
__ test(receiver.reg(), Immediate(kSmiTagMask));
deferred->Branch(zero);
__ bind(deferred->patch_site());
// This is the map check instruction that will be patched (so we can't
// use the double underscore macro that may insert instructions).
// Initially use an invalid map to force a failure.
masm()->cmp(FieldOperand(receiver.reg(), HeapObject::kMapOffset),
Immediate(Factory::null_value()));
// This branch is always a forwards branch so it's always a fixed size
// which allows the assert below to succeed and patching to work.
deferred->Branch(not_equal);
// The delta from the patch label to the load offset must be statically
// known.
ASSERT(masm()->SizeOfCodeGeneratedSince(deferred->patch_site()) ==
LoadIC::kOffsetToLoadInstruction);
// The initial (invalid) offset has to be large enough to force a 32-bit
// instruction encoding to allow patching with an arbitrary offset. Use
// kMaxInt (minus kHeapObjectTag).
int offset = kMaxInt;
masm()->mov(result.reg(), FieldOperand(receiver.reg(), offset));
__ IncrementCounter(&Counters::named_load_inline, 1);
deferred->BindExit();
}
ASSERT(frame()->height() == original_height - 1);
return result;
}
Result CodeGenerator::EmitNamedStore(Handle<String> name, bool is_contextual) {
#ifdef DEBUG
int expected_height = frame()->height() - (is_contextual ? 1 : 2);
#endif
Result result = frame()->CallStoreIC(name, is_contextual);
ASSERT_EQ(expected_height, frame()->height());
return result;
}
Result CodeGenerator::EmitKeyedLoad() {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Result result;
// Inline array load code if inside of a loop. We do not know the
// receiver map yet, so we initially generate the code with a check
// against an invalid map. In the inline cache code, we patch the map
// check if appropriate.
if (loop_nesting() > 0) {
Comment cmnt(masm_, "[ Inlined load from keyed Property");
// Use a fresh temporary to load the elements without destroying
// the receiver which is needed for the deferred slow case.
Result elements = allocator()->Allocate();
ASSERT(elements.is_valid());
Result key = frame_->Pop();
Result receiver = frame_->Pop();
key.ToRegister();
receiver.ToRegister();
// If key and receiver are shared registers on the frame, their values will
// be automatically saved and restored when going to deferred code.
// The result is in elements, which is guaranteed non-shared.
DeferredReferenceGetKeyedValue* deferred =
new DeferredReferenceGetKeyedValue(elements.reg(),
receiver.reg(),
key.reg());
__ test(receiver.reg(), Immediate(kSmiTagMask));
deferred->Branch(zero);
// Check that the receiver has the expected map.
// Initially, use an invalid map. The map is patched in the IC
// initialization code.
__ bind(deferred->patch_site());
// Use masm-> here instead of the double underscore macro since extra
// coverage code can interfere with the patching.
masm_->cmp(FieldOperand(receiver.reg(), HeapObject::kMapOffset),
Immediate(Factory::null_value()));
deferred->Branch(not_equal);
// Check that the key is a smi.
if (!key.is_smi()) {
__ test(key.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(key.reg());
}
// Get the elements array from the receiver and check that it
// is not a dictionary.
__ mov(elements.reg(),
FieldOperand(receiver.reg(), JSObject::kElementsOffset));
__ cmp(FieldOperand(elements.reg(), HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
deferred->Branch(not_equal);
// Check that the key is within bounds.
__ cmp(key.reg(),
FieldOperand(elements.reg(), FixedArray::kLengthOffset));
deferred->Branch(above_equal);
// Load and check that the result is not the hole.
// Key holds a smi.
ASSERT((kSmiTag == 0) && (kSmiTagSize == 1));
__ mov(elements.reg(),
FieldOperand(elements.reg(),
key.reg(),
times_2,
FixedArray::kHeaderSize));
result = elements;
__ cmp(Operand(result.reg()), Immediate(Factory::the_hole_value()));
deferred->Branch(equal);
__ IncrementCounter(&Counters::keyed_load_inline, 1);
deferred->BindExit();
} else {
Comment cmnt(masm_, "[ Load from keyed Property");
result = frame_->CallKeyedLoadIC(RelocInfo::CODE_TARGET);
// Make sure that we do not have a test instruction after the
// call. A test instruction after the call is used to
// indicate that we have generated an inline version of the
// keyed load. The explicit nop instruction is here because
// the push that follows might be peep-hole optimized away.
__ nop();
}
ASSERT(frame()->height() == original_height - 2);
return result;
}
Result CodeGenerator::EmitKeyedStore(StaticType* key_type) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Result result;
// Generate inlined version of the keyed store if the code is in a loop
// and the key is likely to be a smi.
if (loop_nesting() > 0 && key_type->IsLikelySmi()) {
Comment cmnt(masm(), "[ Inlined store to keyed Property");
// Get the receiver, key and value into registers.
result = frame()->Pop();
Result key = frame()->Pop();
Result receiver = frame()->Pop();
Result tmp = allocator_->Allocate();
ASSERT(tmp.is_valid());
Result tmp2 = allocator_->Allocate();
ASSERT(tmp2.is_valid());
// Determine whether the value is a constant before putting it in a
// register.
bool value_is_constant = result.is_constant();
// Make sure that value, key and receiver are in registers.
result.ToRegister();
key.ToRegister();
receiver.ToRegister();
DeferredReferenceSetKeyedValue* deferred =
new DeferredReferenceSetKeyedValue(result.reg(),
key.reg(),
receiver.reg(),
tmp.reg());
// Check that the receiver is not a smi.
__ test(receiver.reg(), Immediate(kSmiTagMask));
deferred->Branch(zero);
// Check that the key is a smi.
if (!key.is_smi()) {
__ test(key.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(key.reg());
}
// Check that the receiver is a JSArray.
__ CmpObjectType(receiver.reg(), JS_ARRAY_TYPE, tmp.reg());
deferred->Branch(not_equal);
// Check that the key is within bounds. Both the key and the length of
// the JSArray are smis. Use unsigned comparison to handle negative keys.
__ cmp(key.reg(),
FieldOperand(receiver.reg(), JSArray::kLengthOffset));
deferred->Branch(above_equal);
// Get the elements array from the receiver and check that it is not a
// dictionary.
__ mov(tmp.reg(),
FieldOperand(receiver.reg(), JSArray::kElementsOffset));
// Check whether it is possible to omit the write barrier. If the elements
// array is in new space or the value written is a smi we can safely update
// the elements array without write barrier.
Label in_new_space;
__ InNewSpace(tmp.reg(), tmp2.reg(), equal, &in_new_space);
if (!value_is_constant) {
__ test(result.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
}
__ bind(&in_new_space);
// Bind the deferred code patch site to be able to locate the fixed
// array map comparison. When debugging, we patch this comparison to
// always fail so that we will hit the IC call in the deferred code
// which will allow the debugger to break for fast case stores.
__ bind(deferred->patch_site());
__ cmp(FieldOperand(tmp.reg(), HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
deferred->Branch(not_equal);
// Store the value.
__ mov(FixedArrayElementOperand(tmp.reg(), key.reg()), result.reg());
__ IncrementCounter(&Counters::keyed_store_inline, 1);
deferred->BindExit();
} else {
result = frame()->CallKeyedStoreIC();
// Make sure that we do not have a test instruction after the
// call. A test instruction after the call is used to
// indicate that we have generated an inline version of the
// keyed store.
__ nop();
}
ASSERT(frame()->height() == original_height - 3);
return result;
}
#undef __
#define __ ACCESS_MASM(masm)
static void CheckTwoForSminess(MacroAssembler* masm,
Register left, Register right, Register scratch,
TypeInfo left_info, TypeInfo right_info,
DeferredInlineBinaryOperation* deferred) {
if (left.is(right)) {
if (!left_info.IsSmi()) {
__ test(left, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left);
}
} else if (!left_info.IsSmi()) {
if (!right_info.IsSmi()) {
__ mov(scratch, left);
__ or_(scratch, Operand(right));
__ test(scratch, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
__ test(left, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
if (FLAG_debug_code) __ AbortIfNotSmi(right);
}
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left);
if (!right_info.IsSmi()) {
__ test(right, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(right);
}
}
}
Handle<String> Reference::GetName() {
ASSERT(type_ == NAMED);
Property* property = expression_->AsProperty();
if (property == NULL) {
// Global variable reference treated as a named property reference.
VariableProxy* proxy = expression_->AsVariableProxy();
ASSERT(proxy->AsVariable() != NULL);
ASSERT(proxy->AsVariable()->is_global());
return proxy->name();
} else {
Literal* raw_name = property->key()->AsLiteral();
ASSERT(raw_name != NULL);
return Handle<String>::cast(raw_name->handle());
}
}
void Reference::GetValue() {
ASSERT(!cgen_->in_spilled_code());
ASSERT(cgen_->HasValidEntryRegisters());
ASSERT(!is_illegal());
MacroAssembler* masm = cgen_->masm();
// Record the source position for the property load.
Property* property = expression_->AsProperty();
if (property != NULL) {
cgen_->CodeForSourcePosition(property->position());
}
switch (type_) {
case SLOT: {
Comment cmnt(masm, "[ Load from Slot");
Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
ASSERT(slot != NULL);
cgen_->LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
if (!persist_after_get_) set_unloaded();
break;
}
case NAMED: {
Variable* var = expression_->AsVariableProxy()->AsVariable();
bool is_global = var != NULL;
ASSERT(!is_global || var->is_global());
if (persist_after_get_) cgen_->frame()->Dup();
Result result = cgen_->EmitNamedLoad(GetName(), is_global);
if (!persist_after_get_) set_unloaded();
cgen_->frame()->Push(&result);
break;
}
case KEYED: {
if (persist_after_get_) {
cgen_->frame()->PushElementAt(1);
cgen_->frame()->PushElementAt(1);
}
Result value = cgen_->EmitKeyedLoad();
cgen_->frame()->Push(&value);
if (!persist_after_get_) set_unloaded();
break;
}
default:
UNREACHABLE();
}
}
void Reference::TakeValue() {
// For non-constant frame-allocated slots, we invalidate the value in the
// slot. For all others, we fall back on GetValue.
ASSERT(!cgen_->in_spilled_code());
ASSERT(!is_illegal());
if (type_ != SLOT) {
GetValue();
return;
}
Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
ASSERT(slot != NULL);
if (slot->type() == Slot::LOOKUP ||
slot->type() == Slot::CONTEXT ||
slot->var()->mode() == Variable::CONST ||
slot->is_arguments()) {
GetValue();
return;
}
// Only non-constant, frame-allocated parameters and locals can
// reach here. Be careful not to use the optimizations for arguments
// object access since it may not have been initialized yet.
ASSERT(!slot->is_arguments());
if (slot->type() == Slot::PARAMETER) {
cgen_->frame()->TakeParameterAt(slot->index());
} else {
ASSERT(slot->type() == Slot::LOCAL);
cgen_->frame()->TakeLocalAt(slot->index());
}
ASSERT(persist_after_get_);
// Do not unload the reference, because it is used in SetValue.
}
void Reference::SetValue(InitState init_state) {
ASSERT(cgen_->HasValidEntryRegisters());
ASSERT(!is_illegal());
MacroAssembler* masm = cgen_->masm();
switch (type_) {
case SLOT: {
Comment cmnt(masm, "[ Store to Slot");
Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
ASSERT(slot != NULL);
cgen_->StoreToSlot(slot, init_state);
set_unloaded();
break;
}
case NAMED: {
Comment cmnt(masm, "[ Store to named Property");
Result answer = cgen_->EmitNamedStore(GetName(), false);
cgen_->frame()->Push(&answer);
set_unloaded();
break;
}
case KEYED: {
Comment cmnt(masm, "[ Store to keyed Property");
Property* property = expression()->AsProperty();
ASSERT(property != NULL);
Result answer = cgen_->EmitKeyedStore(property->key()->type());
cgen_->frame()->Push(&answer);
set_unloaded();
break;
}
case UNLOADED:
case ILLEGAL:
UNREACHABLE();
}
}
void FastNewClosureStub::Generate(MacroAssembler* masm) {
// Create a new closure from the given function info in new
// space. Set the context to the current context in esi.
Label gc;
__ AllocateInNewSpace(JSFunction::kSize, eax, ebx, ecx, &gc, TAG_OBJECT);
// Get the function info from the stack.
__ mov(edx, Operand(esp, 1 * kPointerSize));
// Compute the function map in the current global context and set that
// as the map of the allocated object.
__ mov(ecx, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
__ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalContextOffset));
__ mov(ecx, Operand(ecx, Context::SlotOffset(Context::FUNCTION_MAP_INDEX)));
__ mov(FieldOperand(eax, JSObject::kMapOffset), ecx);
// Initialize the rest of the function. We don't have to update the
// write barrier because the allocated object is in new space.
__ mov(ebx, Immediate(Factory::empty_fixed_array()));
__ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ebx);
__ mov(FieldOperand(eax, JSObject::kElementsOffset), ebx);
__ mov(FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset),
Immediate(Factory::the_hole_value()));
__ mov(FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset), edx);
__ mov(FieldOperand(eax, JSFunction::kContextOffset), esi);
__ mov(FieldOperand(eax, JSFunction::kLiteralsOffset), ebx);
// Return and remove the on-stack parameter.
__ ret(1 * kPointerSize);
// Create a new closure through the slower runtime call.
__ bind(&gc);
__ pop(ecx); // Temporarily remove return address.
__ pop(edx);
__ push(esi);
__ push(edx);
__ push(ecx); // Restore return address.
__ TailCallRuntime(Runtime::kNewClosure, 2, 1);
}
void FastNewContextStub::Generate(MacroAssembler* masm) {
// Try to allocate the context in new space.
Label gc;
int length = slots_ + Context::MIN_CONTEXT_SLOTS;
__ AllocateInNewSpace((length * kPointerSize) + FixedArray::kHeaderSize,
eax, ebx, ecx, &gc, TAG_OBJECT);
// Get the function from the stack.
__ mov(ecx, Operand(esp, 1 * kPointerSize));
// Setup the object header.
__ mov(FieldOperand(eax, HeapObject::kMapOffset), Factory::context_map());
__ mov(FieldOperand(eax, Context::kLengthOffset),
Immediate(Smi::FromInt(length)));
// Setup the fixed slots.
__ xor_(ebx, Operand(ebx)); // Set to NULL.
__ mov(Operand(eax, Context::SlotOffset(Context::CLOSURE_INDEX)), ecx);
__ mov(Operand(eax, Context::SlotOffset(Context::FCONTEXT_INDEX)), eax);
__ mov(Operand(eax, Context::SlotOffset(Context::PREVIOUS_INDEX)), ebx);
__ mov(Operand(eax, Context::SlotOffset(Context::EXTENSION_INDEX)), ebx);
// Copy the global object from the surrounding context. We go through the
// context in the function (ecx) to match the allocation behavior we have
// in the runtime system (see Heap::AllocateFunctionContext).
__ mov(ebx, FieldOperand(ecx, JSFunction::kContextOffset));
__ mov(ebx, Operand(ebx, Context::SlotOffset(Context::GLOBAL_INDEX)));
__ mov(Operand(eax, Context::SlotOffset(Context::GLOBAL_INDEX)), ebx);
// Initialize the rest of the slots to undefined.
__ mov(ebx, Factory::undefined_value());
for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) {
__ mov(Operand(eax, Context::SlotOffset(i)), ebx);
}
// Return and remove the on-stack parameter.
__ mov(esi, Operand(eax));
__ ret(1 * kPointerSize);
// Need to collect. Call into runtime system.
__ bind(&gc);
__ TailCallRuntime(Runtime::kNewContext, 1, 1);
}
void FastCloneShallowArrayStub::Generate(MacroAssembler* masm) {
// Stack layout on entry:
//
// [esp + kPointerSize]: constant elements.
// [esp + (2 * kPointerSize)]: literal index.
// [esp + (3 * kPointerSize)]: literals array.
// All sizes here are multiples of kPointerSize.
int elements_size = (length_ > 0) ? FixedArray::SizeFor(length_) : 0;
int size = JSArray::kSize + elements_size;
// Load boilerplate object into ecx and check if we need to create a
// boilerplate.
Label slow_case;
__ mov(ecx, Operand(esp, 3 * kPointerSize));
__ mov(eax, Operand(esp, 2 * kPointerSize));
ASSERT((kPointerSize == 4) && (kSmiTagSize == 1) && (kSmiTag == 0));
__ mov(ecx, CodeGenerator::FixedArrayElementOperand(ecx, eax));
__ cmp(ecx, Factory::undefined_value());
__ j(equal, &slow_case);
// Allocate both the JS array and the elements array in one big
// allocation. This avoids multiple limit checks.
__ AllocateInNewSpace(size, eax, ebx, edx, &slow_case, TAG_OBJECT);
// Copy the JS array part.
for (int i = 0; i < JSArray::kSize; i += kPointerSize) {
if ((i != JSArray::kElementsOffset) || (length_ == 0)) {
__ mov(ebx, FieldOperand(ecx, i));
__ mov(FieldOperand(eax, i), ebx);
}
}
if (length_ > 0) {
// Get hold of the elements array of the boilerplate and setup the
// elements pointer in the resulting object.
__ mov(ecx, FieldOperand(ecx, JSArray::kElementsOffset));
__ lea(edx, Operand(eax, JSArray::kSize));
__ mov(FieldOperand(eax, JSArray::kElementsOffset), edx);
// Copy the elements array.
for (int i = 0; i < elements_size; i += kPointerSize) {
__ mov(ebx, FieldOperand(ecx, i));
__ mov(FieldOperand(edx, i), ebx);
}
}
// Return and remove the on-stack parameters.
__ ret(3 * kPointerSize);
__ bind(&slow_case);
__ TailCallRuntime(Runtime::kCreateArrayLiteralShallow, 3, 1);
}
// NOTE: The stub does not handle the inlined cases (Smis, Booleans, undefined).
void ToBooleanStub::Generate(MacroAssembler* masm) {
Label false_result, true_result, not_string;
__ mov(eax, Operand(esp, 1 * kPointerSize));
// 'null' => false.
__ cmp(eax, Factory::null_value());
__ j(equal, &false_result);
// Get the map and type of the heap object.
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(edx, Map::kInstanceTypeOffset));
// Undetectable => false.
__ test_b(FieldOperand(edx, Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
__ j(not_zero, &false_result);
// JavaScript object => true.
__ CmpInstanceType(edx, FIRST_JS_OBJECT_TYPE);
__ j(above_equal, &true_result);
// String value => false iff empty.
__ CmpInstanceType(edx, FIRST_NONSTRING_TYPE);
__ j(above_equal, ¬_string);
ASSERT(kSmiTag == 0);
__ cmp(FieldOperand(eax, String::kLengthOffset), Immediate(0));
__ j(zero, &false_result);
__ jmp(&true_result);
__ bind(¬_string);
// HeapNumber => false iff +0, -0, or NaN.
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &true_result);
__ fldz();
__ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ FCmp();
__ j(zero, &false_result);
// Fall through to |true_result|.
// Return 1/0 for true/false in eax.
__ bind(&true_result);
__ mov(eax, 1);
__ ret(1 * kPointerSize);
__ bind(&false_result);
__ mov(eax, 0);
__ ret(1 * kPointerSize);
}
void GenericBinaryOpStub::GenerateCall(
MacroAssembler* masm,
Register left,
Register right) {
if (!ArgsInRegistersSupported()) {
// Pass arguments on the stack.
__ push(left);
__ push(right);
} else {
// The calling convention with registers is left in edx and right in eax.
Register left_arg = edx;
Register right_arg = eax;
if (!(left.is(left_arg) && right.is(right_arg))) {
if (left.is(right_arg) && right.is(left_arg)) {
if (IsOperationCommutative()) {
SetArgsReversed();
} else {
__ xchg(left, right);
}
} else if (left.is(left_arg)) {
__ mov(right_arg, right);
} else if (right.is(right_arg)) {
__ mov(left_arg, left);
} else if (left.is(right_arg)) {
if (IsOperationCommutative()) {
__ mov(left_arg, right);
SetArgsReversed();
} else {
// Order of moves important to avoid destroying left argument.
__ mov(left_arg, left);
__ mov(right_arg, right);
}
} else if (right.is(left_arg)) {
if (IsOperationCommutative()) {
__ mov(right_arg, left);
SetArgsReversed();
} else {
// Order of moves important to avoid destroying right argument.
__ mov(right_arg, right);
__ mov(left_arg, left);
}
} else {
// Order of moves is not important.
__ mov(left_arg, left);
__ mov(right_arg, right);
}
}
// Update flags to indicate that arguments are in registers.
SetArgsInRegisters();
__ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
}
// Call the stub.
__ CallStub(this);
}
void GenericBinaryOpStub::GenerateCall(
MacroAssembler* masm,
Register left,
Smi* right) {
if (!ArgsInRegistersSupported()) {
// Pass arguments on the stack.
__ push(left);
__ push(Immediate(right));
} else {
// The calling convention with registers is left in edx and right in eax.
Register left_arg = edx;
Register right_arg = eax;
if (left.is(left_arg)) {
__ mov(right_arg, Immediate(right));
} else if (left.is(right_arg) && IsOperationCommutative()) {
__ mov(left_arg, Immediate(right));
SetArgsReversed();
} else {
// For non-commutative operations, left and right_arg might be
// the same register. Therefore, the order of the moves is
// important here in order to not overwrite left before moving
// it to left_arg.
__ mov(left_arg, left);
__ mov(right_arg, Immediate(right));
}
// Update flags to indicate that arguments are in registers.
SetArgsInRegisters();
__ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
}
// Call the stub.
__ CallStub(this);
}
void GenericBinaryOpStub::GenerateCall(
MacroAssembler* masm,
Smi* left,
Register right) {
if (!ArgsInRegistersSupported()) {
// Pass arguments on the stack.
__ push(Immediate(left));
__ push(right);
} else {
// The calling convention with registers is left in edx and right in eax.
Register left_arg = edx;
Register right_arg = eax;
if (right.is(right_arg)) {
__ mov(left_arg, Immediate(left));
} else if (right.is(left_arg) && IsOperationCommutative()) {
__ mov(right_arg, Immediate(left));
SetArgsReversed();
} else {
// For non-commutative operations, right and left_arg might be
// the same register. Therefore, the order of the moves is
// important here in order to not overwrite right before moving
// it to right_arg.
__ mov(right_arg, right);
__ mov(left_arg, Immediate(left));
}
// Update flags to indicate that arguments are in registers.
SetArgsInRegisters();
__ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
}
// Call the stub.
__ CallStub(this);
}
Result GenericBinaryOpStub::GenerateCall(MacroAssembler* masm,
VirtualFrame* frame,
Result* left,
Result* right) {
if (ArgsInRegistersSupported()) {
SetArgsInRegisters();
return frame->CallStub(this, left, right);
} else {
frame->Push(left);
frame->Push(right);
return frame->CallStub(this, 2);
}
}
void GenericBinaryOpStub::GenerateSmiCode(MacroAssembler* masm, Label* slow) {
// 1. Move arguments into edx, eax except for DIV and MOD, which need the
// dividend in eax and edx free for the division. Use eax, ebx for those.
Comment load_comment(masm, "-- Load arguments");
Register left = edx;
Register right = eax;
if (op_ == Token::DIV || op_ == Token::MOD) {
left = eax;
right = ebx;
if (HasArgsInRegisters()) {
__ mov(ebx, eax);
__ mov(eax, edx);
}
}
if (!HasArgsInRegisters()) {
__ mov(right, Operand(esp, 1 * kPointerSize));
__ mov(left, Operand(esp, 2 * kPointerSize));
}
if (static_operands_type_.IsSmi()) {
if (FLAG_debug_code) {
__ AbortIfNotSmi(left);
__ AbortIfNotSmi(right);
}
if (op_ == Token::BIT_OR) {
__ or_(right, Operand(left));
GenerateReturn(masm);
return;
} else if (op_ == Token::BIT_AND) {
__ and_(right, Operand(left));
GenerateReturn(masm);
return;
} else if (op_ == Token::BIT_XOR) {
__ xor_(right, Operand(left));
GenerateReturn(masm);
return;
}
}
// 2. Prepare the smi check of both operands by oring them together.
Comment smi_check_comment(masm, "-- Smi check arguments");
Label not_smis;
Register combined = ecx;
ASSERT(!left.is(combined) && !right.is(combined));
switch (op_) {
case Token::BIT_OR:
// Perform the operation into eax and smi check the result. Preserve
// eax in case the result is not a smi.
ASSERT(!left.is(ecx) && !right.is(ecx));
__ mov(ecx, right);
__ or_(right, Operand(left)); // Bitwise or is commutative.
combined = right;
break;
case Token::BIT_XOR:
case Token::BIT_AND:
case Token::ADD:
case Token::SUB:
case Token::MUL:
case Token::DIV:
case Token::MOD:
__ mov(combined, right);
__ or_(combined, Operand(left));
break;
case Token::SHL:
case Token::SAR:
case Token::SHR:
// Move the right operand into ecx for the shift operation, use eax
// for the smi check register.
ASSERT(!left.is(ecx) && !right.is(ecx));
__ mov(ecx, right);
__ or_(right, Operand(left));
combined = right;
break;
default:
break;
}
// 3. Perform the smi check of the operands.
ASSERT(kSmiTag == 0); // Adjust zero check if not the case.
__ test(combined, Immediate(kSmiTagMask));
__ j(not_zero, ¬_smis, not_taken);
// 4. Operands are both smis, perform the operation leaving the result in
// eax and check the result if necessary.
Comment perform_smi(masm, "-- Perform smi operation");
Label use_fp_on_smis;
switch (op_) {
case Token::BIT_OR:
// Nothing to do.
break;
case Token::BIT_XOR:
ASSERT(right.is(eax));
__ xor_(right, Operand(left)); // Bitwise xor is commutative.
break;
case Token::BIT_AND:
ASSERT(right.is(eax));
__ and_(right, Operand(left)); // Bitwise and is commutative.
break;
case Token::SHL:
// Remove tags from operands (but keep sign).
__ SmiUntag(left);
__ SmiUntag(ecx);
// Perform the operation.
__ shl_cl(left);
// Check that the *signed* result fits in a smi.
__ cmp(left, 0xc0000000);
__ j(sign, &use_fp_on_smis, not_taken);
// Tag the result and store it in register eax.
__ SmiTag(left);
__ mov(eax, left);
break;
case Token::SAR:
// Remove tags from operands (but keep sign).
__ SmiUntag(left);
__ SmiUntag(ecx);
// Perform the operation.
__ sar_cl(left);
// Tag the result and store it in register eax.
__ SmiTag(left);
__ mov(eax, left);
break;
case Token::SHR:
// Remove tags from operands (but keep sign).
__ SmiUntag(left);
__ SmiUntag(ecx);
// Perform the operation.
__ shr_cl(left);
// Check that the *unsigned* result fits in a smi.
// Neither of the two high-order bits can be set:
// - 0x80000000: high bit would be lost when smi tagging.
// - 0x40000000: this number would convert to negative when
// Smi tagging these two cases can only happen with shifts
// by 0 or 1 when handed a valid smi.
__ test(left, Immediate(0xc0000000));
__ j(not_zero, slow, not_taken);
// Tag the result and store it in register eax.
__ SmiTag(left);
__ mov(eax, left);
break;
case Token::ADD:
ASSERT(right.is(eax));
__ add(right, Operand(left)); // Addition is commutative.
__ j(overflow, &use_fp_on_smis, not_taken);
break;
case Token::SUB:
__ sub(left, Operand(right));
__ j(overflow, &use_fp_on_smis, not_taken);
__ mov(eax, left);
break;
case Token::MUL:
// If the smi tag is 0 we can just leave the tag on one operand.
ASSERT(kSmiTag == 0); // Adjust code below if not the case.
// We can't revert the multiplication if the result is not a smi
// so save the right operand.
__ mov(ebx, right);
// Remove tag from one of the operands (but keep sign).
__ SmiUntag(right);
// Do multiplication.
__ imul(right, Operand(left)); // Multiplication is commutative.
__ j(overflow, &use_fp_on_smis, not_taken);
// Check for negative zero result. Use combined = left | right.
__ NegativeZeroTest(right, combined, &use_fp_on_smis);
break;
case Token::DIV:
// We can't revert the division if the result is not a smi so
// save the left operand.
__ mov(edi, left);
// Check for 0 divisor.
__ test(right, Operand(right));
__ j(zero, &use_fp_on_smis, not_taken);
// Sign extend left into edx:eax.
ASSERT(left.is(eax));
__ cdq();
// Divide edx:eax by right.
__ idiv(right);
// Check for the corner case of dividing the most negative smi by
// -1. We cannot use the overflow flag, since it is not set by idiv
// instruction.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ cmp(eax, 0x40000000);
__ j(equal, &use_fp_on_smis);
// Check for negative zero result. Use combined = left | right.
__ NegativeZeroTest(eax, combined, &use_fp_on_smis);
// Check that the remainder is zero.
__ test(edx, Operand(edx));
__ j(not_zero, &use_fp_on_smis);
// Tag the result and store it in register eax.
__ SmiTag(eax);
break;
case Token::MOD:
// Check for 0 divisor.
__ test(right, Operand(right));
__ j(zero, ¬_smis, not_taken);
// Sign extend left into edx:eax.
ASSERT(left.is(eax));
__ cdq();
// Divide edx:eax by right.
__ idiv(right);
// Check for negative zero result. Use combined = left | right.
__ NegativeZeroTest(edx, combined, slow);
// Move remainder to register eax.
__ mov(eax, edx);
break;
default:
UNREACHABLE();
}
// 5. Emit return of result in eax.
GenerateReturn(masm);
// 6. For some operations emit inline code to perform floating point
// operations on known smis (e.g., if the result of the operation
// overflowed the smi range).
switch (op_) {
case Token::SHL: {
Comment perform_float(masm, "-- Perform float operation on smis");
__ bind(&use_fp_on_smis);
// Result we want is in left == edx, so we can put the allocated heap
// number in eax.
__ AllocateHeapNumber(eax, ecx, ebx, slow);
// Store the result in the HeapNumber and return.
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
__ cvtsi2sd(xmm0, Operand(left));
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
} else {
// It's OK to overwrite the right argument on the stack because we
// are about to return.
__ mov(Operand(esp, 1 * kPointerSize), left);
__ fild_s(Operand(esp, 1 * kPointerSize));
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
}
GenerateReturn(masm);
break;
}
case Token::ADD:
case Token::SUB:
case Token::MUL:
case Token::DIV: {
Comment perform_float(masm, "-- Perform float operation on smis");
__ bind(&use_fp_on_smis);
// Restore arguments to edx, eax.
switch (op_) {
case Token::ADD:
// Revert right = right + left.
__ sub(right, Operand(left));
break;
case Token::SUB:
// Revert left = left - right.
__ add(left, Operand(right));
break;
case Token::MUL:
// Right was clobbered but a copy is in ebx.
__ mov(right, ebx);
break;
case Token::DIV:
// Left was clobbered but a copy is in edi. Right is in ebx for
// division.
__ mov(edx, edi);
__ mov(eax, right);
break;
default: UNREACHABLE();
break;
}
__ AllocateHeapNumber(ecx, ebx, no_reg, slow);
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
FloatingPointHelper::LoadSSE2Smis(masm, ebx);
switch (op_) {
case Token::ADD: __ addsd(xmm0, xmm1); break;
case Token::SUB: __ subsd(xmm0, xmm1); break;
case Token::MUL: __ mulsd(xmm0, xmm1); break;
case Token::DIV: __ divsd(xmm0, xmm1); break;
default: UNREACHABLE();
}
__ movdbl(FieldOperand(ecx, HeapNumber::kValueOffset), xmm0);
} else { // SSE2 not available, use FPU.
FloatingPointHelper::LoadFloatSmis(masm, ebx);
switch (op_) {
case Token::ADD: __ faddp(1); break;
case Token::SUB: __ fsubp(1); break;
case Token::MUL: __ fmulp(1); break;
case Token::DIV: __ fdivp(1); break;
default: UNREACHABLE();
}
__ fstp_d(FieldOperand(ecx, HeapNumber::kValueOffset));
}
__ mov(eax, ecx);
GenerateReturn(masm);
break;
}
default:
break;
}
// 7. Non-smi operands, fall out to the non-smi code with the operands in
// edx and eax.
Comment done_comment(masm, "-- Enter non-smi code");
__ bind(¬_smis);
switch (op_) {
case Token::BIT_OR:
case Token::SHL:
case Token::SAR:
case Token::SHR:
// Right operand is saved in ecx and eax was destroyed by the smi
// check.
__ mov(eax, ecx);
break;
case Token::DIV:
case Token::MOD:
// Operands are in eax, ebx at this point.
__ mov(edx, eax);
__ mov(eax, ebx);
break;
default:
break;
}
}
void GenericBinaryOpStub::Generate(MacroAssembler* masm) {
Label call_runtime;
__ IncrementCounter(&Counters::generic_binary_stub_calls, 1);
// Generate fast case smi code if requested. This flag is set when the fast
// case smi code is not generated by the caller. Generating it here will speed
// up common operations.
if (ShouldGenerateSmiCode()) {
GenerateSmiCode(masm, &call_runtime);
} else if (op_ != Token::MOD) { // MOD goes straight to runtime.
if (!HasArgsInRegisters()) {
GenerateLoadArguments(masm);
}
}
// Floating point case.
if (ShouldGenerateFPCode()) {
switch (op_) {
case Token::ADD:
case Token::SUB:
case Token::MUL:
case Token::DIV: {
if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
HasSmiCodeInStub()) {
// Execution reaches this point when the first non-smi argument occurs
// (and only if smi code is generated). This is the right moment to
// patch to HEAP_NUMBERS state. The transition is attempted only for
// the four basic operations. The stub stays in the DEFAULT state
// forever for all other operations (also if smi code is skipped).
GenerateTypeTransition(masm);
}
Label not_floats;
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
if (static_operands_type_.IsNumber()) {
if (FLAG_debug_code) {
// Assert at runtime that inputs are only numbers.
__ AbortIfNotNumber(edx);
__ AbortIfNotNumber(eax);
}
if (static_operands_type_.IsSmi()) {
if (FLAG_debug_code) {
__ AbortIfNotSmi(edx);
__ AbortIfNotSmi(eax);
}
FloatingPointHelper::LoadSSE2Smis(masm, ecx);
} else {
FloatingPointHelper::LoadSSE2Operands(masm);
}
} else {
FloatingPointHelper::LoadSSE2Operands(masm, &call_runtime);
}
switch (op_) {
case Token::ADD: __ addsd(xmm0, xmm1); break;
case Token::SUB: __ subsd(xmm0, xmm1); break;
case Token::MUL: __ mulsd(xmm0, xmm1); break;
case Token::DIV: __ divsd(xmm0, xmm1); break;
default: UNREACHABLE();
}
GenerateHeapResultAllocation(masm, &call_runtime);
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
GenerateReturn(masm);
} else { // SSE2 not available, use FPU.
if (static_operands_type_.IsNumber()) {
if (FLAG_debug_code) {
// Assert at runtime that inputs are only numbers.
__ AbortIfNotNumber(edx);
__ AbortIfNotNumber(eax);
}
} else {
FloatingPointHelper::CheckFloatOperands(masm, &call_runtime, ebx);
}
FloatingPointHelper::LoadFloatOperands(
masm,
ecx,
FloatingPointHelper::ARGS_IN_REGISTERS);
switch (op_) {
case Token::ADD: __ faddp(1); break;
case Token::SUB: __ fsubp(1); break;
case Token::MUL: __ fmulp(1); break;
case Token::DIV: __ fdivp(1); break;
default: UNREACHABLE();
}
Label after_alloc_failure;
GenerateHeapResultAllocation(masm, &after_alloc_failure);
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
GenerateReturn(masm);
__ bind(&after_alloc_failure);
__ ffree();
__ jmp(&call_runtime);
}
__ bind(¬_floats);
if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
!HasSmiCodeInStub()) {
// Execution reaches this point when the first non-number argument
// occurs (and only if smi code is skipped from the stub, otherwise
// the patching has already been done earlier in this case branch).
// Try patching to STRINGS for ADD operation.
if (op_ == Token::ADD) {
GenerateTypeTransition(masm);
}
}
break;
}
case Token::MOD: {
// For MOD we go directly to runtime in the non-smi case.
break;
}
case Token::BIT_OR:
case Token::BIT_AND:
case Token::BIT_XOR:
case Token::SAR:
case Token::SHL:
case Token::SHR: {
Label non_smi_result;
FloatingPointHelper::LoadAsIntegers(masm,
static_operands_type_,
use_sse3_,
&call_runtime);
switch (op_) {
case Token::BIT_OR: __ or_(eax, Operand(ecx)); break;
case Token::BIT_AND: __ and_(eax, Operand(ecx)); break;
case Token::BIT_XOR: __ xor_(eax, Operand(ecx)); break;
case Token::SAR: __ sar_cl(eax); break;
case Token::SHL: __ shl_cl(eax); break;
case Token::SHR: __ shr_cl(eax); break;
default: UNREACHABLE();
}
if (op_ == Token::SHR) {
// Check if result is non-negative and fits in a smi.
__ test(eax, Immediate(0xc0000000));
__ j(not_zero, &call_runtime);
} else {
// Check if result fits in a smi.
__ cmp(eax, 0xc0000000);
__ j(negative, &non_smi_result);
}
// Tag smi result and return.
__ SmiTag(eax);
GenerateReturn(masm);
// All ops except SHR return a signed int32 that we load in
// a HeapNumber.
if (op_ != Token::SHR) {
__ bind(&non_smi_result);
// Allocate a heap number if needed.
__ mov(ebx, Operand(eax)); // ebx: result
Label skip_allocation;
switch (mode_) {
case OVERWRITE_LEFT:
case OVERWRITE_RIGHT:
// If the operand was an object, we skip the
// allocation of a heap number.
__ mov(eax, Operand(esp, mode_ == OVERWRITE_RIGHT ?
1 * kPointerSize : 2 * kPointerSize));
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &skip_allocation, not_taken);
// Fall through!
case NO_OVERWRITE:
__ AllocateHeapNumber(eax, ecx, edx, &call_runtime);
__ bind(&skip_allocation);
break;
default: UNREACHABLE();
}
// Store the result in the HeapNumber and return.
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
__ cvtsi2sd(xmm0, Operand(ebx));
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
} else {
__ mov(Operand(esp, 1 * kPointerSize), ebx);
__ fild_s(Operand(esp, 1 * kPointerSize));
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
}
GenerateReturn(masm);
}
break;
}
default: UNREACHABLE(); break;
}
}
// If all else fails, use the runtime system to get the correct
// result. If arguments was passed in registers now place them on the
// stack in the correct order below the return address.
__ bind(&call_runtime);
if (HasArgsInRegisters()) {
GenerateRegisterArgsPush(masm);
}
switch (op_) {
case Token::ADD: {
// Test for string arguments before calling runtime.
Label not_strings, not_string1, string1, string1_smi2;
// If this stub has already generated FP-specific code then the arguments
// are already in edx, eax
if (!ShouldGenerateFPCode() && !HasArgsInRegisters()) {
GenerateLoadArguments(masm);
}
// Registers containing left and right operands respectively.
Register lhs, rhs;
if (HasArgsReversed()) {
lhs = eax;
rhs = edx;
} else {
lhs = edx;
rhs = eax;
}
// Test if first argument is a string.
__ test(lhs, Immediate(kSmiTagMask));
__ j(zero, ¬_string1);
__ CmpObjectType(lhs, FIRST_NONSTRING_TYPE, ecx);
__ j(above_equal, ¬_string1);
// First argument is a string, test second.
__ test(rhs, Immediate(kSmiTagMask));
__ j(zero, &string1_smi2);
__ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, ecx);
__ j(above_equal, &string1);
// First and second argument are strings. Jump to the string add stub.
StringAddStub string_add_stub(NO_STRING_CHECK_IN_STUB);
__ TailCallStub(&string_add_stub);
__ bind(&string1_smi2);
// First argument is a string, second is a smi. Try to lookup the number
// string for the smi in the number string cache.
NumberToStringStub::GenerateLookupNumberStringCache(
masm, rhs, edi, ebx, ecx, true, &string1);
// Replace second argument on stack and tailcall string add stub to make
// the result.
__ mov(Operand(esp, 1 * kPointerSize), edi);
__ TailCallStub(&string_add_stub);
// Only first argument is a string.
__ bind(&string1);
__ InvokeBuiltin(Builtins::STRING_ADD_LEFT, JUMP_FUNCTION);
// First argument was not a string, test second.
__ bind(¬_string1);
__ test(rhs, Immediate(kSmiTagMask));
__ j(zero, ¬_strings);
__ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, ecx);
__ j(above_equal, ¬_strings);
// Only second argument is a string.
__ InvokeBuiltin(Builtins::STRING_ADD_RIGHT, JUMP_FUNCTION);
__ bind(¬_strings);
// Neither argument is a string.
__ InvokeBuiltin(Builtins::ADD, JUMP_FUNCTION);
break;
}
case Token::SUB:
__ InvokeBuiltin(Builtins::SUB, JUMP_FUNCTION);
break;
case Token::MUL:
__ InvokeBuiltin(Builtins::MUL, JUMP_FUNCTION);
break;
case Token::DIV:
__ InvokeBuiltin(Builtins::DIV, JUMP_FUNCTION);
break;
case Token::MOD:
__ InvokeBuiltin(Builtins::MOD, JUMP_FUNCTION);
break;
case Token::BIT_OR:
__ InvokeBuiltin(Builtins::BIT_OR, JUMP_FUNCTION);
break;
case Token::BIT_AND:
__ InvokeBuiltin(Builtins::BIT_AND, JUMP_FUNCTION);
break;
case Token::BIT_XOR:
__ InvokeBuiltin(Builtins::BIT_XOR, JUMP_FUNCTION);
break;
case Token::SAR:
__ InvokeBuiltin(Builtins::SAR, JUMP_FUNCTION);
break;
case Token::SHL:
__ InvokeBuiltin(Builtins::SHL, JUMP_FUNCTION);
break;
case Token::SHR:
__ InvokeBuiltin(Builtins::SHR, JUMP_FUNCTION);
break;
default:
UNREACHABLE();
}
}
void GenericBinaryOpStub::GenerateHeapResultAllocation(MacroAssembler* masm,
Label* alloc_failure) {
Label skip_allocation;
OverwriteMode mode = mode_;
if (HasArgsReversed()) {
if (mode == OVERWRITE_RIGHT) {
mode = OVERWRITE_LEFT;
} else if (mode == OVERWRITE_LEFT) {
mode = OVERWRITE_RIGHT;
}
}
switch (mode) {
case OVERWRITE_LEFT: {
// If the argument in edx is already an object, we skip the
// allocation of a heap number.
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &skip_allocation, not_taken);
// Allocate a heap number for the result. Keep eax and edx intact
// for the possible runtime call.
__ AllocateHeapNumber(ebx, ecx, no_reg, alloc_failure);
// Now edx can be overwritten losing one of the arguments as we are
// now done and will not need it any more.
__ mov(edx, Operand(ebx));
__ bind(&skip_allocation);
// Use object in edx as a result holder
__ mov(eax, Operand(edx));
break;
}
case OVERWRITE_RIGHT:
// If the argument in eax is already an object, we skip the
// allocation of a heap number.
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &skip_allocation, not_taken);
// Fall through!
case NO_OVERWRITE:
// Allocate a heap number for the result. Keep eax and edx intact
// for the possible runtime call.
__ AllocateHeapNumber(ebx, ecx, no_reg, alloc_failure);
// Now eax can be overwritten losing one of the arguments as we are
// now done and will not need it any more.
__ mov(eax, ebx);
__ bind(&skip_allocation);
break;
default: UNREACHABLE();
}
}
void GenericBinaryOpStub::GenerateLoadArguments(MacroAssembler* masm) {
// If arguments are not passed in registers read them from the stack.
ASSERT(!HasArgsInRegisters());
__ mov(eax, Operand(esp, 1 * kPointerSize));
__ mov(edx, Operand(esp, 2 * kPointerSize));
}
void GenericBinaryOpStub::GenerateReturn(MacroAssembler* masm) {
// If arguments are not passed in registers remove them from the stack before
// returning.
if (!HasArgsInRegisters()) {
__ ret(2 * kPointerSize); // Remove both operands
} else {
__ ret(0);
}
}
void GenericBinaryOpStub::GenerateRegisterArgsPush(MacroAssembler* masm) {
ASSERT(HasArgsInRegisters());
__ pop(ecx);
if (HasArgsReversed()) {
__ push(eax);
__ push(edx);
} else {
__ push(edx);
__ push(eax);
}
__ push(ecx);
}
void GenericBinaryOpStub::GenerateTypeTransition(MacroAssembler* masm) {
Label get_result;
// Keep a copy of operands on the stack and make sure they are also in
// edx, eax.
if (HasArgsInRegisters()) {
GenerateRegisterArgsPush(masm);
} else {
GenerateLoadArguments(masm);
}
// Internal frame is necessary to handle exceptions properly.
__ EnterInternalFrame();
// Push arguments on stack if the stub expects them there.
if (!HasArgsInRegisters()) {
__ push(edx);
__ push(eax);
}
// Call the stub proper to get the result in eax.
__ call(&get_result);
__ LeaveInternalFrame();
__ pop(ecx); // Return address.
// Left and right arguments are now on top.
// Push the operation result. The tail call to BinaryOp_Patch will
// return it to the original caller.
__ push(eax);
// Push this stub's key. Although the operation and the type info are
// encoded into the key, the encoding is opaque, so push them too.
__ push(Immediate(Smi::FromInt(MinorKey())));
__ push(Immediate(Smi::FromInt(op_)));
__ push(Immediate(Smi::FromInt(runtime_operands_type_)));
__ push(ecx); // Return address.
// Patch the caller to an appropriate specialized stub
// and return the operation result.
__ TailCallExternalReference(
ExternalReference(IC_Utility(IC::kBinaryOp_Patch)),
6,
1);
// The entry point for the result calculation is assumed to be immediately
// after this sequence.
__ bind(&get_result);
}
Handle<Code> GetBinaryOpStub(int key, BinaryOpIC::TypeInfo type_info) {
GenericBinaryOpStub stub(key, type_info);
return stub.GetCode();
}
void TranscendentalCacheStub::Generate(MacroAssembler* masm) {
// Input on stack:
// esp[4]: argument (should be number).
// esp[0]: return address.
// Test that eax is a number.
Label runtime_call;
Label runtime_call_clear_stack;
Label input_not_smi;
Label loaded;
__ mov(eax, Operand(esp, kPointerSize));
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &input_not_smi);
// Input is a smi. Untag and load it onto the FPU stack.
// Then load the low and high words of the double into ebx, edx.
ASSERT_EQ(1, kSmiTagSize);
__ sar(eax, 1);
__ sub(Operand(esp), Immediate(2 * kPointerSize));
__ mov(Operand(esp, 0), eax);
__ fild_s(Operand(esp, 0));
__ fst_d(Operand(esp, 0));
__ pop(edx);
__ pop(ebx);
__ jmp(&loaded);
__ bind(&input_not_smi);
// Check if input is a HeapNumber.
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(Operand(ebx), Immediate(Factory::heap_number_map()));
__ j(not_equal, &runtime_call);
// Input is a HeapNumber. Push it on the FPU stack and load its
// low and high words into ebx, edx.
__ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ mov(edx, FieldOperand(eax, HeapNumber::kExponentOffset));
__ mov(ebx, FieldOperand(eax, HeapNumber::kMantissaOffset));
__ bind(&loaded);
// ST[0] == double value
// ebx = low 32 bits of double value
// edx = high 32 bits of double value
// Compute hash:
// h = (low ^ high); h ^= h >> 16; h ^= h >> 8; h = h & (cacheSize - 1);
__ mov(ecx, ebx);
__ xor_(ecx, Operand(edx));
__ mov(eax, ecx);
__ sar(eax, 16);
__ xor_(ecx, Operand(eax));
__ mov(eax, ecx);
__ sar(eax, 8);
__ xor_(ecx, Operand(eax));
ASSERT(IsPowerOf2(TranscendentalCache::kCacheSize));
__ and_(Operand(ecx), Immediate(TranscendentalCache::kCacheSize - 1));
// ST[0] == double value.
// ebx = low 32 bits of double value.
// edx = high 32 bits of double value.
// ecx = TranscendentalCache::hash(double value).
__ mov(eax,
Immediate(ExternalReference::transcendental_cache_array_address()));
// Eax points to cache array.
__ mov(eax, Operand(eax, type_ * sizeof(TranscendentalCache::caches_[0])));
// Eax points to the cache for the type type_.
// If NULL, the cache hasn't been initialized yet, so go through runtime.
__ test(eax, Operand(eax));
__ j(zero, &runtime_call_clear_stack);
#ifdef DEBUG
// Check that the layout of cache elements match expectations.
{ TranscendentalCache::Element test_elem[2];
char* elem_start = reinterpret_cast<char*>(&test_elem[0]);
char* elem2_start = reinterpret_cast<char*>(&test_elem[1]);
char* elem_in0 = reinterpret_cast<char*>(&(test_elem[0].in[0]));
char* elem_in1 = reinterpret_cast<char*>(&(test_elem[0].in[1]));
char* elem_out = reinterpret_cast<char*>(&(test_elem[0].output));
CHECK_EQ(12, elem2_start - elem_start); // Two uint_32's and a pointer.
CHECK_EQ(0, elem_in0 - elem_start);
CHECK_EQ(kIntSize, elem_in1 - elem_start);
CHECK_EQ(2 * kIntSize, elem_out - elem_start);
}
#endif
// Find the address of the ecx'th entry in the cache, i.e., &eax[ecx*12].
__ lea(ecx, Operand(ecx, ecx, times_2, 0));
__ lea(ecx, Operand(eax, ecx, times_4, 0));
// Check if cache matches: Double value is stored in uint32_t[2] array.
Label cache_miss;
__ cmp(ebx, Operand(ecx, 0));
__ j(not_equal, &cache_miss);
__ cmp(edx, Operand(ecx, kIntSize));
__ j(not_equal, &cache_miss);
// Cache hit!
__ mov(eax, Operand(ecx, 2 * kIntSize));
__ fstp(0);
__ ret(kPointerSize);
__ bind(&cache_miss);
// Update cache with new value.
// We are short on registers, so use no_reg as scratch.
// This gives slightly larger code.
__ AllocateHeapNumber(eax, edi, no_reg, &runtime_call_clear_stack);
GenerateOperation(masm);
__ mov(Operand(ecx, 0), ebx);
__ mov(Operand(ecx, kIntSize), edx);
__ mov(Operand(ecx, 2 * kIntSize), eax);
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ ret(kPointerSize);
__ bind(&runtime_call_clear_stack);
__ fstp(0);
__ bind(&runtime_call);
__ TailCallExternalReference(ExternalReference(RuntimeFunction()), 1, 1);
}
Runtime::FunctionId TranscendentalCacheStub::RuntimeFunction() {
switch (type_) {
// Add more cases when necessary.
case TranscendentalCache::SIN: return Runtime::kMath_sin;
case TranscendentalCache::COS: return Runtime::kMath_cos;
default:
UNIMPLEMENTED();
return Runtime::kAbort;
}
}
void TranscendentalCacheStub::GenerateOperation(MacroAssembler* masm) {
// Only free register is edi.
Label done;
ASSERT(type_ == TranscendentalCache::SIN ||
type_ == TranscendentalCache::COS);
// More transcendental types can be added later.
// Both fsin and fcos require arguments in the range +/-2^63 and
// return NaN for infinities and NaN. They can share all code except
// the actual fsin/fcos operation.
Label in_range;
// If argument is outside the range -2^63..2^63, fsin/cos doesn't
// work. We must reduce it to the appropriate range.
__ mov(edi, edx);
__ and_(Operand(edi), Immediate(0x7ff00000)); // Exponent only.
int supported_exponent_limit =
(63 + HeapNumber::kExponentBias) << HeapNumber::kExponentShift;
__ cmp(Operand(edi), Immediate(supported_exponent_limit));
__ j(below, &in_range, taken);
// Check for infinity and NaN. Both return NaN for sin.
__ cmp(Operand(edi), Immediate(0x7ff00000));
Label non_nan_result;
__ j(not_equal, &non_nan_result, taken);
// Input is +/-Infinity or NaN. Result is NaN.
__ fstp(0);
// NaN is represented by 0x7ff8000000000000.
__ push(Immediate(0x7ff80000));
__ push(Immediate(0));
__ fld_d(Operand(esp, 0));
__ add(Operand(esp), Immediate(2 * kPointerSize));
__ jmp(&done);
__ bind(&non_nan_result);
// Use fpmod to restrict argument to the range +/-2*PI.
__ mov(edi, eax); // Save eax before using fnstsw_ax.
__ fldpi();
__ fadd(0);
__ fld(1);
// FPU Stack: input, 2*pi, input.
{
Label no_exceptions;
__ fwait();
__ fnstsw_ax();
// Clear if Illegal Operand or Zero Division exceptions are set.
__ test(Operand(eax), Immediate(5));
__ j(zero, &no_exceptions);
__ fnclex();
__ bind(&no_exceptions);
}
// Compute st(0) % st(1)
{
Label partial_remainder_loop;
__ bind(&partial_remainder_loop);
__ fprem1();
__ fwait();
__ fnstsw_ax();
__ test(Operand(eax), Immediate(0x400 /* C2 */));
// If C2 is set, computation only has partial result. Loop to
// continue computation.
__ j(not_zero, &partial_remainder_loop);
}
// FPU Stack: input, 2*pi, input % 2*pi
__ fstp(2);
__ fstp(0);
__ mov(eax, edi); // Restore eax (allocated HeapNumber pointer).
// FPU Stack: input % 2*pi
__ bind(&in_range);
switch (type_) {
case TranscendentalCache::SIN:
__ fsin();
break;
case TranscendentalCache::COS:
__ fcos();
break;
default:
UNREACHABLE();
}
__ bind(&done);
}
// Get the integer part of a heap number. Surprisingly, all this bit twiddling
// is faster than using the built-in instructions on floating point registers.
// Trashes edi and ebx. Dest is ecx. Source cannot be ecx or one of the
// trashed registers.
void IntegerConvert(MacroAssembler* masm,
Register source,
TypeInfo type_info,
bool use_sse3,
Label* conversion_failure) {
ASSERT(!source.is(ecx) && !source.is(edi) && !source.is(ebx));
Label done, right_exponent, normal_exponent;
Register scratch = ebx;
Register scratch2 = edi;
if (type_info.IsInteger32() && CpuFeatures::IsEnabled(SSE2)) {
CpuFeatures::Scope scope(SSE2);
__ cvttsd2si(ecx, FieldOperand(source, HeapNumber::kValueOffset));
return;
}
if (!type_info.IsInteger32() || !use_sse3) {
// Get exponent word.
__ mov(scratch, FieldOperand(source, HeapNumber::kExponentOffset));
// Get exponent alone in scratch2.
__ mov(scratch2, scratch);
__ and_(scratch2, HeapNumber::kExponentMask);
}
if (use_sse3) {
CpuFeatures::Scope scope(SSE3);
if (!type_info.IsInteger32()) {
// Check whether the exponent is too big for a 64 bit signed integer.
static const uint32_t kTooBigExponent =
(HeapNumber::kExponentBias + 63) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch2), Immediate(kTooBigExponent));
__ j(greater_equal, conversion_failure);
}
// Load x87 register with heap number.
__ fld_d(FieldOperand(source, HeapNumber::kValueOffset));
// Reserve space for 64 bit answer.
__ sub(Operand(esp), Immediate(sizeof(uint64_t))); // Nolint.
// Do conversion, which cannot fail because we checked the exponent.
__ fisttp_d(Operand(esp, 0));
__ mov(ecx, Operand(esp, 0)); // Load low word of answer into ecx.
__ add(Operand(esp), Immediate(sizeof(uint64_t))); // Nolint.
} else {
// Load ecx with zero. We use this either for the final shift or
// for the answer.
__ xor_(ecx, Operand(ecx));
// Check whether the exponent matches a 32 bit signed int that cannot be
// represented by a Smi. A non-smi 32 bit integer is 1.xxx * 2^30 so the
// exponent is 30 (biased). This is the exponent that we are fastest at and
// also the highest exponent we can handle here.
const uint32_t non_smi_exponent =
(HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch2), Immediate(non_smi_exponent));
// If we have a match of the int32-but-not-Smi exponent then skip some
// logic.
__ j(equal, &right_exponent);
// If the exponent is higher than that then go to slow case. This catches
// numbers that don't fit in a signed int32, infinities and NaNs.
__ j(less, &normal_exponent);
{
// Handle a big exponent. The only reason we have this code is that the
// >>> operator has a tendency to generate numbers with an exponent of 31.
const uint32_t big_non_smi_exponent =
(HeapNumber::kExponentBias + 31) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch2), Immediate(big_non_smi_exponent));
__ j(not_equal, conversion_failure);
// We have the big exponent, typically from >>>. This means the number is
// in the range 2^31 to 2^32 - 1. Get the top bits of the mantissa.
__ mov(scratch2, scratch);
__ and_(scratch2, HeapNumber::kMantissaMask);
// Put back the implicit 1.
__ or_(scratch2, 1 << HeapNumber::kExponentShift);
// Shift up the mantissa bits to take up the space the exponent used to
// take. We just orred in the implicit bit so that took care of one and
// we want to use the full unsigned range so we subtract 1 bit from the
// shift distance.
const int big_shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 1;
__ shl(scratch2, big_shift_distance);
// Get the second half of the double.
__ mov(ecx, FieldOperand(source, HeapNumber::kMantissaOffset));
// Shift down 21 bits to get the most significant 11 bits or the low
// mantissa word.
__ shr(ecx, 32 - big_shift_distance);
__ or_(ecx, Operand(scratch2));
// We have the answer in ecx, but we may need to negate it.
__ test(scratch, Operand(scratch));
__ j(positive, &done);
__ neg(ecx);
__ jmp(&done);
}
__ bind(&normal_exponent);
// Exponent word in scratch, exponent part of exponent word in scratch2.
// Zero in ecx.
// We know the exponent is smaller than 30 (biased). If it is less than
// 0 (biased) then the number is smaller in magnitude than 1.0 * 2^0, ie
// it rounds to zero.
const uint32_t zero_exponent =
(HeapNumber::kExponentBias + 0) << HeapNumber::kExponentShift;
__ sub(Operand(scratch2), Immediate(zero_exponent));
// ecx already has a Smi zero.
__ j(less, &done);
// We have a shifted exponent between 0 and 30 in scratch2.
__ shr(scratch2, HeapNumber::kExponentShift);
__ mov(ecx, Immediate(30));
__ sub(ecx, Operand(scratch2));
__ bind(&right_exponent);
// Here ecx is the shift, scratch is the exponent word.
// Get the top bits of the mantissa.
__ and_(scratch, HeapNumber::kMantissaMask);
// Put back the implicit 1.
__ or_(scratch, 1 << HeapNumber::kExponentShift);
// Shift up the mantissa bits to take up the space the exponent used to
// take. We have kExponentShift + 1 significant bits int he low end of the
// word. Shift them to the top bits.
const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
__ shl(scratch, shift_distance);
// Get the second half of the double. For some exponents we don't
// actually need this because the bits get shifted out again, but
// it's probably slower to test than just to do it.
__ mov(scratch2, FieldOperand(source, HeapNumber::kMantissaOffset));
// Shift down 22 bits to get the most significant 10 bits or the low
// mantissa word.
__ shr(scratch2, 32 - shift_distance);
__ or_(scratch2, Operand(scratch));
// Move down according to the exponent.
__ shr_cl(scratch2);
// Now the unsigned answer is in scratch2. We need to move it to ecx and
// we may need to fix the sign.
Label negative;
__ xor_(ecx, Operand(ecx));
__ cmp(ecx, FieldOperand(source, HeapNumber::kExponentOffset));
__ j(greater, &negative);
__ mov(ecx, scratch2);
__ jmp(&done);
__ bind(&negative);
__ sub(ecx, Operand(scratch2));
__ bind(&done);
}
}
// Input: edx, eax are the left and right objects of a bit op.
// Output: eax, ecx are left and right integers for a bit op.
void FloatingPointHelper::LoadNumbersAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* conversion_failure) {
// Check float operands.
Label arg1_is_object, check_undefined_arg1;
Label arg2_is_object, check_undefined_arg2;
Label load_arg2, done;
if (!type_info.IsDouble()) {
if (!type_info.IsSmi()) {
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &arg1_is_object);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(edx);
}
__ SmiUntag(edx);
__ jmp(&load_arg2);
}
__ bind(&arg1_is_object);
// Get the untagged integer version of the edx heap number in ecx.
IntegerConvert(masm, edx, type_info, use_sse3, conversion_failure);
__ mov(edx, ecx);
// Here edx has the untagged integer, eax has a Smi or a heap number.
__ bind(&load_arg2);
if (!type_info.IsDouble()) {
// Test if arg2 is a Smi.
if (!type_info.IsSmi()) {
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &arg2_is_object);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(eax);
}
__ SmiUntag(eax);
__ mov(ecx, eax);
__ jmp(&done);
}
__ bind(&arg2_is_object);
// Get the untagged integer version of the eax heap number in ecx.
IntegerConvert(masm, eax, type_info, use_sse3, conversion_failure);
__ bind(&done);
__ mov(eax, edx);
}
// Input: edx, eax are the left and right objects of a bit op.
// Output: eax, ecx are left and right integers for a bit op.
void FloatingPointHelper::LoadUnknownsAsIntegers(MacroAssembler* masm,
bool use_sse3,
Label* conversion_failure) {
// Check float operands.
Label arg1_is_object, check_undefined_arg1;
Label arg2_is_object, check_undefined_arg2;
Label load_arg2, done;
// Test if arg1 is a Smi.
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &arg1_is_object);
__ SmiUntag(edx);
__ jmp(&load_arg2);
// If the argument is undefined it converts to zero (ECMA-262, section 9.5).
__ bind(&check_undefined_arg1);
__ cmp(edx, Factory::undefined_value());
__ j(not_equal, conversion_failure);
__ mov(edx, Immediate(0));
__ jmp(&load_arg2);
__ bind(&arg1_is_object);
__ mov(ebx, FieldOperand(edx, HeapObject::kMapOffset));
__ cmp(ebx, Factory::heap_number_map());
__ j(not_equal, &check_undefined_arg1);
// Get the untagged integer version of the edx heap number in ecx.
IntegerConvert(masm,
edx,
TypeInfo::Unknown(),
use_sse3,
conversion_failure);
__ mov(edx, ecx);
// Here edx has the untagged integer, eax has a Smi or a heap number.
__ bind(&load_arg2);
// Test if arg2 is a Smi.
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &arg2_is_object);
__ SmiUntag(eax);
__ mov(ecx, eax);
__ jmp(&done);
// If the argument is undefined it converts to zero (ECMA-262, section 9.5).
__ bind(&check_undefined_arg2);
__ cmp(eax, Factory::undefined_value());
__ j(not_equal, conversion_failure);
__ mov(ecx, Immediate(0));
__ jmp(&done);
__ bind(&arg2_is_object);
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(ebx, Factory::heap_number_map());
__ j(not_equal, &check_undefined_arg2);
// Get the untagged integer version of the eax heap number in ecx.
IntegerConvert(masm,
eax,
TypeInfo::Unknown(),
use_sse3,
conversion_failure);
__ bind(&done);
__ mov(eax, edx);
}
void FloatingPointHelper::LoadAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* conversion_failure) {
if (type_info.IsNumber()) {
LoadNumbersAsIntegers(masm, type_info, use_sse3, conversion_failure);
} else {
LoadUnknownsAsIntegers(masm, use_sse3, conversion_failure);
}
}
void FloatingPointHelper::LoadFloatOperand(MacroAssembler* masm,
Register number) {
Label load_smi, done;
__ test(number, Immediate(kSmiTagMask));
__ j(zero, &load_smi, not_taken);
__ fld_d(FieldOperand(number, HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&load_smi);
__ SmiUntag(number);
__ push(number);
__ fild_s(Operand(esp, 0));
__ pop(number);
__ bind(&done);
}
void FloatingPointHelper::LoadSSE2Operands(MacroAssembler* masm) {
Label load_smi_edx, load_eax, load_smi_eax, done;
// Load operand in edx into xmm0.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &load_smi_edx, not_taken); // Argument in edx is a smi.
__ movdbl(xmm0, FieldOperand(edx, HeapNumber::kValueOffset));
__ bind(&load_eax);
// Load operand in eax into xmm1.
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &load_smi_eax, not_taken); // Argument in eax is a smi.
__ movdbl(xmm1, FieldOperand(eax, HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&load_smi_edx);
__ SmiUntag(edx); // Untag smi before converting to float.
__ cvtsi2sd(xmm0, Operand(edx));
__ SmiTag(edx); // Retag smi for heap number overwriting test.
__ jmp(&load_eax);
__ bind(&load_smi_eax);
__ SmiUntag(eax); // Untag smi before converting to float.
__ cvtsi2sd(xmm1, Operand(eax));
__ SmiTag(eax); // Retag smi for heap number overwriting test.
__ bind(&done);
}
void FloatingPointHelper::LoadSSE2Operands(MacroAssembler* masm,
Label* not_numbers) {
Label load_smi_edx, load_eax, load_smi_eax, load_float_eax, done;
// Load operand in edx into xmm0, or branch to not_numbers.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &load_smi_edx, not_taken); // Argument in edx is a smi.
__ cmp(FieldOperand(edx, HeapObject::kMapOffset), Factory::heap_number_map());
__ j(not_equal, not_numbers); // Argument in edx is not a number.
__ movdbl(xmm0, FieldOperand(edx, HeapNumber::kValueOffset));
__ bind(&load_eax);
// Load operand in eax into xmm1, or branch to not_numbers.
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &load_smi_eax, not_taken); // Argument in eax is a smi.
__ cmp(FieldOperand(eax, HeapObject::kMapOffset), Factory::heap_number_map());
__ j(equal, &load_float_eax);
__ jmp(not_numbers); // Argument in eax is not a number.
__ bind(&load_smi_edx);
__ SmiUntag(edx); // Untag smi before converting to float.
__ cvtsi2sd(xmm0, Operand(edx));
__ SmiTag(edx); // Retag smi for heap number overwriting test.
__ jmp(&load_eax);
__ bind(&load_smi_eax);
__ SmiUntag(eax); // Untag smi before converting to float.
__ cvtsi2sd(xmm1, Operand(eax));
__ SmiTag(eax); // Retag smi for heap number overwriting test.
__ jmp(&done);
__ bind(&load_float_eax);
__ movdbl(xmm1, FieldOperand(eax, HeapNumber::kValueOffset));
__ bind(&done);
}
void FloatingPointHelper::LoadSSE2Smis(MacroAssembler* masm,
Register scratch) {
const Register left = edx;
const Register right = eax;
__ mov(scratch, left);
ASSERT(!scratch.is(right)); // We're about to clobber scratch.
__ SmiUntag(scratch);
__ cvtsi2sd(xmm0, Operand(scratch));
__ mov(scratch, right);
__ SmiUntag(scratch);
__ cvtsi2sd(xmm1, Operand(scratch));
}
void FloatingPointHelper::LoadFloatOperands(MacroAssembler* masm,
Register scratch,
ArgLocation arg_location) {
Label load_smi_1, load_smi_2, done_load_1, done;
if (arg_location == ARGS_IN_REGISTERS) {
__ mov(scratch, edx);
} else {
__ mov(scratch, Operand(esp, 2 * kPointerSize));
}
__ test(scratch, Immediate(kSmiTagMask));
__ j(zero, &load_smi_1, not_taken);
__ fld_d(FieldOperand(scratch, HeapNumber::kValueOffset));
__ bind(&done_load_1);
if (arg_location == ARGS_IN_REGISTERS) {
__ mov(scratch, eax);
} else {
__ mov(scratch, Operand(esp, 1 * kPointerSize));
}
__ test(scratch, Immediate(kSmiTagMask));
__ j(zero, &load_smi_2, not_taken);
__ fld_d(FieldOperand(scratch, HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&load_smi_1);
__ SmiUntag(scratch);
__ push(scratch);
__ fild_s(Operand(esp, 0));
__ pop(scratch);
__ jmp(&done_load_1);
__ bind(&load_smi_2);
__ SmiUntag(scratch);
__ push(scratch);
__ fild_s(Operand(esp, 0));
__ pop(scratch);
__ bind(&done);
}
void FloatingPointHelper::LoadFloatSmis(MacroAssembler* masm,
Register scratch) {
const Register left = edx;
const Register right = eax;
__ mov(scratch, left);
ASSERT(!scratch.is(right)); // We're about to clobber scratch.
__ SmiUntag(scratch);
__ push(scratch);
__ fild_s(Operand(esp, 0));
__ mov(scratch, right);
__ SmiUntag(scratch);
__ mov(Operand(esp, 0), scratch);
__ fild_s(Operand(esp, 0));
__ pop(scratch);
}
void FloatingPointHelper::CheckFloatOperands(MacroAssembler* masm,
Label* non_float,
Register scratch) {
Label test_other, done;
// Test if both operands are floats or smi -> scratch=k_is_float;
// Otherwise scratch = k_not_float.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &test_other, not_taken); // argument in edx is OK
__ mov(scratch, FieldOperand(edx, HeapObject::kMapOffset));
__ cmp(scratch, Factory::heap_number_map());
__ j(not_equal, non_float); // argument in edx is not a number -> NaN
__ bind(&test_other);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &done); // argument in eax is OK
__ mov(scratch, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(scratch, Factory::heap_number_map());
__ j(not_equal, non_float); // argument in eax is not a number -> NaN
// Fall-through: Both operands are numbers.
__ bind(&done);
}
void GenericUnaryOpStub::Generate(MacroAssembler* masm) {
Label slow, done;
if (op_ == Token::SUB) {
// Check whether the value is a smi.
Label try_float;
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &try_float, not_taken);
// Go slow case if the value of the expression is zero
// to make sure that we switch between 0 and -0.
__ test(eax, Operand(eax));
__ j(zero, &slow, not_taken);
// The value of the expression is a smi that is not zero. Try
// optimistic subtraction '0 - value'.
Label undo;
__ mov(edx, Operand(eax));
__ Set(eax, Immediate(0));
__ sub(eax, Operand(edx));
__ j(overflow, &undo, not_taken);
// If result is a smi we are done.
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &done, taken);
// Restore eax and go slow case.
__ bind(&undo);
__ mov(eax, Operand(edx));
__ jmp(&slow);
// Try floating point case.
__ bind(&try_float);
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &slow);
if (overwrite_) {
__ mov(edx, FieldOperand(eax, HeapNumber::kExponentOffset));
__ xor_(edx, HeapNumber::kSignMask); // Flip sign.
__ mov(FieldOperand(eax, HeapNumber::kExponentOffset), edx);
} else {
__ mov(edx, Operand(eax));
// edx: operand
__ AllocateHeapNumber(eax, ebx, ecx, &undo);
// eax: allocated 'empty' number
__ mov(ecx, FieldOperand(edx, HeapNumber::kExponentOffset));
__ xor_(ecx, HeapNumber::kSignMask); // Flip sign.
__ mov(FieldOperand(eax, HeapNumber::kExponentOffset), ecx);
__ mov(ecx, FieldOperand(edx, HeapNumber::kMantissaOffset));
__ mov(FieldOperand(eax, HeapNumber::kMantissaOffset), ecx);
}
} else if (op_ == Token::BIT_NOT) {
// Check if the operand is a heap number.
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &slow, not_taken);
// Convert the heap number in eax to an untagged integer in ecx.
IntegerConvert(masm,
eax,
TypeInfo::Unknown(),
CpuFeatures::IsSupported(SSE3),
&slow);
// Do the bitwise operation and check if the result fits in a smi.
Label try_float;
__ not_(ecx);
__ cmp(ecx, 0xc0000000);
__ j(sign, &try_float, not_taken);
// Tag the result as a smi and we're done.
ASSERT(kSmiTagSize == 1);
__ lea(eax, Operand(ecx, times_2, kSmiTag));
__ jmp(&done);
// Try to store the result in a heap number.
__ bind(&try_float);
if (!overwrite_) {
// Allocate a fresh heap number, but don't overwrite eax until
// we're sure we can do it without going through the slow case
// that needs the value in eax.
__ AllocateHeapNumber(ebx, edx, edi, &slow);
__ mov(eax, Operand(ebx));
}
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
__ cvtsi2sd(xmm0, Operand(ecx));
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
} else {
__ push(ecx);
__ fild_s(Operand(esp, 0));
__ pop(ecx);
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
}
} else {
UNIMPLEMENTED();
}
// Return from the stub.
__ bind(&done);
__ StubReturn(1);
// Handle the slow case by jumping to the JavaScript builtin.
__ bind(&slow);
__ pop(ecx); // pop return address.
__ push(eax);
__ push(ecx); // push return address
switch (op_) {
case Token::SUB:
__ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_FUNCTION);
break;
case Token::BIT_NOT:
__ InvokeBuiltin(Builtins::BIT_NOT, JUMP_FUNCTION);
break;
default:
UNREACHABLE();
}
}
void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
// The key is in edx and the parameter count is in eax.
// The displacement is used for skipping the frame pointer on the
// stack. It is the offset of the last parameter (if any) relative
// to the frame pointer.
static const int kDisplacement = 1 * kPointerSize;
// Check that the key is a smi.
Label slow;
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &slow, not_taken);
// Check if the calling frame is an arguments adaptor frame.
Label adaptor;
__ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ mov(ecx, Operand(ebx, StandardFrameConstants::kContextOffset));
__ cmp(Operand(ecx), Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &adaptor);
// Check index against formal parameters count limit passed in
// through register eax. Use unsigned comparison to get negative
// check for free.
__ cmp(edx, Operand(eax));
__ j(above_equal, &slow, not_taken);
// Read the argument from the stack and return it.
ASSERT(kSmiTagSize == 1 && kSmiTag == 0); // shifting code depends on this
__ lea(ebx, Operand(ebp, eax, times_2, 0));
__ neg(edx);
__ mov(eax, Operand(ebx, edx, times_2, kDisplacement));
__ ret(0);
// Arguments adaptor case: Check index against actual arguments
// limit found in the arguments adaptor frame. Use unsigned
// comparison to get negative check for free.
__ bind(&adaptor);
__ mov(ecx, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ cmp(edx, Operand(ecx));
__ j(above_equal, &slow, not_taken);
// Read the argument from the stack and return it.
ASSERT(kSmiTagSize == 1 && kSmiTag == 0); // shifting code depends on this
__ lea(ebx, Operand(ebx, ecx, times_2, 0));
__ neg(edx);
__ mov(eax, Operand(ebx, edx, times_2, kDisplacement));
__ ret(0);
// Slow-case: Handle non-smi or out-of-bounds access to arguments
// by calling the runtime system.
__ bind(&slow);
__ pop(ebx); // Return address.
__ push(edx);
__ push(ebx);
__ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
}
void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
// esp[0] : return address
// esp[4] : number of parameters
// esp[8] : receiver displacement
// esp[16] : function
// The displacement is used for skipping the return address and the
// frame pointer on the stack. It is the offset of the last
// parameter (if any) relative to the frame pointer.
static const int kDisplacement = 2 * kPointerSize;
// Check if the calling frame is an arguments adaptor frame.
Label adaptor_frame, try_allocate, runtime;
__ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
__ cmp(Operand(ecx), Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &adaptor_frame);
// Get the length from the frame.
__ mov(ecx, Operand(esp, 1 * kPointerSize));
__ jmp(&try_allocate);
// Patch the arguments.length and the parameters pointer.
__ bind(&adaptor_frame);
__ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ mov(Operand(esp, 1 * kPointerSize), ecx);
__ lea(edx, Operand(edx, ecx, times_2, kDisplacement));
__ mov(Operand(esp, 2 * kPointerSize), edx);
// Try the new space allocation. Start out with computing the size of
// the arguments object and the elements array.
Label add_arguments_object;
__ bind(&try_allocate);
__ test(ecx, Operand(ecx));
__ j(zero, &add_arguments_object);
__ lea(ecx, Operand(ecx, times_2, FixedArray::kHeaderSize));
__ bind(&add_arguments_object);
__ add(Operand(ecx), Immediate(Heap::kArgumentsObjectSize));
// Do the allocation of both objects in one go.
__ AllocateInNewSpace(ecx, eax, edx, ebx, &runtime, TAG_OBJECT);
// Get the arguments boilerplate from the current (global) context.
int offset = Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
__ mov(edi, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
__ mov(edi, FieldOperand(edi, GlobalObject::kGlobalContextOffset));
__ mov(edi, Operand(edi, offset));
// Copy the JS object part.
for (int i = 0; i < JSObject::kHeaderSize; i += kPointerSize) {
__ mov(ebx, FieldOperand(edi, i));
__ mov(FieldOperand(eax, i), ebx);
}
// Setup the callee in-object property.
ASSERT(Heap::arguments_callee_index == 0);
__ mov(ebx, Operand(esp, 3 * kPointerSize));
__ mov(FieldOperand(eax, JSObject::kHeaderSize), ebx);
// Get the length (smi tagged) and set that as an in-object property too.
ASSERT(Heap::arguments_length_index == 1);
__ mov(ecx, Operand(esp, 1 * kPointerSize));
__ mov(FieldOperand(eax, JSObject::kHeaderSize + kPointerSize), ecx);
// If there are no actual arguments, we're done.
Label done;
__ test(ecx, Operand(ecx));
__ j(zero, &done);
// Get the parameters pointer from the stack.
__ mov(edx, Operand(esp, 2 * kPointerSize));
// Setup the elements pointer in the allocated arguments object and
// initialize the header in the elements fixed array.
__ lea(edi, Operand(eax, Heap::kArgumentsObjectSize));
__ mov(FieldOperand(eax, JSObject::kElementsOffset), edi);
__ mov(FieldOperand(edi, FixedArray::kMapOffset),
Immediate(Factory::fixed_array_map()));
__ mov(FieldOperand(edi, FixedArray::kLengthOffset), ecx);
// Untag the length for the loop below.
__ SmiUntag(ecx);
// Copy the fixed array slots.
Label loop;
__ bind(&loop);
__ mov(ebx, Operand(edx, -1 * kPointerSize)); // Skip receiver.
__ mov(FieldOperand(edi, FixedArray::kHeaderSize), ebx);
__ add(Operand(edi), Immediate(kPointerSize));
__ sub(Operand(edx), Immediate(kPointerSize));
__ dec(ecx);
__ j(not_zero, &loop);
// Return and remove the on-stack parameters.
__ bind(&done);
__ ret(3 * kPointerSize);
// Do the runtime call to allocate the arguments object.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
}
void RegExpExecStub::Generate(MacroAssembler* masm) {
// Just jump directly to runtime if native RegExp is not selected at compile
// time or if regexp entry in generated code is turned off runtime switch or
// at compilation.
#ifdef V8_INTERPRETED_REGEXP
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
#else // V8_INTERPRETED_REGEXP
if (!FLAG_regexp_entry_native) {
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
return;
}
// Stack frame on entry.
// esp[0]: return address
// esp[4]: last_match_info (expected JSArray)
// esp[8]: previous index
// esp[12]: subject string
// esp[16]: JSRegExp object
static const int kLastMatchInfoOffset = 1 * kPointerSize;
static const int kPreviousIndexOffset = 2 * kPointerSize;
static const int kSubjectOffset = 3 * kPointerSize;
static const int kJSRegExpOffset = 4 * kPointerSize;
Label runtime, invoke_regexp;
// Ensure that a RegExp stack is allocated.
ExternalReference address_of_regexp_stack_memory_address =
ExternalReference::address_of_regexp_stack_memory_address();
ExternalReference address_of_regexp_stack_memory_size =
ExternalReference::address_of_regexp_stack_memory_size();
__ mov(ebx, Operand::StaticVariable(address_of_regexp_stack_memory_size));
__ test(ebx, Operand(ebx));
__ j(zero, &runtime, not_taken);
// Check that the first argument is a JSRegExp object.
__ mov(eax, Operand(esp, kJSRegExpOffset));
ASSERT_EQ(0, kSmiTag);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
__ CmpObjectType(eax, JS_REGEXP_TYPE, ecx);
__ j(not_equal, &runtime);
// Check that the RegExp has been compiled (data contains a fixed array).
__ mov(ecx, FieldOperand(eax, JSRegExp::kDataOffset));
if (FLAG_debug_code) {
__ test(ecx, Immediate(kSmiTagMask));
__ Check(not_zero, "Unexpected type for RegExp data, FixedArray expected");
__ CmpObjectType(ecx, FIXED_ARRAY_TYPE, ebx);
__ Check(equal, "Unexpected type for RegExp data, FixedArray expected");
}
// ecx: RegExp data (FixedArray)
// Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
__ mov(ebx, FieldOperand(ecx, JSRegExp::kDataTagOffset));
__ cmp(Operand(ebx), Immediate(Smi::FromInt(JSRegExp::IRREGEXP)));
__ j(not_equal, &runtime);
// ecx: RegExp data (FixedArray)
// Check that the number of captures fit in the static offsets vector buffer.
__ mov(edx, FieldOperand(ecx, JSRegExp::kIrregexpCaptureCountOffset));
// Calculate number of capture registers (number_of_captures + 1) * 2. This
// uses the asumption that smis are 2 * their untagged value.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
__ add(Operand(edx), Immediate(2)); // edx was a smi.
// Check that the static offsets vector buffer is large enough.
__ cmp(edx, OffsetsVector::kStaticOffsetsVectorSize);
__ j(above, &runtime);
// ecx: RegExp data (FixedArray)
// edx: Number of capture registers
// Check that the second argument is a string.
__ mov(eax, Operand(esp, kSubjectOffset));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
__ j(NegateCondition(is_string), &runtime);
// Get the length of the string to ebx.
__ mov(ebx, FieldOperand(eax, String::kLengthOffset));
// ebx: Length of subject string as a smi
// ecx: RegExp data (FixedArray)
// edx: Number of capture registers
// Check that the third argument is a positive smi less than the subject
// string length. A negative value will be greater (unsigned comparison).
__ mov(eax, Operand(esp, kPreviousIndexOffset));
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &runtime);
__ cmp(eax, Operand(ebx));
__ j(above_equal, &runtime);
// ecx: RegExp data (FixedArray)
// edx: Number of capture registers
// Check that the fourth object is a JSArray object.
__ mov(eax, Operand(esp, kLastMatchInfoOffset));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
__ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
__ j(not_equal, &runtime);
// Check that the JSArray is in fast case.
__ mov(ebx, FieldOperand(eax, JSArray::kElementsOffset));
__ mov(eax, FieldOperand(ebx, HeapObject::kMapOffset));
__ cmp(eax, Factory::fixed_array_map());
__ j(not_equal, &runtime);
// Check that the last match info has space for the capture registers and the
// additional information.
__ mov(eax, FieldOperand(ebx, FixedArray::kLengthOffset));
__ SmiUntag(eax);
__ add(Operand(edx), Immediate(RegExpImpl::kLastMatchOverhead));
__ cmp(edx, Operand(eax));
__ j(greater, &runtime);
// ecx: RegExp data (FixedArray)
// Check the representation and encoding of the subject string.
Label seq_string, seq_two_byte_string, check_code;
const int kStringRepresentationEncodingMask =
kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask;
__ mov(eax, Operand(esp, kSubjectOffset));
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
__ and_(ebx, kStringRepresentationEncodingMask);
// First check for sequential string.
ASSERT_EQ(0, kStringTag);
ASSERT_EQ(0, kSeqStringTag);
__ test(Operand(ebx),
Immediate(kIsNotStringMask | kStringRepresentationMask));
__ j(zero, &seq_string);
// Check for flat cons string.
// A flat cons string is a cons string where the second part is the empty
// string. In that case the subject string is just the first part of the cons
// string. Also in this case the first part of the cons string is known to be
// a sequential string or an external string.
__ and_(ebx, kStringRepresentationMask);
__ cmp(ebx, kConsStringTag);
__ j(not_equal, &runtime);
__ mov(edx, FieldOperand(eax, ConsString::kSecondOffset));
__ cmp(Operand(edx), Factory::empty_string());
__ j(not_equal, &runtime);
__ mov(eax, FieldOperand(eax, ConsString::kFirstOffset));
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
ASSERT_EQ(0, kSeqStringTag);
__ test(ebx, Immediate(kStringRepresentationMask));
__ j(not_zero, &runtime);
__ and_(ebx, kStringRepresentationEncodingMask);
__ bind(&seq_string);
// eax: subject string (sequential either ascii to two byte)
// ebx: suject string type & kStringRepresentationEncodingMask
// ecx: RegExp data (FixedArray)
// Check that the irregexp code has been generated for an ascii string. If
// it has, the field contains a code object otherwise it contains the hole.
const int kSeqTwoByteString = kStringTag | kSeqStringTag | kTwoByteStringTag;
__ cmp(ebx, kSeqTwoByteString);
__ j(equal, &seq_two_byte_string);
if (FLAG_debug_code) {
__ cmp(ebx, kStringTag | kSeqStringTag | kAsciiStringTag);
__ Check(equal, "Expected sequential ascii string");
}
__ mov(edx, FieldOperand(ecx, JSRegExp::kDataAsciiCodeOffset));
__ Set(edi, Immediate(1)); // Type is ascii.
__ jmp(&check_code);
__ bind(&seq_two_byte_string);
// eax: subject string
// ecx: RegExp data (FixedArray)
__ mov(edx, FieldOperand(ecx, JSRegExp::kDataUC16CodeOffset));
__ Set(edi, Immediate(0)); // Type is two byte.
__ bind(&check_code);
// Check that the irregexp code has been generated for the actual string
// encoding. If it has, the field contains a code object otherwise it contains
// the hole.
__ CmpObjectType(edx, CODE_TYPE, ebx);
__ j(not_equal, &runtime);
// eax: subject string
// edx: code
// edi: encoding of subject string (1 if ascii, 0 if two_byte);
// Load used arguments before starting to push arguments for call to native
// RegExp code to avoid handling changing stack height.
__ mov(ebx, Operand(esp, kPreviousIndexOffset));
__ SmiUntag(ebx); // Previous index from smi.
// eax: subject string
// ebx: previous index
// edx: code
// edi: encoding of subject string (1 if ascii 0 if two_byte);
// All checks done. Now push arguments for native regexp code.
__ IncrementCounter(&Counters::regexp_entry_native, 1);
static const int kRegExpExecuteArguments = 7;
__ PrepareCallCFunction(kRegExpExecuteArguments, ecx);
// Argument 7: Indicate that this is a direct call from JavaScript.
__ mov(Operand(esp, 6 * kPointerSize), Immediate(1));
// Argument 6: Start (high end) of backtracking stack memory area.
__ mov(ecx, Operand::StaticVariable(address_of_regexp_stack_memory_address));
__ add(ecx, Operand::StaticVariable(address_of_regexp_stack_memory_size));
__ mov(Operand(esp, 5 * kPointerSize), ecx);
// Argument 5: static offsets vector buffer.
__ mov(Operand(esp, 4 * kPointerSize),
Immediate(ExternalReference::address_of_static_offsets_vector()));
// Argument 4: End of string data
// Argument 3: Start of string data
Label setup_two_byte, setup_rest;
__ test(edi, Operand(edi));
__ mov(edi, FieldOperand(eax, String::kLengthOffset));
__ j(zero, &setup_two_byte);
__ SmiUntag(edi);
__ lea(ecx, FieldOperand(eax, edi, times_1, SeqAsciiString::kHeaderSize));
__ mov(Operand(esp, 3 * kPointerSize), ecx); // Argument 4.
__ lea(ecx, FieldOperand(eax, ebx, times_1, SeqAsciiString::kHeaderSize));
__ mov(Operand(esp, 2 * kPointerSize), ecx); // Argument 3.
__ jmp(&setup_rest);
__ bind(&setup_two_byte);
ASSERT(kSmiTag == 0 && kSmiTagSize == 1); // edi is smi (powered by 2).
__ lea(ecx, FieldOperand(eax, edi, times_1, SeqTwoByteString::kHeaderSize));
__ mov(Operand(esp, 3 * kPointerSize), ecx); // Argument 4.
__ lea(ecx, FieldOperand(eax, ebx, times_2, SeqTwoByteString::kHeaderSize));
__ mov(Operand(esp, 2 * kPointerSize), ecx); // Argument 3.
__ bind(&setup_rest);
// Argument 2: Previous index.
__ mov(Operand(esp, 1 * kPointerSize), ebx);
// Argument 1: Subject string.
__ mov(Operand(esp, 0 * kPointerSize), eax);
// Locate the code entry and call it.
__ add(Operand(edx), Immediate(Code::kHeaderSize - kHeapObjectTag));
__ CallCFunction(edx, kRegExpExecuteArguments);
// Check the result.
Label success;
__ cmp(eax, NativeRegExpMacroAssembler::SUCCESS);
__ j(equal, &success, taken);
Label failure;
__ cmp(eax, NativeRegExpMacroAssembler::FAILURE);
__ j(equal, &failure, taken);
__ cmp(eax, NativeRegExpMacroAssembler::EXCEPTION);
// If not exception it can only be retry. Handle that in the runtime system.
__ j(not_equal, &runtime);
// Result must now be exception. If there is no pending exception already a
// stack overflow (on the backtrack stack) was detected in RegExp code but
// haven't created the exception yet. Handle that in the runtime system.
// TODO(592): Rerunning the RegExp to get the stack overflow exception.
ExternalReference pending_exception(Top::k_pending_exception_address);
__ mov(eax,
Operand::StaticVariable(ExternalReference::the_hole_value_location()));
__ cmp(eax, Operand::StaticVariable(pending_exception));
__ j(equal, &runtime);
__ bind(&failure);
// For failure and exception return null.
__ mov(Operand(eax), Factory::null_value());
__ ret(4 * kPointerSize);
// Load RegExp data.
__ bind(&success);
__ mov(eax, Operand(esp, kJSRegExpOffset));
__ mov(ecx, FieldOperand(eax, JSRegExp::kDataOffset));
__ mov(edx, FieldOperand(ecx, JSRegExp::kIrregexpCaptureCountOffset));
// Calculate number of capture registers (number_of_captures + 1) * 2.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
__ add(Operand(edx), Immediate(2)); // edx was a smi.
// edx: Number of capture registers
// Load last_match_info which is still known to be a fast case JSArray.
__ mov(eax, Operand(esp, kLastMatchInfoOffset));
__ mov(ebx, FieldOperand(eax, JSArray::kElementsOffset));
// ebx: last_match_info backing store (FixedArray)
// edx: number of capture registers
// Store the capture count.
__ SmiTag(edx); // Number of capture registers to smi.
__ mov(FieldOperand(ebx, RegExpImpl::kLastCaptureCountOffset), edx);
__ SmiUntag(edx); // Number of capture registers back from smi.
// Store last subject and last input.
__ mov(eax, Operand(esp, kSubjectOffset));
__ mov(FieldOperand(ebx, RegExpImpl::kLastSubjectOffset), eax);
__ mov(ecx, ebx);
__ RecordWrite(ecx, RegExpImpl::kLastSubjectOffset, eax, edi);
__ mov(eax, Operand(esp, kSubjectOffset));
__ mov(FieldOperand(ebx, RegExpImpl::kLastInputOffset), eax);
__ mov(ecx, ebx);
__ RecordWrite(ecx, RegExpImpl::kLastInputOffset, eax, edi);
// Get the static offsets vector filled by the native regexp code.
ExternalReference address_of_static_offsets_vector =
ExternalReference::address_of_static_offsets_vector();
__ mov(ecx, Immediate(address_of_static_offsets_vector));
// ebx: last_match_info backing store (FixedArray)
// ecx: offsets vector
// edx: number of capture registers
Label next_capture, done;
// Capture register counter starts from number of capture registers and
// counts down until wraping after zero.
__ bind(&next_capture);
__ sub(Operand(edx), Immediate(1));
__ j(negative, &done);
// Read the value from the static offsets vector buffer.
__ mov(edi, Operand(ecx, edx, times_int_size, 0));
__ SmiTag(edi);
// Store the smi value in the last match info.
__ mov(FieldOperand(ebx,
edx,
times_pointer_size,
RegExpImpl::kFirstCaptureOffset),
edi);
__ jmp(&next_capture);
__ bind(&done);
// Return last match info.
__ mov(eax, Operand(esp, kLastMatchInfoOffset));
__ ret(4 * kPointerSize);
// Do the runtime call to execute the regexp.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
#endif // V8_INTERPRETED_REGEXP
}
void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm,
Register object,
Register result,
Register scratch1,
Register scratch2,
bool object_is_smi,
Label* not_found) {
// Use of registers. Register result is used as a temporary.
Register number_string_cache = result;
Register mask = scratch1;
Register scratch = scratch2;
// Load the number string cache.
ExternalReference roots_address = ExternalReference::roots_address();
__ mov(scratch, Immediate(Heap::kNumberStringCacheRootIndex));
__ mov(number_string_cache,
Operand::StaticArray(scratch, times_pointer_size, roots_address));
// Make the hash mask from the length of the number string cache. It
// contains two elements (number and string) for each cache entry.
__ mov(mask, FieldOperand(number_string_cache, FixedArray::kLengthOffset));
__ shr(mask, kSmiTagSize + 1); // Untag length and divide it by two.
__ sub(Operand(mask), Immediate(1)); // Make mask.
// Calculate the entry in the number string cache. The hash value in the
// number string cache for smis is just the smi value, and the hash for
// doubles is the xor of the upper and lower words. See
// Heap::GetNumberStringCache.
Label smi_hash_calculated;
Label load_result_from_cache;
if (object_is_smi) {
__ mov(scratch, object);
__ SmiUntag(scratch);
} else {
Label not_smi, hash_calculated;
ASSERT(kSmiTag == 0);
__ test(object, Immediate(kSmiTagMask));
__ j(not_zero, ¬_smi);
__ mov(scratch, object);
__ SmiUntag(scratch);
__ jmp(&smi_hash_calculated);
__ bind(¬_smi);
__ cmp(FieldOperand(object, HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, not_found);
ASSERT_EQ(8, kDoubleSize);
__ mov(scratch, FieldOperand(object, HeapNumber::kValueOffset));
__ xor_(scratch, FieldOperand(object, HeapNumber::kValueOffset + 4));
// Object is heap number and hash is now in scratch. Calculate cache index.
__ and_(scratch, Operand(mask));
Register index = scratch;
Register probe = mask;
__ mov(probe,
FieldOperand(number_string_cache,
index,
times_twice_pointer_size,
FixedArray::kHeaderSize));
__ test(probe, Immediate(kSmiTagMask));
__ j(zero, not_found);
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ movdbl(xmm0, FieldOperand(object, HeapNumber::kValueOffset));
__ movdbl(xmm1, FieldOperand(probe, HeapNumber::kValueOffset));
__ comisd(xmm0, xmm1);
} else {
__ fld_d(FieldOperand(object, HeapNumber::kValueOffset));
__ fld_d(FieldOperand(probe, HeapNumber::kValueOffset));
__ FCmp();
}
__ j(parity_even, not_found); // Bail out if NaN is involved.
__ j(not_equal, not_found); // The cache did not contain this value.
__ jmp(&load_result_from_cache);
}
__ bind(&smi_hash_calculated);
// Object is smi and hash is now in scratch. Calculate cache index.
__ and_(scratch, Operand(mask));
Register index = scratch;
// Check if the entry is the smi we are looking for.
__ cmp(object,
FieldOperand(number_string_cache,
index,
times_twice_pointer_size,
FixedArray::kHeaderSize));
__ j(not_equal, not_found);
// Get the result from the cache.
__ bind(&load_result_from_cache);
__ mov(result,
FieldOperand(number_string_cache,
index,
times_twice_pointer_size,
FixedArray::kHeaderSize + kPointerSize));
__ IncrementCounter(&Counters::number_to_string_native, 1);
}
void NumberToStringStub::Generate(MacroAssembler* masm) {
Label runtime;
__ mov(ebx, Operand(esp, kPointerSize));
// Generate code to lookup number in the number string cache.
GenerateLookupNumberStringCache(masm, ebx, eax, ecx, edx, false, &runtime);
__ ret(1 * kPointerSize);
__ bind(&runtime);
// Handle number to string in the runtime system if not found in the cache.
__ TailCallRuntime(Runtime::kNumberToStringSkipCache, 1, 1);
}
static int NegativeComparisonResult(Condition cc) {
ASSERT(cc != equal);
ASSERT((cc == less) || (cc == less_equal)
|| (cc == greater) || (cc == greater_equal));
return (cc == greater || cc == greater_equal) ? LESS : GREATER;
}
void CompareStub::Generate(MacroAssembler* masm) {
Label call_builtin, done;
// NOTICE! This code is only reached after a smi-fast-case check, so
// it is certain that at least one operand isn't a smi.
// Identical objects can be compared fast, but there are some tricky cases
// for NaN and undefined.
{
Label not_identical;
__ cmp(eax, Operand(edx));
__ j(not_equal, ¬_identical);
if (cc_ != equal) {
// Check for undefined. undefined OP undefined is false even though
// undefined == undefined.
Label check_for_nan;
__ cmp(edx, Factory::undefined_value());
__ j(not_equal, &check_for_nan);
__ Set(eax, Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
__ ret(0);
__ bind(&check_for_nan);
}
// Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
// so we do the second best thing - test it ourselves.
// Note: if cc_ != equal, never_nan_nan_ is not used.
if (never_nan_nan_ && (cc_ == equal)) {
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(0);
} else {
Label return_equal;
Label heap_number;
// If it's not a heap number, then return equal.
__ cmp(FieldOperand(edx, HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
__ j(equal, &heap_number);
__ bind(&return_equal);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(0);
__ bind(&heap_number);
// It is a heap number, so return non-equal if it's NaN and equal if
// it's not NaN.
// The representation of NaN values has all exponent bits (52..62) set,
// and not all mantissa bits (0..51) clear.
// We only accept QNaNs, which have bit 51 set.
// Read top bits of double representation (second word of value).
// Value is a QNaN if value & kQuietNaNMask == kQuietNaNMask, i.e.,
// all bits in the mask are set. We only need to check the word
// that contains the exponent and high bit of the mantissa.
ASSERT_NE(0, (kQuietNaNHighBitsMask << 1) & 0x80000000u);
__ mov(edx, FieldOperand(edx, HeapNumber::kExponentOffset));
__ xor_(eax, Operand(eax));
// Shift value and mask so kQuietNaNHighBitsMask applies to topmost
// bits.
__ add(edx, Operand(edx));
__ cmp(edx, kQuietNaNHighBitsMask << 1);
if (cc_ == equal) {
ASSERT_NE(1, EQUAL);
__ setcc(above_equal, eax);
__ ret(0);
} else {
Label nan;
__ j(above_equal, &nan);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(0);
__ bind(&nan);
__ Set(eax, Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
__ ret(0);
}
}
__ bind(¬_identical);
}
if (cc_ == equal) { // Both strict and non-strict.
Label slow; // Fallthrough label.
// If we're doing a strict equality comparison, we don't have to do
// type conversion, so we generate code to do fast comparison for objects
// and oddballs. Non-smi numbers and strings still go through the usual
// slow-case code.
if (strict_) {
// If either is a Smi (we know that not both are), then they can only
// be equal if the other is a HeapNumber. If so, use the slow case.
{
Label not_smis;
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(0, Smi::FromInt(0));
__ mov(ecx, Immediate(kSmiTagMask));
__ and_(ecx, Operand(eax));
__ test(ecx, Operand(edx));
__ j(not_zero, ¬_smis);
// One operand is a smi.
// Check whether the non-smi is a heap number.
ASSERT_EQ(1, kSmiTagMask);
// ecx still holds eax & kSmiTag, which is either zero or one.
__ sub(Operand(ecx), Immediate(0x01));
__ mov(ebx, edx);
__ xor_(ebx, Operand(eax));
__ and_(ebx, Operand(ecx)); // ebx holds either 0 or eax ^ edx.
__ xor_(ebx, Operand(eax));
// if eax was smi, ebx is now edx, else eax.
// Check if the non-smi operand is a heap number.
__ cmp(FieldOperand(ebx, HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
// If heap number, handle it in the slow case.
__ j(equal, &slow);
// Return non-equal (ebx is not zero)
__ mov(eax, ebx);
__ ret(0);
__ bind(¬_smis);
}
// If either operand is a JSObject or an oddball value, then they are not
// equal since their pointers are different
// There is no test for undetectability in strict equality.
// Get the type of the first operand.
// If the first object is a JS object, we have done pointer comparison.
Label first_non_object;
ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
__ j(below, &first_non_object);
// Return non-zero (eax is not zero)
Label return_not_equal;
ASSERT(kHeapObjectTag != 0);
__ bind(&return_not_equal);
__ ret(0);
__ bind(&first_non_object);
// Check for oddballs: true, false, null, undefined.
__ CmpInstanceType(ecx, ODDBALL_TYPE);
__ j(equal, &return_not_equal);
__ CmpObjectType(edx, FIRST_JS_OBJECT_TYPE, ecx);
__ j(above_equal, &return_not_equal);
// Check for oddballs: true, false, null, undefined.
__ CmpInstanceType(ecx, ODDBALL_TYPE);
__ j(equal, &return_not_equal);
// Fall through to the general case.
}
__ bind(&slow);
}
// Push arguments below the return address.
__ pop(ecx);
__ push(eax);
__ push(edx);
__ push(ecx);
// Generate the number comparison code.
if (include_number_compare_) {
Label non_number_comparison;
Label unordered;
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
CpuFeatures::Scope use_cmov(CMOV);
FloatingPointHelper::LoadSSE2Operands(masm, &non_number_comparison);
__ comisd(xmm0, xmm1);
// Don't base result on EFLAGS when a NaN is involved.
__ j(parity_even, &unordered, not_taken);
// Return a result of -1, 0, or 1, based on EFLAGS.
__ mov(eax, 0); // equal
__ mov(ecx, Immediate(Smi::FromInt(1)));
__ cmov(above, eax, Operand(ecx));
__ mov(ecx, Immediate(Smi::FromInt(-1)));
__ cmov(below, eax, Operand(ecx));
__ ret(2 * kPointerSize);
} else {
FloatingPointHelper::CheckFloatOperands(
masm, &non_number_comparison, ebx);
FloatingPointHelper::LoadFloatOperands(masm, ecx);
__ FCmp();
// Don't base result on EFLAGS when a NaN is involved.
__ j(parity_even, &unordered, not_taken);
Label below_label, above_label;
// Return a result of -1, 0, or 1, based on EFLAGS. In all cases remove
// two arguments from the stack as they have been pushed in preparation
// of a possible runtime call.
__ j(below, &below_label, not_taken);
__ j(above, &above_label, not_taken);
__ xor_(eax, Operand(eax));
__ ret(2 * kPointerSize);
__ bind(&below_label);
__ mov(eax, Immediate(Smi::FromInt(-1)));
__ ret(2 * kPointerSize);
__ bind(&above_label);
__ mov(eax, Immediate(Smi::FromInt(1)));
__ ret(2 * kPointerSize);
}
// If one of the numbers was NaN, then the result is always false.
// The cc is never not-equal.
__ bind(&unordered);
ASSERT(cc_ != not_equal);
if (cc_ == less || cc_ == less_equal) {
__ mov(eax, Immediate(Smi::FromInt(1)));
} else {
__ mov(eax, Immediate(Smi::FromInt(-1)));
}
__ ret(2 * kPointerSize); // eax, edx were pushed
// The number comparison code did not provide a valid result.
__ bind(&non_number_comparison);
}
// Fast negative check for symbol-to-symbol equality.
Label check_for_strings;
if (cc_ == equal) {
BranchIfNonSymbol(masm, &check_for_strings, eax, ecx);
BranchIfNonSymbol(masm, &check_for_strings, edx, ecx);
// We've already checked for object identity, so if both operands
// are symbols they aren't equal. Register eax already holds a
// non-zero value, which indicates not equal, so just return.
__ ret(2 * kPointerSize);
}
__ bind(&check_for_strings);
__ JumpIfNotBothSequentialAsciiStrings(edx, eax, ecx, ebx, &call_builtin);
// Inline comparison of ascii strings.
StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
edx,
eax,
ecx,
ebx,
edi);
#ifdef DEBUG
__ Abort("Unexpected fall-through from string comparison");
#endif
__ bind(&call_builtin);
// must swap argument order
__ pop(ecx);
__ pop(edx);
__ pop(eax);
__ push(edx);
__ push(eax);
// Figure out which native to call and setup the arguments.
Builtins::JavaScript builtin;
if (cc_ == equal) {
builtin = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
} else {
builtin = Builtins::COMPARE;
__ push(Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
}
// Restore return address on the stack.
__ push(ecx);
// Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ InvokeBuiltin(builtin, JUMP_FUNCTION);
}
void CompareStub::BranchIfNonSymbol(MacroAssembler* masm,
Label* label,
Register object,
Register scratch) {
__ test(object, Immediate(kSmiTagMask));
__ j(zero, label);
__ mov(scratch, FieldOperand(object, HeapObject::kMapOffset));
__ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
__ and_(scratch, kIsSymbolMask | kIsNotStringMask);
__ cmp(scratch, kSymbolTag | kStringTag);
__ j(not_equal, label);
}
void StackCheckStub::Generate(MacroAssembler* masm) {
// Because builtins always remove the receiver from the stack, we
// have to fake one to avoid underflowing the stack. The receiver
// must be inserted below the return address on the stack so we
// temporarily store that in a register.
__ pop(eax);
__ push(Immediate(Smi::FromInt(0)));
__ push(eax);
// Do tail-call to runtime routine.
__ TailCallRuntime(Runtime::kStackGuard, 1, 1);
}
void CallFunctionStub::Generate(MacroAssembler* masm) {
Label slow;
// If the receiver might be a value (string, number or boolean) check for this
// and box it if it is.
if (ReceiverMightBeValue()) {
// Get the receiver from the stack.
// +1 ~ return address
Label receiver_is_value, receiver_is_js_object;
__ mov(eax, Operand(esp, (argc_ + 1) * kPointerSize));
// Check if receiver is a smi (which is a number value).
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &receiver_is_value, not_taken);
// Check if the receiver is a valid JS object.
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, edi);
__ j(above_equal, &receiver_is_js_object);
// Call the runtime to box the value.
__ bind(&receiver_is_value);
__ EnterInternalFrame();
__ push(eax);
__ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
__ LeaveInternalFrame();
__ mov(Operand(esp, (argc_ + 1) * kPointerSize), eax);
__ bind(&receiver_is_js_object);
}
// Get the function to call from the stack.
// +2 ~ receiver, return address
__ mov(edi, Operand(esp, (argc_ + 2) * kPointerSize));
// Check that the function really is a JavaScript function.
__ test(edi, Immediate(kSmiTagMask));
__ j(zero, &slow, not_taken);
// Goto slow case if we do not have a function.
__ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
__ j(not_equal, &slow, not_taken);
// Fast-case: Just invoke the function.
ParameterCount actual(argc_);
__ InvokeFunction(edi, actual, JUMP_FUNCTION);
// Slow-case: Non-function called.
__ bind(&slow);
// CALL_NON_FUNCTION expects the non-function callee as receiver (instead
// of the original receiver from the call site).
__ mov(Operand(esp, (argc_ + 1) * kPointerSize), edi);
__ Set(eax, Immediate(argc_));
__ Set(ebx, Immediate(0));
__ GetBuiltinEntry(edx, Builtins::CALL_NON_FUNCTION);
Handle<Code> adaptor(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
__ jmp(adaptor, RelocInfo::CODE_TARGET);
}
void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
// eax holds the exception.
// Adjust this code if not the case.
ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
// Drop the sp to the top of the handler.
ExternalReference handler_address(Top::k_handler_address);
__ mov(esp, Operand::StaticVariable(handler_address));
// Restore next handler and frame pointer, discard handler state.
ASSERT(StackHandlerConstants::kNextOffset == 0);
__ pop(Operand::StaticVariable(handler_address));
ASSERT(StackHandlerConstants::kFPOffset == 1 * kPointerSize);
__ pop(ebp);
__ pop(edx); // Remove state.
// Before returning we restore the context from the frame pointer if
// not NULL. The frame pointer is NULL in the exception handler of
// a JS entry frame.
__ xor_(esi, Operand(esi)); // Tentatively set context pointer to NULL.
Label skip;
__ cmp(ebp, 0);
__ j(equal, &skip, not_taken);
__ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
__ bind(&skip);
ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
__ ret(0);
}
// If true, a Handle<T> passed by value is passed and returned by
// using the location_ field directly. If false, it is passed and
// returned as a pointer to a handle.
#ifdef USING_BSD_ABI
static const bool kPassHandlesDirectly = true;
#else
static const bool kPassHandlesDirectly = false;
#endif
void ApiGetterEntryStub::Generate(MacroAssembler* masm) {
Label get_result;
Label prologue;
Label promote_scheduled_exception;
__ EnterApiExitFrame(ExitFrame::MODE_NORMAL, kStackSpace, kArgc);
ASSERT_EQ(kArgc, 4);
if (kPassHandlesDirectly) {
// When handles as passed directly we don't have to allocate extra
// space for and pass an out parameter.
__ mov(Operand(esp, 0 * kPointerSize), ebx); // name.
__ mov(Operand(esp, 1 * kPointerSize), eax); // arguments pointer.
} else {
// The function expects three arguments to be passed but we allocate
// four to get space for the output cell. The argument slots are filled
// as follows:
//
// 3: output cell
// 2: arguments pointer
// 1: name
// 0: pointer to the output cell
//
// Note that this is one more "argument" than the function expects
// so the out cell will have to be popped explicitly after returning
// from the function.
__ mov(Operand(esp, 1 * kPointerSize), ebx); // name.
__ mov(Operand(esp, 2 * kPointerSize), eax); // arguments pointer.
__ mov(ebx, esp);
__ add(Operand(ebx), Immediate(3 * kPointerSize));
__ mov(Operand(esp, 0 * kPointerSize), ebx); // output
__ mov(Operand(esp, 3 * kPointerSize), Immediate(0)); // out cell.
}
// Call the api function!
__ call(fun()->address(), RelocInfo::RUNTIME_ENTRY);
// Check if the function scheduled an exception.
ExternalReference scheduled_exception_address =
ExternalReference::scheduled_exception_address();
__ cmp(Operand::StaticVariable(scheduled_exception_address),
Immediate(Factory::the_hole_value()));
__ j(not_equal, &promote_scheduled_exception, not_taken);
if (!kPassHandlesDirectly) {
// The returned value is a pointer to the handle holding the result.
// Dereference this to get to the location.
__ mov(eax, Operand(eax, 0));
}
// Check if the result handle holds 0
__ test(eax, Operand(eax));
__ j(not_zero, &get_result, taken);
// It was zero; the result is undefined.
__ mov(eax, Factory::undefined_value());
__ jmp(&prologue);
// It was non-zero. Dereference to get the result value.
__ bind(&get_result);
__ mov(eax, Operand(eax, 0));
__ bind(&prologue);
__ LeaveExitFrame(ExitFrame::MODE_NORMAL);
__ ret(0);
__ bind(&promote_scheduled_exception);
__ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
}
void CEntryStub::GenerateCore(MacroAssembler* masm,
Label* throw_normal_exception,
Label* throw_termination_exception,
Label* throw_out_of_memory_exception,
bool do_gc,
bool always_allocate_scope,
int /* alignment_skew */) {
// eax: result parameter for PerformGC, if any
// ebx: pointer to C function (C callee-saved)
// ebp: frame pointer (restored after C call)
// esp: stack pointer (restored after C call)
// edi: number of arguments including receiver (C callee-saved)
// esi: pointer to the first argument (C callee-saved)
// Result returned in eax, or eax+edx if result_size_ is 2.
// Check stack alignment.
if (FLAG_debug_code) {
__ CheckStackAlignment();
}
if (do_gc) {
// Pass failure code returned from last attempt as first argument to
// PerformGC. No need to use PrepareCallCFunction/CallCFunction here as the
// stack alignment is known to be correct. This function takes one argument
// which is passed on the stack, and we know that the stack has been
// prepared to pass at least one argument.
__ mov(Operand(esp, 0 * kPointerSize), eax); // Result.
__ call(FUNCTION_ADDR(Runtime::PerformGC), RelocInfo::RUNTIME_ENTRY);
}
ExternalReference scope_depth =
ExternalReference::heap_always_allocate_scope_depth();
if (always_allocate_scope) {
__ inc(Operand::StaticVariable(scope_depth));
}
// Call C function.
__ mov(Operand(esp, 0 * kPointerSize), edi); // argc.
__ mov(Operand(esp, 1 * kPointerSize), esi); // argv.
__ call(Operand(ebx));
// Result is in eax or edx:eax - do not destroy these registers!
if (always_allocate_scope) {
__ dec(Operand::StaticVariable(scope_depth));
}
// Make sure we're not trying to return 'the hole' from the runtime
// call as this may lead to crashes in the IC code later.
if (FLAG_debug_code) {
Label okay;
__ cmp(eax, Factory::the_hole_value());
__ j(not_equal, &okay);
__ int3();
__ bind(&okay);
}
// Check for failure result.
Label failure_returned;
ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
__ lea(ecx, Operand(eax, 1));
// Lower 2 bits of ecx are 0 iff eax has failure tag.
__ test(ecx, Immediate(kFailureTagMask));
__ j(zero, &failure_returned, not_taken);
// Exit the JavaScript to C++ exit frame.
__ LeaveExitFrame(mode_);
__ ret(0);
// Handling of failure.
__ bind(&failure_returned);
Label retry;
// If the returned exception is RETRY_AFTER_GC continue at retry label
ASSERT(Failure::RETRY_AFTER_GC == 0);
__ test(eax, Immediate(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
__ j(zero, &retry, taken);
// Special handling of out of memory exceptions.
__ cmp(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
__ j(equal, throw_out_of_memory_exception);
// Retrieve the pending exception and clear the variable.
ExternalReference pending_exception_address(Top::k_pending_exception_address);
__ mov(eax, Operand::StaticVariable(pending_exception_address));
__ mov(edx,
Operand::StaticVariable(ExternalReference::the_hole_value_location()));
__ mov(Operand::StaticVariable(pending_exception_address), edx);
// Special handling of termination exceptions which are uncatchable
// by javascript code.
__ cmp(eax, Factory::termination_exception());
__ j(equal, throw_termination_exception);
// Handle normal exception.
__ jmp(throw_normal_exception);
// Retry.
__ bind(&retry);
}
void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
UncatchableExceptionType type) {
// Adjust this code if not the case.
ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
// Drop sp to the top stack handler.
ExternalReference handler_address(Top::k_handler_address);
__ mov(esp, Operand::StaticVariable(handler_address));
// Unwind the handlers until the ENTRY handler is found.
Label loop, done;
__ bind(&loop);
// Load the type of the current stack handler.
const int kStateOffset = StackHandlerConstants::kStateOffset;
__ cmp(Operand(esp, kStateOffset), Immediate(StackHandler::ENTRY));
__ j(equal, &done);
// Fetch the next handler in the list.
const int kNextOffset = StackHandlerConstants::kNextOffset;
__ mov(esp, Operand(esp, kNextOffset));
__ jmp(&loop);
__ bind(&done);
// Set the top handler address to next handler past the current ENTRY handler.
ASSERT(StackHandlerConstants::kNextOffset == 0);
__ pop(Operand::StaticVariable(handler_address));
if (type == OUT_OF_MEMORY) {
// Set external caught exception to false.
ExternalReference external_caught(Top::k_external_caught_exception_address);
__ mov(eax, false);
__ mov(Operand::StaticVariable(external_caught), eax);
// Set pending exception and eax to out of memory exception.
ExternalReference pending_exception(Top::k_pending_exception_address);
__ mov(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
__ mov(Operand::StaticVariable(pending_exception), eax);
}
// Clear the context pointer.
__ xor_(esi, Operand(esi));
// Restore fp from handler and discard handler state.
ASSERT(StackHandlerConstants::kFPOffset == 1 * kPointerSize);
__ pop(ebp);
__ pop(edx); // State.
ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
__ ret(0);
}
void CEntryStub::Generate(MacroAssembler* masm) {
// eax: number of arguments including receiver
// ebx: pointer to C function (C callee-saved)
// ebp: frame pointer (restored after C call)
// esp: stack pointer (restored after C call)
// esi: current context (C callee-saved)
// edi: JS function of the caller (C callee-saved)
// NOTE: Invocations of builtins may return failure objects instead
// of a proper result. The builtin entry handles this by performing
// a garbage collection and retrying the builtin (twice).
// Enter the exit frame that transitions from JavaScript to C++.
__ EnterExitFrame(mode_);
// eax: result parameter for PerformGC, if any (setup below)
// ebx: pointer to builtin function (C callee-saved)
// ebp: frame pointer (restored after C call)
// esp: stack pointer (restored after C call)
// edi: number of arguments including receiver (C callee-saved)
// esi: argv pointer (C callee-saved)
Label throw_normal_exception;
Label throw_termination_exception;
Label throw_out_of_memory_exception;
// Call into the runtime system.
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
false,
false);
// Do space-specific GC and retry runtime call.
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
true,
false);
// Do full GC and retry runtime call one final time.
Failure* failure = Failure::InternalError();
__ mov(eax, Immediate(reinterpret_cast<int32_t>(failure)));
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
true,
true);
__ bind(&throw_out_of_memory_exception);
GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
__ bind(&throw_termination_exception);
GenerateThrowUncatchable(masm, TERMINATION);
__ bind(&throw_normal_exception);
GenerateThrowTOS(masm);
}
void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
Label invoke, exit;
#ifdef ENABLE_LOGGING_AND_PROFILING
Label not_outermost_js, not_outermost_js_2;
#endif
// Setup frame.
__ push(ebp);
__ mov(ebp, Operand(esp));
// Push marker in two places.
int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
__ push(Immediate(Smi::FromInt(marker))); // context slot
__ push(Immediate(Smi::FromInt(marker))); // function slot
// Save callee-saved registers (C calling conventions).
__ push(edi);
__ push(esi);
__ push(ebx);
// Save copies of the top frame descriptor on the stack.
ExternalReference c_entry_fp(Top::k_c_entry_fp_address);
__ push(Operand::StaticVariable(c_entry_fp));
#ifdef ENABLE_LOGGING_AND_PROFILING
// If this is the outermost JS call, set js_entry_sp value.
ExternalReference js_entry_sp(Top::k_js_entry_sp_address);
__ cmp(Operand::StaticVariable(js_entry_sp), Immediate(0));
__ j(not_equal, ¬_outermost_js);
__ mov(Operand::StaticVariable(js_entry_sp), ebp);
__ bind(¬_outermost_js);
#endif
// Call a faked try-block that does the invoke.
__ call(&invoke);
// Caught exception: Store result (exception) in the pending
// exception field in the JSEnv and return a failure sentinel.
ExternalReference pending_exception(Top::k_pending_exception_address);
__ mov(Operand::StaticVariable(pending_exception), eax);
__ mov(eax, reinterpret_cast<int32_t>(Failure::Exception()));
__ jmp(&exit);
// Invoke: Link this frame into the handler chain.
__ bind(&invoke);
__ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
// Clear any pending exceptions.
__ mov(edx,
Operand::StaticVariable(ExternalReference::the_hole_value_location()));
__ mov(Operand::StaticVariable(pending_exception), edx);
// Fake a receiver (NULL).
__ push(Immediate(0)); // receiver
// Invoke the function by calling through JS entry trampoline
// builtin and pop the faked function when we return. Notice that we
// cannot store a reference to the trampoline code directly in this
// stub, because the builtin stubs may not have been generated yet.
if (is_construct) {
ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
__ mov(edx, Immediate(construct_entry));
} else {
ExternalReference entry(Builtins::JSEntryTrampoline);
__ mov(edx, Immediate(entry));
}
__ mov(edx, Operand(edx, 0)); // deref address
__ lea(edx, FieldOperand(edx, Code::kHeaderSize));
__ call(Operand(edx));
// Unlink this frame from the handler chain.
__ pop(Operand::StaticVariable(ExternalReference(Top::k_handler_address)));
// Pop next_sp.
__ add(Operand(esp), Immediate(StackHandlerConstants::kSize - kPointerSize));
#ifdef ENABLE_LOGGING_AND_PROFILING
// If current EBP value is the same as js_entry_sp value, it means that
// the current function is the outermost.
__ cmp(ebp, Operand::StaticVariable(js_entry_sp));
__ j(not_equal, ¬_outermost_js_2);
__ mov(Operand::StaticVariable(js_entry_sp), Immediate(0));
__ bind(¬_outermost_js_2);
#endif
// Restore the top frame descriptor from the stack.
__ bind(&exit);
__ pop(Operand::StaticVariable(ExternalReference(Top::k_c_entry_fp_address)));
// Restore callee-saved registers (C calling conventions).
__ pop(ebx);
__ pop(esi);
__ pop(edi);
__ add(Operand(esp), Immediate(2 * kPointerSize)); // remove markers
// Restore frame pointer and return.
__ pop(ebp);
__ ret(0);
}
void InstanceofStub::Generate(MacroAssembler* masm) {
// Get the object - go slow case if it's a smi.
Label slow;
__ mov(eax, Operand(esp, 2 * kPointerSize)); // 2 ~ return address, function
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &slow, not_taken);
// Check that the left hand is a JS object.
__ IsObjectJSObjectType(eax, eax, edx, &slow);
// Get the prototype of the function.
__ mov(edx, Operand(esp, 1 * kPointerSize)); // 1 ~ return address
// edx is function, eax is map.
// Look up the function and the map in the instanceof cache.
Label miss;
ExternalReference roots_address = ExternalReference::roots_address();
__ mov(ecx, Immediate(Heap::kInstanceofCacheFunctionRootIndex));
__ cmp(edx, Operand::StaticArray(ecx, times_pointer_size, roots_address));
__ j(not_equal, &miss);
__ mov(ecx, Immediate(Heap::kInstanceofCacheMapRootIndex));
__ cmp(eax, Operand::StaticArray(ecx, times_pointer_size, roots_address));
__ j(not_equal, &miss);
__ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
__ mov(eax, Operand::StaticArray(ecx, times_pointer_size, roots_address));
__ ret(2 * kPointerSize);
__ bind(&miss);
__ TryGetFunctionPrototype(edx, ebx, ecx, &slow);
// Check that the function prototype is a JS object.
__ test(ebx, Immediate(kSmiTagMask));
__ j(zero, &slow, not_taken);
__ IsObjectJSObjectType(ebx, ecx, ecx, &slow);
// Register mapping:
// eax is object map.
// edx is function.
// ebx is function prototype.
__ mov(ecx, Immediate(Heap::kInstanceofCacheMapRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
__ mov(ecx, Immediate(Heap::kInstanceofCacheFunctionRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), edx);
__ mov(ecx, FieldOperand(eax, Map::kPrototypeOffset));
// Loop through the prototype chain looking for the function prototype.
Label loop, is_instance, is_not_instance;
__ bind(&loop);
__ cmp(ecx, Operand(ebx));
__ j(equal, &is_instance);
__ cmp(Operand(ecx), Immediate(Factory::null_value()));
__ j(equal, &is_not_instance);
__ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
__ mov(ecx, FieldOperand(ecx, Map::kPrototypeOffset));
__ jmp(&loop);
__ bind(&is_instance);
__ Set(eax, Immediate(0));
__ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
__ ret(2 * kPointerSize);
__ bind(&is_not_instance);
__ Set(eax, Immediate(Smi::FromInt(1)));
__ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
__ ret(2 * kPointerSize);
// Slow-case: Go through the JavaScript implementation.
__ bind(&slow);
__ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
}
int CompareStub::MinorKey() {
// Encode the three parameters in a unique 16 bit value. To avoid duplicate
// stubs the never NaN NaN condition is only taken into account if the
// condition is equals.
ASSERT(static_cast<unsigned>(cc_) < (1 << 13));
return ConditionField::encode(static_cast<unsigned>(cc_))
| StrictField::encode(strict_)
| NeverNanNanField::encode(cc_ == equal ? never_nan_nan_ : false)
| IncludeNumberCompareField::encode(include_number_compare_);
}
// Unfortunately you have to run without snapshots to see most of these
// names in the profile since most compare stubs end up in the snapshot.
const char* CompareStub::GetName() {
if (name_ != NULL) return name_;
const int kMaxNameLength = 100;
name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
if (name_ == NULL) return "OOM";
const char* cc_name;
switch (cc_) {
case less: cc_name = "LT"; break;
case greater: cc_name = "GT"; break;
case less_equal: cc_name = "LE"; break;
case greater_equal: cc_name = "GE"; break;
case equal: cc_name = "EQ"; break;
case not_equal: cc_name = "NE"; break;
default: cc_name = "UnknownCondition"; break;
}
const char* strict_name = "";
if (strict_ && (cc_ == equal || cc_ == not_equal)) {
strict_name = "_STRICT";
}
const char* never_nan_nan_name = "";
if (never_nan_nan_ && (cc_ == equal || cc_ == not_equal)) {
never_nan_nan_name = "_NO_NAN";
}
const char* include_number_compare_name = "";
if (!include_number_compare_) {
include_number_compare_name = "_NO_NUMBER";
}
OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
"CompareStub_%s%s%s%s",
cc_name,
strict_name,
never_nan_nan_name,
include_number_compare_name);
return name_;
}
// -------------------------------------------------------------------------
// StringCharCodeAtGenerator
void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
Label flat_string;
Label ascii_string;
Label got_char_code;
// If the receiver is a smi trigger the non-string case.
ASSERT(kSmiTag == 0);
__ test(object_, Immediate(kSmiTagMask));
__ j(zero, receiver_not_string_);
// Fetch the instance type of the receiver into result register.
__ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
__ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
// If the receiver is not a string trigger the non-string case.
__ test(result_, Immediate(kIsNotStringMask));
__ j(not_zero, receiver_not_string_);
// If the index is non-smi trigger the non-smi case.
ASSERT(kSmiTag == 0);
__ test(index_, Immediate(kSmiTagMask));
__ j(not_zero, &index_not_smi_);
// Put smi-tagged index into scratch register.
__ mov(scratch_, index_);
__ bind(&got_smi_index_);
// Check for index out of range.
__ cmp(scratch_, FieldOperand(object_, String::kLengthOffset));
__ j(above_equal, index_out_of_range_);
// We need special handling for non-flat strings.
ASSERT(kSeqStringTag == 0);
__ test(result_, Immediate(kStringRepresentationMask));
__ j(zero, &flat_string);
// Handle non-flat strings.
__ test(result_, Immediate(kIsConsStringMask));
__ j(zero, &call_runtime_);
// ConsString.
// Check whether the right hand side is the empty string (i.e. if
// this is really a flat string in a cons string). If that is not
// the case we would rather go to the runtime system now to flatten
// the string.
__ cmp(FieldOperand(object_, ConsString::kSecondOffset),
Immediate(Factory::empty_string()));
__ j(not_equal, &call_runtime_);
// Get the first of the two strings and load its instance type.
__ mov(object_, FieldOperand(object_, ConsString::kFirstOffset));
__ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
__ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
// If the first cons component is also non-flat, then go to runtime.
ASSERT(kSeqStringTag == 0);
__ test(result_, Immediate(kStringRepresentationMask));
__ j(not_zero, &call_runtime_);
// Check for 1-byte or 2-byte string.
__ bind(&flat_string);
ASSERT(kAsciiStringTag != 0);
__ test(result_, Immediate(kStringEncodingMask));
__ j(not_zero, &ascii_string);
// 2-byte string.
// Load the 2-byte character code into the result register.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ movzx_w(result_, FieldOperand(object_,
scratch_, times_1, // Scratch is smi-tagged.
SeqTwoByteString::kHeaderSize));
__ jmp(&got_char_code);
// ASCII string.
// Load the byte into the result register.
__ bind(&ascii_string);
__ SmiUntag(scratch_);
__ movzx_b(result_, FieldOperand(object_,
scratch_, times_1,
SeqAsciiString::kHeaderSize));
__ bind(&got_char_code);
__ SmiTag(result_);
__ bind(&exit_);
}
void StringCharCodeAtGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
__ Abort("Unexpected fallthrough to CharCodeAt slow case");
// Index is not a smi.
__ bind(&index_not_smi_);
// If index is a heap number, try converting it to an integer.
__ CheckMap(index_, Factory::heap_number_map(), index_not_number_, true);
call_helper.BeforeCall(masm);
__ push(object_);
__ push(index_);
__ push(index_); // Consumed by runtime conversion function.
if (index_flags_ == STRING_INDEX_IS_NUMBER) {
__ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
} else {
ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
// NumberToSmi discards numbers that are not exact integers.
__ CallRuntime(Runtime::kNumberToSmi, 1);
}
if (!scratch_.is(eax)) {
// Save the conversion result before the pop instructions below
// have a chance to overwrite it.
__ mov(scratch_, eax);
}
__ pop(index_);
__ pop(object_);
// Reload the instance type.
__ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
__ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
call_helper.AfterCall(masm);
// If index is still not a smi, it must be out of range.
ASSERT(kSmiTag == 0);
__ test(scratch_, Immediate(kSmiTagMask));
__ j(not_zero, index_out_of_range_);
// Otherwise, return to the fast path.
__ jmp(&got_smi_index_);
// Call runtime. We get here when the receiver is a string and the
// index is a number, but the code of getting the actual character
// is too complex (e.g., when the string needs to be flattened).
__ bind(&call_runtime_);
call_helper.BeforeCall(masm);
__ push(object_);
__ push(index_);
__ CallRuntime(Runtime::kStringCharCodeAt, 2);
if (!result_.is(eax)) {
__ mov(result_, eax);
}
call_helper.AfterCall(masm);
__ jmp(&exit_);
__ Abort("Unexpected fallthrough from CharCodeAt slow case");
}
// -------------------------------------------------------------------------
// StringCharFromCodeGenerator
void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
// Fast case of Heap::LookupSingleCharacterStringFromCode.
ASSERT(kSmiTag == 0);
ASSERT(kSmiShiftSize == 0);
ASSERT(IsPowerOf2(String::kMaxAsciiCharCode + 1));
__ test(code_,
Immediate(kSmiTagMask |
((~String::kMaxAsciiCharCode) << kSmiTagSize)));
__ j(not_zero, &slow_case_, not_taken);
__ Set(result_, Immediate(Factory::single_character_string_cache()));
ASSERT(kSmiTag == 0);
ASSERT(kSmiTagSize == 1);
ASSERT(kSmiShiftSize == 0);
// At this point code register contains smi tagged ascii char code.
__ mov(result_, FieldOperand(result_,
code_, times_half_pointer_size,
FixedArray::kHeaderSize));
__ cmp(result_, Factory::undefined_value());
__ j(equal, &slow_case_, not_taken);
__ bind(&exit_);
}
void StringCharFromCodeGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
__ Abort("Unexpected fallthrough to CharFromCode slow case");
__ bind(&slow_case_);
call_helper.BeforeCall(masm);
__ push(code_);
__ CallRuntime(Runtime::kCharFromCode, 1);
if (!result_.is(eax)) {
__ mov(result_, eax);
}
call_helper.AfterCall(masm);
__ jmp(&exit_);
__ Abort("Unexpected fallthrough from CharFromCode slow case");
}
// -------------------------------------------------------------------------
// StringCharAtGenerator
void StringCharAtGenerator::GenerateFast(MacroAssembler* masm) {
char_code_at_generator_.GenerateFast(masm);
char_from_code_generator_.GenerateFast(masm);
}
void StringCharAtGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
char_code_at_generator_.GenerateSlow(masm, call_helper);
char_from_code_generator_.GenerateSlow(masm, call_helper);
}
void StringAddStub::Generate(MacroAssembler* masm) {
Label string_add_runtime;
// Load the two arguments.
__ mov(eax, Operand(esp, 2 * kPointerSize)); // First argument.
__ mov(edx, Operand(esp, 1 * kPointerSize)); // Second argument.
// Make sure that both arguments are strings if not known in advance.
if (string_check_) {
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &string_add_runtime);
__ CmpObjectType(eax, FIRST_NONSTRING_TYPE, ebx);
__ j(above_equal, &string_add_runtime);
// First argument is a a string, test second.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &string_add_runtime);
__ CmpObjectType(edx, FIRST_NONSTRING_TYPE, ebx);
__ j(above_equal, &string_add_runtime);
}
// Both arguments are strings.
// eax: first string
// edx: second string
// Check if either of the strings are empty. In that case return the other.
Label second_not_zero_length, both_not_zero_length;
__ mov(ecx, FieldOperand(edx, String::kLengthOffset));
ASSERT(kSmiTag == 0);
__ test(ecx, Operand(ecx));
__ j(not_zero, &second_not_zero_length);
// Second string is empty, result is first string which is already in eax.
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
__ bind(&second_not_zero_length);
__ mov(ebx, FieldOperand(eax, String::kLengthOffset));
ASSERT(kSmiTag == 0);
__ test(ebx, Operand(ebx));
__ j(not_zero, &both_not_zero_length);
// First string is empty, result is second string which is in edx.
__ mov(eax, edx);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
// Both strings are non-empty.
// eax: first string
// ebx: length of first string as a smi
// ecx: length of second string as a smi
// edx: second string
// Look at the length of the result of adding the two strings.
Label string_add_flat_result, longer_than_two;
__ bind(&both_not_zero_length);
__ add(ebx, Operand(ecx));
ASSERT(Smi::kMaxValue == String::kMaxLength);
// Handle exceptionally long strings in the runtime system.
__ j(overflow, &string_add_runtime);
// Use the runtime system when adding two one character strings, as it
// contains optimizations for this specific case using the symbol table.
__ cmp(Operand(ebx), Immediate(Smi::FromInt(2)));
__ j(not_equal, &longer_than_two);
// Check that both strings are non-external ascii strings.
__ JumpIfNotBothSequentialAsciiStrings(eax, edx, ebx, ecx,
&string_add_runtime);
// Get the two characters forming the sub string.
__ movzx_b(ebx, FieldOperand(eax, SeqAsciiString::kHeaderSize));
__ movzx_b(ecx, FieldOperand(edx, SeqAsciiString::kHeaderSize));
// Try to lookup two character string in symbol table. If it is not found
// just allocate a new one.
Label make_two_character_string, make_flat_ascii_string;
StringHelper::GenerateTwoCharacterSymbolTableProbe(
masm, ebx, ecx, eax, edx, edi, &make_two_character_string);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
__ bind(&make_two_character_string);
__ Set(ebx, Immediate(Smi::FromInt(2)));
__ jmp(&make_flat_ascii_string);
__ bind(&longer_than_two);
// Check if resulting string will be flat.
__ cmp(Operand(ebx), Immediate(Smi::FromInt(String::kMinNonFlatLength)));
__ j(below, &string_add_flat_result);
// If result is not supposed to be flat allocate a cons string object. If both
// strings are ascii the result is an ascii cons string.
Label non_ascii, allocated;
__ mov(edi, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(edi, Map::kInstanceTypeOffset));
__ mov(edi, FieldOperand(edx, HeapObject::kMapOffset));
__ movzx_b(edi, FieldOperand(edi, Map::kInstanceTypeOffset));
__ and_(ecx, Operand(edi));
ASSERT(kStringEncodingMask == kAsciiStringTag);
__ test(ecx, Immediate(kAsciiStringTag));
__ j(zero, &non_ascii);
// Allocate an acsii cons string.
__ AllocateAsciiConsString(ecx, edi, no_reg, &string_add_runtime);
__ bind(&allocated);
// Fill the fields of the cons string.
if (FLAG_debug_code) __ AbortIfNotSmi(ebx);
__ mov(FieldOperand(ecx, ConsString::kLengthOffset), ebx);
__ mov(FieldOperand(ecx, ConsString::kHashFieldOffset),
Immediate(String::kEmptyHashField));
__ mov(FieldOperand(ecx, ConsString::kFirstOffset), eax);
__ mov(FieldOperand(ecx, ConsString::kSecondOffset), edx);
__ mov(eax, ecx);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
__ bind(&non_ascii);
// Allocate a two byte cons string.
__ AllocateConsString(ecx, edi, no_reg, &string_add_runtime);
__ jmp(&allocated);
// Handle creating a flat result. First check that both strings are not
// external strings.
// eax: first string
// ebx: length of resulting flat string as a smi
// edx: second string
__ bind(&string_add_flat_result);
__ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
__ and_(ecx, kStringRepresentationMask);
__ cmp(ecx, kExternalStringTag);
__ j(equal, &string_add_runtime);
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
__ and_(ecx, kStringRepresentationMask);
__ cmp(ecx, kExternalStringTag);
__ j(equal, &string_add_runtime);
// Now check if both strings are ascii strings.
// eax: first string
// ebx: length of resulting flat string as a smi
// edx: second string
Label non_ascii_string_add_flat_result;
ASSERT(kStringEncodingMask == kAsciiStringTag);
__ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset));
__ test_b(FieldOperand(ecx, Map::kInstanceTypeOffset), kAsciiStringTag);
__ j(zero, &non_ascii_string_add_flat_result);
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ test_b(FieldOperand(ecx, Map::kInstanceTypeOffset), kAsciiStringTag);
__ j(zero, &string_add_runtime);
__ bind(&make_flat_ascii_string);
// Both strings are ascii strings. As they are short they are both flat.
// ebx: length of resulting flat string as a smi
__ SmiUntag(ebx);
__ AllocateAsciiString(eax, ebx, ecx, edx, edi, &string_add_runtime);
// eax: result string
__ mov(ecx, eax);
// Locate first character of result.
__ add(Operand(ecx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// Load first argument and locate first character.
__ mov(edx, Operand(esp, 2 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: first character of result
// edx: first char of first argument
// edi: length of first argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, true);
// Load second argument and locate first character.
__ mov(edx, Operand(esp, 1 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: next character of result
// edx: first char of second argument
// edi: length of second argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, true);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
// Handle creating a flat two byte result.
// eax: first string - known to be two byte
// ebx: length of resulting flat string as a smi
// edx: second string
__ bind(&non_ascii_string_add_flat_result);
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ test_b(FieldOperand(ecx, Map::kInstanceTypeOffset), kAsciiStringTag);
__ j(not_zero, &string_add_runtime);
// Both strings are two byte strings. As they are short they are both
// flat.
__ SmiUntag(ebx);
__ AllocateTwoByteString(eax, ebx, ecx, edx, edi, &string_add_runtime);
// eax: result string
__ mov(ecx, eax);
// Locate first character of result.
__ add(Operand(ecx),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// Load first argument and locate first character.
__ mov(edx, Operand(esp, 2 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: first character of result
// edx: first char of first argument
// edi: length of first argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, false);
// Load second argument and locate first character.
__ mov(edx, Operand(esp, 1 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: next character of result
// edx: first char of second argument
// edi: length of second argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, false);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
// Just jump to runtime to add the two strings.
__ bind(&string_add_runtime);
__ TailCallRuntime(Runtime::kStringAdd, 2, 1);
}
void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
Register dest,
Register src,
Register count,
Register scratch,
bool ascii) {
Label loop;
__ bind(&loop);
// This loop just copies one character at a time, as it is only used for very
// short strings.
if (ascii) {
__ mov_b(scratch, Operand(src, 0));
__ mov_b(Operand(dest, 0), scratch);
__ add(Operand(src), Immediate(1));
__ add(Operand(dest), Immediate(1));
} else {
__ mov_w(scratch, Operand(src, 0));
__ mov_w(Operand(dest, 0), scratch);
__ add(Operand(src), Immediate(2));
__ add(Operand(dest), Immediate(2));
}
__ sub(Operand(count), Immediate(1));
__ j(not_zero, &loop);
}
void StringHelper::GenerateCopyCharactersREP(MacroAssembler* masm,
Register dest,
Register src,
Register count,
Register scratch,
bool ascii) {
// Copy characters using rep movs of doublewords. Align destination on 4 byte
// boundary before starting rep movs. Copy remaining characters after running
// rep movs.
ASSERT(dest.is(edi)); // rep movs destination
ASSERT(src.is(esi)); // rep movs source
ASSERT(count.is(ecx)); // rep movs count
ASSERT(!scratch.is(dest));
ASSERT(!scratch.is(src));
ASSERT(!scratch.is(count));
// Nothing to do for zero characters.
Label done;
__ test(count, Operand(count));
__ j(zero, &done);
// Make count the number of bytes to copy.
if (!ascii) {
__ shl(count, 1);
}
// Don't enter the rep movs if there are less than 4 bytes to copy.
Label last_bytes;
__ test(count, Immediate(~3));
__ j(zero, &last_bytes);
// Copy from edi to esi using rep movs instruction.
__ mov(scratch, count);
__ sar(count, 2); // Number of doublewords to copy.
__ cld();
__ rep_movs();
// Find number of bytes left.
__ mov(count, scratch);
__ and_(count, 3);
// Check if there are more bytes to copy.
__ bind(&last_bytes);
__ test(count, Operand(count));
__ j(zero, &done);
// Copy remaining characters.
Label loop;
__ bind(&loop);
__ mov_b(scratch, Operand(src, 0));
__ mov_b(Operand(dest, 0), scratch);
__ add(Operand(src), Immediate(1));
__ add(Operand(dest), Immediate(1));
__ sub(Operand(count), Immediate(1));
__ j(not_zero, &loop);
__ bind(&done);
}
void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
Register c1,
Register c2,
Register scratch1,
Register scratch2,
Register scratch3,
Label* not_found) {
// Register scratch3 is the general scratch register in this function.
Register scratch = scratch3;
// Make sure that both characters are not digits as such strings has a
// different hash algorithm. Don't try to look for these in the symbol table.
Label not_array_index;
__ mov(scratch, c1);
__ sub(Operand(scratch), Immediate(static_cast<int>('0')));
__ cmp(Operand(scratch), Immediate(static_cast<int>('9' - '0')));
__ j(above, ¬_array_index);
__ mov(scratch, c2);
__ sub(Operand(scratch), Immediate(static_cast<int>('0')));
__ cmp(Operand(scratch), Immediate(static_cast<int>('9' - '0')));
__ j(below_equal, not_found);
__ bind(¬_array_index);
// Calculate the two character string hash.
Register hash = scratch1;
GenerateHashInit(masm, hash, c1, scratch);
GenerateHashAddCharacter(masm, hash, c2, scratch);
GenerateHashGetHash(masm, hash, scratch);
// Collect the two characters in a register.
Register chars = c1;
__ shl(c2, kBitsPerByte);
__ or_(chars, Operand(c2));
// chars: two character string, char 1 in byte 0 and char 2 in byte 1.
// hash: hash of two character string.
// Load the symbol table.
Register symbol_table = c2;
ExternalReference roots_address = ExternalReference::roots_address();
__ mov(scratch, Immediate(Heap::kSymbolTableRootIndex));
__ mov(symbol_table,
Operand::StaticArray(scratch, times_pointer_size, roots_address));
// Calculate capacity mask from the symbol table capacity.
Register mask = scratch2;
__ mov(mask, FieldOperand(symbol_table, SymbolTable::kCapacityOffset));
__ SmiUntag(mask);
__ sub(Operand(mask), Immediate(1));
// Registers
// chars: two character string, char 1 in byte 0 and char 2 in byte 1.
// hash: hash of two character string
// symbol_table: symbol table
// mask: capacity mask
// scratch: -
// Perform a number of probes in the symbol table.
static const int kProbes = 4;
Label found_in_symbol_table;
Label next_probe[kProbes], next_probe_pop_mask[kProbes];
for (int i = 0; i < kProbes; i++) {
// Calculate entry in symbol table.
__ mov(scratch, hash);
if (i > 0) {
__ add(Operand(scratch), Immediate(SymbolTable::GetProbeOffset(i)));
}
__ and_(scratch, Operand(mask));
// Load the entry from the symble table.
Register candidate = scratch; // Scratch register contains candidate.
ASSERT_EQ(1, SymbolTable::kEntrySize);
__ mov(candidate,
FieldOperand(symbol_table,
scratch,
times_pointer_size,
SymbolTable::kElementsStartOffset));
// If entry is undefined no string with this hash can be found.
__ cmp(candidate, Factory::undefined_value());
__ j(equal, not_found);
// If length is not 2 the string is not a candidate.
__ cmp(FieldOperand(candidate, String::kLengthOffset),
Immediate(Smi::FromInt(2)));
__ j(not_equal, &next_probe[i]);
// As we are out of registers save the mask on the stack and use that
// register as a temporary.
__ push(mask);
Register temp = mask;
// Check that the candidate is a non-external ascii string.
__ mov(temp, FieldOperand(candidate, HeapObject::kMapOffset));
__ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
__ JumpIfInstanceTypeIsNotSequentialAscii(
temp, temp, &next_probe_pop_mask[i]);
// Check if the two characters match.
__ mov(temp, FieldOperand(candidate, SeqAsciiString::kHeaderSize));
__ and_(temp, 0x0000ffff);
__ cmp(chars, Operand(temp));
__ j(equal, &found_in_symbol_table);
__ bind(&next_probe_pop_mask[i]);
__ pop(mask);
__ bind(&next_probe[i]);
}
// No matching 2 character string found by probing.
__ jmp(not_found);
// Scratch register contains result when we fall through to here.
Register result = scratch;
__ bind(&found_in_symbol_table);
__ pop(mask); // Pop temporally saved mask from the stack.
if (!result.is(eax)) {
__ mov(eax, result);
}
}
void StringHelper::GenerateHashInit(MacroAssembler* masm,
Register hash,
Register character,
Register scratch) {
// hash = character + (character << 10);
__ mov(hash, character);
__ shl(hash, 10);
__ add(hash, Operand(character));
// hash ^= hash >> 6;
__ mov(scratch, hash);
__ sar(scratch, 6);
__ xor_(hash, Operand(scratch));
}
void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
Register hash,
Register character,
Register scratch) {
// hash += character;
__ add(hash, Operand(character));
// hash += hash << 10;
__ mov(scratch, hash);
__ shl(scratch, 10);
__ add(hash, Operand(scratch));
// hash ^= hash >> 6;
__ mov(scratch, hash);
__ sar(scratch, 6);
__ xor_(hash, Operand(scratch));
}
void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
Register hash,
Register scratch) {
// hash += hash << 3;
__ mov(scratch, hash);
__ shl(scratch, 3);
__ add(hash, Operand(scratch));
// hash ^= hash >> 11;
__ mov(scratch, hash);
__ sar(scratch, 11);
__ xor_(hash, Operand(scratch));
// hash += hash << 15;
__ mov(scratch, hash);
__ shl(scratch, 15);
__ add(hash, Operand(scratch));
// if (hash == 0) hash = 27;
Label hash_not_zero;
__ test(hash, Operand(hash));
__ j(not_zero, &hash_not_zero);
__ mov(hash, Immediate(27));
__ bind(&hash_not_zero);
}
void SubStringStub::Generate(MacroAssembler* masm) {
Label runtime;
// Stack frame on entry.
// esp[0]: return address
// esp[4]: to
// esp[8]: from
// esp[12]: string
// Make sure first argument is a string.
__ mov(eax, Operand(esp, 3 * kPointerSize));
ASSERT_EQ(0, kSmiTag);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
__ j(NegateCondition(is_string), &runtime);
// eax: string
// ebx: instance type
// Calculate length of sub string using the smi values.
Label result_longer_than_two;
__ mov(ecx, Operand(esp, 1 * kPointerSize)); // To index.
__ test(ecx, Immediate(kSmiTagMask));
__ j(not_zero, &runtime);
__ mov(edx, Operand(esp, 2 * kPointerSize)); // From index.
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &runtime);
__ sub(ecx, Operand(edx));
// Special handling of sub-strings of length 1 and 2. One character strings
// are handled in the runtime system (looked up in the single character
// cache). Two character strings are looked for in the symbol cache.
__ SmiUntag(ecx); // Result length is no longer smi.
__ cmp(ecx, 2);
__ j(greater, &result_longer_than_two);
__ j(less, &runtime);
// Sub string of length 2 requested.
// eax: string
// ebx: instance type
// ecx: sub string length (value is 2)
// edx: from index (smi)
__ JumpIfInstanceTypeIsNotSequentialAscii(ebx, ebx, &runtime);
// Get the two characters forming the sub string.
__ SmiUntag(edx); // From index is no longer smi.
__ movzx_b(ebx, FieldOperand(eax, edx, times_1, SeqAsciiString::kHeaderSize));
__ movzx_b(ecx,
FieldOperand(eax, edx, times_1, SeqAsciiString::kHeaderSize + 1));
// Try to lookup two character string in symbol table.
Label make_two_character_string;
StringHelper::GenerateTwoCharacterSymbolTableProbe(
masm, ebx, ecx, eax, edx, edi, &make_two_character_string);
__ ret(3 * kPointerSize);
__ bind(&make_two_character_string);
// Setup registers for allocating the two character string.
__ mov(eax, Operand(esp, 3 * kPointerSize));
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
__ Set(ecx, Immediate(2));
__ bind(&result_longer_than_two);
// eax: string
// ebx: instance type
// ecx: result string length
// Check for flat ascii string
Label non_ascii_flat;
__ JumpIfInstanceTypeIsNotSequentialAscii(ebx, ebx, &non_ascii_flat);
// Allocate the result.
__ AllocateAsciiString(eax, ecx, ebx, edx, edi, &runtime);
// eax: result string
// ecx: result string length
__ mov(edx, esi); // esi used by following code.
// Locate first character of result.
__ mov(edi, eax);
__ add(Operand(edi), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// Load string argument and locate character of sub string start.
__ mov(esi, Operand(esp, 3 * kPointerSize));
__ add(Operand(esi), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
__ mov(ebx, Operand(esp, 2 * kPointerSize)); // from
__ SmiUntag(ebx);
__ add(esi, Operand(ebx));
// eax: result string
// ecx: result length
// edx: original value of esi
// edi: first character of result
// esi: character of sub string start
StringHelper::GenerateCopyCharactersREP(masm, edi, esi, ecx, ebx, true);
__ mov(esi, edx); // Restore esi.
__ IncrementCounter(&Counters::sub_string_native, 1);
__ ret(3 * kPointerSize);
__ bind(&non_ascii_flat);
// eax: string
// ebx: instance type & kStringRepresentationMask | kStringEncodingMask
// ecx: result string length
// Check for flat two byte string
__ cmp(ebx, kSeqStringTag | kTwoByteStringTag);
__ j(not_equal, &runtime);
// Allocate the result.
__ AllocateTwoByteString(eax, ecx, ebx, edx, edi, &runtime);
// eax: result string
// ecx: result string length
__ mov(edx, esi); // esi used by following code.
// Locate first character of result.
__ mov(edi, eax);
__ add(Operand(edi),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// Load string argument and locate character of sub string start.
__ mov(esi, Operand(esp, 3 * kPointerSize));
__ add(Operand(esi),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
__ mov(ebx, Operand(esp, 2 * kPointerSize)); // from
// As from is a smi it is 2 times the value which matches the size of a two
// byte character.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
__ add(esi, Operand(ebx));
// eax: result string
// ecx: result length
// edx: original value of esi
// edi: first character of result
// esi: character of sub string start
StringHelper::GenerateCopyCharactersREP(masm, edi, esi, ecx, ebx, false);
__ mov(esi, edx); // Restore esi.
__ IncrementCounter(&Counters::sub_string_native, 1);
__ ret(3 * kPointerSize);
// Just jump to runtime to create the sub string.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kSubString, 3, 1);
}
void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
Register left,
Register right,
Register scratch1,
Register scratch2,
Register scratch3) {
Label result_not_equal;
Label result_greater;
Label compare_lengths;
__ IncrementCounter(&Counters::string_compare_native, 1);
// Find minimum length.
Label left_shorter;
__ mov(scratch1, FieldOperand(left, String::kLengthOffset));
__ mov(scratch3, scratch1);
__ sub(scratch3, FieldOperand(right, String::kLengthOffset));
Register length_delta = scratch3;
__ j(less_equal, &left_shorter);
// Right string is shorter. Change scratch1 to be length of right string.
__ sub(scratch1, Operand(length_delta));
__ bind(&left_shorter);
Register min_length = scratch1;
// If either length is zero, just compare lengths.
__ test(min_length, Operand(min_length));
__ j(zero, &compare_lengths);
// Change index to run from -min_length to -1 by adding min_length
// to string start. This means that loop ends when index reaches zero,
// which doesn't need an additional compare.
__ SmiUntag(min_length);
__ lea(left,
FieldOperand(left,
min_length, times_1,
SeqAsciiString::kHeaderSize));
__ lea(right,
FieldOperand(right,
min_length, times_1,
SeqAsciiString::kHeaderSize));
__ neg(min_length);
Register index = min_length; // index = -min_length;
{
// Compare loop.
Label loop;
__ bind(&loop);
// Compare characters.
__ mov_b(scratch2, Operand(left, index, times_1, 0));
__ cmpb(scratch2, Operand(right, index, times_1, 0));
__ j(not_equal, &result_not_equal);
__ add(Operand(index), Immediate(1));
__ j(not_zero, &loop);
}
// Compare lengths - strings up to min-length are equal.
__ bind(&compare_lengths);
__ test(length_delta, Operand(length_delta));
__ j(not_zero, &result_not_equal);
// Result is EQUAL.
ASSERT_EQ(0, EQUAL);
ASSERT_EQ(0, kSmiTag);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(2 * kPointerSize);
__ bind(&result_not_equal);
__ j(greater, &result_greater);
// Result is LESS.
__ Set(eax, Immediate(Smi::FromInt(LESS)));
__ ret(2 * kPointerSize);
// Result is GREATER.
__ bind(&result_greater);
__ Set(eax, Immediate(Smi::FromInt(GREATER)));
__ ret(2 * kPointerSize);
}
void StringCompareStub::Generate(MacroAssembler* masm) {
Label runtime;
// Stack frame on entry.
// esp[0]: return address
// esp[4]: right string
// esp[8]: left string
__ mov(edx, Operand(esp, 2 * kPointerSize)); // left
__ mov(eax, Operand(esp, 1 * kPointerSize)); // right
Label not_same;
__ cmp(edx, Operand(eax));
__ j(not_equal, ¬_same);
ASSERT_EQ(0, EQUAL);
ASSERT_EQ(0, kSmiTag);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ IncrementCounter(&Counters::string_compare_native, 1);
__ ret(2 * kPointerSize);
__ bind(¬_same);
// Check that both objects are sequential ascii strings.
__ JumpIfNotBothSequentialAsciiStrings(edx, eax, ecx, ebx, &runtime);
// Compare flat ascii strings.
GenerateCompareFlatAsciiStrings(masm, edx, eax, ecx, ebx, edi);
// Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kStringCompare, 2, 1);
}
#undef __
#define __ masm.
MemCopyFunction CreateMemCopyFunction() {
size_t actual_size;
byte* buffer = static_cast<byte*>(OS::Allocate(Assembler::kMinimalBufferSize,
&actual_size,
true));
CHECK(buffer);
HandleScope handles;
MacroAssembler masm(buffer, static_cast<int>(actual_size));
// Generated code is put into a fixed, unmovable, buffer, and not into
// the V8 heap. We can't, and don't, refer to any relocatable addresses
// (e.g. the JavaScript nan-object).
// 32-bit C declaration function calls pass arguments on stack.
// Stack layout:
// esp[12]: Third argument, size.
// esp[8]: Second argument, source pointer.
// esp[4]: First argument, destination pointer.
// esp[0]: return address
const int kDestinationOffset = 1 * kPointerSize;
const int kSourceOffset = 2 * kPointerSize;
const int kSizeOffset = 3 * kPointerSize;
int stack_offset = 0; // Update if we change the stack height.
if (FLAG_debug_code) {
__ cmp(Operand(esp, kSizeOffset + stack_offset),
Immediate(kMinComplexMemCopy));
Label ok;
__ j(greater_equal, &ok);
__ int3();
__ bind(&ok);
}
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope enable(SSE2);
__ push(edi);
__ push(esi);
stack_offset += 2 * kPointerSize;
Register dst = edi;
Register src = esi;
Register count = ecx;
__ mov(dst, Operand(esp, stack_offset + kDestinationOffset));
__ mov(src, Operand(esp, stack_offset + kSourceOffset));
__ mov(count, Operand(esp, stack_offset + kSizeOffset));
__ movdqu(xmm0, Operand(src, 0));
__ movdqu(Operand(dst, 0), xmm0);
__ mov(edx, dst);
__ and_(edx, 0xF);
__ neg(edx);
__ add(Operand(edx), Immediate(16));
__ add(dst, Operand(edx));
__ add(src, Operand(edx));
__ sub(Operand(count), edx);
// edi is now aligned. Check if esi is also aligned.
Label unaligned_source;
__ test(Operand(src), Immediate(0x0F));
__ j(not_zero, &unaligned_source);
{
__ IncrementCounter(&Counters::memcopy_aligned, 1);
// Copy loop for aligned source and destination.
__ mov(edx, count);
Register loop_count = ecx;
Register count = edx;
__ shr(loop_count, 5);
{
// Main copy loop.
Label loop;
__ bind(&loop);
__ prefetch(Operand(src, 0x20), 1);
__ movdqa(xmm0, Operand(src, 0x00));
__ movdqa(xmm1, Operand(src, 0x10));
__ add(Operand(src), Immediate(0x20));
__ movdqa(Operand(dst, 0x00), xmm0);
__ movdqa(Operand(dst, 0x10), xmm1);
__ add(Operand(dst), Immediate(0x20));
__ dec(loop_count);
__ j(not_zero, &loop);
}
// At most 31 bytes to copy.
Label move_less_16;
__ test(Operand(count), Immediate(0x10));
__ j(zero, &move_less_16);
__ movdqa(xmm0, Operand(src, 0));
__ add(Operand(src), Immediate(0x10));
__ movdqa(Operand(dst, 0), xmm0);
__ add(Operand(dst), Immediate(0x10));
__ bind(&move_less_16);
// At most 15 bytes to copy. Copy 16 bytes at end of string.
__ and_(count, 0xF);
__ movdqu(xmm0, Operand(src, count, times_1, -0x10));
__ movdqu(Operand(dst, count, times_1, -0x10), xmm0);
__ pop(esi);
__ pop(edi);
__ ret(0);
}
__ Align(16);
{
// Copy loop for unaligned source and aligned destination.
// If source is not aligned, we can't read it as efficiently.
__ bind(&unaligned_source);
__ IncrementCounter(&Counters::memcopy_unaligned, 1);
__ mov(edx, ecx);
Register loop_count = ecx;
Register count = edx;
__ shr(loop_count, 5);
{
// Main copy loop
Label loop;
__ bind(&loop);
__ prefetch(Operand(src, 0x20), 1);
__ movdqu(xmm0, Operand(src, 0x00));
__ movdqu(xmm1, Operand(src, 0x10));
__ add(Operand(src), Immediate(0x20));
__ movdqa(Operand(dst, 0x00), xmm0);
__ movdqa(Operand(dst, 0x10), xmm1);
__ add(Operand(dst), Immediate(0x20));
__ dec(loop_count);
__ j(not_zero, &loop);
}
// At most 31 bytes to copy.
Label move_less_16;
__ test(Operand(count), Immediate(0x10));
__ j(zero, &move_less_16);
__ movdqu(xmm0, Operand(src, 0));
__ add(Operand(src), Immediate(0x10));
__ movdqa(Operand(dst, 0), xmm0);
__ add(Operand(dst), Immediate(0x10));
__ bind(&move_less_16);
// At most 15 bytes to copy. Copy 16 bytes at end of string.
__ and_(count, 0x0F);
__ movdqu(xmm0, Operand(src, count, times_1, -0x10));
__ movdqu(Operand(dst, count, times_1, -0x10), xmm0);
__ pop(esi);
__ pop(edi);
__ ret(0);
}
} else {
__ IncrementCounter(&Counters::memcopy_noxmm, 1);
// SSE2 not supported. Unlikely to happen in practice.
__ push(edi);
__ push(esi);
stack_offset += 2 * kPointerSize;
__ cld();
Register dst = edi;
Register src = esi;
Register count = ecx;
__ mov(dst, Operand(esp, stack_offset + kDestinationOffset));
__ mov(src, Operand(esp, stack_offset + kSourceOffset));
__ mov(count, Operand(esp, stack_offset + kSizeOffset));
// Copy the first word.
__ mov(eax, Operand(src, 0));
__ mov(Operand(dst, 0), eax);
// Increment src,dstso that dst is aligned.
__ mov(edx, dst);
__ and_(edx, 0x03);
__ neg(edx);
__ add(Operand(edx), Immediate(4)); // edx = 4 - (dst & 3)
__ add(dst, Operand(edx));
__ add(src, Operand(edx));
__ sub(Operand(count), edx);
// edi is now aligned, ecx holds number of remaning bytes to copy.
__ mov(edx, count);
count = edx;
__ shr(ecx, 2); // Make word count instead of byte count.
__ rep_movs();
// At most 3 bytes left to copy. Copy 4 bytes at end of string.
__ and_(count, 3);
__ mov(eax, Operand(src, count, times_1, -4));
__ mov(Operand(dst, count, times_1, -4), eax);
__ pop(esi);
__ pop(edi);
__ ret(0);
}
CodeDesc desc;
masm.GetCode(&desc);
// Call the function from C++.
return FUNCTION_CAST<MemCopyFunction>(buffer);
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_IA32
Improve generated code for string encoding tests on ia32.
Review URL: http://codereview.chromium.org/2673001
git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@4812 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
// Copyright 2010 the V8 project authors. 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 Google Inc. 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 COPYRIGHT
// OWNER OR CONTRIBUTORS 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 "v8.h"
#if defined(V8_TARGET_ARCH_IA32)
#include "bootstrapper.h"
#include "codegen-inl.h"
#include "compiler.h"
#include "debug.h"
#include "ic-inl.h"
#include "jsregexp.h"
#include "parser.h"
#include "regexp-macro-assembler.h"
#include "regexp-stack.h"
#include "register-allocator-inl.h"
#include "runtime.h"
#include "scopes.h"
#include "virtual-frame-inl.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
// -------------------------------------------------------------------------
// Platform-specific FrameRegisterState functions.
void FrameRegisterState::Save(MacroAssembler* masm) const {
for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
int action = registers_[i];
if (action == kPush) {
__ push(RegisterAllocator::ToRegister(i));
} else if (action != kIgnore && (action & kSyncedFlag) == 0) {
__ mov(Operand(ebp, action), RegisterAllocator::ToRegister(i));
}
}
}
void FrameRegisterState::Restore(MacroAssembler* masm) const {
// Restore registers in reverse order due to the stack.
for (int i = RegisterAllocator::kNumRegisters - 1; i >= 0; i--) {
int action = registers_[i];
if (action == kPush) {
__ pop(RegisterAllocator::ToRegister(i));
} else if (action != kIgnore) {
action &= ~kSyncedFlag;
__ mov(RegisterAllocator::ToRegister(i), Operand(ebp, action));
}
}
}
#undef __
#define __ ACCESS_MASM(masm_)
// -------------------------------------------------------------------------
// Platform-specific DeferredCode functions.
void DeferredCode::SaveRegisters() {
frame_state_.Save(masm_);
}
void DeferredCode::RestoreRegisters() {
frame_state_.Restore(masm_);
}
// -------------------------------------------------------------------------
// Platform-specific RuntimeCallHelper functions.
void VirtualFrameRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
frame_state_->Save(masm);
}
void VirtualFrameRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
frame_state_->Restore(masm);
}
void ICRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
masm->EnterInternalFrame();
}
void ICRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
masm->LeaveInternalFrame();
}
// -------------------------------------------------------------------------
// CodeGenState implementation.
CodeGenState::CodeGenState(CodeGenerator* owner)
: owner_(owner),
destination_(NULL),
previous_(NULL) {
owner_->set_state(this);
}
CodeGenState::CodeGenState(CodeGenerator* owner,
ControlDestination* destination)
: owner_(owner),
destination_(destination),
previous_(owner->state()) {
owner_->set_state(this);
}
CodeGenState::~CodeGenState() {
ASSERT(owner_->state() == this);
owner_->set_state(previous_);
}
// -------------------------------------------------------------------------
// CodeGenerator implementation
CodeGenerator::CodeGenerator(MacroAssembler* masm)
: deferred_(8),
masm_(masm),
info_(NULL),
frame_(NULL),
allocator_(NULL),
state_(NULL),
loop_nesting_(0),
in_safe_int32_mode_(false),
safe_int32_mode_enabled_(true),
function_return_is_shadowed_(false),
in_spilled_code_(false) {
}
// Calling conventions:
// ebp: caller's frame pointer
// esp: stack pointer
// edi: called JS function
// esi: callee's context
void CodeGenerator::Generate(CompilationInfo* info) {
// Record the position for debugging purposes.
CodeForFunctionPosition(info->function());
Comment cmnt(masm_, "[ function compiled by virtual frame code generator");
// Initialize state.
info_ = info;
ASSERT(allocator_ == NULL);
RegisterAllocator register_allocator(this);
allocator_ = ®ister_allocator;
ASSERT(frame_ == NULL);
frame_ = new VirtualFrame();
set_in_spilled_code(false);
// Adjust for function-level loop nesting.
ASSERT_EQ(0, loop_nesting_);
loop_nesting_ = info->loop_nesting();
JumpTarget::set_compiling_deferred_code(false);
#ifdef DEBUG
if (strlen(FLAG_stop_at) > 0 &&
info->function()->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
frame_->SpillAll();
__ int3();
}
#endif
// New scope to get automatic timing calculation.
{ HistogramTimerScope codegen_timer(&Counters::code_generation);
CodeGenState state(this);
// Entry:
// Stack: receiver, arguments, return address.
// ebp: caller's frame pointer
// esp: stack pointer
// edi: called JS function
// esi: callee's context
allocator_->Initialize();
if (info->mode() == CompilationInfo::PRIMARY) {
frame_->Enter();
// Allocate space for locals and initialize them.
frame_->AllocateStackSlots();
// Allocate the local context if needed.
int heap_slots = scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
if (heap_slots > 0) {
Comment cmnt(masm_, "[ allocate local context");
// Allocate local context.
// Get outer context and create a new context based on it.
frame_->PushFunction();
Result context;
if (heap_slots <= FastNewContextStub::kMaximumSlots) {
FastNewContextStub stub(heap_slots);
context = frame_->CallStub(&stub, 1);
} else {
context = frame_->CallRuntime(Runtime::kNewContext, 1);
}
// Update context local.
frame_->SaveContextRegister();
// Verify that the runtime call result and esi agree.
if (FLAG_debug_code) {
__ cmp(context.reg(), Operand(esi));
__ Assert(equal, "Runtime::NewContext should end up in esi");
}
}
// TODO(1241774): Improve this code:
// 1) only needed if we have a context
// 2) no need to recompute context ptr every single time
// 3) don't copy parameter operand code from SlotOperand!
{
Comment cmnt2(masm_, "[ copy context parameters into .context");
// Note that iteration order is relevant here! If we have the same
// parameter twice (e.g., function (x, y, x)), and that parameter
// needs to be copied into the context, it must be the last argument
// passed to the parameter that needs to be copied. This is a rare
// case so we don't check for it, instead we rely on the copying
// order: such a parameter is copied repeatedly into the same
// context location and thus the last value is what is seen inside
// the function.
for (int i = 0; i < scope()->num_parameters(); i++) {
Variable* par = scope()->parameter(i);
Slot* slot = par->slot();
if (slot != NULL && slot->type() == Slot::CONTEXT) {
// The use of SlotOperand below is safe in unspilled code
// because the slot is guaranteed to be a context slot.
//
// There are no parameters in the global scope.
ASSERT(!scope()->is_global_scope());
frame_->PushParameterAt(i);
Result value = frame_->Pop();
value.ToRegister();
// SlotOperand loads context.reg() with the context object
// stored to, used below in RecordWrite.
Result context = allocator_->Allocate();
ASSERT(context.is_valid());
__ mov(SlotOperand(slot, context.reg()), value.reg());
int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_valid());
frame_->Spill(context.reg());
frame_->Spill(value.reg());
__ RecordWrite(context.reg(), offset, value.reg(), scratch.reg());
}
}
}
// Store the arguments object. This must happen after context
// initialization because the arguments object may be stored in
// the context.
if (ArgumentsMode() != NO_ARGUMENTS_ALLOCATION) {
StoreArgumentsObject(true);
}
// Initialize ThisFunction reference if present.
if (scope()->is_function_scope() && scope()->function() != NULL) {
frame_->Push(Factory::the_hole_value());
StoreToSlot(scope()->function()->slot(), NOT_CONST_INIT);
}
} else {
// When used as the secondary compiler for splitting, ebp, esi,
// and edi have been pushed on the stack. Adjust the virtual
// frame to match this state.
frame_->Adjust(3);
allocator_->Unuse(edi);
// Bind all the bailout labels to the beginning of the function.
List<CompilationInfo::Bailout*>* bailouts = info->bailouts();
for (int i = 0; i < bailouts->length(); i++) {
__ bind(bailouts->at(i)->label());
}
}
// Initialize the function return target after the locals are set
// up, because it needs the expected frame height from the frame.
function_return_.set_direction(JumpTarget::BIDIRECTIONAL);
function_return_is_shadowed_ = false;
// Generate code to 'execute' declarations and initialize functions
// (source elements). In case of an illegal redeclaration we need to
// handle that instead of processing the declarations.
if (scope()->HasIllegalRedeclaration()) {
Comment cmnt(masm_, "[ illegal redeclarations");
scope()->VisitIllegalRedeclaration(this);
} else {
Comment cmnt(masm_, "[ declarations");
ProcessDeclarations(scope()->declarations());
// Bail out if a stack-overflow exception occurred when processing
// declarations.
if (HasStackOverflow()) return;
}
if (FLAG_trace) {
frame_->CallRuntime(Runtime::kTraceEnter, 0);
// Ignore the return value.
}
CheckStack();
// Compile the body of the function in a vanilla state. Don't
// bother compiling all the code if the scope has an illegal
// redeclaration.
if (!scope()->HasIllegalRedeclaration()) {
Comment cmnt(masm_, "[ function body");
#ifdef DEBUG
bool is_builtin = Bootstrapper::IsActive();
bool should_trace =
is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
if (should_trace) {
frame_->CallRuntime(Runtime::kDebugTrace, 0);
// Ignore the return value.
}
#endif
VisitStatements(info->function()->body());
// Handle the return from the function.
if (has_valid_frame()) {
// If there is a valid frame, control flow can fall off the end of
// the body. In that case there is an implicit return statement.
ASSERT(!function_return_is_shadowed_);
CodeForReturnPosition(info->function());
frame_->PrepareForReturn();
Result undefined(Factory::undefined_value());
if (function_return_.is_bound()) {
function_return_.Jump(&undefined);
} else {
function_return_.Bind(&undefined);
GenerateReturnSequence(&undefined);
}
} else if (function_return_.is_linked()) {
// If the return target has dangling jumps to it, then we have not
// yet generated the return sequence. This can happen when (a)
// control does not flow off the end of the body so we did not
// compile an artificial return statement just above, and (b) there
// are return statements in the body but (c) they are all shadowed.
Result return_value;
function_return_.Bind(&return_value);
GenerateReturnSequence(&return_value);
}
}
}
// Adjust for function-level loop nesting.
ASSERT_EQ(info->loop_nesting(), loop_nesting_);
loop_nesting_ = 0;
// Code generation state must be reset.
ASSERT(state_ == NULL);
ASSERT(loop_nesting() == 0);
ASSERT(!function_return_is_shadowed_);
function_return_.Unuse();
DeleteFrame();
// Process any deferred code using the register allocator.
if (!HasStackOverflow()) {
HistogramTimerScope deferred_timer(&Counters::deferred_code_generation);
JumpTarget::set_compiling_deferred_code(true);
ProcessDeferred();
JumpTarget::set_compiling_deferred_code(false);
}
// There is no need to delete the register allocator, it is a
// stack-allocated local.
allocator_ = NULL;
}
Operand CodeGenerator::SlotOperand(Slot* slot, Register tmp) {
// Currently, this assertion will fail if we try to assign to
// a constant variable that is constant because it is read-only
// (such as the variable referring to a named function expression).
// We need to implement assignments to read-only variables.
// Ideally, we should do this during AST generation (by converting
// such assignments into expression statements); however, in general
// we may not be able to make the decision until past AST generation,
// that is when the entire program is known.
ASSERT(slot != NULL);
int index = slot->index();
switch (slot->type()) {
case Slot::PARAMETER:
return frame_->ParameterAt(index);
case Slot::LOCAL:
return frame_->LocalAt(index);
case Slot::CONTEXT: {
// Follow the context chain if necessary.
ASSERT(!tmp.is(esi)); // do not overwrite context register
Register context = esi;
int chain_length = scope()->ContextChainLength(slot->var()->scope());
for (int i = 0; i < chain_length; i++) {
// Load the closure.
// (All contexts, even 'with' contexts, have a closure,
// and it is the same for all contexts inside a function.
// There is no need to go to the function context first.)
__ mov(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
// Load the function context (which is the incoming, outer context).
__ mov(tmp, FieldOperand(tmp, JSFunction::kContextOffset));
context = tmp;
}
// We may have a 'with' context now. Get the function context.
// (In fact this mov may never be the needed, since the scope analysis
// may not permit a direct context access in this case and thus we are
// always at a function context. However it is safe to dereference be-
// cause the function context of a function context is itself. Before
// deleting this mov we should try to create a counter-example first,
// though...)
__ mov(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
return ContextOperand(tmp, index);
}
default:
UNREACHABLE();
return Operand(eax);
}
}
Operand CodeGenerator::ContextSlotOperandCheckExtensions(Slot* slot,
Result tmp,
JumpTarget* slow) {
ASSERT(slot->type() == Slot::CONTEXT);
ASSERT(tmp.is_register());
Register context = esi;
for (Scope* s = scope(); s != slot->var()->scope(); s = s->outer_scope()) {
if (s->num_heap_slots() > 0) {
if (s->calls_eval()) {
// Check that extension is NULL.
__ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
Immediate(0));
slow->Branch(not_equal, not_taken);
}
__ mov(tmp.reg(), ContextOperand(context, Context::CLOSURE_INDEX));
__ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
context = tmp.reg();
}
}
// Check that last extension is NULL.
__ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
slow->Branch(not_equal, not_taken);
__ mov(tmp.reg(), ContextOperand(context, Context::FCONTEXT_INDEX));
return ContextOperand(tmp.reg(), slot->index());
}
// Emit code to load the value of an expression to the top of the
// frame. If the expression is boolean-valued it may be compiled (or
// partially compiled) into control flow to the control destination.
// If force_control is true, control flow is forced.
void CodeGenerator::LoadCondition(Expression* expr,
ControlDestination* dest,
bool force_control) {
ASSERT(!in_spilled_code());
int original_height = frame_->height();
{ CodeGenState new_state(this, dest);
Visit(expr);
// If we hit a stack overflow, we may not have actually visited
// the expression. In that case, we ensure that we have a
// valid-looking frame state because we will continue to generate
// code as we unwind the C++ stack.
//
// It's possible to have both a stack overflow and a valid frame
// state (eg, a subexpression overflowed, visiting it returned
// with a dummied frame state, and visiting this expression
// returned with a normal-looking state).
if (HasStackOverflow() &&
!dest->is_used() &&
frame_->height() == original_height) {
dest->Goto(true);
}
}
if (force_control && !dest->is_used()) {
// Convert the TOS value into flow to the control destination.
ToBoolean(dest);
}
ASSERT(!(force_control && !dest->is_used()));
ASSERT(dest->is_used() || frame_->height() == original_height + 1);
}
void CodeGenerator::LoadAndSpill(Expression* expression) {
ASSERT(in_spilled_code());
set_in_spilled_code(false);
Load(expression);
frame_->SpillAll();
set_in_spilled_code(true);
}
void CodeGenerator::LoadInSafeInt32Mode(Expression* expr,
BreakTarget* unsafe_bailout) {
set_unsafe_bailout(unsafe_bailout);
set_in_safe_int32_mode(true);
Load(expr);
Result value = frame_->Pop();
ASSERT(frame_->HasNoUntaggedInt32Elements());
if (expr->GuaranteedSmiResult()) {
ConvertInt32ResultToSmi(&value);
} else {
ConvertInt32ResultToNumber(&value);
}
set_in_safe_int32_mode(false);
set_unsafe_bailout(NULL);
frame_->Push(&value);
}
void CodeGenerator::LoadWithSafeInt32ModeDisabled(Expression* expr) {
set_safe_int32_mode_enabled(false);
Load(expr);
set_safe_int32_mode_enabled(true);
}
void CodeGenerator::ConvertInt32ResultToSmi(Result* value) {
ASSERT(value->is_untagged_int32());
if (value->is_register()) {
__ add(value->reg(), Operand(value->reg()));
} else {
ASSERT(value->is_constant());
ASSERT(value->handle()->IsSmi());
}
value->set_untagged_int32(false);
value->set_type_info(TypeInfo::Smi());
}
void CodeGenerator::ConvertInt32ResultToNumber(Result* value) {
ASSERT(value->is_untagged_int32());
if (value->is_register()) {
Register val = value->reg();
JumpTarget done;
__ add(val, Operand(val));
done.Branch(no_overflow, value);
__ sar(val, 1);
// If there was an overflow, bits 30 and 31 of the original number disagree.
__ xor_(val, 0x80000000u);
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ cvtsi2sd(xmm0, Operand(val));
} else {
// Move val to ST[0] in the FPU
// Push and pop are safe with respect to the virtual frame because
// all synced elements are below the actual stack pointer.
__ push(val);
__ fild_s(Operand(esp, 0));
__ pop(val);
}
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_register());
Label allocation_failed;
__ AllocateHeapNumber(val, scratch.reg(),
no_reg, &allocation_failed);
VirtualFrame* clone = new VirtualFrame(frame_);
scratch.Unuse();
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ movdbl(FieldOperand(val, HeapNumber::kValueOffset), xmm0);
} else {
__ fstp_d(FieldOperand(val, HeapNumber::kValueOffset));
}
done.Jump(value);
// Establish the virtual frame, cloned from where AllocateHeapNumber
// jumped to allocation_failed.
RegisterFile empty_regs;
SetFrame(clone, &empty_regs);
__ bind(&allocation_failed);
unsafe_bailout_->Jump();
done.Bind(value);
} else {
ASSERT(value->is_constant());
}
value->set_untagged_int32(false);
value->set_type_info(TypeInfo::Integer32());
}
void CodeGenerator::Load(Expression* expr) {
#ifdef DEBUG
int original_height = frame_->height();
#endif
ASSERT(!in_spilled_code());
// If the expression should be a side-effect-free 32-bit int computation,
// compile that SafeInt32 path, and a bailout path.
if (!in_safe_int32_mode() &&
safe_int32_mode_enabled() &&
expr->side_effect_free() &&
expr->num_bit_ops() > 2 &&
CpuFeatures::IsSupported(SSE2)) {
BreakTarget unsafe_bailout;
JumpTarget done;
unsafe_bailout.set_expected_height(frame_->height());
LoadInSafeInt32Mode(expr, &unsafe_bailout);
done.Jump();
if (unsafe_bailout.is_linked()) {
unsafe_bailout.Bind();
LoadWithSafeInt32ModeDisabled(expr);
}
done.Bind();
} else {
JumpTarget true_target;
JumpTarget false_target;
ControlDestination dest(&true_target, &false_target, true);
LoadCondition(expr, &dest, false);
if (dest.false_was_fall_through()) {
// The false target was just bound.
JumpTarget loaded;
frame_->Push(Factory::false_value());
// There may be dangling jumps to the true target.
if (true_target.is_linked()) {
loaded.Jump();
true_target.Bind();
frame_->Push(Factory::true_value());
loaded.Bind();
}
} else if (dest.is_used()) {
// There is true, and possibly false, control flow (with true as
// the fall through).
JumpTarget loaded;
frame_->Push(Factory::true_value());
if (false_target.is_linked()) {
loaded.Jump();
false_target.Bind();
frame_->Push(Factory::false_value());
loaded.Bind();
}
} else {
// We have a valid value on top of the frame, but we still may
// have dangling jumps to the true and false targets from nested
// subexpressions (eg, the left subexpressions of the
// short-circuited boolean operators).
ASSERT(has_valid_frame());
if (true_target.is_linked() || false_target.is_linked()) {
JumpTarget loaded;
loaded.Jump(); // Don't lose the current TOS.
if (true_target.is_linked()) {
true_target.Bind();
frame_->Push(Factory::true_value());
if (false_target.is_linked()) {
loaded.Jump();
}
}
if (false_target.is_linked()) {
false_target.Bind();
frame_->Push(Factory::false_value());
}
loaded.Bind();
}
}
}
ASSERT(has_valid_frame());
ASSERT(frame_->height() == original_height + 1);
}
void CodeGenerator::LoadGlobal() {
if (in_spilled_code()) {
frame_->EmitPush(GlobalObject());
} else {
Result temp = allocator_->Allocate();
__ mov(temp.reg(), GlobalObject());
frame_->Push(&temp);
}
}
void CodeGenerator::LoadGlobalReceiver() {
Result temp = allocator_->Allocate();
Register reg = temp.reg();
__ mov(reg, GlobalObject());
__ mov(reg, FieldOperand(reg, GlobalObject::kGlobalReceiverOffset));
frame_->Push(&temp);
}
void CodeGenerator::LoadTypeofExpression(Expression* expr) {
// Special handling of identifiers as subexpressions of typeof.
Variable* variable = expr->AsVariableProxy()->AsVariable();
if (variable != NULL && !variable->is_this() && variable->is_global()) {
// For a global variable we build the property reference
// <global>.<variable> and perform a (regular non-contextual) property
// load to make sure we do not get reference errors.
Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
Literal key(variable->name());
Property property(&global, &key, RelocInfo::kNoPosition);
Reference ref(this, &property);
ref.GetValue();
} else if (variable != NULL && variable->slot() != NULL) {
// For a variable that rewrites to a slot, we signal it is the immediate
// subexpression of a typeof.
LoadFromSlotCheckForArguments(variable->slot(), INSIDE_TYPEOF);
} else {
// Anything else can be handled normally.
Load(expr);
}
}
ArgumentsAllocationMode CodeGenerator::ArgumentsMode() {
if (scope()->arguments() == NULL) return NO_ARGUMENTS_ALLOCATION;
ASSERT(scope()->arguments_shadow() != NULL);
// We don't want to do lazy arguments allocation for functions that
// have heap-allocated contexts, because it interfers with the
// uninitialized const tracking in the context objects.
return (scope()->num_heap_slots() > 0)
? EAGER_ARGUMENTS_ALLOCATION
: LAZY_ARGUMENTS_ALLOCATION;
}
Result CodeGenerator::StoreArgumentsObject(bool initial) {
ArgumentsAllocationMode mode = ArgumentsMode();
ASSERT(mode != NO_ARGUMENTS_ALLOCATION);
Comment cmnt(masm_, "[ store arguments object");
if (mode == LAZY_ARGUMENTS_ALLOCATION && initial) {
// When using lazy arguments allocation, we store the hole value
// as a sentinel indicating that the arguments object hasn't been
// allocated yet.
frame_->Push(Factory::the_hole_value());
} else {
ArgumentsAccessStub stub(ArgumentsAccessStub::NEW_OBJECT);
frame_->PushFunction();
frame_->PushReceiverSlotAddress();
frame_->Push(Smi::FromInt(scope()->num_parameters()));
Result result = frame_->CallStub(&stub, 3);
frame_->Push(&result);
}
Variable* arguments = scope()->arguments()->var();
Variable* shadow = scope()->arguments_shadow()->var();
ASSERT(arguments != NULL && arguments->slot() != NULL);
ASSERT(shadow != NULL && shadow->slot() != NULL);
JumpTarget done;
bool skip_arguments = false;
if (mode == LAZY_ARGUMENTS_ALLOCATION && !initial) {
// We have to skip storing into the arguments slot if it has already
// been written to. This can happen if the a function has a local
// variable named 'arguments'.
LoadFromSlot(arguments->slot(), NOT_INSIDE_TYPEOF);
Result probe = frame_->Pop();
if (probe.is_constant()) {
// We have to skip updating the arguments object if it has
// been assigned a proper value.
skip_arguments = !probe.handle()->IsTheHole();
} else {
__ cmp(Operand(probe.reg()), Immediate(Factory::the_hole_value()));
probe.Unuse();
done.Branch(not_equal);
}
}
if (!skip_arguments) {
StoreToSlot(arguments->slot(), NOT_CONST_INIT);
if (mode == LAZY_ARGUMENTS_ALLOCATION) done.Bind();
}
StoreToSlot(shadow->slot(), NOT_CONST_INIT);
return frame_->Pop();
}
//------------------------------------------------------------------------------
// CodeGenerator implementation of variables, lookups, and stores.
Reference::Reference(CodeGenerator* cgen,
Expression* expression,
bool persist_after_get)
: cgen_(cgen),
expression_(expression),
type_(ILLEGAL),
persist_after_get_(persist_after_get) {
cgen->LoadReference(this);
}
Reference::~Reference() {
ASSERT(is_unloaded() || is_illegal());
}
void CodeGenerator::LoadReference(Reference* ref) {
// References are loaded from both spilled and unspilled code. Set the
// state to unspilled to allow that (and explicitly spill after
// construction at the construction sites).
bool was_in_spilled_code = in_spilled_code_;
in_spilled_code_ = false;
Comment cmnt(masm_, "[ LoadReference");
Expression* e = ref->expression();
Property* property = e->AsProperty();
Variable* var = e->AsVariableProxy()->AsVariable();
if (property != NULL) {
// The expression is either a property or a variable proxy that rewrites
// to a property.
Load(property->obj());
if (property->key()->IsPropertyName()) {
ref->set_type(Reference::NAMED);
} else {
Load(property->key());
ref->set_type(Reference::KEYED);
}
} else if (var != NULL) {
// The expression is a variable proxy that does not rewrite to a
// property. Global variables are treated as named property references.
if (var->is_global()) {
// If eax is free, the register allocator prefers it. Thus the code
// generator will load the global object into eax, which is where
// LoadIC wants it. Most uses of Reference call LoadIC directly
// after the reference is created.
frame_->Spill(eax);
LoadGlobal();
ref->set_type(Reference::NAMED);
} else {
ASSERT(var->slot() != NULL);
ref->set_type(Reference::SLOT);
}
} else {
// Anything else is a runtime error.
Load(e);
frame_->CallRuntime(Runtime::kThrowReferenceError, 1);
}
in_spilled_code_ = was_in_spilled_code;
}
// ECMA-262, section 9.2, page 30: ToBoolean(). Pop the top of stack and
// convert it to a boolean in the condition code register or jump to
// 'false_target'/'true_target' as appropriate.
void CodeGenerator::ToBoolean(ControlDestination* dest) {
Comment cmnt(masm_, "[ ToBoolean");
// The value to convert should be popped from the frame.
Result value = frame_->Pop();
value.ToRegister();
if (value.is_integer32()) { // Also takes Smi case.
Comment cmnt(masm_, "ONLY_INTEGER_32");
if (FLAG_debug_code) {
Label ok;
__ AbortIfNotNumber(value.reg());
__ test(value.reg(), Immediate(kSmiTagMask));
__ j(zero, &ok);
__ fldz();
__ fld_d(FieldOperand(value.reg(), HeapNumber::kValueOffset));
__ FCmp();
__ j(not_zero, &ok);
__ Abort("Smi was wrapped in HeapNumber in output from bitop");
__ bind(&ok);
}
// In the integer32 case there are no Smis hidden in heap numbers, so we
// need only test for Smi zero.
__ test(value.reg(), Operand(value.reg()));
dest->false_target()->Branch(zero);
value.Unuse();
dest->Split(not_zero);
} else if (value.is_number()) {
Comment cmnt(masm_, "ONLY_NUMBER");
// Fast case if TypeInfo indicates only numbers.
if (FLAG_debug_code) {
__ AbortIfNotNumber(value.reg());
}
// Smi => false iff zero.
ASSERT(kSmiTag == 0);
__ test(value.reg(), Operand(value.reg()));
dest->false_target()->Branch(zero);
__ test(value.reg(), Immediate(kSmiTagMask));
dest->true_target()->Branch(zero);
__ fldz();
__ fld_d(FieldOperand(value.reg(), HeapNumber::kValueOffset));
__ FCmp();
value.Unuse();
dest->Split(not_zero);
} else {
// Fast case checks.
// 'false' => false.
__ cmp(value.reg(), Factory::false_value());
dest->false_target()->Branch(equal);
// 'true' => true.
__ cmp(value.reg(), Factory::true_value());
dest->true_target()->Branch(equal);
// 'undefined' => false.
__ cmp(value.reg(), Factory::undefined_value());
dest->false_target()->Branch(equal);
// Smi => false iff zero.
ASSERT(kSmiTag == 0);
__ test(value.reg(), Operand(value.reg()));
dest->false_target()->Branch(zero);
__ test(value.reg(), Immediate(kSmiTagMask));
dest->true_target()->Branch(zero);
// Call the stub for all other cases.
frame_->Push(&value); // Undo the Pop() from above.
ToBooleanStub stub;
Result temp = frame_->CallStub(&stub, 1);
// Convert the result to a condition code.
__ test(temp.reg(), Operand(temp.reg()));
temp.Unuse();
dest->Split(not_equal);
}
}
class FloatingPointHelper : public AllStatic {
public:
enum ArgLocation {
ARGS_ON_STACK,
ARGS_IN_REGISTERS
};
// Code pattern for loading a floating point value. Input value must
// be either a smi or a heap number object (fp value). Requirements:
// operand in register number. Returns operand as floating point number
// on FPU stack.
static void LoadFloatOperand(MacroAssembler* masm, Register number);
// Code pattern for loading floating point values. Input values must
// be either smi or heap number objects (fp values). Requirements:
// operand_1 on TOS+1 or in edx, operand_2 on TOS+2 or in eax.
// Returns operands as floating point numbers on FPU stack.
static void LoadFloatOperands(MacroAssembler* masm,
Register scratch,
ArgLocation arg_location = ARGS_ON_STACK);
// Similar to LoadFloatOperand but assumes that both operands are smis.
// Expects operands in edx, eax.
static void LoadFloatSmis(MacroAssembler* masm, Register scratch);
// Test if operands are smi or number objects (fp). Requirements:
// operand_1 in eax, operand_2 in edx; falls through on float
// operands, jumps to the non_float label otherwise.
static void CheckFloatOperands(MacroAssembler* masm,
Label* non_float,
Register scratch);
// Takes the operands in edx and eax and loads them as integers in eax
// and ecx.
static void LoadAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* operand_conversion_failure);
static void LoadNumbersAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* operand_conversion_failure);
static void LoadUnknownsAsIntegers(MacroAssembler* masm,
bool use_sse3,
Label* operand_conversion_failure);
// Test if operands are smis or heap numbers and load them
// into xmm0 and xmm1 if they are. Operands are in edx and eax.
// Leaves operands unchanged.
static void LoadSSE2Operands(MacroAssembler* masm);
// Test if operands are numbers (smi or HeapNumber objects), and load
// them into xmm0 and xmm1 if they are. Jump to label not_numbers if
// either operand is not a number. Operands are in edx and eax.
// Leaves operands unchanged.
static void LoadSSE2Operands(MacroAssembler* masm, Label* not_numbers);
// Similar to LoadSSE2Operands but assumes that both operands are smis.
// Expects operands in edx, eax.
static void LoadSSE2Smis(MacroAssembler* masm, Register scratch);
};
const char* GenericBinaryOpStub::GetName() {
if (name_ != NULL) return name_;
const int kMaxNameLength = 100;
name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
if (name_ == NULL) return "OOM";
const char* op_name = Token::Name(op_);
const char* overwrite_name;
switch (mode_) {
case NO_OVERWRITE: overwrite_name = "Alloc"; break;
case OVERWRITE_RIGHT: overwrite_name = "OverwriteRight"; break;
case OVERWRITE_LEFT: overwrite_name = "OverwriteLeft"; break;
default: overwrite_name = "UnknownOverwrite"; break;
}
OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
"GenericBinaryOpStub_%s_%s%s_%s%s_%s_%s",
op_name,
overwrite_name,
(flags_ & NO_SMI_CODE_IN_STUB) ? "_NoSmiInStub" : "",
args_in_registers_ ? "RegArgs" : "StackArgs",
args_reversed_ ? "_R" : "",
static_operands_type_.ToString(),
BinaryOpIC::GetName(runtime_operands_type_));
return name_;
}
// Call the specialized stub for a binary operation.
class DeferredInlineBinaryOperation: public DeferredCode {
public:
DeferredInlineBinaryOperation(Token::Value op,
Register dst,
Register left,
Register right,
TypeInfo left_info,
TypeInfo right_info,
OverwriteMode mode)
: op_(op), dst_(dst), left_(left), right_(right),
left_info_(left_info), right_info_(right_info), mode_(mode) {
set_comment("[ DeferredInlineBinaryOperation");
}
virtual void Generate();
private:
Token::Value op_;
Register dst_;
Register left_;
Register right_;
TypeInfo left_info_;
TypeInfo right_info_;
OverwriteMode mode_;
};
void DeferredInlineBinaryOperation::Generate() {
Label done;
if (CpuFeatures::IsSupported(SSE2) && ((op_ == Token::ADD) ||
(op_ ==Token::SUB) ||
(op_ == Token::MUL) ||
(op_ == Token::DIV))) {
CpuFeatures::Scope use_sse2(SSE2);
Label call_runtime, after_alloc_failure;
Label left_smi, right_smi, load_right, do_op;
if (!left_info_.IsSmi()) {
__ test(left_, Immediate(kSmiTagMask));
__ j(zero, &left_smi);
if (!left_info_.IsNumber()) {
__ cmp(FieldOperand(left_, HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, &call_runtime);
}
__ movdbl(xmm0, FieldOperand(left_, HeapNumber::kValueOffset));
if (mode_ == OVERWRITE_LEFT) {
__ mov(dst_, left_);
}
__ jmp(&load_right);
__ bind(&left_smi);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left_);
}
__ SmiUntag(left_);
__ cvtsi2sd(xmm0, Operand(left_));
__ SmiTag(left_);
if (mode_ == OVERWRITE_LEFT) {
Label alloc_failure;
__ push(left_);
__ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
__ pop(left_);
}
__ bind(&load_right);
if (!right_info_.IsSmi()) {
__ test(right_, Immediate(kSmiTagMask));
__ j(zero, &right_smi);
if (!right_info_.IsNumber()) {
__ cmp(FieldOperand(right_, HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, &call_runtime);
}
__ movdbl(xmm1, FieldOperand(right_, HeapNumber::kValueOffset));
if (mode_ == OVERWRITE_RIGHT) {
__ mov(dst_, right_);
} else if (mode_ == NO_OVERWRITE) {
Label alloc_failure;
__ push(left_);
__ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
__ pop(left_);
}
__ jmp(&do_op);
__ bind(&right_smi);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(right_);
}
__ SmiUntag(right_);
__ cvtsi2sd(xmm1, Operand(right_));
__ SmiTag(right_);
if (mode_ == OVERWRITE_RIGHT || mode_ == NO_OVERWRITE) {
Label alloc_failure;
__ push(left_);
__ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
__ pop(left_);
}
__ bind(&do_op);
switch (op_) {
case Token::ADD: __ addsd(xmm0, xmm1); break;
case Token::SUB: __ subsd(xmm0, xmm1); break;
case Token::MUL: __ mulsd(xmm0, xmm1); break;
case Token::DIV: __ divsd(xmm0, xmm1); break;
default: UNREACHABLE();
}
__ movdbl(FieldOperand(dst_, HeapNumber::kValueOffset), xmm0);
__ jmp(&done);
__ bind(&after_alloc_failure);
__ pop(left_);
__ bind(&call_runtime);
}
GenericBinaryOpStub stub(op_,
mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(left_info_, right_info_));
stub.GenerateCall(masm_, left_, right_);
if (!dst_.is(eax)) __ mov(dst_, eax);
__ bind(&done);
}
static TypeInfo CalculateTypeInfo(TypeInfo operands_type,
Token::Value op,
const Result& right,
const Result& left) {
// Set TypeInfo of result according to the operation performed.
// Rely on the fact that smis have a 31 bit payload on ia32.
ASSERT(kSmiValueSize == 31);
switch (op) {
case Token::COMMA:
return right.type_info();
case Token::OR:
case Token::AND:
// Result type can be either of the two input types.
return operands_type;
case Token::BIT_AND: {
// Anding with positive Smis will give you a Smi.
if (right.is_constant() && right.handle()->IsSmi() &&
Smi::cast(*right.handle())->value() >= 0) {
return TypeInfo::Smi();
} else if (left.is_constant() && left.handle()->IsSmi() &&
Smi::cast(*left.handle())->value() >= 0) {
return TypeInfo::Smi();
}
return (operands_type.IsSmi())
? TypeInfo::Smi()
: TypeInfo::Integer32();
}
case Token::BIT_OR: {
// Oring with negative Smis will give you a Smi.
if (right.is_constant() && right.handle()->IsSmi() &&
Smi::cast(*right.handle())->value() < 0) {
return TypeInfo::Smi();
} else if (left.is_constant() && left.handle()->IsSmi() &&
Smi::cast(*left.handle())->value() < 0) {
return TypeInfo::Smi();
}
return (operands_type.IsSmi())
? TypeInfo::Smi()
: TypeInfo::Integer32();
}
case Token::BIT_XOR:
// Result is always a 32 bit integer. Smi property of inputs is preserved.
return (operands_type.IsSmi())
? TypeInfo::Smi()
: TypeInfo::Integer32();
case Token::SAR:
if (left.is_smi()) return TypeInfo::Smi();
// Result is a smi if we shift by a constant >= 1, otherwise an integer32.
// Shift amount is masked with 0x1F (ECMA standard 11.7.2).
return (right.is_constant() && right.handle()->IsSmi()
&& (Smi::cast(*right.handle())->value() & 0x1F) >= 1)
? TypeInfo::Smi()
: TypeInfo::Integer32();
case Token::SHR:
// Result is a smi if we shift by a constant >= 2, an integer32 if
// we shift by 1, and an unsigned 32-bit integer if we shift by 0.
if (right.is_constant() && right.handle()->IsSmi()) {
int shift_amount = Smi::cast(*right.handle())->value() & 0x1F;
if (shift_amount > 1) {
return TypeInfo::Smi();
} else if (shift_amount > 0) {
return TypeInfo::Integer32();
}
}
return TypeInfo::Number();
case Token::ADD:
if (operands_type.IsSmi()) {
// The Integer32 range is big enough to take the sum of any two Smis.
return TypeInfo::Integer32();
} else if (operands_type.IsNumber()) {
return TypeInfo::Number();
} else if (left.type_info().IsString() || right.type_info().IsString()) {
return TypeInfo::String();
} else {
return TypeInfo::Unknown();
}
case Token::SHL:
return TypeInfo::Integer32();
case Token::SUB:
// The Integer32 range is big enough to take the difference of any two
// Smis.
return (operands_type.IsSmi()) ?
TypeInfo::Integer32() :
TypeInfo::Number();
case Token::MUL:
case Token::DIV:
case Token::MOD:
// Result is always a number.
return TypeInfo::Number();
default:
UNREACHABLE();
}
UNREACHABLE();
return TypeInfo::Unknown();
}
void CodeGenerator::GenericBinaryOperation(BinaryOperation* expr,
OverwriteMode overwrite_mode) {
Comment cmnt(masm_, "[ BinaryOperation");
Token::Value op = expr->op();
Comment cmnt_token(masm_, Token::String(op));
if (op == Token::COMMA) {
// Simply discard left value.
frame_->Nip(1);
return;
}
Result right = frame_->Pop();
Result left = frame_->Pop();
if (op == Token::ADD) {
const bool left_is_string = left.type_info().IsString();
const bool right_is_string = right.type_info().IsString();
// Make sure constant strings have string type info.
ASSERT(!(left.is_constant() && left.handle()->IsString()) ||
left_is_string);
ASSERT(!(right.is_constant() && right.handle()->IsString()) ||
right_is_string);
if (left_is_string || right_is_string) {
frame_->Push(&left);
frame_->Push(&right);
Result answer;
if (left_is_string) {
if (right_is_string) {
StringAddStub stub(NO_STRING_CHECK_IN_STUB);
answer = frame_->CallStub(&stub, 2);
} else {
answer =
frame_->InvokeBuiltin(Builtins::STRING_ADD_LEFT, CALL_FUNCTION, 2);
}
} else if (right_is_string) {
answer =
frame_->InvokeBuiltin(Builtins::STRING_ADD_RIGHT, CALL_FUNCTION, 2);
}
answer.set_type_info(TypeInfo::String());
frame_->Push(&answer);
return;
}
// Neither operand is known to be a string.
}
bool left_is_smi_constant = left.is_constant() && left.handle()->IsSmi();
bool left_is_non_smi_constant = left.is_constant() && !left.handle()->IsSmi();
bool right_is_smi_constant = right.is_constant() && right.handle()->IsSmi();
bool right_is_non_smi_constant =
right.is_constant() && !right.handle()->IsSmi();
if (left_is_smi_constant && right_is_smi_constant) {
// Compute the constant result at compile time, and leave it on the frame.
int left_int = Smi::cast(*left.handle())->value();
int right_int = Smi::cast(*right.handle())->value();
if (FoldConstantSmis(op, left_int, right_int)) return;
}
// Get number type of left and right sub-expressions.
TypeInfo operands_type =
TypeInfo::Combine(left.type_info(), right.type_info());
TypeInfo result_type = CalculateTypeInfo(operands_type, op, right, left);
Result answer;
if (left_is_non_smi_constant || right_is_non_smi_constant) {
// Go straight to the slow case, with no smi code.
GenericBinaryOpStub stub(op,
overwrite_mode,
NO_SMI_CODE_IN_STUB,
operands_type);
answer = stub.GenerateCall(masm_, frame_, &left, &right);
} else if (right_is_smi_constant) {
answer = ConstantSmiBinaryOperation(expr, &left, right.handle(),
false, overwrite_mode);
} else if (left_is_smi_constant) {
answer = ConstantSmiBinaryOperation(expr, &right, left.handle(),
true, overwrite_mode);
} else {
// Set the flags based on the operation, type and loop nesting level.
// Bit operations always assume they likely operate on Smis. Still only
// generate the inline Smi check code if this operation is part of a loop.
// For all other operations only inline the Smi check code for likely smis
// if the operation is part of a loop.
if (loop_nesting() > 0 &&
(Token::IsBitOp(op) ||
operands_type.IsInteger32() ||
expr->type()->IsLikelySmi())) {
answer = LikelySmiBinaryOperation(expr, &left, &right, overwrite_mode);
} else {
GenericBinaryOpStub stub(op,
overwrite_mode,
NO_GENERIC_BINARY_FLAGS,
operands_type);
answer = stub.GenerateCall(masm_, frame_, &left, &right);
}
}
answer.set_type_info(result_type);
frame_->Push(&answer);
}
bool CodeGenerator::FoldConstantSmis(Token::Value op, int left, int right) {
Object* answer_object = Heap::undefined_value();
switch (op) {
case Token::ADD:
if (Smi::IsValid(left + right)) {
answer_object = Smi::FromInt(left + right);
}
break;
case Token::SUB:
if (Smi::IsValid(left - right)) {
answer_object = Smi::FromInt(left - right);
}
break;
case Token::MUL: {
double answer = static_cast<double>(left) * right;
if (answer >= Smi::kMinValue && answer <= Smi::kMaxValue) {
// If the product is zero and the non-zero factor is negative,
// the spec requires us to return floating point negative zero.
if (answer != 0 || (left >= 0 && right >= 0)) {
answer_object = Smi::FromInt(static_cast<int>(answer));
}
}
}
break;
case Token::DIV:
case Token::MOD:
break;
case Token::BIT_OR:
answer_object = Smi::FromInt(left | right);
break;
case Token::BIT_AND:
answer_object = Smi::FromInt(left & right);
break;
case Token::BIT_XOR:
answer_object = Smi::FromInt(left ^ right);
break;
case Token::SHL: {
int shift_amount = right & 0x1F;
if (Smi::IsValid(left << shift_amount)) {
answer_object = Smi::FromInt(left << shift_amount);
}
break;
}
case Token::SHR: {
int shift_amount = right & 0x1F;
unsigned int unsigned_left = left;
unsigned_left >>= shift_amount;
if (unsigned_left <= static_cast<unsigned int>(Smi::kMaxValue)) {
answer_object = Smi::FromInt(unsigned_left);
}
break;
}
case Token::SAR: {
int shift_amount = right & 0x1F;
unsigned int unsigned_left = left;
if (left < 0) {
// Perform arithmetic shift of a negative number by
// complementing number, logical shifting, complementing again.
unsigned_left = ~unsigned_left;
unsigned_left >>= shift_amount;
unsigned_left = ~unsigned_left;
} else {
unsigned_left >>= shift_amount;
}
ASSERT(Smi::IsValid(unsigned_left)); // Converted to signed.
answer_object = Smi::FromInt(unsigned_left); // Converted to signed.
break;
}
default:
UNREACHABLE();
break;
}
if (answer_object == Heap::undefined_value()) {
return false;
}
frame_->Push(Handle<Object>(answer_object));
return true;
}
static void CheckTwoForSminess(MacroAssembler* masm,
Register left, Register right, Register scratch,
TypeInfo left_info, TypeInfo right_info,
DeferredInlineBinaryOperation* deferred);
// Implements a binary operation using a deferred code object and some
// inline code to operate on smis quickly.
Result CodeGenerator::LikelySmiBinaryOperation(BinaryOperation* expr,
Result* left,
Result* right,
OverwriteMode overwrite_mode) {
// Copy the type info because left and right may be overwritten.
TypeInfo left_type_info = left->type_info();
TypeInfo right_type_info = right->type_info();
Token::Value op = expr->op();
Result answer;
// Special handling of div and mod because they use fixed registers.
if (op == Token::DIV || op == Token::MOD) {
// We need eax as the quotient register, edx as the remainder
// register, neither left nor right in eax or edx, and left copied
// to eax.
Result quotient;
Result remainder;
bool left_is_in_eax = false;
// Step 1: get eax for quotient.
if ((left->is_register() && left->reg().is(eax)) ||
(right->is_register() && right->reg().is(eax))) {
// One or both is in eax. Use a fresh non-edx register for
// them.
Result fresh = allocator_->Allocate();
ASSERT(fresh.is_valid());
if (fresh.reg().is(edx)) {
remainder = fresh;
fresh = allocator_->Allocate();
ASSERT(fresh.is_valid());
}
if (left->is_register() && left->reg().is(eax)) {
quotient = *left;
*left = fresh;
left_is_in_eax = true;
}
if (right->is_register() && right->reg().is(eax)) {
quotient = *right;
*right = fresh;
}
__ mov(fresh.reg(), eax);
} else {
// Neither left nor right is in eax.
quotient = allocator_->Allocate(eax);
}
ASSERT(quotient.is_register() && quotient.reg().is(eax));
ASSERT(!(left->is_register() && left->reg().is(eax)));
ASSERT(!(right->is_register() && right->reg().is(eax)));
// Step 2: get edx for remainder if necessary.
if (!remainder.is_valid()) {
if ((left->is_register() && left->reg().is(edx)) ||
(right->is_register() && right->reg().is(edx))) {
Result fresh = allocator_->Allocate();
ASSERT(fresh.is_valid());
if (left->is_register() && left->reg().is(edx)) {
remainder = *left;
*left = fresh;
}
if (right->is_register() && right->reg().is(edx)) {
remainder = *right;
*right = fresh;
}
__ mov(fresh.reg(), edx);
} else {
// Neither left nor right is in edx.
remainder = allocator_->Allocate(edx);
}
}
ASSERT(remainder.is_register() && remainder.reg().is(edx));
ASSERT(!(left->is_register() && left->reg().is(edx)));
ASSERT(!(right->is_register() && right->reg().is(edx)));
left->ToRegister();
right->ToRegister();
frame_->Spill(eax);
frame_->Spill(edx);
// Check that left and right are smi tagged.
DeferredInlineBinaryOperation* deferred =
new DeferredInlineBinaryOperation(op,
(op == Token::DIV) ? eax : edx,
left->reg(),
right->reg(),
left_type_info,
right_type_info,
overwrite_mode);
if (left->reg().is(right->reg())) {
__ test(left->reg(), Immediate(kSmiTagMask));
} else {
// Use the quotient register as a scratch for the tag check.
if (!left_is_in_eax) __ mov(eax, left->reg());
left_is_in_eax = false; // About to destroy the value in eax.
__ or_(eax, Operand(right->reg()));
ASSERT(kSmiTag == 0); // Adjust test if not the case.
__ test(eax, Immediate(kSmiTagMask));
}
deferred->Branch(not_zero);
if (!left_is_in_eax) __ mov(eax, left->reg());
// Sign extend eax into edx:eax.
__ cdq();
// Check for 0 divisor.
__ test(right->reg(), Operand(right->reg()));
deferred->Branch(zero);
// Divide edx:eax by the right operand.
__ idiv(right->reg());
// Complete the operation.
if (op == Token::DIV) {
// Check for negative zero result. If result is zero, and divisor
// is negative, return a floating point negative zero. The
// virtual frame is unchanged in this block, so local control flow
// can use a Label rather than a JumpTarget. If the context of this
// expression will treat -0 like 0, do not do this test.
if (!expr->no_negative_zero()) {
Label non_zero_result;
__ test(left->reg(), Operand(left->reg()));
__ j(not_zero, &non_zero_result);
__ test(right->reg(), Operand(right->reg()));
deferred->Branch(negative);
__ bind(&non_zero_result);
}
// Check for the corner case of dividing the most negative smi by
// -1. We cannot use the overflow flag, since it is not set by
// idiv instruction.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ cmp(eax, 0x40000000);
deferred->Branch(equal);
// Check that the remainder is zero.
__ test(edx, Operand(edx));
deferred->Branch(not_zero);
// Tag the result and store it in the quotient register.
__ SmiTag(eax);
deferred->BindExit();
left->Unuse();
right->Unuse();
answer = quotient;
} else {
ASSERT(op == Token::MOD);
// Check for a negative zero result. If the result is zero, and
// the dividend is negative, return a floating point negative
// zero. The frame is unchanged in this block, so local control
// flow can use a Label rather than a JumpTarget.
if (!expr->no_negative_zero()) {
Label non_zero_result;
__ test(edx, Operand(edx));
__ j(not_zero, &non_zero_result, taken);
__ test(left->reg(), Operand(left->reg()));
deferred->Branch(negative);
__ bind(&non_zero_result);
}
deferred->BindExit();
left->Unuse();
right->Unuse();
answer = remainder;
}
ASSERT(answer.is_valid());
return answer;
}
// Special handling of shift operations because they use fixed
// registers.
if (op == Token::SHL || op == Token::SHR || op == Token::SAR) {
// Move left out of ecx if necessary.
if (left->is_register() && left->reg().is(ecx)) {
*left = allocator_->Allocate();
ASSERT(left->is_valid());
__ mov(left->reg(), ecx);
}
right->ToRegister(ecx);
left->ToRegister();
ASSERT(left->is_register() && !left->reg().is(ecx));
ASSERT(right->is_register() && right->reg().is(ecx));
// We will modify right, it must be spilled.
frame_->Spill(ecx);
// Use a fresh answer register to avoid spilling the left operand.
answer = allocator_->Allocate();
ASSERT(answer.is_valid());
// Check that both operands are smis using the answer register as a
// temporary.
DeferredInlineBinaryOperation* deferred =
new DeferredInlineBinaryOperation(op,
answer.reg(),
left->reg(),
ecx,
left_type_info,
right_type_info,
overwrite_mode);
Label do_op, left_nonsmi;
// If right is a smi we make a fast case if left is either a smi
// or a heapnumber.
if (CpuFeatures::IsSupported(SSE2) && right_type_info.IsSmi()) {
CpuFeatures::Scope use_sse2(SSE2);
__ mov(answer.reg(), left->reg());
// Fast case - both are actually smis.
if (!left_type_info.IsSmi()) {
__ test(answer.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &left_nonsmi);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left->reg());
}
if (FLAG_debug_code) __ AbortIfNotSmi(right->reg());
__ SmiUntag(answer.reg());
__ jmp(&do_op);
__ bind(&left_nonsmi);
// Branch if not a heapnumber.
__ cmp(FieldOperand(answer.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
deferred->Branch(not_equal);
// Load integer value into answer register using truncation.
__ cvttsd2si(answer.reg(),
FieldOperand(answer.reg(), HeapNumber::kValueOffset));
// Branch if we do not fit in a smi.
__ cmp(answer.reg(), 0xc0000000);
deferred->Branch(negative);
} else {
CheckTwoForSminess(masm_, left->reg(), right->reg(), answer.reg(),
left_type_info, right_type_info, deferred);
// Untag both operands.
__ mov(answer.reg(), left->reg());
__ SmiUntag(answer.reg());
}
__ bind(&do_op);
__ SmiUntag(ecx);
// Perform the operation.
switch (op) {
case Token::SAR:
__ sar_cl(answer.reg());
// No checks of result necessary
break;
case Token::SHR: {
Label result_ok;
__ shr_cl(answer.reg());
// Check that the *unsigned* result fits in a smi. Neither of
// the two high-order bits can be set:
// * 0x80000000: high bit would be lost when smi tagging.
// * 0x40000000: this number would convert to negative when smi
// tagging.
// These two cases can only happen with shifts by 0 or 1 when
// handed a valid smi. If the answer cannot be represented by a
// smi, restore the left and right arguments, and jump to slow
// case. The low bit of the left argument may be lost, but only
// in a case where it is dropped anyway.
__ test(answer.reg(), Immediate(0xc0000000));
__ j(zero, &result_ok);
__ SmiTag(ecx);
deferred->Jump();
__ bind(&result_ok);
break;
}
case Token::SHL: {
Label result_ok;
__ shl_cl(answer.reg());
// Check that the *signed* result fits in a smi.
__ cmp(answer.reg(), 0xc0000000);
__ j(positive, &result_ok);
__ SmiTag(ecx);
deferred->Jump();
__ bind(&result_ok);
break;
}
default:
UNREACHABLE();
}
// Smi-tag the result in answer.
__ SmiTag(answer.reg());
deferred->BindExit();
left->Unuse();
right->Unuse();
ASSERT(answer.is_valid());
return answer;
}
// Handle the other binary operations.
left->ToRegister();
right->ToRegister();
// A newly allocated register answer is used to hold the answer. The
// registers containing left and right are not modified so they don't
// need to be spilled in the fast case.
answer = allocator_->Allocate();
ASSERT(answer.is_valid());
// Perform the smi tag check.
DeferredInlineBinaryOperation* deferred =
new DeferredInlineBinaryOperation(op,
answer.reg(),
left->reg(),
right->reg(),
left_type_info,
right_type_info,
overwrite_mode);
CheckTwoForSminess(masm_, left->reg(), right->reg(), answer.reg(),
left_type_info, right_type_info, deferred);
__ mov(answer.reg(), left->reg());
switch (op) {
case Token::ADD:
__ add(answer.reg(), Operand(right->reg()));
deferred->Branch(overflow);
break;
case Token::SUB:
__ sub(answer.reg(), Operand(right->reg()));
deferred->Branch(overflow);
break;
case Token::MUL: {
// If the smi tag is 0 we can just leave the tag on one operand.
ASSERT(kSmiTag == 0); // Adjust code below if not the case.
// Remove smi tag from the left operand (but keep sign).
// Left-hand operand has been copied into answer.
__ SmiUntag(answer.reg());
// Do multiplication of smis, leaving result in answer.
__ imul(answer.reg(), Operand(right->reg()));
// Go slow on overflows.
deferred->Branch(overflow);
// Check for negative zero result. If product is zero, and one
// argument is negative, go to slow case. The frame is unchanged
// in this block, so local control flow can use a Label rather
// than a JumpTarget.
if (!expr->no_negative_zero()) {
Label non_zero_result;
__ test(answer.reg(), Operand(answer.reg()));
__ j(not_zero, &non_zero_result, taken);
__ mov(answer.reg(), left->reg());
__ or_(answer.reg(), Operand(right->reg()));
deferred->Branch(negative);
__ xor_(answer.reg(), Operand(answer.reg())); // Positive 0 is correct.
__ bind(&non_zero_result);
}
break;
}
case Token::BIT_OR:
__ or_(answer.reg(), Operand(right->reg()));
break;
case Token::BIT_AND:
__ and_(answer.reg(), Operand(right->reg()));
break;
case Token::BIT_XOR:
__ xor_(answer.reg(), Operand(right->reg()));
break;
default:
UNREACHABLE();
break;
}
deferred->BindExit();
left->Unuse();
right->Unuse();
ASSERT(answer.is_valid());
return answer;
}
// Call the appropriate binary operation stub to compute src op value
// and leave the result in dst.
class DeferredInlineSmiOperation: public DeferredCode {
public:
DeferredInlineSmiOperation(Token::Value op,
Register dst,
Register src,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: op_(op),
dst_(dst),
src_(src),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
if (type_info.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
set_comment("[ DeferredInlineSmiOperation");
}
virtual void Generate();
private:
Token::Value op_;
Register dst_;
Register src_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiOperation::Generate() {
// For mod we don't generate all the Smi code inline.
GenericBinaryOpStub stub(
op_,
overwrite_mode_,
(op_ == Token::MOD) ? NO_GENERIC_BINARY_FLAGS : NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
stub.GenerateCall(masm_, src_, value_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// Call the appropriate binary operation stub to compute value op src
// and leave the result in dst.
class DeferredInlineSmiOperationReversed: public DeferredCode {
public:
DeferredInlineSmiOperationReversed(Token::Value op,
Register dst,
Smi* value,
Register src,
TypeInfo type_info,
OverwriteMode overwrite_mode)
: op_(op),
dst_(dst),
type_info_(type_info),
value_(value),
src_(src),
overwrite_mode_(overwrite_mode) {
set_comment("[ DeferredInlineSmiOperationReversed");
}
virtual void Generate();
private:
Token::Value op_;
Register dst_;
TypeInfo type_info_;
Smi* value_;
Register src_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiOperationReversed::Generate() {
GenericBinaryOpStub igostub(
op_,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, value_, src_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The result of src + value is in dst. It either overflowed or was not
// smi tagged. Undo the speculative addition and call the appropriate
// specialized stub for add. The result is left in dst.
class DeferredInlineSmiAdd: public DeferredCode {
public:
DeferredInlineSmiAdd(Register dst,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: dst_(dst),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
if (type_info_.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
set_comment("[ DeferredInlineSmiAdd");
}
virtual void Generate();
private:
Register dst_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiAdd::Generate() {
// Undo the optimistic add operation and call the shared stub.
__ sub(Operand(dst_), Immediate(value_));
GenericBinaryOpStub igostub(
Token::ADD,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, dst_, value_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The result of value + src is in dst. It either overflowed or was not
// smi tagged. Undo the speculative addition and call the appropriate
// specialized stub for add. The result is left in dst.
class DeferredInlineSmiAddReversed: public DeferredCode {
public:
DeferredInlineSmiAddReversed(Register dst,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: dst_(dst),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
set_comment("[ DeferredInlineSmiAddReversed");
}
virtual void Generate();
private:
Register dst_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiAddReversed::Generate() {
// Undo the optimistic add operation and call the shared stub.
__ sub(Operand(dst_), Immediate(value_));
GenericBinaryOpStub igostub(
Token::ADD,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, value_, dst_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The result of src - value is in dst. It either overflowed or was not
// smi tagged. Undo the speculative subtraction and call the
// appropriate specialized stub for subtract. The result is left in
// dst.
class DeferredInlineSmiSub: public DeferredCode {
public:
DeferredInlineSmiSub(Register dst,
TypeInfo type_info,
Smi* value,
OverwriteMode overwrite_mode)
: dst_(dst),
type_info_(type_info),
value_(value),
overwrite_mode_(overwrite_mode) {
if (type_info.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
set_comment("[ DeferredInlineSmiSub");
}
virtual void Generate();
private:
Register dst_;
TypeInfo type_info_;
Smi* value_;
OverwriteMode overwrite_mode_;
};
void DeferredInlineSmiSub::Generate() {
// Undo the optimistic sub operation and call the shared stub.
__ add(Operand(dst_), Immediate(value_));
GenericBinaryOpStub igostub(
Token::SUB,
overwrite_mode_,
NO_SMI_CODE_IN_STUB,
TypeInfo::Combine(TypeInfo::Smi(), type_info_));
igostub.GenerateCall(masm_, dst_, value_);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
Result CodeGenerator::ConstantSmiBinaryOperation(BinaryOperation* expr,
Result* operand,
Handle<Object> value,
bool reversed,
OverwriteMode overwrite_mode) {
// Generate inline code for a binary operation when one of the
// operands is a constant smi. Consumes the argument "operand".
if (IsUnsafeSmi(value)) {
Result unsafe_operand(value);
if (reversed) {
return LikelySmiBinaryOperation(expr, &unsafe_operand, operand,
overwrite_mode);
} else {
return LikelySmiBinaryOperation(expr, operand, &unsafe_operand,
overwrite_mode);
}
}
// Get the literal value.
Smi* smi_value = Smi::cast(*value);
int int_value = smi_value->value();
Token::Value op = expr->op();
Result answer;
switch (op) {
case Token::ADD: {
operand->ToRegister();
frame_->Spill(operand->reg());
// Optimistically add. Call the specialized add stub if the
// result is not a smi or overflows.
DeferredCode* deferred = NULL;
if (reversed) {
deferred = new DeferredInlineSmiAddReversed(operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
} else {
deferred = new DeferredInlineSmiAdd(operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
}
__ add(Operand(operand->reg()), Immediate(value));
deferred->Branch(overflow);
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
deferred->BindExit();
answer = *operand;
break;
}
case Token::SUB: {
DeferredCode* deferred = NULL;
if (reversed) {
// The reversed case is only hit when the right operand is not a
// constant.
ASSERT(operand->is_register());
answer = allocator()->Allocate();
ASSERT(answer.is_valid());
__ Set(answer.reg(), Immediate(value));
deferred =
new DeferredInlineSmiOperationReversed(op,
answer.reg(),
smi_value,
operand->reg(),
operand->type_info(),
overwrite_mode);
__ sub(answer.reg(), Operand(operand->reg()));
} else {
operand->ToRegister();
frame_->Spill(operand->reg());
answer = *operand;
deferred = new DeferredInlineSmiSub(operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
__ sub(Operand(operand->reg()), Immediate(value));
}
deferred->Branch(overflow);
if (!operand->type_info().IsSmi()) {
__ test(answer.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
deferred->BindExit();
operand->Unuse();
break;
}
case Token::SAR:
if (reversed) {
Result constant_operand(value);
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
// Only the least significant 5 bits of the shift value are used.
// In the slow case, this masking is done inside the runtime call.
int shift_value = int_value & 0x1f;
operand->ToRegister();
frame_->Spill(operand->reg());
if (!operand->type_info().IsSmi()) {
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
if (shift_value > 0) {
__ sar(operand->reg(), shift_value);
__ and_(operand->reg(), ~kSmiTagMask);
}
deferred->BindExit();
} else {
if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
if (shift_value > 0) {
__ sar(operand->reg(), shift_value);
__ and_(operand->reg(), ~kSmiTagMask);
}
}
answer = *operand;
}
break;
case Token::SHR:
if (reversed) {
Result constant_operand(value);
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
// Only the least significant 5 bits of the shift value are used.
// In the slow case, this masking is done inside the runtime call.
int shift_value = int_value & 0x1f;
operand->ToRegister();
answer = allocator()->Allocate();
ASSERT(answer.is_valid());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
answer.reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
__ mov(answer.reg(), operand->reg());
__ SmiUntag(answer.reg());
__ shr(answer.reg(), shift_value);
// A negative Smi shifted right two is in the positive Smi range.
if (shift_value < 2) {
__ test(answer.reg(), Immediate(0xc0000000));
deferred->Branch(not_zero);
}
operand->Unuse();
__ SmiTag(answer.reg());
deferred->BindExit();
}
break;
case Token::SHL:
if (reversed) {
// Move operand into ecx and also into a second register.
// If operand is already in a register, take advantage of that.
// This lets us modify ecx, but still bail out to deferred code.
Result right;
Result right_copy_in_ecx;
TypeInfo right_type_info = operand->type_info();
operand->ToRegister();
if (operand->reg().is(ecx)) {
right = allocator()->Allocate();
__ mov(right.reg(), ecx);
frame_->Spill(ecx);
right_copy_in_ecx = *operand;
} else {
right_copy_in_ecx = allocator()->Allocate(ecx);
__ mov(ecx, operand->reg());
right = *operand;
}
operand->Unuse();
answer = allocator()->Allocate();
DeferredInlineSmiOperationReversed* deferred =
new DeferredInlineSmiOperationReversed(op,
answer.reg(),
smi_value,
right.reg(),
right_type_info,
overwrite_mode);
__ mov(answer.reg(), Immediate(int_value));
__ sar(ecx, kSmiTagSize);
if (!right_type_info.IsSmi()) {
deferred->Branch(carry);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(right.reg());
}
__ shl_cl(answer.reg());
__ cmp(answer.reg(), 0xc0000000);
deferred->Branch(sign);
__ SmiTag(answer.reg());
deferred->BindExit();
} else {
// Only the least significant 5 bits of the shift value are used.
// In the slow case, this masking is done inside the runtime call.
int shift_value = int_value & 0x1f;
operand->ToRegister();
if (shift_value == 0) {
// Spill operand so it can be overwritten in the slow case.
frame_->Spill(operand->reg());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
deferred->BindExit();
answer = *operand;
} else {
// Use a fresh temporary for nonzero shift values.
answer = allocator()->Allocate();
ASSERT(answer.is_valid());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
answer.reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
__ mov(answer.reg(), operand->reg());
ASSERT(kSmiTag == 0); // adjust code if not the case
// We do no shifts, only the Smi conversion, if shift_value is 1.
if (shift_value > 1) {
__ shl(answer.reg(), shift_value - 1);
}
// Convert int result to Smi, checking that it is in int range.
ASSERT(kSmiTagSize == 1); // adjust code if not the case
__ add(answer.reg(), Operand(answer.reg()));
deferred->Branch(overflow);
deferred->BindExit();
operand->Unuse();
}
}
break;
case Token::BIT_OR:
case Token::BIT_XOR:
case Token::BIT_AND: {
operand->ToRegister();
frame_->Spill(operand->reg());
DeferredCode* deferred = NULL;
if (reversed) {
deferred =
new DeferredInlineSmiOperationReversed(op,
operand->reg(),
smi_value,
operand->reg(),
operand->type_info(),
overwrite_mode);
} else {
deferred = new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
}
if (!operand->type_info().IsSmi()) {
__ test(operand->reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else if (FLAG_debug_code) {
__ AbortIfNotSmi(operand->reg());
}
if (op == Token::BIT_AND) {
__ and_(Operand(operand->reg()), Immediate(value));
} else if (op == Token::BIT_XOR) {
if (int_value != 0) {
__ xor_(Operand(operand->reg()), Immediate(value));
}
} else {
ASSERT(op == Token::BIT_OR);
if (int_value != 0) {
__ or_(Operand(operand->reg()), Immediate(value));
}
}
deferred->BindExit();
answer = *operand;
break;
}
case Token::DIV:
if (!reversed && int_value == 2) {
operand->ToRegister();
frame_->Spill(operand->reg());
DeferredInlineSmiOperation* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
// Check that lowest log2(value) bits of operand are zero, and test
// smi tag at the same time.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize);
__ test(operand->reg(), Immediate(3));
deferred->Branch(not_zero); // Branch if non-smi or odd smi.
__ sar(operand->reg(), 1);
deferred->BindExit();
answer = *operand;
} else {
// Cannot fall through MOD to default case, so we duplicate the
// default case here.
Result constant_operand(value);
if (reversed) {
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
answer = LikelySmiBinaryOperation(expr, operand, &constant_operand,
overwrite_mode);
}
}
break;
// Generate inline code for mod of powers of 2 and negative powers of 2.
case Token::MOD:
if (!reversed &&
int_value != 0 &&
(IsPowerOf2(int_value) || IsPowerOf2(-int_value))) {
operand->ToRegister();
frame_->Spill(operand->reg());
DeferredCode* deferred =
new DeferredInlineSmiOperation(op,
operand->reg(),
operand->reg(),
operand->type_info(),
smi_value,
overwrite_mode);
// Check for negative or non-Smi left hand side.
__ test(operand->reg(), Immediate(kSmiTagMask | kSmiSignMask));
deferred->Branch(not_zero);
if (int_value < 0) int_value = -int_value;
if (int_value == 1) {
__ mov(operand->reg(), Immediate(Smi::FromInt(0)));
} else {
__ and_(operand->reg(), (int_value << kSmiTagSize) - 1);
}
deferred->BindExit();
answer = *operand;
break;
}
// Fall through if we did not find a power of 2 on the right hand side!
default: {
Result constant_operand(value);
if (reversed) {
answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
overwrite_mode);
} else {
answer = LikelySmiBinaryOperation(expr, operand, &constant_operand,
overwrite_mode);
}
break;
}
}
ASSERT(answer.is_valid());
return answer;
}
static bool CouldBeNaN(const Result& result) {
if (result.type_info().IsSmi()) return false;
if (result.type_info().IsInteger32()) return false;
if (!result.is_constant()) return true;
if (!result.handle()->IsHeapNumber()) return false;
return isnan(HeapNumber::cast(*result.handle())->value());
}
// Convert from signed to unsigned comparison to match the way EFLAGS are set
// by FPU and XMM compare instructions.
static Condition DoubleCondition(Condition cc) {
switch (cc) {
case less: return below;
case equal: return equal;
case less_equal: return below_equal;
case greater: return above;
case greater_equal: return above_equal;
default: UNREACHABLE();
}
UNREACHABLE();
return equal;
}
void CodeGenerator::Comparison(AstNode* node,
Condition cc,
bool strict,
ControlDestination* dest) {
// Strict only makes sense for equality comparisons.
ASSERT(!strict || cc == equal);
Result left_side;
Result right_side;
// Implement '>' and '<=' by reversal to obtain ECMA-262 conversion order.
if (cc == greater || cc == less_equal) {
cc = ReverseCondition(cc);
left_side = frame_->Pop();
right_side = frame_->Pop();
} else {
right_side = frame_->Pop();
left_side = frame_->Pop();
}
ASSERT(cc == less || cc == equal || cc == greater_equal);
// If either side is a constant of some sort, we can probably optimize the
// comparison.
bool left_side_constant_smi = false;
bool left_side_constant_null = false;
bool left_side_constant_1_char_string = false;
if (left_side.is_constant()) {
left_side_constant_smi = left_side.handle()->IsSmi();
left_side_constant_null = left_side.handle()->IsNull();
left_side_constant_1_char_string =
(left_side.handle()->IsString() &&
String::cast(*left_side.handle())->length() == 1 &&
String::cast(*left_side.handle())->IsAsciiRepresentation());
}
bool right_side_constant_smi = false;
bool right_side_constant_null = false;
bool right_side_constant_1_char_string = false;
if (right_side.is_constant()) {
right_side_constant_smi = right_side.handle()->IsSmi();
right_side_constant_null = right_side.handle()->IsNull();
right_side_constant_1_char_string =
(right_side.handle()->IsString() &&
String::cast(*right_side.handle())->length() == 1 &&
String::cast(*right_side.handle())->IsAsciiRepresentation());
}
if (left_side_constant_smi || right_side_constant_smi) {
if (left_side_constant_smi && right_side_constant_smi) {
// Trivial case, comparing two constants.
int left_value = Smi::cast(*left_side.handle())->value();
int right_value = Smi::cast(*right_side.handle())->value();
switch (cc) {
case less:
dest->Goto(left_value < right_value);
break;
case equal:
dest->Goto(left_value == right_value);
break;
case greater_equal:
dest->Goto(left_value >= right_value);
break;
default:
UNREACHABLE();
}
} else {
// Only one side is a constant Smi.
// If left side is a constant Smi, reverse the operands.
// Since one side is a constant Smi, conversion order does not matter.
if (left_side_constant_smi) {
Result temp = left_side;
left_side = right_side;
right_side = temp;
cc = ReverseCondition(cc);
// This may re-introduce greater or less_equal as the value of cc.
// CompareStub and the inline code both support all values of cc.
}
// Implement comparison against a constant Smi, inlining the case
// where both sides are Smis.
left_side.ToRegister();
Register left_reg = left_side.reg();
Handle<Object> right_val = right_side.handle();
// Here we split control flow to the stub call and inlined cases
// before finally splitting it to the control destination. We use
// a jump target and branching to duplicate the virtual frame at
// the first split. We manually handle the off-frame references
// by reconstituting them on the non-fall-through path.
if (left_side.is_smi()) {
if (FLAG_debug_code) {
__ AbortIfNotSmi(left_side.reg());
}
} else {
JumpTarget is_smi;
__ test(left_side.reg(), Immediate(kSmiTagMask));
is_smi.Branch(zero, taken);
bool is_loop_condition = (node->AsExpression() != NULL) &&
node->AsExpression()->is_loop_condition();
if (!is_loop_condition &&
CpuFeatures::IsSupported(SSE2) &&
right_val->IsSmi()) {
// Right side is a constant smi and left side has been checked
// not to be a smi.
CpuFeatures::Scope use_sse2(SSE2);
JumpTarget not_number;
__ cmp(FieldOperand(left_reg, HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
not_number.Branch(not_equal, &left_side);
__ movdbl(xmm1,
FieldOperand(left_reg, HeapNumber::kValueOffset));
int value = Smi::cast(*right_val)->value();
if (value == 0) {
__ xorpd(xmm0, xmm0);
} else {
Result temp = allocator()->Allocate();
__ mov(temp.reg(), Immediate(value));
__ cvtsi2sd(xmm0, Operand(temp.reg()));
temp.Unuse();
}
__ ucomisd(xmm1, xmm0);
// Jump to builtin for NaN.
not_number.Branch(parity_even, &left_side);
left_side.Unuse();
dest->true_target()->Branch(DoubleCondition(cc));
dest->false_target()->Jump();
not_number.Bind(&left_side);
}
// Setup and call the compare stub.
CompareStub stub(cc, strict, kCantBothBeNaN);
Result result = frame_->CallStub(&stub, &left_side, &right_side);
result.ToRegister();
__ cmp(result.reg(), 0);
result.Unuse();
dest->true_target()->Branch(cc);
dest->false_target()->Jump();
is_smi.Bind();
}
left_side = Result(left_reg);
right_side = Result(right_val);
// Test smi equality and comparison by signed int comparison.
if (IsUnsafeSmi(right_side.handle())) {
right_side.ToRegister();
__ cmp(left_side.reg(), Operand(right_side.reg()));
} else {
__ cmp(Operand(left_side.reg()), Immediate(right_side.handle()));
}
left_side.Unuse();
right_side.Unuse();
dest->Split(cc);
}
} else if (cc == equal &&
(left_side_constant_null || right_side_constant_null)) {
// To make null checks efficient, we check if either the left side or
// the right side is the constant 'null'.
// If so, we optimize the code by inlining a null check instead of
// calling the (very) general runtime routine for checking equality.
Result operand = left_side_constant_null ? right_side : left_side;
right_side.Unuse();
left_side.Unuse();
operand.ToRegister();
__ cmp(operand.reg(), Factory::null_value());
if (strict) {
operand.Unuse();
dest->Split(equal);
} else {
// The 'null' value is only equal to 'undefined' if using non-strict
// comparisons.
dest->true_target()->Branch(equal);
__ cmp(operand.reg(), Factory::undefined_value());
dest->true_target()->Branch(equal);
__ test(operand.reg(), Immediate(kSmiTagMask));
dest->false_target()->Branch(equal);
// It can be an undetectable object.
// Use a scratch register in preference to spilling operand.reg().
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(),
FieldOperand(operand.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
temp.Unuse();
operand.Unuse();
dest->Split(not_zero);
}
} else if (left_side_constant_1_char_string ||
right_side_constant_1_char_string) {
if (left_side_constant_1_char_string && right_side_constant_1_char_string) {
// Trivial case, comparing two constants.
int left_value = String::cast(*left_side.handle())->Get(0);
int right_value = String::cast(*right_side.handle())->Get(0);
switch (cc) {
case less:
dest->Goto(left_value < right_value);
break;
case equal:
dest->Goto(left_value == right_value);
break;
case greater_equal:
dest->Goto(left_value >= right_value);
break;
default:
UNREACHABLE();
}
} else {
// Only one side is a constant 1 character string.
// If left side is a constant 1-character string, reverse the operands.
// Since one side is a constant string, conversion order does not matter.
if (left_side_constant_1_char_string) {
Result temp = left_side;
left_side = right_side;
right_side = temp;
cc = ReverseCondition(cc);
// This may reintroduce greater or less_equal as the value of cc.
// CompareStub and the inline code both support all values of cc.
}
// Implement comparison against a constant string, inlining the case
// where both sides are strings.
left_side.ToRegister();
// Here we split control flow to the stub call and inlined cases
// before finally splitting it to the control destination. We use
// a jump target and branching to duplicate the virtual frame at
// the first split. We manually handle the off-frame references
// by reconstituting them on the non-fall-through path.
JumpTarget is_not_string, is_string;
Register left_reg = left_side.reg();
Handle<Object> right_val = right_side.handle();
ASSERT(StringShape(String::cast(*right_val)).IsSymbol());
__ test(left_side.reg(), Immediate(kSmiTagMask));
is_not_string.Branch(zero, &left_side);
Result temp = allocator_->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(),
FieldOperand(left_side.reg(), HeapObject::kMapOffset));
__ movzx_b(temp.reg(),
FieldOperand(temp.reg(), Map::kInstanceTypeOffset));
// If we are testing for equality then make use of the symbol shortcut.
// Check if the right left hand side has the same type as the left hand
// side (which is always a symbol).
if (cc == equal) {
Label not_a_symbol;
ASSERT(kSymbolTag != 0);
// Ensure that no non-strings have the symbol bit set.
ASSERT(kNotStringTag + kIsSymbolMask > LAST_TYPE);
__ test(temp.reg(), Immediate(kIsSymbolMask)); // Test the symbol bit.
__ j(zero, ¬_a_symbol);
// They are symbols, so do identity compare.
__ cmp(left_side.reg(), right_side.handle());
dest->true_target()->Branch(equal);
dest->false_target()->Branch(not_equal);
__ bind(¬_a_symbol);
}
// Call the compare stub if the left side is not a flat ascii string.
__ and_(temp.reg(),
kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
__ cmp(temp.reg(), kStringTag | kSeqStringTag | kAsciiStringTag);
temp.Unuse();
is_string.Branch(equal, &left_side);
// Setup and call the compare stub.
is_not_string.Bind(&left_side);
CompareStub stub(cc, strict, kCantBothBeNaN);
Result result = frame_->CallStub(&stub, &left_side, &right_side);
result.ToRegister();
__ cmp(result.reg(), 0);
result.Unuse();
dest->true_target()->Branch(cc);
dest->false_target()->Jump();
is_string.Bind(&left_side);
// left_side is a sequential ASCII string.
left_side = Result(left_reg);
right_side = Result(right_val);
// Test string equality and comparison.
Label comparison_done;
if (cc == equal) {
__ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Immediate(Smi::FromInt(1)));
__ j(not_equal, &comparison_done);
uint8_t char_value =
static_cast<uint8_t>(String::cast(*right_val)->Get(0));
__ cmpb(FieldOperand(left_side.reg(), SeqAsciiString::kHeaderSize),
char_value);
} else {
__ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Immediate(Smi::FromInt(1)));
// If the length is 0 then the jump is taken and the flags
// correctly represent being less than the one-character string.
__ j(below, &comparison_done);
// Compare the first character of the string with the
// constant 1-character string.
uint8_t char_value =
static_cast<uint8_t>(String::cast(*right_val)->Get(0));
__ cmpb(FieldOperand(left_side.reg(), SeqAsciiString::kHeaderSize),
char_value);
__ j(not_equal, &comparison_done);
// If the first character is the same then the long string sorts after
// the short one.
__ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Immediate(Smi::FromInt(1)));
}
__ bind(&comparison_done);
left_side.Unuse();
right_side.Unuse();
dest->Split(cc);
}
} else {
// Neither side is a constant Smi, constant 1-char string or constant null.
// If either side is a non-smi constant, or known to be a heap number skip
// the smi check.
bool known_non_smi =
(left_side.is_constant() && !left_side.handle()->IsSmi()) ||
(right_side.is_constant() && !right_side.handle()->IsSmi()) ||
left_side.type_info().IsDouble() ||
right_side.type_info().IsDouble();
NaNInformation nan_info =
(CouldBeNaN(left_side) && CouldBeNaN(right_side)) ?
kBothCouldBeNaN :
kCantBothBeNaN;
// Inline number comparison handling any combination of smi's and heap
// numbers if:
// code is in a loop
// the compare operation is different from equal
// compare is not a for-loop comparison
// The reason for excluding equal is that it will most likely be done
// with smi's (not heap numbers) and the code to comparing smi's is inlined
// separately. The same reason applies for for-loop comparison which will
// also most likely be smi comparisons.
bool is_loop_condition = (node->AsExpression() != NULL)
&& node->AsExpression()->is_loop_condition();
bool inline_number_compare =
loop_nesting() > 0 && cc != equal && !is_loop_condition;
// Left and right needed in registers for the following code.
left_side.ToRegister();
right_side.ToRegister();
if (known_non_smi) {
// Inline the equality check if both operands can't be a NaN. If both
// objects are the same they are equal.
if (nan_info == kCantBothBeNaN && cc == equal) {
__ cmp(left_side.reg(), Operand(right_side.reg()));
dest->true_target()->Branch(equal);
}
// Inline number comparison.
if (inline_number_compare) {
GenerateInlineNumberComparison(&left_side, &right_side, cc, dest);
}
// End of in-line compare, call out to the compare stub. Don't include
// number comparison in the stub if it was inlined.
CompareStub stub(cc, strict, nan_info, !inline_number_compare);
Result answer = frame_->CallStub(&stub, &left_side, &right_side);
__ test(answer.reg(), Operand(answer.reg()));
answer.Unuse();
dest->Split(cc);
} else {
// Here we split control flow to the stub call and inlined cases
// before finally splitting it to the control destination. We use
// a jump target and branching to duplicate the virtual frame at
// the first split. We manually handle the off-frame references
// by reconstituting them on the non-fall-through path.
JumpTarget is_smi;
Register left_reg = left_side.reg();
Register right_reg = right_side.reg();
// In-line check for comparing two smis.
Result temp = allocator_->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), left_side.reg());
__ or_(temp.reg(), Operand(right_side.reg()));
__ test(temp.reg(), Immediate(kSmiTagMask));
temp.Unuse();
is_smi.Branch(zero, taken);
// Inline the equality check if both operands can't be a NaN. If both
// objects are the same they are equal.
if (nan_info == kCantBothBeNaN && cc == equal) {
__ cmp(left_side.reg(), Operand(right_side.reg()));
dest->true_target()->Branch(equal);
}
// Inline number comparison.
if (inline_number_compare) {
GenerateInlineNumberComparison(&left_side, &right_side, cc, dest);
}
// End of in-line compare, call out to the compare stub. Don't include
// number comparison in the stub if it was inlined.
CompareStub stub(cc, strict, nan_info, !inline_number_compare);
Result answer = frame_->CallStub(&stub, &left_side, &right_side);
__ test(answer.reg(), Operand(answer.reg()));
answer.Unuse();
dest->true_target()->Branch(cc);
dest->false_target()->Jump();
is_smi.Bind();
left_side = Result(left_reg);
right_side = Result(right_reg);
__ cmp(left_side.reg(), Operand(right_side.reg()));
right_side.Unuse();
left_side.Unuse();
dest->Split(cc);
}
}
}
// Check that the comparison operand is a number. Jump to not_numbers jump
// target passing the left and right result if the operand is not a number.
static void CheckComparisonOperand(MacroAssembler* masm_,
Result* operand,
Result* left_side,
Result* right_side,
JumpTarget* not_numbers) {
// Perform check if operand is not known to be a number.
if (!operand->type_info().IsNumber()) {
Label done;
__ test(operand->reg(), Immediate(kSmiTagMask));
__ j(zero, &done);
__ cmp(FieldOperand(operand->reg(), HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
not_numbers->Branch(not_equal, left_side, right_side, not_taken);
__ bind(&done);
}
}
// Load a comparison operand to the FPU stack. This assumes that the operand has
// already been checked and is a number.
static void LoadComparisonOperand(MacroAssembler* masm_,
Result* operand) {
Label done;
if (operand->type_info().IsDouble()) {
// Operand is known to be a heap number, just load it.
__ fld_d(FieldOperand(operand->reg(), HeapNumber::kValueOffset));
} else if (operand->type_info().IsSmi()) {
// Operand is known to be a smi. Convert it to double and keep the original
// smi.
__ SmiUntag(operand->reg());
__ push(operand->reg());
__ fild_s(Operand(esp, 0));
__ pop(operand->reg());
__ SmiTag(operand->reg());
} else {
// Operand type not known, check for smi otherwise assume heap number.
Label smi;
__ test(operand->reg(), Immediate(kSmiTagMask));
__ j(zero, &smi);
__ fld_d(FieldOperand(operand->reg(), HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&smi);
__ SmiUntag(operand->reg());
__ push(operand->reg());
__ fild_s(Operand(esp, 0));
__ pop(operand->reg());
__ SmiTag(operand->reg());
__ jmp(&done);
}
__ bind(&done);
}
// Load a comparison operand into into a XMM register. Jump to not_numbers jump
// target passing the left and right result if the operand is not a number.
static void LoadComparisonOperandSSE2(MacroAssembler* masm_,
Result* operand,
XMMRegister reg,
Result* left_side,
Result* right_side,
JumpTarget* not_numbers) {
Label done;
if (operand->type_info().IsDouble()) {
// Operand is known to be a heap number, just load it.
__ movdbl(reg, FieldOperand(operand->reg(), HeapNumber::kValueOffset));
} else if (operand->type_info().IsSmi()) {
// Operand is known to be a smi. Convert it to double and keep the original
// smi.
__ SmiUntag(operand->reg());
__ cvtsi2sd(reg, Operand(operand->reg()));
__ SmiTag(operand->reg());
} else {
// Operand type not known, check for smi or heap number.
Label smi;
__ test(operand->reg(), Immediate(kSmiTagMask));
__ j(zero, &smi);
if (!operand->type_info().IsNumber()) {
__ cmp(FieldOperand(operand->reg(), HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
not_numbers->Branch(not_equal, left_side, right_side, taken);
}
__ movdbl(reg, FieldOperand(operand->reg(), HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&smi);
// Comvert smi to float and keep the original smi.
__ SmiUntag(operand->reg());
__ cvtsi2sd(reg, Operand(operand->reg()));
__ SmiTag(operand->reg());
__ jmp(&done);
}
__ bind(&done);
}
void CodeGenerator::GenerateInlineNumberComparison(Result* left_side,
Result* right_side,
Condition cc,
ControlDestination* dest) {
ASSERT(left_side->is_register());
ASSERT(right_side->is_register());
JumpTarget not_numbers;
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
// Load left and right operand into registers xmm0 and xmm1 and compare.
LoadComparisonOperandSSE2(masm_, left_side, xmm0, left_side, right_side,
¬_numbers);
LoadComparisonOperandSSE2(masm_, right_side, xmm1, left_side, right_side,
¬_numbers);
__ comisd(xmm0, xmm1);
} else {
Label check_right, compare;
// Make sure that both comparison operands are numbers.
CheckComparisonOperand(masm_, left_side, left_side, right_side,
¬_numbers);
CheckComparisonOperand(masm_, right_side, left_side, right_side,
¬_numbers);
// Load right and left operand to FPU stack and compare.
LoadComparisonOperand(masm_, right_side);
LoadComparisonOperand(masm_, left_side);
__ FCmp();
}
// Bail out if a NaN is involved.
not_numbers.Branch(parity_even, left_side, right_side, not_taken);
// Split to destination targets based on comparison.
left_side->Unuse();
right_side->Unuse();
dest->true_target()->Branch(DoubleCondition(cc));
dest->false_target()->Jump();
not_numbers.Bind(left_side, right_side);
}
// Call the function just below TOS on the stack with the given
// arguments. The receiver is the TOS.
void CodeGenerator::CallWithArguments(ZoneList<Expression*>* args,
CallFunctionFlags flags,
int position) {
// Push the arguments ("left-to-right") on the stack.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Record the position for debugging purposes.
CodeForSourcePosition(position);
// Use the shared code stub to call the function.
InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
CallFunctionStub call_function(arg_count, in_loop, flags);
Result answer = frame_->CallStub(&call_function, arg_count + 1);
// Restore context and replace function on the stack with the
// result of the stub invocation.
frame_->RestoreContextRegister();
frame_->SetElementAt(0, &answer);
}
void CodeGenerator::CallApplyLazy(Expression* applicand,
Expression* receiver,
VariableProxy* arguments,
int position) {
// An optimized implementation of expressions of the form
// x.apply(y, arguments).
// If the arguments object of the scope has not been allocated,
// and x.apply is Function.prototype.apply, this optimization
// just copies y and the arguments of the current function on the
// stack, as receiver and arguments, and calls x.
// In the implementation comments, we call x the applicand
// and y the receiver.
ASSERT(ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION);
ASSERT(arguments->IsArguments());
// Load applicand.apply onto the stack. This will usually
// give us a megamorphic load site. Not super, but it works.
Load(applicand);
frame()->Dup();
Handle<String> name = Factory::LookupAsciiSymbol("apply");
frame()->Push(name);
Result answer = frame()->CallLoadIC(RelocInfo::CODE_TARGET);
__ nop();
frame()->Push(&answer);
// Load the receiver and the existing arguments object onto the
// expression stack. Avoid allocating the arguments object here.
Load(receiver);
LoadFromSlot(scope()->arguments()->var()->slot(), NOT_INSIDE_TYPEOF);
// Emit the source position information after having loaded the
// receiver and the arguments.
CodeForSourcePosition(position);
// Contents of frame at this point:
// Frame[0]: arguments object of the current function or the hole.
// Frame[1]: receiver
// Frame[2]: applicand.apply
// Frame[3]: applicand.
// Check if the arguments object has been lazily allocated
// already. If so, just use that instead of copying the arguments
// from the stack. This also deals with cases where a local variable
// named 'arguments' has been introduced.
frame_->Dup();
Result probe = frame_->Pop();
{ VirtualFrame::SpilledScope spilled_scope;
Label slow, done;
bool try_lazy = true;
if (probe.is_constant()) {
try_lazy = probe.handle()->IsTheHole();
} else {
__ cmp(Operand(probe.reg()), Immediate(Factory::the_hole_value()));
probe.Unuse();
__ j(not_equal, &slow);
}
if (try_lazy) {
Label build_args;
// Get rid of the arguments object probe.
frame_->Drop(); // Can be called on a spilled frame.
// Stack now has 3 elements on it.
// Contents of stack at this point:
// esp[0]: receiver
// esp[1]: applicand.apply
// esp[2]: applicand.
// Check that the receiver really is a JavaScript object.
__ mov(eax, Operand(esp, 0));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &build_args);
// We allow all JSObjects including JSFunctions. As long as
// JS_FUNCTION_TYPE is the last instance type and it is right
// after LAST_JS_OBJECT_TYPE, we do not have to check the upper
// bound.
ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
__ j(below, &build_args);
// Check that applicand.apply is Function.prototype.apply.
__ mov(eax, Operand(esp, kPointerSize));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &build_args);
__ CmpObjectType(eax, JS_FUNCTION_TYPE, ecx);
__ j(not_equal, &build_args);
__ mov(ecx, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
Handle<Code> apply_code(Builtins::builtin(Builtins::FunctionApply));
__ cmp(FieldOperand(ecx, SharedFunctionInfo::kCodeOffset),
Immediate(apply_code));
__ j(not_equal, &build_args);
// Check that applicand is a function.
__ mov(edi, Operand(esp, 2 * kPointerSize));
__ test(edi, Immediate(kSmiTagMask));
__ j(zero, &build_args);
__ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
__ j(not_equal, &build_args);
// Copy the arguments to this function possibly from the
// adaptor frame below it.
Label invoke, adapted;
__ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
__ cmp(Operand(ecx),
Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &adapted);
// No arguments adaptor frame. Copy fixed number of arguments.
__ mov(eax, Immediate(scope()->num_parameters()));
for (int i = 0; i < scope()->num_parameters(); i++) {
__ push(frame_->ParameterAt(i));
}
__ jmp(&invoke);
// Arguments adaptor frame present. Copy arguments from there, but
// avoid copying too many arguments to avoid stack overflows.
__ bind(&adapted);
static const uint32_t kArgumentsLimit = 1 * KB;
__ mov(eax, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ SmiUntag(eax);
__ mov(ecx, Operand(eax));
__ cmp(eax, kArgumentsLimit);
__ j(above, &build_args);
// Loop through the arguments pushing them onto the execution
// stack. We don't inform the virtual frame of the push, so we don't
// have to worry about getting rid of the elements from the virtual
// frame.
Label loop;
// ecx is a small non-negative integer, due to the test above.
__ test(ecx, Operand(ecx));
__ j(zero, &invoke);
__ bind(&loop);
__ push(Operand(edx, ecx, times_pointer_size, 1 * kPointerSize));
__ dec(ecx);
__ j(not_zero, &loop);
// Invoke the function.
__ bind(&invoke);
ParameterCount actual(eax);
__ InvokeFunction(edi, actual, CALL_FUNCTION);
// Drop applicand.apply and applicand from the stack, and push
// the result of the function call, but leave the spilled frame
// unchanged, with 3 elements, so it is correct when we compile the
// slow-case code.
__ add(Operand(esp), Immediate(2 * kPointerSize));
__ push(eax);
// Stack now has 1 element:
// esp[0]: result
__ jmp(&done);
// Slow-case: Allocate the arguments object since we know it isn't
// there, and fall-through to the slow-case where we call
// applicand.apply.
__ bind(&build_args);
// Stack now has 3 elements, because we have jumped from where:
// esp[0]: receiver
// esp[1]: applicand.apply
// esp[2]: applicand.
// StoreArgumentsObject requires a correct frame, and may modify it.
Result arguments_object = StoreArgumentsObject(false);
frame_->SpillAll();
arguments_object.ToRegister();
frame_->EmitPush(arguments_object.reg());
arguments_object.Unuse();
// Stack and frame now have 4 elements.
__ bind(&slow);
}
// Generic computation of x.apply(y, args) with no special optimization.
// Flip applicand.apply and applicand on the stack, so
// applicand looks like the receiver of the applicand.apply call.
// Then process it as a normal function call.
__ mov(eax, Operand(esp, 3 * kPointerSize));
__ mov(ebx, Operand(esp, 2 * kPointerSize));
__ mov(Operand(esp, 2 * kPointerSize), eax);
__ mov(Operand(esp, 3 * kPointerSize), ebx);
CallFunctionStub call_function(2, NOT_IN_LOOP, NO_CALL_FUNCTION_FLAGS);
Result res = frame_->CallStub(&call_function, 3);
// The function and its two arguments have been dropped.
frame_->Drop(1); // Drop the receiver as well.
res.ToRegister();
frame_->EmitPush(res.reg());
// Stack now has 1 element:
// esp[0]: result
if (try_lazy) __ bind(&done);
} // End of spilled scope.
// Restore the context register after a call.
frame_->RestoreContextRegister();
}
class DeferredStackCheck: public DeferredCode {
public:
DeferredStackCheck() {
set_comment("[ DeferredStackCheck");
}
virtual void Generate();
};
void DeferredStackCheck::Generate() {
StackCheckStub stub;
__ CallStub(&stub);
}
void CodeGenerator::CheckStack() {
DeferredStackCheck* deferred = new DeferredStackCheck;
ExternalReference stack_limit =
ExternalReference::address_of_stack_limit();
__ cmp(esp, Operand::StaticVariable(stack_limit));
deferred->Branch(below);
deferred->BindExit();
}
void CodeGenerator::VisitAndSpill(Statement* statement) {
ASSERT(in_spilled_code());
set_in_spilled_code(false);
Visit(statement);
if (frame_ != NULL) {
frame_->SpillAll();
}
set_in_spilled_code(true);
}
void CodeGenerator::VisitStatementsAndSpill(ZoneList<Statement*>* statements) {
ASSERT(in_spilled_code());
set_in_spilled_code(false);
VisitStatements(statements);
if (frame_ != NULL) {
frame_->SpillAll();
}
set_in_spilled_code(true);
}
void CodeGenerator::VisitStatements(ZoneList<Statement*>* statements) {
ASSERT(!in_spilled_code());
for (int i = 0; has_valid_frame() && i < statements->length(); i++) {
Visit(statements->at(i));
}
}
void CodeGenerator::VisitBlock(Block* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ Block");
CodeForStatementPosition(node);
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
VisitStatements(node->statements());
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
node->break_target()->Unuse();
}
void CodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
// Call the runtime to declare the globals. The inevitable call
// will sync frame elements to memory anyway, so we do it eagerly to
// allow us to push the arguments directly into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi); // The context is the first argument.
frame_->EmitPush(Immediate(pairs));
frame_->EmitPush(Immediate(Smi::FromInt(is_eval() ? 1 : 0)));
Result ignored = frame_->CallRuntime(Runtime::kDeclareGlobals, 3);
// Return value is ignored.
}
void CodeGenerator::VisitDeclaration(Declaration* node) {
Comment cmnt(masm_, "[ Declaration");
Variable* var = node->proxy()->var();
ASSERT(var != NULL); // must have been resolved
Slot* slot = var->slot();
// If it was not possible to allocate the variable at compile time,
// we need to "declare" it at runtime to make sure it actually
// exists in the local context.
if (slot != NULL && slot->type() == Slot::LOOKUP) {
// Variables with a "LOOKUP" slot were introduced as non-locals
// during variable resolution and must have mode DYNAMIC.
ASSERT(var->is_dynamic());
// For now, just do a runtime call. Sync the virtual frame eagerly
// so we can simply push the arguments into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(var->name()));
// Declaration nodes are always introduced in one of two modes.
ASSERT(node->mode() == Variable::VAR || node->mode() == Variable::CONST);
PropertyAttributes attr = node->mode() == Variable::VAR ? NONE : READ_ONLY;
frame_->EmitPush(Immediate(Smi::FromInt(attr)));
// Push initial value, if any.
// Note: For variables we must not push an initial value (such as
// 'undefined') because we may have a (legal) redeclaration and we
// must not destroy the current value.
if (node->mode() == Variable::CONST) {
frame_->EmitPush(Immediate(Factory::the_hole_value()));
} else if (node->fun() != NULL) {
Load(node->fun());
} else {
frame_->EmitPush(Immediate(Smi::FromInt(0))); // no initial value!
}
Result ignored = frame_->CallRuntime(Runtime::kDeclareContextSlot, 4);
// Ignore the return value (declarations are statements).
return;
}
ASSERT(!var->is_global());
// If we have a function or a constant, we need to initialize the variable.
Expression* val = NULL;
if (node->mode() == Variable::CONST) {
val = new Literal(Factory::the_hole_value());
} else {
val = node->fun(); // NULL if we don't have a function
}
if (val != NULL) {
{
// Set the initial value.
Reference target(this, node->proxy());
Load(val);
target.SetValue(NOT_CONST_INIT);
// The reference is removed from the stack (preserving TOS) when
// it goes out of scope.
}
// Get rid of the assigned value (declarations are statements).
frame_->Drop();
}
}
void CodeGenerator::VisitExpressionStatement(ExpressionStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ExpressionStatement");
CodeForStatementPosition(node);
Expression* expression = node->expression();
expression->MarkAsStatement();
Load(expression);
// Remove the lingering expression result from the top of stack.
frame_->Drop();
}
void CodeGenerator::VisitEmptyStatement(EmptyStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "// EmptyStatement");
CodeForStatementPosition(node);
// nothing to do
}
void CodeGenerator::VisitIfStatement(IfStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ IfStatement");
// Generate different code depending on which parts of the if statement
// are present or not.
bool has_then_stm = node->HasThenStatement();
bool has_else_stm = node->HasElseStatement();
CodeForStatementPosition(node);
JumpTarget exit;
if (has_then_stm && has_else_stm) {
JumpTarget then;
JumpTarget else_;
ControlDestination dest(&then, &else_, true);
LoadCondition(node->condition(), &dest, true);
if (dest.false_was_fall_through()) {
// The else target was bound, so we compile the else part first.
Visit(node->else_statement());
// We may have dangling jumps to the then part.
if (then.is_linked()) {
if (has_valid_frame()) exit.Jump();
then.Bind();
Visit(node->then_statement());
}
} else {
// The then target was bound, so we compile the then part first.
Visit(node->then_statement());
if (else_.is_linked()) {
if (has_valid_frame()) exit.Jump();
else_.Bind();
Visit(node->else_statement());
}
}
} else if (has_then_stm) {
ASSERT(!has_else_stm);
JumpTarget then;
ControlDestination dest(&then, &exit, true);
LoadCondition(node->condition(), &dest, true);
if (dest.false_was_fall_through()) {
// The exit label was bound. We may have dangling jumps to the
// then part.
if (then.is_linked()) {
exit.Unuse();
exit.Jump();
then.Bind();
Visit(node->then_statement());
}
} else {
// The then label was bound.
Visit(node->then_statement());
}
} else if (has_else_stm) {
ASSERT(!has_then_stm);
JumpTarget else_;
ControlDestination dest(&exit, &else_, false);
LoadCondition(node->condition(), &dest, true);
if (dest.true_was_fall_through()) {
// The exit label was bound. We may have dangling jumps to the
// else part.
if (else_.is_linked()) {
exit.Unuse();
exit.Jump();
else_.Bind();
Visit(node->else_statement());
}
} else {
// The else label was bound.
Visit(node->else_statement());
}
} else {
ASSERT(!has_then_stm && !has_else_stm);
// We only care about the condition's side effects (not its value
// or control flow effect). LoadCondition is called without
// forcing control flow.
ControlDestination dest(&exit, &exit, true);
LoadCondition(node->condition(), &dest, false);
if (!dest.is_used()) {
// We got a value on the frame rather than (or in addition to)
// control flow.
frame_->Drop();
}
}
if (exit.is_linked()) {
exit.Bind();
}
}
void CodeGenerator::VisitContinueStatement(ContinueStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ContinueStatement");
CodeForStatementPosition(node);
node->target()->continue_target()->Jump();
}
void CodeGenerator::VisitBreakStatement(BreakStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ BreakStatement");
CodeForStatementPosition(node);
node->target()->break_target()->Jump();
}
void CodeGenerator::VisitReturnStatement(ReturnStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ReturnStatement");
CodeForStatementPosition(node);
Load(node->expression());
Result return_value = frame_->Pop();
masm()->WriteRecordedPositions();
if (function_return_is_shadowed_) {
function_return_.Jump(&return_value);
} else {
frame_->PrepareForReturn();
if (function_return_.is_bound()) {
// If the function return label is already bound we reuse the
// code by jumping to the return site.
function_return_.Jump(&return_value);
} else {
function_return_.Bind(&return_value);
GenerateReturnSequence(&return_value);
}
}
}
void CodeGenerator::GenerateReturnSequence(Result* return_value) {
// The return value is a live (but not currently reference counted)
// reference to eax. This is safe because the current frame does not
// contain a reference to eax (it is prepared for the return by spilling
// all registers).
if (FLAG_trace) {
frame_->Push(return_value);
*return_value = frame_->CallRuntime(Runtime::kTraceExit, 1);
}
return_value->ToRegister(eax);
// Add a label for checking the size of the code used for returning.
Label check_exit_codesize;
masm_->bind(&check_exit_codesize);
// Leave the frame and return popping the arguments and the
// receiver.
frame_->Exit();
masm_->ret((scope()->num_parameters() + 1) * kPointerSize);
DeleteFrame();
#ifdef ENABLE_DEBUGGER_SUPPORT
// Check that the size of the code used for returning matches what is
// expected by the debugger.
ASSERT_EQ(Assembler::kJSReturnSequenceLength,
masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
#endif
}
void CodeGenerator::VisitWithEnterStatement(WithEnterStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ WithEnterStatement");
CodeForStatementPosition(node);
Load(node->expression());
Result context;
if (node->is_catch_block()) {
context = frame_->CallRuntime(Runtime::kPushCatchContext, 1);
} else {
context = frame_->CallRuntime(Runtime::kPushContext, 1);
}
// Update context local.
frame_->SaveContextRegister();
// Verify that the runtime call result and esi agree.
if (FLAG_debug_code) {
__ cmp(context.reg(), Operand(esi));
__ Assert(equal, "Runtime::NewContext should end up in esi");
}
}
void CodeGenerator::VisitWithExitStatement(WithExitStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ WithExitStatement");
CodeForStatementPosition(node);
// Pop context.
__ mov(esi, ContextOperand(esi, Context::PREVIOUS_INDEX));
// Update context local.
frame_->SaveContextRegister();
}
void CodeGenerator::VisitSwitchStatement(SwitchStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ SwitchStatement");
CodeForStatementPosition(node);
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
// Compile the switch value.
Load(node->tag());
ZoneList<CaseClause*>* cases = node->cases();
int length = cases->length();
CaseClause* default_clause = NULL;
JumpTarget next_test;
// Compile the case label expressions and comparisons. Exit early
// if a comparison is unconditionally true. The target next_test is
// bound before the loop in order to indicate control flow to the
// first comparison.
next_test.Bind();
for (int i = 0; i < length && !next_test.is_unused(); i++) {
CaseClause* clause = cases->at(i);
// The default is not a test, but remember it for later.
if (clause->is_default()) {
default_clause = clause;
continue;
}
Comment cmnt(masm_, "[ Case comparison");
// We recycle the same target next_test for each test. Bind it if
// the previous test has not done so and then unuse it for the
// loop.
if (next_test.is_linked()) {
next_test.Bind();
}
next_test.Unuse();
// Duplicate the switch value.
frame_->Dup();
// Compile the label expression.
Load(clause->label());
// Compare and branch to the body if true or the next test if
// false. Prefer the next test as a fall through.
ControlDestination dest(clause->body_target(), &next_test, false);
Comparison(node, equal, true, &dest);
// If the comparison fell through to the true target, jump to the
// actual body.
if (dest.true_was_fall_through()) {
clause->body_target()->Unuse();
clause->body_target()->Jump();
}
}
// If there was control flow to a next test from the last one
// compiled, compile a jump to the default or break target.
if (!next_test.is_unused()) {
if (next_test.is_linked()) {
next_test.Bind();
}
// Drop the switch value.
frame_->Drop();
if (default_clause != NULL) {
default_clause->body_target()->Jump();
} else {
node->break_target()->Jump();
}
}
// The last instruction emitted was a jump, either to the default
// clause or the break target, or else to a case body from the loop
// that compiles the tests.
ASSERT(!has_valid_frame());
// Compile case bodies as needed.
for (int i = 0; i < length; i++) {
CaseClause* clause = cases->at(i);
// There are two ways to reach the body: from the corresponding
// test or as the fall through of the previous body.
if (clause->body_target()->is_linked() || has_valid_frame()) {
if (clause->body_target()->is_linked()) {
if (has_valid_frame()) {
// If we have both a jump to the test and a fall through, put
// a jump on the fall through path to avoid the dropping of
// the switch value on the test path. The exception is the
// default which has already had the switch value dropped.
if (clause->is_default()) {
clause->body_target()->Bind();
} else {
JumpTarget body;
body.Jump();
clause->body_target()->Bind();
frame_->Drop();
body.Bind();
}
} else {
// No fall through to worry about.
clause->body_target()->Bind();
if (!clause->is_default()) {
frame_->Drop();
}
}
} else {
// Otherwise, we have only fall through.
ASSERT(has_valid_frame());
}
// We are now prepared to compile the body.
Comment cmnt(masm_, "[ Case body");
VisitStatements(clause->statements());
}
clause->body_target()->Unuse();
}
// We may not have a valid frame here so bind the break target only
// if needed.
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
node->break_target()->Unuse();
}
void CodeGenerator::VisitDoWhileStatement(DoWhileStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ DoWhileStatement");
CodeForStatementPosition(node);
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
JumpTarget body(JumpTarget::BIDIRECTIONAL);
IncrementLoopNesting();
ConditionAnalysis info = AnalyzeCondition(node->cond());
// Label the top of the loop for the backward jump if necessary.
switch (info) {
case ALWAYS_TRUE:
// Use the continue target.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
break;
case ALWAYS_FALSE:
// No need to label it.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
break;
case DONT_KNOW:
// Continue is the test, so use the backward body target.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
body.Bind();
break;
}
CheckStack(); // TODO(1222600): ignore if body contains calls.
Visit(node->body());
// Compile the test.
switch (info) {
case ALWAYS_TRUE:
// If control flow can fall off the end of the body, jump back to
// the top and bind the break target at the exit.
if (has_valid_frame()) {
node->continue_target()->Jump();
}
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
break;
case ALWAYS_FALSE:
// We may have had continues or breaks in the body.
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
break;
case DONT_KNOW:
// We have to compile the test expression if it can be reached by
// control flow falling out of the body or via continue.
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
if (has_valid_frame()) {
Comment cmnt(masm_, "[ DoWhileCondition");
CodeForDoWhileConditionPosition(node);
ControlDestination dest(&body, node->break_target(), false);
LoadCondition(node->cond(), &dest, true);
}
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
break;
}
DecrementLoopNesting();
}
void CodeGenerator::VisitWhileStatement(WhileStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ WhileStatement");
CodeForStatementPosition(node);
// If the condition is always false and has no side effects, we do not
// need to compile anything.
ConditionAnalysis info = AnalyzeCondition(node->cond());
if (info == ALWAYS_FALSE) return;
// Do not duplicate conditions that may have function literal
// subexpressions. This can cause us to compile the function literal
// twice.
bool test_at_bottom = !node->may_have_function_literal();
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
IncrementLoopNesting();
JumpTarget body;
if (test_at_bottom) {
body.set_direction(JumpTarget::BIDIRECTIONAL);
}
// Based on the condition analysis, compile the test as necessary.
switch (info) {
case ALWAYS_TRUE:
// We will not compile the test expression. Label the top of the
// loop with the continue target.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
break;
case DONT_KNOW: {
if (test_at_bottom) {
// Continue is the test at the bottom, no need to label the test
// at the top. The body is a backward target.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
} else {
// Label the test at the top as the continue target. The body
// is a forward-only target.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
}
// Compile the test with the body as the true target and preferred
// fall-through and with the break target as the false target.
ControlDestination dest(&body, node->break_target(), true);
LoadCondition(node->cond(), &dest, true);
if (dest.false_was_fall_through()) {
// If we got the break target as fall-through, the test may have
// been unconditionally false (if there are no jumps to the
// body).
if (!body.is_linked()) {
DecrementLoopNesting();
return;
}
// Otherwise, jump around the body on the fall through and then
// bind the body target.
node->break_target()->Unuse();
node->break_target()->Jump();
body.Bind();
}
break;
}
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
CheckStack(); // TODO(1222600): ignore if body contains calls.
Visit(node->body());
// Based on the condition analysis, compile the backward jump as
// necessary.
switch (info) {
case ALWAYS_TRUE:
// The loop body has been labeled with the continue target.
if (has_valid_frame()) {
node->continue_target()->Jump();
}
break;
case DONT_KNOW:
if (test_at_bottom) {
// If we have chosen to recompile the test at the bottom, then
// it is the continue target.
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
if (has_valid_frame()) {
// The break target is the fall-through (body is a backward
// jump from here and thus an invalid fall-through).
ControlDestination dest(&body, node->break_target(), false);
LoadCondition(node->cond(), &dest, true);
}
} else {
// If we have chosen not to recompile the test at the bottom,
// jump back to the one at the top.
if (has_valid_frame()) {
node->continue_target()->Jump();
}
}
break;
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
// The break target may be already bound (by the condition), or there
// may not be a valid frame. Bind it only if needed.
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
DecrementLoopNesting();
}
void CodeGenerator::SetTypeForStackSlot(Slot* slot, TypeInfo info) {
ASSERT(slot->type() == Slot::LOCAL || slot->type() == Slot::PARAMETER);
if (slot->type() == Slot::LOCAL) {
frame_->SetTypeForLocalAt(slot->index(), info);
} else {
frame_->SetTypeForParamAt(slot->index(), info);
}
if (FLAG_debug_code && info.IsSmi()) {
if (slot->type() == Slot::LOCAL) {
frame_->PushLocalAt(slot->index());
} else {
frame_->PushParameterAt(slot->index());
}
Result var = frame_->Pop();
var.ToRegister();
__ AbortIfNotSmi(var.reg());
}
}
void CodeGenerator::VisitForStatement(ForStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ ForStatement");
CodeForStatementPosition(node);
// Compile the init expression if present.
if (node->init() != NULL) {
Visit(node->init());
}
// If the condition is always false and has no side effects, we do not
// need to compile anything else.
ConditionAnalysis info = AnalyzeCondition(node->cond());
if (info == ALWAYS_FALSE) return;
// Do not duplicate conditions that may have function literal
// subexpressions. This can cause us to compile the function literal
// twice.
bool test_at_bottom = !node->may_have_function_literal();
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
IncrementLoopNesting();
// Target for backward edge if no test at the bottom, otherwise
// unused.
JumpTarget loop(JumpTarget::BIDIRECTIONAL);
// Target for backward edge if there is a test at the bottom,
// otherwise used as target for test at the top.
JumpTarget body;
if (test_at_bottom) {
body.set_direction(JumpTarget::BIDIRECTIONAL);
}
// Based on the condition analysis, compile the test as necessary.
switch (info) {
case ALWAYS_TRUE:
// We will not compile the test expression. Label the top of the
// loop.
if (node->next() == NULL) {
// Use the continue target if there is no update expression.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
} else {
// Otherwise use the backward loop target.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
loop.Bind();
}
break;
case DONT_KNOW: {
if (test_at_bottom) {
// Continue is either the update expression or the test at the
// bottom, no need to label the test at the top.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
} else if (node->next() == NULL) {
// We are not recompiling the test at the bottom and there is no
// update expression.
node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
node->continue_target()->Bind();
} else {
// We are not recompiling the test at the bottom and there is an
// update expression.
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
loop.Bind();
}
// Compile the test with the body as the true target and preferred
// fall-through and with the break target as the false target.
ControlDestination dest(&body, node->break_target(), true);
LoadCondition(node->cond(), &dest, true);
if (dest.false_was_fall_through()) {
// If we got the break target as fall-through, the test may have
// been unconditionally false (if there are no jumps to the
// body).
if (!body.is_linked()) {
DecrementLoopNesting();
return;
}
// Otherwise, jump around the body on the fall through and then
// bind the body target.
node->break_target()->Unuse();
node->break_target()->Jump();
body.Bind();
}
break;
}
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
CheckStack(); // TODO(1222600): ignore if body contains calls.
// We know that the loop index is a smi if it is not modified in the
// loop body and it is checked against a constant limit in the loop
// condition. In this case, we reset the static type information of the
// loop index to smi before compiling the body, the update expression, and
// the bottom check of the loop condition.
if (node->is_fast_smi_loop()) {
// Set number type of the loop variable to smi.
SetTypeForStackSlot(node->loop_variable()->slot(), TypeInfo::Smi());
}
Visit(node->body());
// If there is an update expression, compile it if necessary.
if (node->next() != NULL) {
if (node->continue_target()->is_linked()) {
node->continue_target()->Bind();
}
// Control can reach the update by falling out of the body or by a
// continue.
if (has_valid_frame()) {
// Record the source position of the statement as this code which
// is after the code for the body actually belongs to the loop
// statement and not the body.
CodeForStatementPosition(node);
Visit(node->next());
}
}
// Set the type of the loop variable to smi before compiling the test
// expression if we are in a fast smi loop condition.
if (node->is_fast_smi_loop() && has_valid_frame()) {
// Set number type of the loop variable to smi.
SetTypeForStackSlot(node->loop_variable()->slot(), TypeInfo::Smi());
}
// Based on the condition analysis, compile the backward jump as
// necessary.
switch (info) {
case ALWAYS_TRUE:
if (has_valid_frame()) {
if (node->next() == NULL) {
node->continue_target()->Jump();
} else {
loop.Jump();
}
}
break;
case DONT_KNOW:
if (test_at_bottom) {
if (node->continue_target()->is_linked()) {
// We can have dangling jumps to the continue target if there
// was no update expression.
node->continue_target()->Bind();
}
// Control can reach the test at the bottom by falling out of
// the body, by a continue in the body, or from the update
// expression.
if (has_valid_frame()) {
// The break target is the fall-through (body is a backward
// jump from here).
ControlDestination dest(&body, node->break_target(), false);
LoadCondition(node->cond(), &dest, true);
}
} else {
// Otherwise, jump back to the test at the top.
if (has_valid_frame()) {
if (node->next() == NULL) {
node->continue_target()->Jump();
} else {
loop.Jump();
}
}
}
break;
case ALWAYS_FALSE:
UNREACHABLE();
break;
}
// The break target may be already bound (by the condition), or
// there may not be a valid frame. Bind it only if needed.
if (node->break_target()->is_linked()) {
node->break_target()->Bind();
}
DecrementLoopNesting();
}
void CodeGenerator::VisitForInStatement(ForInStatement* node) {
ASSERT(!in_spilled_code());
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ ForInStatement");
CodeForStatementPosition(node);
JumpTarget primitive;
JumpTarget jsobject;
JumpTarget fixed_array;
JumpTarget entry(JumpTarget::BIDIRECTIONAL);
JumpTarget end_del_check;
JumpTarget exit;
// Get the object to enumerate over (converted to JSObject).
LoadAndSpill(node->enumerable());
// Both SpiderMonkey and kjs ignore null and undefined in contrast
// to the specification. 12.6.4 mandates a call to ToObject.
frame_->EmitPop(eax);
// eax: value to be iterated over
__ cmp(eax, Factory::undefined_value());
exit.Branch(equal);
__ cmp(eax, Factory::null_value());
exit.Branch(equal);
// Stack layout in body:
// [iteration counter (smi)] <- slot 0
// [length of array] <- slot 1
// [FixedArray] <- slot 2
// [Map or 0] <- slot 3
// [Object] <- slot 4
// Check if enumerable is already a JSObject
// eax: value to be iterated over
__ test(eax, Immediate(kSmiTagMask));
primitive.Branch(zero);
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
jsobject.Branch(above_equal);
primitive.Bind();
frame_->EmitPush(eax);
frame_->InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION, 1);
// function call returns the value in eax, which is where we want it below
jsobject.Bind();
// Get the set of properties (as a FixedArray or Map).
// eax: value to be iterated over
frame_->EmitPush(eax); // Push the object being iterated over.
// Check cache validity in generated code. This is a fast case for
// the JSObject::IsSimpleEnum cache validity checks. If we cannot
// guarantee cache validity, call the runtime system to check cache
// validity or get the property names in a fixed array.
JumpTarget call_runtime;
JumpTarget loop(JumpTarget::BIDIRECTIONAL);
JumpTarget check_prototype;
JumpTarget use_cache;
__ mov(ecx, eax);
loop.Bind();
// Check that there are no elements.
__ mov(edx, FieldOperand(ecx, JSObject::kElementsOffset));
__ cmp(Operand(edx), Immediate(Factory::empty_fixed_array()));
call_runtime.Branch(not_equal);
// Check that instance descriptors are not empty so that we can
// check for an enum cache. Leave the map in ebx for the subsequent
// prototype load.
__ mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));
__ mov(edx, FieldOperand(ebx, Map::kInstanceDescriptorsOffset));
__ cmp(Operand(edx), Immediate(Factory::empty_descriptor_array()));
call_runtime.Branch(equal);
// Check that there in an enum cache in the non-empty instance
// descriptors. This is the case if the next enumeration index
// field does not contain a smi.
__ mov(edx, FieldOperand(edx, DescriptorArray::kEnumerationIndexOffset));
__ test(edx, Immediate(kSmiTagMask));
call_runtime.Branch(zero);
// For all objects but the receiver, check that the cache is empty.
__ cmp(ecx, Operand(eax));
check_prototype.Branch(equal);
__ mov(edx, FieldOperand(edx, DescriptorArray::kEnumCacheBridgeCacheOffset));
__ cmp(Operand(edx), Immediate(Factory::empty_fixed_array()));
call_runtime.Branch(not_equal);
check_prototype.Bind();
// Load the prototype from the map and loop if non-null.
__ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
__ cmp(Operand(ecx), Immediate(Factory::null_value()));
loop.Branch(not_equal);
// The enum cache is valid. Load the map of the object being
// iterated over and use the cache for the iteration.
__ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
use_cache.Jump();
call_runtime.Bind();
// Call the runtime to get the property names for the object.
frame_->EmitPush(eax); // push the Object (slot 4) for the runtime call
frame_->CallRuntime(Runtime::kGetPropertyNamesFast, 1);
// If we got a map from the runtime call, we can do a fast
// modification check. Otherwise, we got a fixed array, and we have
// to do a slow check.
// eax: map or fixed array (result from call to
// Runtime::kGetPropertyNamesFast)
__ mov(edx, Operand(eax));
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ cmp(ecx, Factory::meta_map());
fixed_array.Branch(not_equal);
use_cache.Bind();
// Get enum cache
// eax: map (either the result from a call to
// Runtime::kGetPropertyNamesFast or has been fetched directly from
// the object)
__ mov(ecx, Operand(eax));
__ mov(ecx, FieldOperand(ecx, Map::kInstanceDescriptorsOffset));
// Get the bridge array held in the enumeration index field.
__ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumerationIndexOffset));
// Get the cache from the bridge array.
__ mov(edx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
frame_->EmitPush(eax); // <- slot 3
frame_->EmitPush(edx); // <- slot 2
__ mov(eax, FieldOperand(edx, FixedArray::kLengthOffset));
frame_->EmitPush(eax); // <- slot 1
frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 0
entry.Jump();
fixed_array.Bind();
// eax: fixed array (result from call to Runtime::kGetPropertyNamesFast)
frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 3
frame_->EmitPush(eax); // <- slot 2
// Push the length of the array and the initial index onto the stack.
__ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
frame_->EmitPush(eax); // <- slot 1
frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 0
// Condition.
entry.Bind();
// Grab the current frame's height for the break and continue
// targets only after all the state is pushed on the frame.
node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
__ mov(eax, frame_->ElementAt(0)); // load the current count
__ cmp(eax, frame_->ElementAt(1)); // compare to the array length
node->break_target()->Branch(above_equal);
// Get the i'th entry of the array.
__ mov(edx, frame_->ElementAt(2));
__ mov(ebx, FixedArrayElementOperand(edx, eax));
// Get the expected map from the stack or a zero map in the
// permanent slow case eax: current iteration count ebx: i'th entry
// of the enum cache
__ mov(edx, frame_->ElementAt(3));
// Check if the expected map still matches that of the enumerable.
// If not, we have to filter the key.
// eax: current iteration count
// ebx: i'th entry of the enum cache
// edx: expected map value
__ mov(ecx, frame_->ElementAt(4));
__ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
__ cmp(ecx, Operand(edx));
end_del_check.Branch(equal);
// Convert the entry to a string (or null if it isn't a property anymore).
frame_->EmitPush(frame_->ElementAt(4)); // push enumerable
frame_->EmitPush(ebx); // push entry
frame_->InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION, 2);
__ mov(ebx, Operand(eax));
// If the property has been removed while iterating, we just skip it.
__ cmp(ebx, Factory::null_value());
node->continue_target()->Branch(equal);
end_del_check.Bind();
// Store the entry in the 'each' expression and take another spin in the
// loop. edx: i'th entry of the enum cache (or string there of)
frame_->EmitPush(ebx);
{ Reference each(this, node->each());
// Loading a reference may leave the frame in an unspilled state.
frame_->SpillAll();
if (!each.is_illegal()) {
if (each.size() > 0) {
frame_->EmitPush(frame_->ElementAt(each.size()));
each.SetValue(NOT_CONST_INIT);
frame_->Drop(2);
} else {
// If the reference was to a slot we rely on the convenient property
// that it doesn't matter whether a value (eg, ebx pushed above) is
// right on top of or right underneath a zero-sized reference.
each.SetValue(NOT_CONST_INIT);
frame_->Drop();
}
}
}
// Unloading a reference may leave the frame in an unspilled state.
frame_->SpillAll();
// Body.
CheckStack(); // TODO(1222600): ignore if body contains calls.
VisitAndSpill(node->body());
// Next. Reestablish a spilled frame in case we are coming here via
// a continue in the body.
node->continue_target()->Bind();
frame_->SpillAll();
frame_->EmitPop(eax);
__ add(Operand(eax), Immediate(Smi::FromInt(1)));
frame_->EmitPush(eax);
entry.Jump();
// Cleanup. No need to spill because VirtualFrame::Drop is safe for
// any frame.
node->break_target()->Bind();
frame_->Drop(5);
// Exit.
exit.Bind();
node->continue_target()->Unuse();
node->break_target()->Unuse();
}
void CodeGenerator::VisitTryCatchStatement(TryCatchStatement* node) {
ASSERT(!in_spilled_code());
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ TryCatchStatement");
CodeForStatementPosition(node);
JumpTarget try_block;
JumpTarget exit;
try_block.Call();
// --- Catch block ---
frame_->EmitPush(eax);
// Store the caught exception in the catch variable.
Variable* catch_var = node->catch_var()->var();
ASSERT(catch_var != NULL && catch_var->slot() != NULL);
StoreToSlot(catch_var->slot(), NOT_CONST_INIT);
// Remove the exception from the stack.
frame_->Drop();
VisitStatementsAndSpill(node->catch_block()->statements());
if (has_valid_frame()) {
exit.Jump();
}
// --- Try block ---
try_block.Bind();
frame_->PushTryHandler(TRY_CATCH_HANDLER);
int handler_height = frame_->height();
// Shadow the jump targets for all escapes from the try block, including
// returns. During shadowing, the original target is hidden as the
// ShadowTarget and operations on the original actually affect the
// shadowing target.
//
// We should probably try to unify the escaping targets and the return
// target.
int nof_escapes = node->escaping_targets()->length();
List<ShadowTarget*> shadows(1 + nof_escapes);
// Add the shadow target for the function return.
static const int kReturnShadowIndex = 0;
shadows.Add(new ShadowTarget(&function_return_));
bool function_return_was_shadowed = function_return_is_shadowed_;
function_return_is_shadowed_ = true;
ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
// Add the remaining shadow targets.
for (int i = 0; i < nof_escapes; i++) {
shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
}
// Generate code for the statements in the try block.
VisitStatementsAndSpill(node->try_block()->statements());
// Stop the introduced shadowing and count the number of required unlinks.
// After shadowing stops, the original targets are unshadowed and the
// ShadowTargets represent the formerly shadowing targets.
bool has_unlinks = false;
for (int i = 0; i < shadows.length(); i++) {
shadows[i]->StopShadowing();
has_unlinks = has_unlinks || shadows[i]->is_linked();
}
function_return_is_shadowed_ = function_return_was_shadowed;
// Get an external reference to the handler address.
ExternalReference handler_address(Top::k_handler_address);
// Make sure that there's nothing left on the stack above the
// handler structure.
if (FLAG_debug_code) {
__ mov(eax, Operand::StaticVariable(handler_address));
__ cmp(esp, Operand(eax));
__ Assert(equal, "stack pointer should point to top handler");
}
// If we can fall off the end of the try block, unlink from try chain.
if (has_valid_frame()) {
// The next handler address is on top of the frame. Unlink from
// the handler list and drop the rest of this handler from the
// frame.
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
if (has_unlinks) {
exit.Jump();
}
}
// Generate unlink code for the (formerly) shadowing targets that
// have been jumped to. Deallocate each shadow target.
Result return_value;
for (int i = 0; i < shadows.length(); i++) {
if (shadows[i]->is_linked()) {
// Unlink from try chain; be careful not to destroy the TOS if
// there is one.
if (i == kReturnShadowIndex) {
shadows[i]->Bind(&return_value);
return_value.ToRegister(eax);
} else {
shadows[i]->Bind();
}
// Because we can be jumping here (to spilled code) from
// unspilled code, we need to reestablish a spilled frame at
// this block.
frame_->SpillAll();
// Reload sp from the top handler, because some statements that we
// break from (eg, for...in) may have left stuff on the stack.
__ mov(esp, Operand::StaticVariable(handler_address));
frame_->Forget(frame_->height() - handler_height);
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
if (i == kReturnShadowIndex) {
if (!function_return_is_shadowed_) frame_->PrepareForReturn();
shadows[i]->other_target()->Jump(&return_value);
} else {
shadows[i]->other_target()->Jump();
}
}
}
exit.Bind();
}
void CodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* node) {
ASSERT(!in_spilled_code());
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ TryFinallyStatement");
CodeForStatementPosition(node);
// State: Used to keep track of reason for entering the finally
// block. Should probably be extended to hold information for
// break/continue from within the try block.
enum { FALLING, THROWING, JUMPING };
JumpTarget try_block;
JumpTarget finally_block;
try_block.Call();
frame_->EmitPush(eax);
// In case of thrown exceptions, this is where we continue.
__ Set(ecx, Immediate(Smi::FromInt(THROWING)));
finally_block.Jump();
// --- Try block ---
try_block.Bind();
frame_->PushTryHandler(TRY_FINALLY_HANDLER);
int handler_height = frame_->height();
// Shadow the jump targets for all escapes from the try block, including
// returns. During shadowing, the original target is hidden as the
// ShadowTarget and operations on the original actually affect the
// shadowing target.
//
// We should probably try to unify the escaping targets and the return
// target.
int nof_escapes = node->escaping_targets()->length();
List<ShadowTarget*> shadows(1 + nof_escapes);
// Add the shadow target for the function return.
static const int kReturnShadowIndex = 0;
shadows.Add(new ShadowTarget(&function_return_));
bool function_return_was_shadowed = function_return_is_shadowed_;
function_return_is_shadowed_ = true;
ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
// Add the remaining shadow targets.
for (int i = 0; i < nof_escapes; i++) {
shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
}
// Generate code for the statements in the try block.
VisitStatementsAndSpill(node->try_block()->statements());
// Stop the introduced shadowing and count the number of required unlinks.
// After shadowing stops, the original targets are unshadowed and the
// ShadowTargets represent the formerly shadowing targets.
int nof_unlinks = 0;
for (int i = 0; i < shadows.length(); i++) {
shadows[i]->StopShadowing();
if (shadows[i]->is_linked()) nof_unlinks++;
}
function_return_is_shadowed_ = function_return_was_shadowed;
// Get an external reference to the handler address.
ExternalReference handler_address(Top::k_handler_address);
// If we can fall off the end of the try block, unlink from the try
// chain and set the state on the frame to FALLING.
if (has_valid_frame()) {
// The next handler address is on top of the frame.
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
// Fake a top of stack value (unneeded when FALLING) and set the
// state in ecx, then jump around the unlink blocks if any.
frame_->EmitPush(Immediate(Factory::undefined_value()));
__ Set(ecx, Immediate(Smi::FromInt(FALLING)));
if (nof_unlinks > 0) {
finally_block.Jump();
}
}
// Generate code to unlink and set the state for the (formerly)
// shadowing targets that have been jumped to.
for (int i = 0; i < shadows.length(); i++) {
if (shadows[i]->is_linked()) {
// If we have come from the shadowed return, the return value is
// on the virtual frame. We must preserve it until it is
// pushed.
if (i == kReturnShadowIndex) {
Result return_value;
shadows[i]->Bind(&return_value);
return_value.ToRegister(eax);
} else {
shadows[i]->Bind();
}
// Because we can be jumping here (to spilled code) from
// unspilled code, we need to reestablish a spilled frame at
// this block.
frame_->SpillAll();
// Reload sp from the top handler, because some statements that
// we break from (eg, for...in) may have left stuff on the
// stack.
__ mov(esp, Operand::StaticVariable(handler_address));
frame_->Forget(frame_->height() - handler_height);
// Unlink this handler and drop it from the frame.
ASSERT(StackHandlerConstants::kNextOffset == 0);
frame_->EmitPop(Operand::StaticVariable(handler_address));
frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
if (i == kReturnShadowIndex) {
// If this target shadowed the function return, materialize
// the return value on the stack.
frame_->EmitPush(eax);
} else {
// Fake TOS for targets that shadowed breaks and continues.
frame_->EmitPush(Immediate(Factory::undefined_value()));
}
__ Set(ecx, Immediate(Smi::FromInt(JUMPING + i)));
if (--nof_unlinks > 0) {
// If this is not the last unlink block, jump around the next.
finally_block.Jump();
}
}
}
// --- Finally block ---
finally_block.Bind();
// Push the state on the stack.
frame_->EmitPush(ecx);
// We keep two elements on the stack - the (possibly faked) result
// and the state - while evaluating the finally block.
//
// Generate code for the statements in the finally block.
VisitStatementsAndSpill(node->finally_block()->statements());
if (has_valid_frame()) {
// Restore state and return value or faked TOS.
frame_->EmitPop(ecx);
frame_->EmitPop(eax);
}
// Generate code to jump to the right destination for all used
// formerly shadowing targets. Deallocate each shadow target.
for (int i = 0; i < shadows.length(); i++) {
if (has_valid_frame() && shadows[i]->is_bound()) {
BreakTarget* original = shadows[i]->other_target();
__ cmp(Operand(ecx), Immediate(Smi::FromInt(JUMPING + i)));
if (i == kReturnShadowIndex) {
// The return value is (already) in eax.
Result return_value = allocator_->Allocate(eax);
ASSERT(return_value.is_valid());
if (function_return_is_shadowed_) {
original->Branch(equal, &return_value);
} else {
// Branch around the preparation for return which may emit
// code.
JumpTarget skip;
skip.Branch(not_equal);
frame_->PrepareForReturn();
original->Jump(&return_value);
skip.Bind();
}
} else {
original->Branch(equal);
}
}
}
if (has_valid_frame()) {
// Check if we need to rethrow the exception.
JumpTarget exit;
__ cmp(Operand(ecx), Immediate(Smi::FromInt(THROWING)));
exit.Branch(not_equal);
// Rethrow exception.
frame_->EmitPush(eax); // undo pop from above
frame_->CallRuntime(Runtime::kReThrow, 1);
// Done.
exit.Bind();
}
}
void CodeGenerator::VisitDebuggerStatement(DebuggerStatement* node) {
ASSERT(!in_spilled_code());
Comment cmnt(masm_, "[ DebuggerStatement");
CodeForStatementPosition(node);
#ifdef ENABLE_DEBUGGER_SUPPORT
// Spill everything, even constants, to the frame.
frame_->SpillAll();
frame_->DebugBreak();
// Ignore the return value.
#endif
}
Result CodeGenerator::InstantiateFunction(
Handle<SharedFunctionInfo> function_info) {
// The inevitable call will sync frame elements to memory anyway, so
// we do it eagerly to allow us to push the arguments directly into
// place.
frame()->SyncRange(0, frame()->element_count() - 1);
// Use the fast case closure allocation code that allocates in new
// space for nested functions that don't need literals cloning.
if (scope()->is_function_scope() && function_info->num_literals() == 0) {
FastNewClosureStub stub;
frame()->EmitPush(Immediate(function_info));
return frame()->CallStub(&stub, 1);
} else {
// Call the runtime to instantiate the function based on the
// shared function info.
frame()->EmitPush(esi);
frame()->EmitPush(Immediate(function_info));
return frame()->CallRuntime(Runtime::kNewClosure, 2);
}
}
void CodeGenerator::VisitFunctionLiteral(FunctionLiteral* node) {
Comment cmnt(masm_, "[ FunctionLiteral");
ASSERT(!in_safe_int32_mode());
// Build the function info and instantiate it.
Handle<SharedFunctionInfo> function_info =
Compiler::BuildFunctionInfo(node, script(), this);
// Check for stack-overflow exception.
if (HasStackOverflow()) return;
Result result = InstantiateFunction(function_info);
frame()->Push(&result);
}
void CodeGenerator::VisitSharedFunctionInfoLiteral(
SharedFunctionInfoLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ SharedFunctionInfoLiteral");
Result result = InstantiateFunction(node->shared_function_info());
frame()->Push(&result);
}
void CodeGenerator::VisitConditional(Conditional* node) {
Comment cmnt(masm_, "[ Conditional");
ASSERT(!in_safe_int32_mode());
JumpTarget then;
JumpTarget else_;
JumpTarget exit;
ControlDestination dest(&then, &else_, true);
LoadCondition(node->condition(), &dest, true);
if (dest.false_was_fall_through()) {
// The else target was bound, so we compile the else part first.
Load(node->else_expression());
if (then.is_linked()) {
exit.Jump();
then.Bind();
Load(node->then_expression());
}
} else {
// The then target was bound, so we compile the then part first.
Load(node->then_expression());
if (else_.is_linked()) {
exit.Jump();
else_.Bind();
Load(node->else_expression());
}
}
exit.Bind();
}
void CodeGenerator::LoadFromSlot(Slot* slot, TypeofState typeof_state) {
if (slot->type() == Slot::LOOKUP) {
ASSERT(slot->var()->is_dynamic());
JumpTarget slow;
JumpTarget done;
Result value;
// Generate fast case for loading from slots that correspond to
// local/global variables or arguments unless they are shadowed by
// eval-introduced bindings.
EmitDynamicLoadFromSlotFastCase(slot,
typeof_state,
&value,
&slow,
&done);
slow.Bind();
// A runtime call is inevitable. We eagerly sync frame elements
// to memory so that we can push the arguments directly into place
// on top of the frame.
frame()->SyncRange(0, frame()->element_count() - 1);
frame()->EmitPush(esi);
frame()->EmitPush(Immediate(slot->var()->name()));
if (typeof_state == INSIDE_TYPEOF) {
value =
frame()->CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2);
} else {
value = frame()->CallRuntime(Runtime::kLoadContextSlot, 2);
}
done.Bind(&value);
frame_->Push(&value);
} else if (slot->var()->mode() == Variable::CONST) {
// Const slots may contain 'the hole' value (the constant hasn't been
// initialized yet) which needs to be converted into the 'undefined'
// value.
//
// We currently spill the virtual frame because constants use the
// potentially unsafe direct-frame access of SlotOperand.
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ Load const");
Label exit;
__ mov(ecx, SlotOperand(slot, ecx));
__ cmp(ecx, Factory::the_hole_value());
__ j(not_equal, &exit);
__ mov(ecx, Factory::undefined_value());
__ bind(&exit);
frame()->EmitPush(ecx);
} else if (slot->type() == Slot::PARAMETER) {
frame()->PushParameterAt(slot->index());
} else if (slot->type() == Slot::LOCAL) {
frame()->PushLocalAt(slot->index());
} else {
// The other remaining slot types (LOOKUP and GLOBAL) cannot reach
// here.
//
// The use of SlotOperand below is safe for an unspilled frame
// because it will always be a context slot.
ASSERT(slot->type() == Slot::CONTEXT);
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), SlotOperand(slot, temp.reg()));
frame()->Push(&temp);
}
}
void CodeGenerator::LoadFromSlotCheckForArguments(Slot* slot,
TypeofState state) {
LoadFromSlot(slot, state);
// Bail out quickly if we're not using lazy arguments allocation.
if (ArgumentsMode() != LAZY_ARGUMENTS_ALLOCATION) return;
// ... or if the slot isn't a non-parameter arguments slot.
if (slot->type() == Slot::PARAMETER || !slot->is_arguments()) return;
// If the loaded value is a constant, we know if the arguments
// object has been lazily loaded yet.
Result result = frame()->Pop();
if (result.is_constant()) {
if (result.handle()->IsTheHole()) {
result = StoreArgumentsObject(false);
}
frame()->Push(&result);
return;
}
ASSERT(result.is_register());
// The loaded value is in a register. If it is the sentinel that
// indicates that we haven't loaded the arguments object yet, we
// need to do it now.
JumpTarget exit;
__ cmp(Operand(result.reg()), Immediate(Factory::the_hole_value()));
frame()->Push(&result);
exit.Branch(not_equal);
result = StoreArgumentsObject(false);
frame()->SetElementAt(0, &result);
result.Unuse();
exit.Bind();
return;
}
Result CodeGenerator::LoadFromGlobalSlotCheckExtensions(
Slot* slot,
TypeofState typeof_state,
JumpTarget* slow) {
ASSERT(!in_safe_int32_mode());
// Check that no extension objects have been created by calls to
// eval from the current scope to the global scope.
Register context = esi;
Result tmp = allocator_->Allocate();
ASSERT(tmp.is_valid()); // All non-reserved registers were available.
Scope* s = scope();
while (s != NULL) {
if (s->num_heap_slots() > 0) {
if (s->calls_eval()) {
// Check that extension is NULL.
__ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
Immediate(0));
slow->Branch(not_equal, not_taken);
}
// Load next context in chain.
__ mov(tmp.reg(), ContextOperand(context, Context::CLOSURE_INDEX));
__ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
context = tmp.reg();
}
// If no outer scope calls eval, we do not need to check more
// context extensions. If we have reached an eval scope, we check
// all extensions from this point.
if (!s->outer_scope_calls_eval() || s->is_eval_scope()) break;
s = s->outer_scope();
}
if (s != NULL && s->is_eval_scope()) {
// Loop up the context chain. There is no frame effect so it is
// safe to use raw labels here.
Label next, fast;
if (!context.is(tmp.reg())) {
__ mov(tmp.reg(), context);
}
__ bind(&next);
// Terminate at global context.
__ cmp(FieldOperand(tmp.reg(), HeapObject::kMapOffset),
Immediate(Factory::global_context_map()));
__ j(equal, &fast);
// Check that extension is NULL.
__ cmp(ContextOperand(tmp.reg(), Context::EXTENSION_INDEX), Immediate(0));
slow->Branch(not_equal, not_taken);
// Load next context in chain.
__ mov(tmp.reg(), ContextOperand(tmp.reg(), Context::CLOSURE_INDEX));
__ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
__ jmp(&next);
__ bind(&fast);
}
tmp.Unuse();
// All extension objects were empty and it is safe to use a global
// load IC call.
// The register allocator prefers eax if it is free, so the code generator
// will load the global object directly into eax, which is where the LoadIC
// expects it.
frame_->Spill(eax);
LoadGlobal();
frame_->Push(slot->var()->name());
RelocInfo::Mode mode = (typeof_state == INSIDE_TYPEOF)
? RelocInfo::CODE_TARGET
: RelocInfo::CODE_TARGET_CONTEXT;
Result answer = frame_->CallLoadIC(mode);
// A test eax instruction following the call signals that the inobject
// property case was inlined. Ensure that there is not a test eax
// instruction here.
__ nop();
return answer;
}
void CodeGenerator::EmitDynamicLoadFromSlotFastCase(Slot* slot,
TypeofState typeof_state,
Result* result,
JumpTarget* slow,
JumpTarget* done) {
// Generate fast-case code for variables that might be shadowed by
// eval-introduced variables. Eval is used a lot without
// introducing variables. In those cases, we do not want to
// perform a runtime call for all variables in the scope
// containing the eval.
if (slot->var()->mode() == Variable::DYNAMIC_GLOBAL) {
*result = LoadFromGlobalSlotCheckExtensions(slot, typeof_state, slow);
done->Jump(result);
} else if (slot->var()->mode() == Variable::DYNAMIC_LOCAL) {
Slot* potential_slot = slot->var()->local_if_not_shadowed()->slot();
Expression* rewrite = slot->var()->local_if_not_shadowed()->rewrite();
if (potential_slot != NULL) {
// Generate fast case for locals that rewrite to slots.
// Allocate a fresh register to use as a temp in
// ContextSlotOperandCheckExtensions and to hold the result
// value.
*result = allocator()->Allocate();
ASSERT(result->is_valid());
__ mov(result->reg(),
ContextSlotOperandCheckExtensions(potential_slot, *result, slow));
if (potential_slot->var()->mode() == Variable::CONST) {
__ cmp(result->reg(), Factory::the_hole_value());
done->Branch(not_equal, result);
__ mov(result->reg(), Factory::undefined_value());
}
done->Jump(result);
} else if (rewrite != NULL) {
// Generate fast case for calls of an argument function.
Property* property = rewrite->AsProperty();
if (property != NULL) {
VariableProxy* obj_proxy = property->obj()->AsVariableProxy();
Literal* key_literal = property->key()->AsLiteral();
if (obj_proxy != NULL &&
key_literal != NULL &&
obj_proxy->IsArguments() &&
key_literal->handle()->IsSmi()) {
// Load arguments object if there are no eval-introduced
// variables. Then load the argument from the arguments
// object using keyed load.
Result arguments = allocator()->Allocate();
ASSERT(arguments.is_valid());
__ mov(arguments.reg(),
ContextSlotOperandCheckExtensions(obj_proxy->var()->slot(),
arguments,
slow));
frame_->Push(&arguments);
frame_->Push(key_literal->handle());
*result = EmitKeyedLoad();
done->Jump(result);
}
}
}
}
}
void CodeGenerator::StoreToSlot(Slot* slot, InitState init_state) {
if (slot->type() == Slot::LOOKUP) {
ASSERT(slot->var()->is_dynamic());
// For now, just do a runtime call. Since the call is inevitable,
// we eagerly sync the virtual frame so we can directly push the
// arguments into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(slot->var()->name()));
Result value;
if (init_state == CONST_INIT) {
// Same as the case for a normal store, but ignores attribute
// (e.g. READ_ONLY) of context slot so that we can initialize const
// properties (introduced via eval("const foo = (some expr);")). Also,
// uses the current function context instead of the top context.
//
// Note that we must declare the foo upon entry of eval(), via a
// context slot declaration, but we cannot initialize it at the same
// time, because the const declaration may be at the end of the eval
// code (sigh...) and the const variable may have been used before
// (where its value is 'undefined'). Thus, we can only do the
// initialization when we actually encounter the expression and when
// the expression operands are defined and valid, and thus we need the
// split into 2 operations: declaration of the context slot followed
// by initialization.
value = frame_->CallRuntime(Runtime::kInitializeConstContextSlot, 3);
} else {
value = frame_->CallRuntime(Runtime::kStoreContextSlot, 3);
}
// Storing a variable must keep the (new) value on the expression
// stack. This is necessary for compiling chained assignment
// expressions.
frame_->Push(&value);
} else {
ASSERT(!slot->var()->is_dynamic());
JumpTarget exit;
if (init_state == CONST_INIT) {
ASSERT(slot->var()->mode() == Variable::CONST);
// Only the first const initialization must be executed (the slot
// still contains 'the hole' value). When the assignment is executed,
// the code is identical to a normal store (see below).
//
// We spill the frame in the code below because the direct-frame
// access of SlotOperand is potentially unsafe with an unspilled
// frame.
VirtualFrame::SpilledScope spilled_scope;
Comment cmnt(masm_, "[ Init const");
__ mov(ecx, SlotOperand(slot, ecx));
__ cmp(ecx, Factory::the_hole_value());
exit.Branch(not_equal);
}
// We must execute the store. Storing a variable must keep the (new)
// value on the stack. This is necessary for compiling assignment
// expressions.
//
// Note: We will reach here even with slot->var()->mode() ==
// Variable::CONST because of const declarations which will initialize
// consts to 'the hole' value and by doing so, end up calling this code.
if (slot->type() == Slot::PARAMETER) {
frame_->StoreToParameterAt(slot->index());
} else if (slot->type() == Slot::LOCAL) {
frame_->StoreToLocalAt(slot->index());
} else {
// The other slot types (LOOKUP and GLOBAL) cannot reach here.
//
// The use of SlotOperand below is safe for an unspilled frame
// because the slot is a context slot.
ASSERT(slot->type() == Slot::CONTEXT);
frame_->Dup();
Result value = frame_->Pop();
value.ToRegister();
Result start = allocator_->Allocate();
ASSERT(start.is_valid());
__ mov(SlotOperand(slot, start.reg()), value.reg());
// RecordWrite may destroy the value registers.
//
// TODO(204): Avoid actually spilling when the value is not
// needed (probably the common case).
frame_->Spill(value.reg());
int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
Result temp = allocator_->Allocate();
ASSERT(temp.is_valid());
__ RecordWrite(start.reg(), offset, value.reg(), temp.reg());
// The results start, value, and temp are unused by going out of
// scope.
}
exit.Bind();
}
}
void CodeGenerator::VisitSlot(Slot* slot) {
Comment cmnt(masm_, "[ Slot");
if (in_safe_int32_mode()) {
if ((slot->type() == Slot::LOCAL && !slot->is_arguments())) {
frame()->UntaggedPushLocalAt(slot->index());
} else if (slot->type() == Slot::PARAMETER) {
frame()->UntaggedPushParameterAt(slot->index());
} else {
UNREACHABLE();
}
} else {
LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
}
}
void CodeGenerator::VisitVariableProxy(VariableProxy* node) {
Comment cmnt(masm_, "[ VariableProxy");
Variable* var = node->var();
Expression* expr = var->rewrite();
if (expr != NULL) {
Visit(expr);
} else {
ASSERT(var->is_global());
ASSERT(!in_safe_int32_mode());
Reference ref(this, node);
ref.GetValue();
}
}
void CodeGenerator::VisitLiteral(Literal* node) {
Comment cmnt(masm_, "[ Literal");
if (in_safe_int32_mode()) {
frame_->PushUntaggedElement(node->handle());
} else {
frame_->Push(node->handle());
}
}
void CodeGenerator::PushUnsafeSmi(Handle<Object> value) {
ASSERT(value->IsSmi());
int bits = reinterpret_cast<int>(*value);
__ push(Immediate(bits & 0x0000FFFF));
__ or_(Operand(esp, 0), Immediate(bits & 0xFFFF0000));
}
void CodeGenerator::StoreUnsafeSmiToLocal(int offset, Handle<Object> value) {
ASSERT(value->IsSmi());
int bits = reinterpret_cast<int>(*value);
__ mov(Operand(ebp, offset), Immediate(bits & 0x0000FFFF));
__ or_(Operand(ebp, offset), Immediate(bits & 0xFFFF0000));
}
void CodeGenerator::MoveUnsafeSmi(Register target, Handle<Object> value) {
ASSERT(target.is_valid());
ASSERT(value->IsSmi());
int bits = reinterpret_cast<int>(*value);
__ Set(target, Immediate(bits & 0x0000FFFF));
__ or_(target, bits & 0xFFFF0000);
}
bool CodeGenerator::IsUnsafeSmi(Handle<Object> value) {
if (!value->IsSmi()) return false;
int int_value = Smi::cast(*value)->value();
return !is_intn(int_value, kMaxSmiInlinedBits);
}
// Materialize the regexp literal 'node' in the literals array
// 'literals' of the function. Leave the regexp boilerplate in
// 'boilerplate'.
class DeferredRegExpLiteral: public DeferredCode {
public:
DeferredRegExpLiteral(Register boilerplate,
Register literals,
RegExpLiteral* node)
: boilerplate_(boilerplate), literals_(literals), node_(node) {
set_comment("[ DeferredRegExpLiteral");
}
void Generate();
private:
Register boilerplate_;
Register literals_;
RegExpLiteral* node_;
};
void DeferredRegExpLiteral::Generate() {
// Since the entry is undefined we call the runtime system to
// compute the literal.
// Literal array (0).
__ push(literals_);
// Literal index (1).
__ push(Immediate(Smi::FromInt(node_->literal_index())));
// RegExp pattern (2).
__ push(Immediate(node_->pattern()));
// RegExp flags (3).
__ push(Immediate(node_->flags()));
__ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
if (!boilerplate_.is(eax)) __ mov(boilerplate_, eax);
}
void CodeGenerator::VisitRegExpLiteral(RegExpLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ RegExp Literal");
// Retrieve the literals array and check the allocated entry. Begin
// with a writable copy of the function of this activation in a
// register.
frame_->PushFunction();
Result literals = frame_->Pop();
literals.ToRegister();
frame_->Spill(literals.reg());
// Load the literals array of the function.
__ mov(literals.reg(),
FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
// Load the literal at the ast saved index.
Result boilerplate = allocator_->Allocate();
ASSERT(boilerplate.is_valid());
int literal_offset =
FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
__ mov(boilerplate.reg(), FieldOperand(literals.reg(), literal_offset));
// Check whether we need to materialize the RegExp object. If so,
// jump to the deferred code passing the literals array.
DeferredRegExpLiteral* deferred =
new DeferredRegExpLiteral(boilerplate.reg(), literals.reg(), node);
__ cmp(boilerplate.reg(), Factory::undefined_value());
deferred->Branch(equal);
deferred->BindExit();
literals.Unuse();
// Push the boilerplate object.
frame_->Push(&boilerplate);
}
void CodeGenerator::VisitObjectLiteral(ObjectLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ ObjectLiteral");
// Load a writable copy of the function of this activation in a
// register.
frame_->PushFunction();
Result literals = frame_->Pop();
literals.ToRegister();
frame_->Spill(literals.reg());
// Load the literals array of the function.
__ mov(literals.reg(),
FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
// Literal array.
frame_->Push(&literals);
// Literal index.
frame_->Push(Smi::FromInt(node->literal_index()));
// Constant properties.
frame_->Push(node->constant_properties());
// Should the object literal have fast elements?
frame_->Push(Smi::FromInt(node->fast_elements() ? 1 : 0));
Result clone;
if (node->depth() > 1) {
clone = frame_->CallRuntime(Runtime::kCreateObjectLiteral, 4);
} else {
clone = frame_->CallRuntime(Runtime::kCreateObjectLiteralShallow, 4);
}
frame_->Push(&clone);
for (int i = 0; i < node->properties()->length(); i++) {
ObjectLiteral::Property* property = node->properties()->at(i);
switch (property->kind()) {
case ObjectLiteral::Property::CONSTANT:
break;
case ObjectLiteral::Property::MATERIALIZED_LITERAL:
if (CompileTimeValue::IsCompileTimeValue(property->value())) break;
// else fall through.
case ObjectLiteral::Property::COMPUTED: {
Handle<Object> key(property->key()->handle());
if (key->IsSymbol()) {
// Duplicate the object as the IC receiver.
frame_->Dup();
Load(property->value());
Result dummy = frame_->CallStoreIC(Handle<String>::cast(key), false);
dummy.Unuse();
break;
}
// Fall through
}
case ObjectLiteral::Property::PROTOTYPE: {
// Duplicate the object as an argument to the runtime call.
frame_->Dup();
Load(property->key());
Load(property->value());
Result ignored = frame_->CallRuntime(Runtime::kSetProperty, 3);
// Ignore the result.
break;
}
case ObjectLiteral::Property::SETTER: {
// Duplicate the object as an argument to the runtime call.
frame_->Dup();
Load(property->key());
frame_->Push(Smi::FromInt(1));
Load(property->value());
Result ignored = frame_->CallRuntime(Runtime::kDefineAccessor, 4);
// Ignore the result.
break;
}
case ObjectLiteral::Property::GETTER: {
// Duplicate the object as an argument to the runtime call.
frame_->Dup();
Load(property->key());
frame_->Push(Smi::FromInt(0));
Load(property->value());
Result ignored = frame_->CallRuntime(Runtime::kDefineAccessor, 4);
// Ignore the result.
break;
}
default: UNREACHABLE();
}
}
}
void CodeGenerator::VisitArrayLiteral(ArrayLiteral* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ ArrayLiteral");
// Load a writable copy of the function of this activation in a
// register.
frame_->PushFunction();
Result literals = frame_->Pop();
literals.ToRegister();
frame_->Spill(literals.reg());
// Load the literals array of the function.
__ mov(literals.reg(),
FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
frame_->Push(&literals);
frame_->Push(Smi::FromInt(node->literal_index()));
frame_->Push(node->constant_elements());
int length = node->values()->length();
Result clone;
if (node->depth() > 1) {
clone = frame_->CallRuntime(Runtime::kCreateArrayLiteral, 3);
} else if (length > FastCloneShallowArrayStub::kMaximumLength) {
clone = frame_->CallRuntime(Runtime::kCreateArrayLiteralShallow, 3);
} else {
FastCloneShallowArrayStub stub(length);
clone = frame_->CallStub(&stub, 3);
}
frame_->Push(&clone);
// Generate code to set the elements in the array that are not
// literals.
for (int i = 0; i < length; i++) {
Expression* value = node->values()->at(i);
// If value is a literal the property value is already set in the
// boilerplate object.
if (value->AsLiteral() != NULL) continue;
// If value is a materialized literal the property value is already set
// in the boilerplate object if it is simple.
if (CompileTimeValue::IsCompileTimeValue(value)) continue;
// The property must be set by generated code.
Load(value);
// Get the property value off the stack.
Result prop_value = frame_->Pop();
prop_value.ToRegister();
// Fetch the array literal while leaving a copy on the stack and
// use it to get the elements array.
frame_->Dup();
Result elements = frame_->Pop();
elements.ToRegister();
frame_->Spill(elements.reg());
// Get the elements array.
__ mov(elements.reg(),
FieldOperand(elements.reg(), JSObject::kElementsOffset));
// Write to the indexed properties array.
int offset = i * kPointerSize + FixedArray::kHeaderSize;
__ mov(FieldOperand(elements.reg(), offset), prop_value.reg());
// Update the write barrier for the array address.
frame_->Spill(prop_value.reg()); // Overwritten by the write barrier.
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_valid());
__ RecordWrite(elements.reg(), offset, prop_value.reg(), scratch.reg());
}
}
void CodeGenerator::VisitCatchExtensionObject(CatchExtensionObject* node) {
ASSERT(!in_safe_int32_mode());
ASSERT(!in_spilled_code());
// Call runtime routine to allocate the catch extension object and
// assign the exception value to the catch variable.
Comment cmnt(masm_, "[ CatchExtensionObject");
Load(node->key());
Load(node->value());
Result result =
frame_->CallRuntime(Runtime::kCreateCatchExtensionObject, 2);
frame_->Push(&result);
}
void CodeGenerator::EmitSlotAssignment(Assignment* node) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Comment cmnt(masm(), "[ Variable Assignment");
Variable* var = node->target()->AsVariableProxy()->AsVariable();
ASSERT(var != NULL);
Slot* slot = var->slot();
ASSERT(slot != NULL);
// Evaluate the right-hand side.
if (node->is_compound()) {
// For a compound assignment the right-hand side is a binary operation
// between the current property value and the actual right-hand side.
LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
Load(node->value());
// Perform the binary operation.
bool overwrite_value =
(node->value()->AsBinaryOperation() != NULL &&
node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
// Construct the implicit binary operation.
BinaryOperation expr(node, node->binary_op(), node->target(),
node->value());
GenericBinaryOperation(&expr,
overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
} else {
// For non-compound assignment just load the right-hand side.
Load(node->value());
}
// Perform the assignment.
if (var->mode() != Variable::CONST || node->op() == Token::INIT_CONST) {
CodeForSourcePosition(node->position());
StoreToSlot(slot,
node->op() == Token::INIT_CONST ? CONST_INIT : NOT_CONST_INIT);
}
ASSERT(frame()->height() == original_height + 1);
}
void CodeGenerator::EmitNamedPropertyAssignment(Assignment* node) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Comment cmnt(masm(), "[ Named Property Assignment");
Variable* var = node->target()->AsVariableProxy()->AsVariable();
Property* prop = node->target()->AsProperty();
ASSERT(var == NULL || (prop == NULL && var->is_global()));
// Initialize name and evaluate the receiver sub-expression if necessary. If
// the receiver is trivial it is not placed on the stack at this point, but
// loaded whenever actually needed.
Handle<String> name;
bool is_trivial_receiver = false;
if (var != NULL) {
name = var->name();
} else {
Literal* lit = prop->key()->AsLiteral();
ASSERT_NOT_NULL(lit);
name = Handle<String>::cast(lit->handle());
// Do not materialize the receiver on the frame if it is trivial.
is_trivial_receiver = prop->obj()->IsTrivial();
if (!is_trivial_receiver) Load(prop->obj());
}
// Change to slow case in the beginning of an initialization block to
// avoid the quadratic behavior of repeatedly adding fast properties.
if (node->starts_initialization_block()) {
// Initialization block consists of assignments of the form expr.x = ..., so
// this will never be an assignment to a variable, so there must be a
// receiver object.
ASSERT_EQ(NULL, var);
if (is_trivial_receiver) {
frame()->Push(prop->obj());
} else {
frame()->Dup();
}
Result ignored = frame()->CallRuntime(Runtime::kToSlowProperties, 1);
}
// Change to fast case at the end of an initialization block. To prepare for
// that add an extra copy of the receiver to the frame, so that it can be
// converted back to fast case after the assignment.
if (node->ends_initialization_block() && !is_trivial_receiver) {
frame()->Dup();
}
// Stack layout:
// [tos] : receiver (only materialized if non-trivial)
// [tos+1] : receiver if at the end of an initialization block
// Evaluate the right-hand side.
if (node->is_compound()) {
// For a compound assignment the right-hand side is a binary operation
// between the current property value and the actual right-hand side.
if (is_trivial_receiver) {
frame()->Push(prop->obj());
} else if (var != NULL) {
// The LoadIC stub expects the object in eax.
// Freeing eax causes the code generator to load the global into it.
frame_->Spill(eax);
LoadGlobal();
} else {
frame()->Dup();
}
Result value = EmitNamedLoad(name, var != NULL);
frame()->Push(&value);
Load(node->value());
bool overwrite_value =
(node->value()->AsBinaryOperation() != NULL &&
node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
// Construct the implicit binary operation.
BinaryOperation expr(node, node->binary_op(), node->target(),
node->value());
GenericBinaryOperation(&expr,
overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
} else {
// For non-compound assignment just load the right-hand side.
Load(node->value());
}
// Stack layout:
// [tos] : value
// [tos+1] : receiver (only materialized if non-trivial)
// [tos+2] : receiver if at the end of an initialization block
// Perform the assignment. It is safe to ignore constants here.
ASSERT(var == NULL || var->mode() != Variable::CONST);
ASSERT_NE(Token::INIT_CONST, node->op());
if (is_trivial_receiver) {
Result value = frame()->Pop();
frame()->Push(prop->obj());
frame()->Push(&value);
}
CodeForSourcePosition(node->position());
bool is_contextual = (var != NULL);
Result answer = EmitNamedStore(name, is_contextual);
frame()->Push(&answer);
// Stack layout:
// [tos] : result
// [tos+1] : receiver if at the end of an initialization block
if (node->ends_initialization_block()) {
ASSERT_EQ(NULL, var);
// The argument to the runtime call is the receiver.
if (is_trivial_receiver) {
frame()->Push(prop->obj());
} else {
// A copy of the receiver is below the value of the assignment. Swap
// the receiver and the value of the assignment expression.
Result result = frame()->Pop();
Result receiver = frame()->Pop();
frame()->Push(&result);
frame()->Push(&receiver);
}
Result ignored = frame_->CallRuntime(Runtime::kToFastProperties, 1);
}
// Stack layout:
// [tos] : result
ASSERT_EQ(frame()->height(), original_height + 1);
}
void CodeGenerator::EmitKeyedPropertyAssignment(Assignment* node) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Comment cmnt(masm_, "[ Keyed Property Assignment");
Property* prop = node->target()->AsProperty();
ASSERT_NOT_NULL(prop);
// Evaluate the receiver subexpression.
Load(prop->obj());
// Change to slow case in the beginning of an initialization block to
// avoid the quadratic behavior of repeatedly adding fast properties.
if (node->starts_initialization_block()) {
frame_->Dup();
Result ignored = frame_->CallRuntime(Runtime::kToSlowProperties, 1);
}
// Change to fast case at the end of an initialization block. To prepare for
// that add an extra copy of the receiver to the frame, so that it can be
// converted back to fast case after the assignment.
if (node->ends_initialization_block()) {
frame_->Dup();
}
// Evaluate the key subexpression.
Load(prop->key());
// Stack layout:
// [tos] : key
// [tos+1] : receiver
// [tos+2] : receiver if at the end of an initialization block
// Evaluate the right-hand side.
if (node->is_compound()) {
// For a compound assignment the right-hand side is a binary operation
// between the current property value and the actual right-hand side.
// Duplicate receiver and key for loading the current property value.
frame()->PushElementAt(1);
frame()->PushElementAt(1);
Result value = EmitKeyedLoad();
frame()->Push(&value);
Load(node->value());
// Perform the binary operation.
bool overwrite_value =
(node->value()->AsBinaryOperation() != NULL &&
node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
BinaryOperation expr(node, node->binary_op(), node->target(),
node->value());
GenericBinaryOperation(&expr,
overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
} else {
// For non-compound assignment just load the right-hand side.
Load(node->value());
}
// Stack layout:
// [tos] : value
// [tos+1] : key
// [tos+2] : receiver
// [tos+3] : receiver if at the end of an initialization block
// Perform the assignment. It is safe to ignore constants here.
ASSERT(node->op() != Token::INIT_CONST);
CodeForSourcePosition(node->position());
Result answer = EmitKeyedStore(prop->key()->type());
frame()->Push(&answer);
// Stack layout:
// [tos] : result
// [tos+1] : receiver if at the end of an initialization block
// Change to fast case at the end of an initialization block.
if (node->ends_initialization_block()) {
// The argument to the runtime call is the extra copy of the receiver,
// which is below the value of the assignment. Swap the receiver and
// the value of the assignment expression.
Result result = frame()->Pop();
Result receiver = frame()->Pop();
frame()->Push(&result);
frame()->Push(&receiver);
Result ignored = frame_->CallRuntime(Runtime::kToFastProperties, 1);
}
// Stack layout:
// [tos] : result
ASSERT(frame()->height() == original_height + 1);
}
void CodeGenerator::VisitAssignment(Assignment* node) {
ASSERT(!in_safe_int32_mode());
#ifdef DEBUG
int original_height = frame()->height();
#endif
Variable* var = node->target()->AsVariableProxy()->AsVariable();
Property* prop = node->target()->AsProperty();
if (var != NULL && !var->is_global()) {
EmitSlotAssignment(node);
} else if ((prop != NULL && prop->key()->IsPropertyName()) ||
(var != NULL && var->is_global())) {
// Properties whose keys are property names and global variables are
// treated as named property references. We do not need to consider
// global 'this' because it is not a valid left-hand side.
EmitNamedPropertyAssignment(node);
} else if (prop != NULL) {
// Other properties (including rewritten parameters for a function that
// uses arguments) are keyed property assignments.
EmitKeyedPropertyAssignment(node);
} else {
// Invalid left-hand side.
Load(node->target());
Result result = frame()->CallRuntime(Runtime::kThrowReferenceError, 1);
// The runtime call doesn't actually return but the code generator will
// still generate code and expects a certain frame height.
frame()->Push(&result);
}
ASSERT(frame()->height() == original_height + 1);
}
void CodeGenerator::VisitThrow(Throw* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ Throw");
Load(node->exception());
Result result = frame_->CallRuntime(Runtime::kThrow, 1);
frame_->Push(&result);
}
void CodeGenerator::VisitProperty(Property* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ Property");
Reference property(this, node);
property.GetValue();
}
void CodeGenerator::VisitCall(Call* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ Call");
Expression* function = node->expression();
ZoneList<Expression*>* args = node->arguments();
// Check if the function is a variable or a property.
Variable* var = function->AsVariableProxy()->AsVariable();
Property* property = function->AsProperty();
// ------------------------------------------------------------------------
// Fast-case: Use inline caching.
// ---
// According to ECMA-262, section 11.2.3, page 44, the function to call
// must be resolved after the arguments have been evaluated. The IC code
// automatically handles this by loading the arguments before the function
// is resolved in cache misses (this also holds for megamorphic calls).
// ------------------------------------------------------------------------
if (var != NULL && var->is_possibly_eval()) {
// ----------------------------------
// JavaScript example: 'eval(arg)' // eval is not known to be shadowed
// ----------------------------------
// In a call to eval, we first call %ResolvePossiblyDirectEval to
// resolve the function we need to call and the receiver of the
// call. Then we call the resolved function using the given
// arguments.
// Prepare the stack for the call to the resolved function.
Load(function);
// Allocate a frame slot for the receiver.
frame_->Push(Factory::undefined_value());
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Result to hold the result of the function resolution and the
// final result of the eval call.
Result result;
// If we know that eval can only be shadowed by eval-introduced
// variables we attempt to load the global eval function directly
// in generated code. If we succeed, there is no need to perform a
// context lookup in the runtime system.
JumpTarget done;
if (var->slot() != NULL && var->mode() == Variable::DYNAMIC_GLOBAL) {
ASSERT(var->slot()->type() == Slot::LOOKUP);
JumpTarget slow;
// Prepare the stack for the call to
// ResolvePossiblyDirectEvalNoLookup by pushing the loaded
// function, the first argument to the eval call and the
// receiver.
Result fun = LoadFromGlobalSlotCheckExtensions(var->slot(),
NOT_INSIDE_TYPEOF,
&slow);
frame_->Push(&fun);
if (arg_count > 0) {
frame_->PushElementAt(arg_count);
} else {
frame_->Push(Factory::undefined_value());
}
frame_->PushParameterAt(-1);
// Resolve the call.
result =
frame_->CallRuntime(Runtime::kResolvePossiblyDirectEvalNoLookup, 3);
done.Jump(&result);
slow.Bind();
}
// Prepare the stack for the call to ResolvePossiblyDirectEval by
// pushing the loaded function, the first argument to the eval
// call and the receiver.
frame_->PushElementAt(arg_count + 1);
if (arg_count > 0) {
frame_->PushElementAt(arg_count);
} else {
frame_->Push(Factory::undefined_value());
}
frame_->PushParameterAt(-1);
// Resolve the call.
result = frame_->CallRuntime(Runtime::kResolvePossiblyDirectEval, 3);
// If we generated fast-case code bind the jump-target where fast
// and slow case merge.
if (done.is_linked()) done.Bind(&result);
// The runtime call returns a pair of values in eax (function) and
// edx (receiver). Touch up the stack with the right values.
Result receiver = allocator_->Allocate(edx);
frame_->SetElementAt(arg_count + 1, &result);
frame_->SetElementAt(arg_count, &receiver);
receiver.Unuse();
// Call the function.
CodeForSourcePosition(node->position());
InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
CallFunctionStub call_function(arg_count, in_loop, RECEIVER_MIGHT_BE_VALUE);
result = frame_->CallStub(&call_function, arg_count + 1);
// Restore the context and overwrite the function on the stack with
// the result.
frame_->RestoreContextRegister();
frame_->SetElementAt(0, &result);
} else if (var != NULL && !var->is_this() && var->is_global()) {
// ----------------------------------
// JavaScript example: 'foo(1, 2, 3)' // foo is global
// ----------------------------------
// Pass the global object as the receiver and let the IC stub
// patch the stack to use the global proxy as 'this' in the
// invoked function.
LoadGlobal();
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Push the name of the function onto the frame.
frame_->Push(var->name());
// Call the IC initialization code.
CodeForSourcePosition(node->position());
Result result = frame_->CallCallIC(RelocInfo::CODE_TARGET_CONTEXT,
arg_count,
loop_nesting());
frame_->RestoreContextRegister();
frame_->Push(&result);
} else if (var != NULL && var->slot() != NULL &&
var->slot()->type() == Slot::LOOKUP) {
// ----------------------------------
// JavaScript examples:
//
// with (obj) foo(1, 2, 3) // foo may be in obj.
//
// function f() {};
// function g() {
// eval(...);
// f(); // f could be in extension object.
// }
// ----------------------------------
JumpTarget slow, done;
Result function;
// Generate fast case for loading functions from slots that
// correspond to local/global variables or arguments unless they
// are shadowed by eval-introduced bindings.
EmitDynamicLoadFromSlotFastCase(var->slot(),
NOT_INSIDE_TYPEOF,
&function,
&slow,
&done);
slow.Bind();
// Enter the runtime system to load the function from the context.
// Sync the frame so we can push the arguments directly into
// place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(var->name()));
frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
// The runtime call returns a pair of values in eax and edx. The
// looked-up function is in eax and the receiver is in edx. These
// register references are not ref counted here. We spill them
// eagerly since they are arguments to an inevitable call (and are
// not sharable by the arguments).
ASSERT(!allocator()->is_used(eax));
frame_->EmitPush(eax);
// Load the receiver.
ASSERT(!allocator()->is_used(edx));
frame_->EmitPush(edx);
// If fast case code has been generated, emit code to push the
// function and receiver and have the slow path jump around this
// code.
if (done.is_linked()) {
JumpTarget call;
call.Jump();
done.Bind(&function);
frame_->Push(&function);
LoadGlobalReceiver();
call.Bind();
}
// Call the function.
CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
} else if (property != NULL) {
// Check if the key is a literal string.
Literal* literal = property->key()->AsLiteral();
if (literal != NULL && literal->handle()->IsSymbol()) {
// ------------------------------------------------------------------
// JavaScript example: 'object.foo(1, 2, 3)' or 'map["key"](1, 2, 3)'
// ------------------------------------------------------------------
Handle<String> name = Handle<String>::cast(literal->handle());
if (ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION &&
name->IsEqualTo(CStrVector("apply")) &&
args->length() == 2 &&
args->at(1)->AsVariableProxy() != NULL &&
args->at(1)->AsVariableProxy()->IsArguments()) {
// Use the optimized Function.prototype.apply that avoids
// allocating lazily allocated arguments objects.
CallApplyLazy(property->obj(),
args->at(0),
args->at(1)->AsVariableProxy(),
node->position());
} else {
// Push the receiver onto the frame.
Load(property->obj());
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Push the name of the function onto the frame.
frame_->Push(name);
// Call the IC initialization code.
CodeForSourcePosition(node->position());
Result result =
frame_->CallCallIC(RelocInfo::CODE_TARGET, arg_count,
loop_nesting());
frame_->RestoreContextRegister();
frame_->Push(&result);
}
} else {
// -------------------------------------------
// JavaScript example: 'array[index](1, 2, 3)'
// -------------------------------------------
// Load the function to call from the property through a reference.
// Pass receiver to called function.
if (property->is_synthetic()) {
Reference ref(this, property);
ref.GetValue();
// Use global object as receiver.
LoadGlobalReceiver();
// Call the function.
CallWithArguments(args, RECEIVER_MIGHT_BE_VALUE, node->position());
} else {
// Push the receiver onto the frame.
Load(property->obj());
// Load the arguments.
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
frame_->SpillTop();
}
// Load the name of the function.
Load(property->key());
// Call the IC initialization code.
CodeForSourcePosition(node->position());
Result result =
frame_->CallKeyedCallIC(RelocInfo::CODE_TARGET,
arg_count,
loop_nesting());
frame_->RestoreContextRegister();
frame_->Push(&result);
}
}
} else {
// ----------------------------------
// JavaScript example: 'foo(1, 2, 3)' // foo is not global
// ----------------------------------
// Load the function.
Load(function);
// Pass the global proxy as the receiver.
LoadGlobalReceiver();
// Call the function.
CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
}
}
void CodeGenerator::VisitCallNew(CallNew* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ CallNew");
// According to ECMA-262, section 11.2.2, page 44, the function
// expression in new calls must be evaluated before the
// arguments. This is different from ordinary calls, where the
// actual function to call is resolved after the arguments have been
// evaluated.
// Compute function to call and use the global object as the
// receiver. There is no need to use the global proxy here because
// it will always be replaced with a newly allocated object.
Load(node->expression());
LoadGlobal();
// Push the arguments ("left-to-right") on the stack.
ZoneList<Expression*>* args = node->arguments();
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
}
// Call the construct call builtin that handles allocation and
// constructor invocation.
CodeForSourcePosition(node->position());
Result result = frame_->CallConstructor(arg_count);
// Replace the function on the stack with the result.
frame_->SetElementAt(0, &result);
}
void CodeGenerator::GenerateIsSmi(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask));
value.Unuse();
destination()->Split(zero);
}
void CodeGenerator::GenerateLog(ZoneList<Expression*>* args) {
// Conditionally generate a log call.
// Args:
// 0 (literal string): The type of logging (corresponds to the flags).
// This is used to determine whether or not to generate the log call.
// 1 (string): Format string. Access the string at argument index 2
// with '%2s' (see Logger::LogRuntime for all the formats).
// 2 (array): Arguments to the format string.
ASSERT_EQ(args->length(), 3);
#ifdef ENABLE_LOGGING_AND_PROFILING
if (ShouldGenerateLog(args->at(0))) {
Load(args->at(1));
Load(args->at(2));
frame_->CallRuntime(Runtime::kLog, 2);
}
#endif
// Finally, we're expected to leave a value on the top of the stack.
frame_->Push(Factory::undefined_value());
}
void CodeGenerator::GenerateIsNonNegativeSmi(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask | kSmiSignMask));
value.Unuse();
destination()->Split(zero);
}
class DeferredStringCharCodeAt : public DeferredCode {
public:
DeferredStringCharCodeAt(Register object,
Register index,
Register scratch,
Register result)
: result_(result),
char_code_at_generator_(object,
index,
scratch,
result,
&need_conversion_,
&need_conversion_,
&index_out_of_range_,
STRING_INDEX_IS_NUMBER) {}
StringCharCodeAtGenerator* fast_case_generator() {
return &char_code_at_generator_;
}
virtual void Generate() {
VirtualFrameRuntimeCallHelper call_helper(frame_state());
char_code_at_generator_.GenerateSlow(masm(), call_helper);
__ bind(&need_conversion_);
// Move the undefined value into the result register, which will
// trigger conversion.
__ Set(result_, Immediate(Factory::undefined_value()));
__ jmp(exit_label());
__ bind(&index_out_of_range_);
// When the index is out of range, the spec requires us to return
// NaN.
__ Set(result_, Immediate(Factory::nan_value()));
__ jmp(exit_label());
}
private:
Register result_;
Label need_conversion_;
Label index_out_of_range_;
StringCharCodeAtGenerator char_code_at_generator_;
};
// This generates code that performs a String.prototype.charCodeAt() call
// or returns a smi in order to trigger conversion.
void CodeGenerator::GenerateStringCharCodeAt(ZoneList<Expression*>* args) {
Comment(masm_, "[ GenerateStringCharCodeAt");
ASSERT(args->length() == 2);
Load(args->at(0));
Load(args->at(1));
Result index = frame_->Pop();
Result object = frame_->Pop();
object.ToRegister();
index.ToRegister();
// We might mutate the object register.
frame_->Spill(object.reg());
// We need two extra registers.
Result result = allocator()->Allocate();
ASSERT(result.is_valid());
Result scratch = allocator()->Allocate();
ASSERT(scratch.is_valid());
DeferredStringCharCodeAt* deferred =
new DeferredStringCharCodeAt(object.reg(),
index.reg(),
scratch.reg(),
result.reg());
deferred->fast_case_generator()->GenerateFast(masm_);
deferred->BindExit();
frame_->Push(&result);
}
class DeferredStringCharFromCode : public DeferredCode {
public:
DeferredStringCharFromCode(Register code,
Register result)
: char_from_code_generator_(code, result) {}
StringCharFromCodeGenerator* fast_case_generator() {
return &char_from_code_generator_;
}
virtual void Generate() {
VirtualFrameRuntimeCallHelper call_helper(frame_state());
char_from_code_generator_.GenerateSlow(masm(), call_helper);
}
private:
StringCharFromCodeGenerator char_from_code_generator_;
};
// Generates code for creating a one-char string from a char code.
void CodeGenerator::GenerateStringCharFromCode(ZoneList<Expression*>* args) {
Comment(masm_, "[ GenerateStringCharFromCode");
ASSERT(args->length() == 1);
Load(args->at(0));
Result code = frame_->Pop();
code.ToRegister();
ASSERT(code.is_valid());
Result result = allocator()->Allocate();
ASSERT(result.is_valid());
DeferredStringCharFromCode* deferred = new DeferredStringCharFromCode(
code.reg(), result.reg());
deferred->fast_case_generator()->GenerateFast(masm_);
deferred->BindExit();
frame_->Push(&result);
}
class DeferredStringCharAt : public DeferredCode {
public:
DeferredStringCharAt(Register object,
Register index,
Register scratch1,
Register scratch2,
Register result)
: result_(result),
char_at_generator_(object,
index,
scratch1,
scratch2,
result,
&need_conversion_,
&need_conversion_,
&index_out_of_range_,
STRING_INDEX_IS_NUMBER) {}
StringCharAtGenerator* fast_case_generator() {
return &char_at_generator_;
}
virtual void Generate() {
VirtualFrameRuntimeCallHelper call_helper(frame_state());
char_at_generator_.GenerateSlow(masm(), call_helper);
__ bind(&need_conversion_);
// Move smi zero into the result register, which will trigger
// conversion.
__ Set(result_, Immediate(Smi::FromInt(0)));
__ jmp(exit_label());
__ bind(&index_out_of_range_);
// When the index is out of range, the spec requires us to return
// the empty string.
__ Set(result_, Immediate(Factory::empty_string()));
__ jmp(exit_label());
}
private:
Register result_;
Label need_conversion_;
Label index_out_of_range_;
StringCharAtGenerator char_at_generator_;
};
// This generates code that performs a String.prototype.charAt() call
// or returns a smi in order to trigger conversion.
void CodeGenerator::GenerateStringCharAt(ZoneList<Expression*>* args) {
Comment(masm_, "[ GenerateStringCharAt");
ASSERT(args->length() == 2);
Load(args->at(0));
Load(args->at(1));
Result index = frame_->Pop();
Result object = frame_->Pop();
object.ToRegister();
index.ToRegister();
// We might mutate the object register.
frame_->Spill(object.reg());
// We need three extra registers.
Result result = allocator()->Allocate();
ASSERT(result.is_valid());
Result scratch1 = allocator()->Allocate();
ASSERT(scratch1.is_valid());
Result scratch2 = allocator()->Allocate();
ASSERT(scratch2.is_valid());
DeferredStringCharAt* deferred =
new DeferredStringCharAt(object.reg(),
index.reg(),
scratch1.reg(),
scratch2.reg(),
result.reg());
deferred->fast_case_generator()->GenerateFast(masm_);
deferred->BindExit();
frame_->Push(&result);
}
void CodeGenerator::GenerateIsArray(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(equal);
// It is a heap object - get map.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
// Check if the object is a JS array or not.
__ CmpObjectType(value.reg(), JS_ARRAY_TYPE, temp.reg());
value.Unuse();
temp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateIsRegExp(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result value = frame_->Pop();
value.ToRegister();
ASSERT(value.is_valid());
__ test(value.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(equal);
// It is a heap object - get map.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
// Check if the object is a regexp.
__ CmpObjectType(value.reg(), JS_REGEXP_TYPE, temp.reg());
value.Unuse();
temp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateIsObject(ZoneList<Expression*>* args) {
// This generates a fast version of:
// (typeof(arg) === 'object' || %_ClassOf(arg) == 'RegExp')
ASSERT(args->length() == 1);
Load(args->at(0));
Result obj = frame_->Pop();
obj.ToRegister();
__ test(obj.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
__ cmp(obj.reg(), Factory::null_value());
destination()->true_target()->Branch(equal);
Result map = allocator()->Allocate();
ASSERT(map.is_valid());
__ mov(map.reg(), FieldOperand(obj.reg(), HeapObject::kMapOffset));
// Undetectable objects behave like undefined when tested with typeof.
__ test_b(FieldOperand(map.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
destination()->false_target()->Branch(not_zero);
// Do a range test for JSObject type. We can't use
// MacroAssembler::IsInstanceJSObjectType, because we are using a
// ControlDestination, so we copy its implementation here.
__ movzx_b(map.reg(), FieldOperand(map.reg(), Map::kInstanceTypeOffset));
__ sub(Operand(map.reg()), Immediate(FIRST_JS_OBJECT_TYPE));
__ cmp(map.reg(), LAST_JS_OBJECT_TYPE - FIRST_JS_OBJECT_TYPE);
obj.Unuse();
map.Unuse();
destination()->Split(below_equal);
}
void CodeGenerator::GenerateIsFunction(ZoneList<Expression*>* args) {
// This generates a fast version of:
// (%_ClassOf(arg) === 'Function')
ASSERT(args->length() == 1);
Load(args->at(0));
Result obj = frame_->Pop();
obj.ToRegister();
__ test(obj.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ CmpObjectType(obj.reg(), JS_FUNCTION_TYPE, temp.reg());
obj.Unuse();
temp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateIsUndetectableObject(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
Load(args->at(0));
Result obj = frame_->Pop();
obj.ToRegister();
__ test(obj.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(),
FieldOperand(obj.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
obj.Unuse();
temp.Unuse();
destination()->Split(not_zero);
}
void CodeGenerator::GenerateIsConstructCall(ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
// Get the frame pointer for the calling frame.
Result fp = allocator()->Allocate();
__ mov(fp.reg(), Operand(ebp, StandardFrameConstants::kCallerFPOffset));
// Skip the arguments adaptor frame if it exists.
Label check_frame_marker;
__ cmp(Operand(fp.reg(), StandardFrameConstants::kContextOffset),
Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(not_equal, &check_frame_marker);
__ mov(fp.reg(), Operand(fp.reg(), StandardFrameConstants::kCallerFPOffset));
// Check the marker in the calling frame.
__ bind(&check_frame_marker);
__ cmp(Operand(fp.reg(), StandardFrameConstants::kMarkerOffset),
Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
fp.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateArgumentsLength(ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
Result fp = allocator_->Allocate();
Result result = allocator_->Allocate();
ASSERT(fp.is_valid() && result.is_valid());
Label exit;
// Get the number of formal parameters.
__ Set(result.reg(), Immediate(Smi::FromInt(scope()->num_parameters())));
// Check if the calling frame is an arguments adaptor frame.
__ mov(fp.reg(), Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ cmp(Operand(fp.reg(), StandardFrameConstants::kContextOffset),
Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(not_equal, &exit);
// Arguments adaptor case: Read the arguments length from the
// adaptor frame.
__ mov(result.reg(),
Operand(fp.reg(), ArgumentsAdaptorFrameConstants::kLengthOffset));
__ bind(&exit);
result.set_type_info(TypeInfo::Smi());
if (FLAG_debug_code) __ AbortIfNotSmi(result.reg());
frame_->Push(&result);
}
void CodeGenerator::GenerateClassOf(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
JumpTarget leave, null, function, non_function_constructor;
Load(args->at(0)); // Load the object.
Result obj = frame_->Pop();
obj.ToRegister();
frame_->Spill(obj.reg());
// If the object is a smi, we return null.
__ test(obj.reg(), Immediate(kSmiTagMask));
null.Branch(zero);
// Check that the object is a JS object but take special care of JS
// functions to make sure they have 'Function' as their class.
__ CmpObjectType(obj.reg(), FIRST_JS_OBJECT_TYPE, obj.reg());
null.Branch(below);
// As long as JS_FUNCTION_TYPE is the last instance type and it is
// right after LAST_JS_OBJECT_TYPE, we can avoid checking for
// LAST_JS_OBJECT_TYPE.
ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
__ CmpInstanceType(obj.reg(), JS_FUNCTION_TYPE);
function.Branch(equal);
// Check if the constructor in the map is a function.
{ Result tmp = allocator()->Allocate();
__ mov(obj.reg(), FieldOperand(obj.reg(), Map::kConstructorOffset));
__ CmpObjectType(obj.reg(), JS_FUNCTION_TYPE, tmp.reg());
non_function_constructor.Branch(not_equal);
}
// The map register now contains the constructor function. Grab the
// instance class name from there.
__ mov(obj.reg(),
FieldOperand(obj.reg(), JSFunction::kSharedFunctionInfoOffset));
__ mov(obj.reg(),
FieldOperand(obj.reg(), SharedFunctionInfo::kInstanceClassNameOffset));
frame_->Push(&obj);
leave.Jump();
// Functions have class 'Function'.
function.Bind();
frame_->Push(Factory::function_class_symbol());
leave.Jump();
// Objects with a non-function constructor have class 'Object'.
non_function_constructor.Bind();
frame_->Push(Factory::Object_symbol());
leave.Jump();
// Non-JS objects have class null.
null.Bind();
frame_->Push(Factory::null_value());
// All done.
leave.Bind();
}
void CodeGenerator::GenerateValueOf(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
JumpTarget leave;
Load(args->at(0)); // Load the object.
frame_->Dup();
Result object = frame_->Pop();
object.ToRegister();
ASSERT(object.is_valid());
// if (object->IsSmi()) return object.
__ test(object.reg(), Immediate(kSmiTagMask));
leave.Branch(zero, taken);
// It is a heap object - get map.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
// if (!object->IsJSValue()) return object.
__ CmpObjectType(object.reg(), JS_VALUE_TYPE, temp.reg());
leave.Branch(not_equal, not_taken);
__ mov(temp.reg(), FieldOperand(object.reg(), JSValue::kValueOffset));
object.Unuse();
frame_->SetElementAt(0, &temp);
leave.Bind();
}
void CodeGenerator::GenerateSetValueOf(ZoneList<Expression*>* args) {
ASSERT(args->length() == 2);
JumpTarget leave;
Load(args->at(0)); // Load the object.
Load(args->at(1)); // Load the value.
Result value = frame_->Pop();
Result object = frame_->Pop();
value.ToRegister();
object.ToRegister();
// if (object->IsSmi()) return value.
__ test(object.reg(), Immediate(kSmiTagMask));
leave.Branch(zero, &value, taken);
// It is a heap object - get its map.
Result scratch = allocator_->Allocate();
ASSERT(scratch.is_valid());
// if (!object->IsJSValue()) return value.
__ CmpObjectType(object.reg(), JS_VALUE_TYPE, scratch.reg());
leave.Branch(not_equal, &value, not_taken);
// Store the value.
__ mov(FieldOperand(object.reg(), JSValue::kValueOffset), value.reg());
// Update the write barrier. Save the value as it will be
// overwritten by the write barrier code and is needed afterward.
Result duplicate_value = allocator_->Allocate();
ASSERT(duplicate_value.is_valid());
__ mov(duplicate_value.reg(), value.reg());
// The object register is also overwritten by the write barrier and
// possibly aliased in the frame.
frame_->Spill(object.reg());
__ RecordWrite(object.reg(), JSValue::kValueOffset, duplicate_value.reg(),
scratch.reg());
object.Unuse();
scratch.Unuse();
duplicate_value.Unuse();
// Leave.
leave.Bind(&value);
frame_->Push(&value);
}
void CodeGenerator::GenerateArguments(ZoneList<Expression*>* args) {
ASSERT(args->length() == 1);
// ArgumentsAccessStub expects the key in edx and the formal
// parameter count in eax.
Load(args->at(0));
Result key = frame_->Pop();
// Explicitly create a constant result.
Result count(Handle<Smi>(Smi::FromInt(scope()->num_parameters())));
// Call the shared stub to get to arguments[key].
ArgumentsAccessStub stub(ArgumentsAccessStub::READ_ELEMENT);
Result result = frame_->CallStub(&stub, &key, &count);
frame_->Push(&result);
}
void CodeGenerator::GenerateObjectEquals(ZoneList<Expression*>* args) {
ASSERT(args->length() == 2);
// Load the two objects into registers and perform the comparison.
Load(args->at(0));
Load(args->at(1));
Result right = frame_->Pop();
Result left = frame_->Pop();
right.ToRegister();
left.ToRegister();
__ cmp(right.reg(), Operand(left.reg()));
right.Unuse();
left.Unuse();
destination()->Split(equal);
}
void CodeGenerator::GenerateGetFramePointer(ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
ASSERT(kSmiTag == 0); // EBP value is aligned, so it should look like Smi.
Result ebp_as_smi = allocator_->Allocate();
ASSERT(ebp_as_smi.is_valid());
__ mov(ebp_as_smi.reg(), Operand(ebp));
frame_->Push(&ebp_as_smi);
}
void CodeGenerator::GenerateRandomHeapNumber(
ZoneList<Expression*>* args) {
ASSERT(args->length() == 0);
frame_->SpillAll();
Label slow_allocate_heapnumber;
Label heapnumber_allocated;
__ AllocateHeapNumber(edi, ebx, ecx, &slow_allocate_heapnumber);
__ jmp(&heapnumber_allocated);
__ bind(&slow_allocate_heapnumber);
// To allocate a heap number, and ensure that it is not a smi, we
// call the runtime function FUnaryMinus on 0, returning the double
// -0.0. A new, distinct heap number is returned each time.
__ push(Immediate(Smi::FromInt(0)));
__ CallRuntime(Runtime::kNumberUnaryMinus, 1);
__ mov(edi, eax);
__ bind(&heapnumber_allocated);
__ PrepareCallCFunction(0, ebx);
__ CallCFunction(ExternalReference::random_uint32_function(), 0);
// Convert 32 random bits in eax to 0.(32 random bits) in a double
// by computing:
// ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
// This is implemented on both SSE2 and FPU.
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ mov(ebx, Immediate(0x49800000)); // 1.0 x 2^20 as single.
__ movd(xmm1, Operand(ebx));
__ movd(xmm0, Operand(eax));
__ cvtss2sd(xmm1, xmm1);
__ pxor(xmm0, xmm1);
__ subsd(xmm0, xmm1);
__ movdbl(FieldOperand(edi, HeapNumber::kValueOffset), xmm0);
} else {
// 0x4130000000000000 is 1.0 x 2^20 as a double.
__ mov(FieldOperand(edi, HeapNumber::kExponentOffset),
Immediate(0x41300000));
__ mov(FieldOperand(edi, HeapNumber::kMantissaOffset), eax);
__ fld_d(FieldOperand(edi, HeapNumber::kValueOffset));
__ mov(FieldOperand(edi, HeapNumber::kMantissaOffset), Immediate(0));
__ fld_d(FieldOperand(edi, HeapNumber::kValueOffset));
__ fsubp(1);
__ fstp_d(FieldOperand(edi, HeapNumber::kValueOffset));
}
__ mov(eax, edi);
Result result = allocator_->Allocate(eax);
frame_->Push(&result);
}
void CodeGenerator::GenerateStringAdd(ZoneList<Expression*>* args) {
ASSERT_EQ(2, args->length());
Load(args->at(0));
Load(args->at(1));
StringAddStub stub(NO_STRING_ADD_FLAGS);
Result answer = frame_->CallStub(&stub, 2);
frame_->Push(&answer);
}
void CodeGenerator::GenerateSubString(ZoneList<Expression*>* args) {
ASSERT_EQ(3, args->length());
Load(args->at(0));
Load(args->at(1));
Load(args->at(2));
SubStringStub stub;
Result answer = frame_->CallStub(&stub, 3);
frame_->Push(&answer);
}
void CodeGenerator::GenerateStringCompare(ZoneList<Expression*>* args) {
ASSERT_EQ(2, args->length());
Load(args->at(0));
Load(args->at(1));
StringCompareStub stub;
Result answer = frame_->CallStub(&stub, 2);
frame_->Push(&answer);
}
void CodeGenerator::GenerateRegExpExec(ZoneList<Expression*>* args) {
ASSERT_EQ(4, args->length());
// Load the arguments on the stack and call the stub.
Load(args->at(0));
Load(args->at(1));
Load(args->at(2));
Load(args->at(3));
RegExpExecStub stub;
Result result = frame_->CallStub(&stub, 4);
frame_->Push(&result);
}
void CodeGenerator::GenerateRegExpConstructResult(ZoneList<Expression*>* args) {
// No stub. This code only occurs a few times in regexp.js.
const int kMaxInlineLength = 100;
ASSERT_EQ(3, args->length());
Load(args->at(0)); // Size of array, smi.
Load(args->at(1)); // "index" property value.
Load(args->at(2)); // "input" property value.
{
VirtualFrame::SpilledScope spilled_scope;
Label slowcase;
Label done;
__ mov(ebx, Operand(esp, kPointerSize * 2));
__ test(ebx, Immediate(kSmiTagMask));
__ j(not_zero, &slowcase);
__ cmp(Operand(ebx), Immediate(Smi::FromInt(kMaxInlineLength)));
__ j(above, &slowcase);
// Smi-tagging is equivalent to multiplying by 2.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
// Allocate RegExpResult followed by FixedArray with size in ebx.
// JSArray: [Map][empty properties][Elements][Length-smi][index][input]
// Elements: [Map][Length][..elements..]
__ AllocateInNewSpace(JSRegExpResult::kSize + FixedArray::kHeaderSize,
times_half_pointer_size,
ebx, // In: Number of elements (times 2, being a smi)
eax, // Out: Start of allocation (tagged).
ecx, // Out: End of allocation.
edx, // Scratch register
&slowcase,
TAG_OBJECT);
// eax: Start of allocated area, object-tagged.
// Set JSArray map to global.regexp_result_map().
// Set empty properties FixedArray.
// Set elements to point to FixedArray allocated right after the JSArray.
// Interleave operations for better latency.
__ mov(edx, ContextOperand(esi, Context::GLOBAL_INDEX));
__ mov(ecx, Immediate(Factory::empty_fixed_array()));
__ lea(ebx, Operand(eax, JSRegExpResult::kSize));
__ mov(edx, FieldOperand(edx, GlobalObject::kGlobalContextOffset));
__ mov(FieldOperand(eax, JSObject::kElementsOffset), ebx);
__ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ecx);
__ mov(edx, ContextOperand(edx, Context::REGEXP_RESULT_MAP_INDEX));
__ mov(FieldOperand(eax, HeapObject::kMapOffset), edx);
// Set input, index and length fields from arguments.
__ pop(FieldOperand(eax, JSRegExpResult::kInputOffset));
__ pop(FieldOperand(eax, JSRegExpResult::kIndexOffset));
__ pop(ecx);
__ mov(FieldOperand(eax, JSArray::kLengthOffset), ecx);
// Fill out the elements FixedArray.
// eax: JSArray.
// ebx: FixedArray.
// ecx: Number of elements in array, as smi.
// Set map.
__ mov(FieldOperand(ebx, HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
// Set length.
__ mov(FieldOperand(ebx, FixedArray::kLengthOffset), ecx);
// Fill contents of fixed-array with the-hole.
__ SmiUntag(ecx);
__ mov(edx, Immediate(Factory::the_hole_value()));
__ lea(ebx, FieldOperand(ebx, FixedArray::kHeaderSize));
// Fill fixed array elements with hole.
// eax: JSArray.
// ecx: Number of elements to fill.
// ebx: Start of elements in FixedArray.
// edx: the hole.
Label loop;
__ test(ecx, Operand(ecx));
__ bind(&loop);
__ j(less_equal, &done); // Jump if ecx is negative or zero.
__ sub(Operand(ecx), Immediate(1));
__ mov(Operand(ebx, ecx, times_pointer_size, 0), edx);
__ jmp(&loop);
__ bind(&slowcase);
__ CallRuntime(Runtime::kRegExpConstructResult, 3);
__ bind(&done);
}
frame_->Forget(3);
frame_->Push(eax);
}
class DeferredSearchCache: public DeferredCode {
public:
DeferredSearchCache(Register dst, Register cache, Register key)
: dst_(dst), cache_(cache), key_(key) {
set_comment("[ DeferredSearchCache");
}
virtual void Generate();
private:
Register dst_; // on invocation Smi index of finger, on exit
// holds value being looked up.
Register cache_; // instance of JSFunctionResultCache.
Register key_; // key being looked up.
};
void DeferredSearchCache::Generate() {
Label first_loop, search_further, second_loop, cache_miss;
// Smi-tagging is equivalent to multiplying by 2.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
Smi* kEntrySizeSmi = Smi::FromInt(JSFunctionResultCache::kEntrySize);
Smi* kEntriesIndexSmi = Smi::FromInt(JSFunctionResultCache::kEntriesIndex);
// Check the cache from finger to start of the cache.
__ bind(&first_loop);
__ sub(Operand(dst_), Immediate(kEntrySizeSmi));
__ cmp(Operand(dst_), Immediate(kEntriesIndexSmi));
__ j(less, &search_further);
__ cmp(key_, CodeGenerator::FixedArrayElementOperand(cache_, dst_));
__ j(not_equal, &first_loop);
__ mov(FieldOperand(cache_, JSFunctionResultCache::kFingerOffset), dst_);
__ mov(dst_, CodeGenerator::FixedArrayElementOperand(cache_, dst_, 1));
__ jmp(exit_label());
__ bind(&search_further);
// Check the cache from end of cache up to finger.
__ mov(dst_, FieldOperand(cache_, JSFunctionResultCache::kCacheSizeOffset));
__ bind(&second_loop);
__ sub(Operand(dst_), Immediate(kEntrySizeSmi));
// Consider prefetching into some reg.
__ cmp(dst_, FieldOperand(cache_, JSFunctionResultCache::kFingerOffset));
__ j(less_equal, &cache_miss);
__ cmp(key_, CodeGenerator::FixedArrayElementOperand(cache_, dst_));
__ j(not_equal, &second_loop);
__ mov(FieldOperand(cache_, JSFunctionResultCache::kFingerOffset), dst_);
__ mov(dst_, CodeGenerator::FixedArrayElementOperand(cache_, dst_, 1));
__ jmp(exit_label());
__ bind(&cache_miss);
__ push(cache_); // store a reference to cache
__ push(key_); // store a key
Handle<Object> receiver(Top::global_context()->global());
__ push(Immediate(receiver));
__ push(key_);
// On ia32 function must be in edi.
__ mov(edi, FieldOperand(cache_, JSFunctionResultCache::kFactoryOffset));
ParameterCount expected(1);
__ InvokeFunction(edi, expected, CALL_FUNCTION);
// Find a place to put new cached value into.
Label add_new_entry, update_cache;
__ mov(ecx, Operand(esp, kPointerSize)); // restore the cache
// Possible optimization: cache size is constant for the given cache
// so technically we could use a constant here. However, if we have
// cache miss this optimization would hardly matter much.
// Check if we could add new entry to cache.
__ mov(ebx, FieldOperand(ecx, FixedArray::kLengthOffset));
__ cmp(ebx, FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset));
__ j(greater, &add_new_entry);
// Check if we could evict entry after finger.
__ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kFingerOffset));
__ add(Operand(edx), Immediate(kEntrySizeSmi));
__ cmp(ebx, Operand(edx));
__ j(greater, &update_cache);
// Need to wrap over the cache.
__ mov(edx, Immediate(kEntriesIndexSmi));
__ jmp(&update_cache);
__ bind(&add_new_entry);
__ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset));
__ lea(ebx, Operand(edx, JSFunctionResultCache::kEntrySize << 1));
__ mov(FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset), ebx);
// Update the cache itself.
// edx holds the index.
__ bind(&update_cache);
__ pop(ebx); // restore the key
__ mov(FieldOperand(ecx, JSFunctionResultCache::kFingerOffset), edx);
// Store key.
__ mov(CodeGenerator::FixedArrayElementOperand(ecx, edx), ebx);
__ RecordWrite(ecx, 0, ebx, edx);
// Store value.
__ pop(ecx); // restore the cache.
__ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kFingerOffset));
__ add(Operand(edx), Immediate(Smi::FromInt(1)));
__ mov(ebx, eax);
__ mov(CodeGenerator::FixedArrayElementOperand(ecx, edx), ebx);
__ RecordWrite(ecx, 0, ebx, edx);
if (!dst_.is(eax)) {
__ mov(dst_, eax);
}
}
void CodeGenerator::GenerateGetFromCache(ZoneList<Expression*>* args) {
ASSERT_EQ(2, args->length());
ASSERT_NE(NULL, args->at(0)->AsLiteral());
int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->handle()))->value();
Handle<FixedArray> jsfunction_result_caches(
Top::global_context()->jsfunction_result_caches());
if (jsfunction_result_caches->length() <= cache_id) {
__ Abort("Attempt to use undefined cache.");
frame_->Push(Factory::undefined_value());
return;
}
Load(args->at(1));
Result key = frame_->Pop();
key.ToRegister();
Result cache = allocator()->Allocate();
ASSERT(cache.is_valid());
__ mov(cache.reg(), ContextOperand(esi, Context::GLOBAL_INDEX));
__ mov(cache.reg(),
FieldOperand(cache.reg(), GlobalObject::kGlobalContextOffset));
__ mov(cache.reg(),
ContextOperand(cache.reg(), Context::JSFUNCTION_RESULT_CACHES_INDEX));
__ mov(cache.reg(),
FieldOperand(cache.reg(), FixedArray::OffsetOfElementAt(cache_id)));
Result tmp = allocator()->Allocate();
ASSERT(tmp.is_valid());
DeferredSearchCache* deferred = new DeferredSearchCache(tmp.reg(),
cache.reg(),
key.reg());
// tmp.reg() now holds finger offset as a smi.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ mov(tmp.reg(), FieldOperand(cache.reg(),
JSFunctionResultCache::kFingerOffset));
__ cmp(key.reg(), FixedArrayElementOperand(cache.reg(), tmp.reg()));
deferred->Branch(not_equal);
__ mov(tmp.reg(), FixedArrayElementOperand(cache.reg(), tmp.reg(), 1));
deferred->BindExit();
frame_->Push(&tmp);
}
void CodeGenerator::GenerateNumberToString(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
// Load the argument on the stack and call the stub.
Load(args->at(0));
NumberToStringStub stub;
Result result = frame_->CallStub(&stub, 1);
frame_->Push(&result);
}
class DeferredSwapElements: public DeferredCode {
public:
DeferredSwapElements(Register object, Register index1, Register index2)
: object_(object), index1_(index1), index2_(index2) {
set_comment("[ DeferredSwapElements");
}
virtual void Generate();
private:
Register object_, index1_, index2_;
};
void DeferredSwapElements::Generate() {
__ push(object_);
__ push(index1_);
__ push(index2_);
__ CallRuntime(Runtime::kSwapElements, 3);
}
void CodeGenerator::GenerateSwapElements(ZoneList<Expression*>* args) {
// Note: this code assumes that indices are passed are within
// elements' bounds and refer to valid (not holes) values.
Comment cmnt(masm_, "[ GenerateSwapElements");
ASSERT_EQ(3, args->length());
Load(args->at(0));
Load(args->at(1));
Load(args->at(2));
Result index2 = frame_->Pop();
index2.ToRegister();
Result index1 = frame_->Pop();
index1.ToRegister();
Result object = frame_->Pop();
object.ToRegister();
Result tmp1 = allocator()->Allocate();
tmp1.ToRegister();
Result tmp2 = allocator()->Allocate();
tmp2.ToRegister();
frame_->Spill(object.reg());
frame_->Spill(index1.reg());
frame_->Spill(index2.reg());
DeferredSwapElements* deferred = new DeferredSwapElements(object.reg(),
index1.reg(),
index2.reg());
// Fetch the map and check if array is in fast case.
// Check that object doesn't require security checks and
// has no indexed interceptor.
__ CmpObjectType(object.reg(), FIRST_JS_OBJECT_TYPE, tmp1.reg());
deferred->Branch(below);
__ test_b(FieldOperand(tmp1.reg(), Map::kBitFieldOffset),
KeyedLoadIC::kSlowCaseBitFieldMask);
deferred->Branch(not_zero);
// Check the object's elements are in fast case.
__ mov(tmp1.reg(), FieldOperand(object.reg(), JSObject::kElementsOffset));
__ cmp(FieldOperand(tmp1.reg(), HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
deferred->Branch(not_equal);
// Smi-tagging is equivalent to multiplying by 2.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
// Check that both indices are smis.
__ mov(tmp2.reg(), index1.reg());
__ or_(tmp2.reg(), Operand(index2.reg()));
__ test(tmp2.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
// Bring addresses into index1 and index2.
__ lea(index1.reg(), FixedArrayElementOperand(tmp1.reg(), index1.reg()));
__ lea(index2.reg(), FixedArrayElementOperand(tmp1.reg(), index2.reg()));
// Swap elements.
__ mov(object.reg(), Operand(index1.reg(), 0));
__ mov(tmp2.reg(), Operand(index2.reg(), 0));
__ mov(Operand(index2.reg(), 0), object.reg());
__ mov(Operand(index1.reg(), 0), tmp2.reg());
Label done;
__ InNewSpace(tmp1.reg(), tmp2.reg(), equal, &done);
// Possible optimization: do a check that both values are Smis
// (or them and test against Smi mask.)
__ mov(tmp2.reg(), tmp1.reg());
__ RecordWriteHelper(tmp2.reg(), index1.reg(), object.reg());
__ RecordWriteHelper(tmp1.reg(), index2.reg(), object.reg());
__ bind(&done);
deferred->BindExit();
frame_->Push(Factory::undefined_value());
}
void CodeGenerator::GenerateCallFunction(ZoneList<Expression*>* args) {
Comment cmnt(masm_, "[ GenerateCallFunction");
ASSERT(args->length() >= 2);
int n_args = args->length() - 2; // for receiver and function.
Load(args->at(0)); // receiver
for (int i = 0; i < n_args; i++) {
Load(args->at(i + 1));
}
Load(args->at(n_args + 1)); // function
Result result = frame_->CallJSFunction(n_args);
frame_->Push(&result);
}
// Generates the Math.pow method. Only handles special cases and
// branches to the runtime system for everything else. Please note
// that this function assumes that the callsite has executed ToNumber
// on both arguments.
void CodeGenerator::GenerateMathPow(ZoneList<Expression*>* args) {
ASSERT(args->length() == 2);
Load(args->at(0));
Load(args->at(1));
if (!CpuFeatures::IsSupported(SSE2)) {
Result res = frame_->CallRuntime(Runtime::kMath_pow, 2);
frame_->Push(&res);
} else {
CpuFeatures::Scope use_sse2(SSE2);
Label allocate_return;
// Load the two operands while leaving the values on the frame.
frame()->Dup();
Result exponent = frame()->Pop();
exponent.ToRegister();
frame()->Spill(exponent.reg());
frame()->PushElementAt(1);
Result base = frame()->Pop();
base.ToRegister();
frame()->Spill(base.reg());
Result answer = allocator()->Allocate();
ASSERT(answer.is_valid());
ASSERT(!exponent.reg().is(base.reg()));
JumpTarget call_runtime;
// Save 1 in xmm3 - we need this several times later on.
__ mov(answer.reg(), Immediate(1));
__ cvtsi2sd(xmm3, Operand(answer.reg()));
Label exponent_nonsmi;
Label base_nonsmi;
// If the exponent is a heap number go to that specific case.
__ test(exponent.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &exponent_nonsmi);
__ test(base.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &base_nonsmi);
// Optimized version when y is an integer.
Label powi;
__ SmiUntag(base.reg());
__ cvtsi2sd(xmm0, Operand(base.reg()));
__ jmp(&powi);
// exponent is smi and base is a heapnumber.
__ bind(&base_nonsmi);
__ cmp(FieldOperand(base.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
call_runtime.Branch(not_equal);
__ movdbl(xmm0, FieldOperand(base.reg(), HeapNumber::kValueOffset));
// Optimized version of pow if y is an integer.
__ bind(&powi);
__ SmiUntag(exponent.reg());
// Save exponent in base as we need to check if exponent is negative later.
// We know that base and exponent are in different registers.
__ mov(base.reg(), exponent.reg());
// Get absolute value of exponent.
Label no_neg;
__ cmp(exponent.reg(), 0);
__ j(greater_equal, &no_neg);
__ neg(exponent.reg());
__ bind(&no_neg);
// Load xmm1 with 1.
__ movsd(xmm1, xmm3);
Label while_true;
Label no_multiply;
__ bind(&while_true);
__ shr(exponent.reg(), 1);
__ j(not_carry, &no_multiply);
__ mulsd(xmm1, xmm0);
__ bind(&no_multiply);
__ test(exponent.reg(), Operand(exponent.reg()));
__ mulsd(xmm0, xmm0);
__ j(not_zero, &while_true);
// x has the original value of y - if y is negative return 1/result.
__ test(base.reg(), Operand(base.reg()));
__ j(positive, &allocate_return);
// Special case if xmm1 has reached infinity.
__ mov(answer.reg(), Immediate(0x7FB00000));
__ movd(xmm0, Operand(answer.reg()));
__ cvtss2sd(xmm0, xmm0);
__ ucomisd(xmm0, xmm1);
call_runtime.Branch(equal);
__ divsd(xmm3, xmm1);
__ movsd(xmm1, xmm3);
__ jmp(&allocate_return);
// exponent (or both) is a heapnumber - no matter what we should now work
// on doubles.
__ bind(&exponent_nonsmi);
__ cmp(FieldOperand(exponent.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
call_runtime.Branch(not_equal);
__ movdbl(xmm1, FieldOperand(exponent.reg(), HeapNumber::kValueOffset));
// Test if exponent is nan.
__ ucomisd(xmm1, xmm1);
call_runtime.Branch(parity_even);
Label base_not_smi;
Label handle_special_cases;
__ test(base.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &base_not_smi);
__ SmiUntag(base.reg());
__ cvtsi2sd(xmm0, Operand(base.reg()));
__ jmp(&handle_special_cases);
__ bind(&base_not_smi);
__ cmp(FieldOperand(base.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
call_runtime.Branch(not_equal);
__ mov(answer.reg(), FieldOperand(base.reg(), HeapNumber::kExponentOffset));
__ and_(answer.reg(), HeapNumber::kExponentMask);
__ cmp(Operand(answer.reg()), Immediate(HeapNumber::kExponentMask));
// base is NaN or +/-Infinity
call_runtime.Branch(greater_equal);
__ movdbl(xmm0, FieldOperand(base.reg(), HeapNumber::kValueOffset));
// base is in xmm0 and exponent is in xmm1.
__ bind(&handle_special_cases);
Label not_minus_half;
// Test for -0.5.
// Load xmm2 with -0.5.
__ mov(answer.reg(), Immediate(0xBF000000));
__ movd(xmm2, Operand(answer.reg()));
__ cvtss2sd(xmm2, xmm2);
// xmm2 now has -0.5.
__ ucomisd(xmm2, xmm1);
__ j(not_equal, ¬_minus_half);
// Calculates reciprocal of square root.
// Note that 1/sqrt(x) = sqrt(1/x))
__ divsd(xmm3, xmm0);
__ movsd(xmm1, xmm3);
__ sqrtsd(xmm1, xmm1);
__ jmp(&allocate_return);
// Test for 0.5.
__ bind(¬_minus_half);
// Load xmm2 with 0.5.
// Since xmm3 is 1 and xmm2 is -0.5 this is simply xmm2 + xmm3.
__ addsd(xmm2, xmm3);
// xmm2 now has 0.5.
__ comisd(xmm2, xmm1);
call_runtime.Branch(not_equal);
// Calculates square root.
__ movsd(xmm1, xmm0);
__ sqrtsd(xmm1, xmm1);
JumpTarget done;
Label failure, success;
__ bind(&allocate_return);
// Make a copy of the frame to enable us to handle allocation
// failure after the JumpTarget jump.
VirtualFrame* clone = new VirtualFrame(frame());
__ AllocateHeapNumber(answer.reg(), exponent.reg(),
base.reg(), &failure);
__ movdbl(FieldOperand(answer.reg(), HeapNumber::kValueOffset), xmm1);
// Remove the two original values from the frame - we only need those
// in the case where we branch to runtime.
frame()->Drop(2);
exponent.Unuse();
base.Unuse();
done.Jump(&answer);
// Use the copy of the original frame as our current frame.
RegisterFile empty_regs;
SetFrame(clone, &empty_regs);
// If we experience an allocation failure we branch to runtime.
__ bind(&failure);
call_runtime.Bind();
answer = frame()->CallRuntime(Runtime::kMath_pow_cfunction, 2);
done.Bind(&answer);
frame()->Push(&answer);
}
}
void CodeGenerator::GenerateMathSin(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
Load(args->at(0));
TranscendentalCacheStub stub(TranscendentalCache::SIN);
Result result = frame_->CallStub(&stub, 1);
frame_->Push(&result);
}
void CodeGenerator::GenerateMathCos(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
Load(args->at(0));
TranscendentalCacheStub stub(TranscendentalCache::COS);
Result result = frame_->CallStub(&stub, 1);
frame_->Push(&result);
}
// Generates the Math.sqrt method. Please note - this function assumes that
// the callsite has executed ToNumber on the argument.
void CodeGenerator::GenerateMathSqrt(ZoneList<Expression*>* args) {
ASSERT_EQ(args->length(), 1);
Load(args->at(0));
if (!CpuFeatures::IsSupported(SSE2)) {
Result result = frame()->CallRuntime(Runtime::kMath_sqrt, 1);
frame()->Push(&result);
} else {
CpuFeatures::Scope use_sse2(SSE2);
// Leave original value on the frame if we need to call runtime.
frame()->Dup();
Result result = frame()->Pop();
result.ToRegister();
frame()->Spill(result.reg());
Label runtime;
Label non_smi;
Label load_done;
JumpTarget end;
__ test(result.reg(), Immediate(kSmiTagMask));
__ j(not_zero, &non_smi);
__ SmiUntag(result.reg());
__ cvtsi2sd(xmm0, Operand(result.reg()));
__ jmp(&load_done);
__ bind(&non_smi);
__ cmp(FieldOperand(result.reg(), HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, &runtime);
__ movdbl(xmm0, FieldOperand(result.reg(), HeapNumber::kValueOffset));
__ bind(&load_done);
__ sqrtsd(xmm0, xmm0);
// A copy of the virtual frame to allow us to go to runtime after the
// JumpTarget jump.
Result scratch = allocator()->Allocate();
VirtualFrame* clone = new VirtualFrame(frame());
__ AllocateHeapNumber(result.reg(), scratch.reg(), no_reg, &runtime);
__ movdbl(FieldOperand(result.reg(), HeapNumber::kValueOffset), xmm0);
frame()->Drop(1);
scratch.Unuse();
end.Jump(&result);
// We only branch to runtime if we have an allocation error.
// Use the copy of the original frame as our current frame.
RegisterFile empty_regs;
SetFrame(clone, &empty_regs);
__ bind(&runtime);
result = frame()->CallRuntime(Runtime::kMath_sqrt, 1);
end.Bind(&result);
frame()->Push(&result);
}
}
void CodeGenerator::VisitCallRuntime(CallRuntime* node) {
ASSERT(!in_safe_int32_mode());
if (CheckForInlineRuntimeCall(node)) {
return;
}
ZoneList<Expression*>* args = node->arguments();
Comment cmnt(masm_, "[ CallRuntime");
Runtime::Function* function = node->function();
if (function == NULL) {
// Push the builtins object found in the current global object.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), GlobalObject());
__ mov(temp.reg(), FieldOperand(temp.reg(), GlobalObject::kBuiltinsOffset));
frame_->Push(&temp);
}
// Push the arguments ("left-to-right").
int arg_count = args->length();
for (int i = 0; i < arg_count; i++) {
Load(args->at(i));
}
if (function == NULL) {
// Call the JS runtime function.
frame_->Push(node->name());
Result answer = frame_->CallCallIC(RelocInfo::CODE_TARGET,
arg_count,
loop_nesting_);
frame_->RestoreContextRegister();
frame_->Push(&answer);
} else {
// Call the C runtime function.
Result answer = frame_->CallRuntime(function, arg_count);
frame_->Push(&answer);
}
}
void CodeGenerator::VisitUnaryOperation(UnaryOperation* node) {
Comment cmnt(masm_, "[ UnaryOperation");
Token::Value op = node->op();
if (op == Token::NOT) {
// Swap the true and false targets but keep the same actual label
// as the fall through.
destination()->Invert();
LoadCondition(node->expression(), destination(), true);
// Swap the labels back.
destination()->Invert();
} else if (op == Token::DELETE) {
Property* property = node->expression()->AsProperty();
if (property != NULL) {
Load(property->obj());
Load(property->key());
Result answer = frame_->InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, 2);
frame_->Push(&answer);
return;
}
Variable* variable = node->expression()->AsVariableProxy()->AsVariable();
if (variable != NULL) {
Slot* slot = variable->slot();
if (variable->is_global()) {
LoadGlobal();
frame_->Push(variable->name());
Result answer = frame_->InvokeBuiltin(Builtins::DELETE,
CALL_FUNCTION, 2);
frame_->Push(&answer);
return;
} else if (slot != NULL && slot->type() == Slot::LOOKUP) {
// Call the runtime to look up the context holding the named
// variable. Sync the virtual frame eagerly so we can push the
// arguments directly into place.
frame_->SyncRange(0, frame_->element_count() - 1);
frame_->EmitPush(esi);
frame_->EmitPush(Immediate(variable->name()));
Result context = frame_->CallRuntime(Runtime::kLookupContext, 2);
ASSERT(context.is_register());
frame_->EmitPush(context.reg());
context.Unuse();
frame_->EmitPush(Immediate(variable->name()));
Result answer = frame_->InvokeBuiltin(Builtins::DELETE,
CALL_FUNCTION, 2);
frame_->Push(&answer);
return;
}
// Default: Result of deleting non-global, not dynamically
// introduced variables is false.
frame_->Push(Factory::false_value());
} else {
// Default: Result of deleting expressions is true.
Load(node->expression()); // may have side-effects
frame_->SetElementAt(0, Factory::true_value());
}
} else if (op == Token::TYPEOF) {
// Special case for loading the typeof expression; see comment on
// LoadTypeofExpression().
LoadTypeofExpression(node->expression());
Result answer = frame_->CallRuntime(Runtime::kTypeof, 1);
frame_->Push(&answer);
} else if (op == Token::VOID) {
Expression* expression = node->expression();
if (expression && expression->AsLiteral() && (
expression->AsLiteral()->IsTrue() ||
expression->AsLiteral()->IsFalse() ||
expression->AsLiteral()->handle()->IsNumber() ||
expression->AsLiteral()->handle()->IsString() ||
expression->AsLiteral()->handle()->IsJSRegExp() ||
expression->AsLiteral()->IsNull())) {
// Omit evaluating the value of the primitive literal.
// It will be discarded anyway, and can have no side effect.
frame_->Push(Factory::undefined_value());
} else {
Load(node->expression());
frame_->SetElementAt(0, Factory::undefined_value());
}
} else {
if (in_safe_int32_mode()) {
Visit(node->expression());
Result value = frame_->Pop();
ASSERT(value.is_untagged_int32());
// Registers containing an int32 value are not multiply used.
ASSERT(!value.is_register() || !frame_->is_used(value.reg()));
value.ToRegister();
switch (op) {
case Token::SUB: {
__ neg(value.reg());
if (node->no_negative_zero()) {
// -MIN_INT is MIN_INT with the overflow flag set.
unsafe_bailout_->Branch(overflow);
} else {
// MIN_INT and 0 both have bad negations. They both have 31 zeros.
__ test(value.reg(), Immediate(0x7FFFFFFF));
unsafe_bailout_->Branch(zero);
}
break;
}
case Token::BIT_NOT: {
__ not_(value.reg());
break;
}
case Token::ADD: {
// Unary plus has no effect on int32 values.
break;
}
default:
UNREACHABLE();
break;
}
frame_->Push(&value);
} else {
Load(node->expression());
bool overwrite =
(node->expression()->AsBinaryOperation() != NULL &&
node->expression()->AsBinaryOperation()->ResultOverwriteAllowed());
switch (op) {
case Token::NOT:
case Token::DELETE:
case Token::TYPEOF:
UNREACHABLE(); // handled above
break;
case Token::SUB: {
GenericUnaryOpStub stub(Token::SUB, overwrite);
Result operand = frame_->Pop();
Result answer = frame_->CallStub(&stub, &operand);
answer.set_type_info(TypeInfo::Number());
frame_->Push(&answer);
break;
}
case Token::BIT_NOT: {
// Smi check.
JumpTarget smi_label;
JumpTarget continue_label;
Result operand = frame_->Pop();
TypeInfo operand_info = operand.type_info();
operand.ToRegister();
if (operand_info.IsSmi()) {
if (FLAG_debug_code) __ AbortIfNotSmi(operand.reg());
frame_->Spill(operand.reg());
// Set smi tag bit. It will be reset by the not operation.
__ lea(operand.reg(), Operand(operand.reg(), kSmiTagMask));
__ not_(operand.reg());
Result answer = operand;
answer.set_type_info(TypeInfo::Smi());
frame_->Push(&answer);
} else {
__ test(operand.reg(), Immediate(kSmiTagMask));
smi_label.Branch(zero, &operand, taken);
GenericUnaryOpStub stub(Token::BIT_NOT, overwrite);
Result answer = frame_->CallStub(&stub, &operand);
continue_label.Jump(&answer);
smi_label.Bind(&answer);
answer.ToRegister();
frame_->Spill(answer.reg());
// Set smi tag bit. It will be reset by the not operation.
__ lea(answer.reg(), Operand(answer.reg(), kSmiTagMask));
__ not_(answer.reg());
continue_label.Bind(&answer);
answer.set_type_info(TypeInfo::Integer32());
frame_->Push(&answer);
}
break;
}
case Token::ADD: {
// Smi check.
JumpTarget continue_label;
Result operand = frame_->Pop();
TypeInfo operand_info = operand.type_info();
operand.ToRegister();
__ test(operand.reg(), Immediate(kSmiTagMask));
continue_label.Branch(zero, &operand, taken);
frame_->Push(&operand);
Result answer = frame_->InvokeBuiltin(Builtins::TO_NUMBER,
CALL_FUNCTION, 1);
continue_label.Bind(&answer);
if (operand_info.IsSmi()) {
answer.set_type_info(TypeInfo::Smi());
} else if (operand_info.IsInteger32()) {
answer.set_type_info(TypeInfo::Integer32());
} else {
answer.set_type_info(TypeInfo::Number());
}
frame_->Push(&answer);
break;
}
default:
UNREACHABLE();
}
}
}
}
// The value in dst was optimistically incremented or decremented. The
// result overflowed or was not smi tagged. Undo the operation, call
// into the runtime to convert the argument to a number, and call the
// specialized add or subtract stub. The result is left in dst.
class DeferredPrefixCountOperation: public DeferredCode {
public:
DeferredPrefixCountOperation(Register dst,
bool is_increment,
TypeInfo input_type)
: dst_(dst), is_increment_(is_increment), input_type_(input_type) {
set_comment("[ DeferredCountOperation");
}
virtual void Generate();
private:
Register dst_;
bool is_increment_;
TypeInfo input_type_;
};
void DeferredPrefixCountOperation::Generate() {
// Undo the optimistic smi operation.
if (is_increment_) {
__ sub(Operand(dst_), Immediate(Smi::FromInt(1)));
} else {
__ add(Operand(dst_), Immediate(Smi::FromInt(1)));
}
Register left;
if (input_type_.IsNumber()) {
left = dst_;
} else {
__ push(dst_);
__ InvokeBuiltin(Builtins::TO_NUMBER, CALL_FUNCTION);
left = eax;
}
GenericBinaryOpStub stub(is_increment_ ? Token::ADD : Token::SUB,
NO_OVERWRITE,
NO_GENERIC_BINARY_FLAGS,
TypeInfo::Number());
stub.GenerateCall(masm_, left, Smi::FromInt(1));
if (!dst_.is(eax)) __ mov(dst_, eax);
}
// The value in dst was optimistically incremented or decremented. The
// result overflowed or was not smi tagged. Undo the operation and call
// into the runtime to convert the argument to a number. Update the
// original value in old. Call the specialized add or subtract stub.
// The result is left in dst.
class DeferredPostfixCountOperation: public DeferredCode {
public:
DeferredPostfixCountOperation(Register dst,
Register old,
bool is_increment,
TypeInfo input_type)
: dst_(dst),
old_(old),
is_increment_(is_increment),
input_type_(input_type) {
set_comment("[ DeferredCountOperation");
}
virtual void Generate();
private:
Register dst_;
Register old_;
bool is_increment_;
TypeInfo input_type_;
};
void DeferredPostfixCountOperation::Generate() {
// Undo the optimistic smi operation.
if (is_increment_) {
__ sub(Operand(dst_), Immediate(Smi::FromInt(1)));
} else {
__ add(Operand(dst_), Immediate(Smi::FromInt(1)));
}
Register left;
if (input_type_.IsNumber()) {
__ push(dst_); // Save the input to use as the old value.
left = dst_;
} else {
__ push(dst_);
__ InvokeBuiltin(Builtins::TO_NUMBER, CALL_FUNCTION);
__ push(eax); // Save the result of ToNumber to use as the old value.
left = eax;
}
GenericBinaryOpStub stub(is_increment_ ? Token::ADD : Token::SUB,
NO_OVERWRITE,
NO_GENERIC_BINARY_FLAGS,
TypeInfo::Number());
stub.GenerateCall(masm_, left, Smi::FromInt(1));
if (!dst_.is(eax)) __ mov(dst_, eax);
__ pop(old_);
}
void CodeGenerator::VisitCountOperation(CountOperation* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ CountOperation");
bool is_postfix = node->is_postfix();
bool is_increment = node->op() == Token::INC;
Variable* var = node->expression()->AsVariableProxy()->AsVariable();
bool is_const = (var != NULL && var->mode() == Variable::CONST);
// Postfix operations need a stack slot under the reference to hold
// the old value while the new value is being stored. This is so that
// in the case that storing the new value requires a call, the old
// value will be in the frame to be spilled.
if (is_postfix) frame_->Push(Smi::FromInt(0));
// A constant reference is not saved to, so a constant reference is not a
// compound assignment reference.
{ Reference target(this, node->expression(), !is_const);
if (target.is_illegal()) {
// Spoof the virtual frame to have the expected height (one higher
// than on entry).
if (!is_postfix) frame_->Push(Smi::FromInt(0));
return;
}
target.TakeValue();
Result new_value = frame_->Pop();
new_value.ToRegister();
Result old_value; // Only allocated in the postfix case.
if (is_postfix) {
// Allocate a temporary to preserve the old value.
old_value = allocator_->Allocate();
ASSERT(old_value.is_valid());
__ mov(old_value.reg(), new_value.reg());
// The return value for postfix operations is ToNumber(input).
// Keep more precise type info if the input is some kind of
// number already. If the input is not a number we have to wait
// for the deferred code to convert it.
if (new_value.type_info().IsNumber()) {
old_value.set_type_info(new_value.type_info());
}
}
// Ensure the new value is writable.
frame_->Spill(new_value.reg());
Result tmp;
if (new_value.is_smi()) {
if (FLAG_debug_code) __ AbortIfNotSmi(new_value.reg());
} else {
// We don't know statically if the input is a smi.
// In order to combine the overflow and the smi tag check, we need
// to be able to allocate a byte register. We attempt to do so
// without spilling. If we fail, we will generate separate overflow
// and smi tag checks.
// We allocate and clear a temporary byte register before performing
// the count operation since clearing the register using xor will clear
// the overflow flag.
tmp = allocator_->AllocateByteRegisterWithoutSpilling();
if (tmp.is_valid()) {
__ Set(tmp.reg(), Immediate(0));
}
}
if (is_increment) {
__ add(Operand(new_value.reg()), Immediate(Smi::FromInt(1)));
} else {
__ sub(Operand(new_value.reg()), Immediate(Smi::FromInt(1)));
}
DeferredCode* deferred = NULL;
if (is_postfix) {
deferred = new DeferredPostfixCountOperation(new_value.reg(),
old_value.reg(),
is_increment,
new_value.type_info());
} else {
deferred = new DeferredPrefixCountOperation(new_value.reg(),
is_increment,
new_value.type_info());
}
if (new_value.is_smi()) {
// In case we have a smi as input just check for overflow.
deferred->Branch(overflow);
} else {
// If the count operation didn't overflow and the result is a valid
// smi, we're done. Otherwise, we jump to the deferred slow-case
// code.
// We combine the overflow and the smi tag check if we could
// successfully allocate a temporary byte register.
if (tmp.is_valid()) {
__ setcc(overflow, tmp.reg());
__ or_(Operand(tmp.reg()), new_value.reg());
__ test(tmp.reg(), Immediate(kSmiTagMask));
tmp.Unuse();
deferred->Branch(not_zero);
} else {
// Otherwise we test separately for overflow and smi tag.
deferred->Branch(overflow);
__ test(new_value.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
}
}
deferred->BindExit();
// Postfix count operations return their input converted to
// number. The case when the input is already a number is covered
// above in the allocation code for old_value.
if (is_postfix && !new_value.type_info().IsNumber()) {
old_value.set_type_info(TypeInfo::Number());
}
// The result of ++ or -- is an Integer32 if the
// input is a smi. Otherwise it is a number.
if (new_value.is_smi()) {
new_value.set_type_info(TypeInfo::Integer32());
} else {
new_value.set_type_info(TypeInfo::Number());
}
// Postfix: store the old value in the allocated slot under the
// reference.
if (is_postfix) frame_->SetElementAt(target.size(), &old_value);
frame_->Push(&new_value);
// Non-constant: update the reference.
if (!is_const) target.SetValue(NOT_CONST_INIT);
}
// Postfix: drop the new value and use the old.
if (is_postfix) frame_->Drop();
}
void CodeGenerator::Int32BinaryOperation(BinaryOperation* node) {
Token::Value op = node->op();
Comment cmnt(masm_, "[ Int32BinaryOperation");
ASSERT(in_safe_int32_mode());
ASSERT(safe_int32_mode_enabled());
ASSERT(FLAG_safe_int32_compiler);
if (op == Token::COMMA) {
// Discard left value.
frame_->Nip(1);
return;
}
Result right = frame_->Pop();
Result left = frame_->Pop();
ASSERT(right.is_untagged_int32());
ASSERT(left.is_untagged_int32());
// Registers containing an int32 value are not multiply used.
ASSERT(!left.is_register() || !frame_->is_used(left.reg()));
ASSERT(!right.is_register() || !frame_->is_used(right.reg()));
switch (op) {
case Token::COMMA:
case Token::OR:
case Token::AND:
UNREACHABLE();
break;
case Token::BIT_OR:
case Token::BIT_XOR:
case Token::BIT_AND:
if (left.is_constant() || right.is_constant()) {
int32_t value; // Put constant in value, non-constant in left.
// Constants are known to be int32 values, from static analysis,
// or else will be converted to int32 by implicit ECMA [[ToInt32]].
if (left.is_constant()) {
ASSERT(left.handle()->IsSmi() || left.handle()->IsHeapNumber());
value = NumberToInt32(*left.handle());
left = right;
} else {
ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
value = NumberToInt32(*right.handle());
}
left.ToRegister();
if (op == Token::BIT_OR) {
__ or_(Operand(left.reg()), Immediate(value));
} else if (op == Token::BIT_XOR) {
__ xor_(Operand(left.reg()), Immediate(value));
} else {
ASSERT(op == Token::BIT_AND);
__ and_(Operand(left.reg()), Immediate(value));
}
} else {
ASSERT(left.is_register());
ASSERT(right.is_register());
if (op == Token::BIT_OR) {
__ or_(left.reg(), Operand(right.reg()));
} else if (op == Token::BIT_XOR) {
__ xor_(left.reg(), Operand(right.reg()));
} else {
ASSERT(op == Token::BIT_AND);
__ and_(left.reg(), Operand(right.reg()));
}
}
frame_->Push(&left);
right.Unuse();
break;
case Token::SAR:
case Token::SHL:
case Token::SHR: {
bool test_shr_overflow = false;
left.ToRegister();
if (right.is_constant()) {
ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
int shift_amount = NumberToInt32(*right.handle()) & 0x1F;
if (op == Token::SAR) {
__ sar(left.reg(), shift_amount);
} else if (op == Token::SHL) {
__ shl(left.reg(), shift_amount);
} else {
ASSERT(op == Token::SHR);
__ shr(left.reg(), shift_amount);
if (shift_amount == 0) test_shr_overflow = true;
}
} else {
// Move right to ecx
if (left.is_register() && left.reg().is(ecx)) {
right.ToRegister();
__ xchg(left.reg(), right.reg());
left = right; // Left is unused here, copy of right unused by Push.
} else {
right.ToRegister(ecx);
left.ToRegister();
}
if (op == Token::SAR) {
__ sar_cl(left.reg());
} else if (op == Token::SHL) {
__ shl_cl(left.reg());
} else {
ASSERT(op == Token::SHR);
__ shr_cl(left.reg());
test_shr_overflow = true;
}
}
{
Register left_reg = left.reg();
frame_->Push(&left);
right.Unuse();
if (test_shr_overflow && !node->to_int32()) {
// Uint32 results with top bit set are not Int32 values.
// If they will be forced to Int32, skip the test.
// Test is needed because shr with shift amount 0 does not set flags.
__ test(left_reg, Operand(left_reg));
unsafe_bailout_->Branch(sign);
}
}
break;
}
case Token::ADD:
case Token::SUB:
case Token::MUL:
if ((left.is_constant() && op != Token::SUB) || right.is_constant()) {
int32_t value; // Put constant in value, non-constant in left.
if (right.is_constant()) {
ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
value = NumberToInt32(*right.handle());
} else {
ASSERT(left.handle()->IsSmi() || left.handle()->IsHeapNumber());
value = NumberToInt32(*left.handle());
left = right;
}
left.ToRegister();
if (op == Token::ADD) {
__ add(Operand(left.reg()), Immediate(value));
} else if (op == Token::SUB) {
__ sub(Operand(left.reg()), Immediate(value));
} else {
ASSERT(op == Token::MUL);
__ imul(left.reg(), left.reg(), value);
}
} else {
left.ToRegister();
ASSERT(left.is_register());
ASSERT(right.is_register());
if (op == Token::ADD) {
__ add(left.reg(), Operand(right.reg()));
} else if (op == Token::SUB) {
__ sub(left.reg(), Operand(right.reg()));
} else {
ASSERT(op == Token::MUL);
// We have statically verified that a negative zero can be ignored.
__ imul(left.reg(), Operand(right.reg()));
}
}
right.Unuse();
frame_->Push(&left);
if (!node->to_int32()) {
// If ToInt32 is called on the result of ADD, SUB, or MUL, we don't
// care about overflows.
unsafe_bailout_->Branch(overflow);
}
break;
case Token::DIV:
case Token::MOD: {
if (right.is_register() && (right.reg().is(eax) || right.reg().is(edx))) {
if (left.is_register() && left.reg().is(edi)) {
right.ToRegister(ebx);
} else {
right.ToRegister(edi);
}
}
left.ToRegister(eax);
Result edx_reg = allocator_->Allocate(edx);
right.ToRegister();
// The results are unused here because BreakTarget::Branch cannot handle
// live results.
Register right_reg = right.reg();
left.Unuse();
right.Unuse();
edx_reg.Unuse();
__ cmp(right_reg, 0);
// Ensure divisor is positive: no chance of non-int32 or -0 result.
unsafe_bailout_->Branch(less_equal);
__ cdq(); // Sign-extend eax into edx:eax
__ idiv(right_reg);
if (op == Token::MOD) {
// Negative zero can arise as a negative divident with a zero result.
if (!node->no_negative_zero()) {
Label not_negative_zero;
__ test(edx, Operand(edx));
__ j(not_zero, ¬_negative_zero);
__ test(eax, Operand(eax));
unsafe_bailout_->Branch(negative);
__ bind(¬_negative_zero);
}
Result edx_result(edx, TypeInfo::Integer32());
edx_result.set_untagged_int32(true);
frame_->Push(&edx_result);
} else {
ASSERT(op == Token::DIV);
__ test(edx, Operand(edx));
unsafe_bailout_->Branch(not_equal);
Result eax_result(eax, TypeInfo::Integer32());
eax_result.set_untagged_int32(true);
frame_->Push(&eax_result);
}
break;
}
default:
UNREACHABLE();
break;
}
}
void CodeGenerator::GenerateLogicalBooleanOperation(BinaryOperation* node) {
// According to ECMA-262 section 11.11, page 58, the binary logical
// operators must yield the result of one of the two expressions
// before any ToBoolean() conversions. This means that the value
// produced by a && or || operator is not necessarily a boolean.
// NOTE: If the left hand side produces a materialized value (not
// control flow), we force the right hand side to do the same. This
// is necessary because we assume that if we get control flow on the
// last path out of an expression we got it on all paths.
if (node->op() == Token::AND) {
ASSERT(!in_safe_int32_mode());
JumpTarget is_true;
ControlDestination dest(&is_true, destination()->false_target(), true);
LoadCondition(node->left(), &dest, false);
if (dest.false_was_fall_through()) {
// The current false target was used as the fall-through. If
// there are no dangling jumps to is_true then the left
// subexpression was unconditionally false. Otherwise we have
// paths where we do have to evaluate the right subexpression.
if (is_true.is_linked()) {
// We need to compile the right subexpression. If the jump to
// the current false target was a forward jump then we have a
// valid frame, we have just bound the false target, and we
// have to jump around the code for the right subexpression.
if (has_valid_frame()) {
destination()->false_target()->Unuse();
destination()->false_target()->Jump();
}
is_true.Bind();
// The left subexpression compiled to control flow, so the
// right one is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have actually just jumped to or bound the current false
// target but the current control destination is not marked as
// used.
destination()->Use(false);
}
} else if (dest.is_used()) {
// The left subexpression compiled to control flow (and is_true
// was just bound), so the right is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have a materialized value on the frame, so we exit with
// one on all paths. There are possibly also jumps to is_true
// from nested subexpressions.
JumpTarget pop_and_continue;
JumpTarget exit;
// Avoid popping the result if it converts to 'false' using the
// standard ToBoolean() conversion as described in ECMA-262,
// section 9.2, page 30.
//
// Duplicate the TOS value. The duplicate will be popped by
// ToBoolean.
frame_->Dup();
ControlDestination dest(&pop_and_continue, &exit, true);
ToBoolean(&dest);
// Pop the result of evaluating the first part.
frame_->Drop();
// Compile right side expression.
is_true.Bind();
Load(node->right());
// Exit (always with a materialized value).
exit.Bind();
}
} else {
ASSERT(node->op() == Token::OR);
ASSERT(!in_safe_int32_mode());
JumpTarget is_false;
ControlDestination dest(destination()->true_target(), &is_false, false);
LoadCondition(node->left(), &dest, false);
if (dest.true_was_fall_through()) {
// The current true target was used as the fall-through. If
// there are no dangling jumps to is_false then the left
// subexpression was unconditionally true. Otherwise we have
// paths where we do have to evaluate the right subexpression.
if (is_false.is_linked()) {
// We need to compile the right subexpression. If the jump to
// the current true target was a forward jump then we have a
// valid frame, we have just bound the true target, and we
// have to jump around the code for the right subexpression.
if (has_valid_frame()) {
destination()->true_target()->Unuse();
destination()->true_target()->Jump();
}
is_false.Bind();
// The left subexpression compiled to control flow, so the
// right one is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have just jumped to or bound the current true target but
// the current control destination is not marked as used.
destination()->Use(true);
}
} else if (dest.is_used()) {
// The left subexpression compiled to control flow (and is_false
// was just bound), so the right is free to do so as well.
LoadCondition(node->right(), destination(), false);
} else {
// We have a materialized value on the frame, so we exit with
// one on all paths. There are possibly also jumps to is_false
// from nested subexpressions.
JumpTarget pop_and_continue;
JumpTarget exit;
// Avoid popping the result if it converts to 'true' using the
// standard ToBoolean() conversion as described in ECMA-262,
// section 9.2, page 30.
//
// Duplicate the TOS value. The duplicate will be popped by
// ToBoolean.
frame_->Dup();
ControlDestination dest(&exit, &pop_and_continue, false);
ToBoolean(&dest);
// Pop the result of evaluating the first part.
frame_->Drop();
// Compile right side expression.
is_false.Bind();
Load(node->right());
// Exit (always with a materialized value).
exit.Bind();
}
}
}
void CodeGenerator::VisitBinaryOperation(BinaryOperation* node) {
Comment cmnt(masm_, "[ BinaryOperation");
if (node->op() == Token::AND || node->op() == Token::OR) {
GenerateLogicalBooleanOperation(node);
} else if (in_safe_int32_mode()) {
Visit(node->left());
Visit(node->right());
Int32BinaryOperation(node);
} else {
// NOTE: The code below assumes that the slow cases (calls to runtime)
// never return a constant/immutable object.
OverwriteMode overwrite_mode = NO_OVERWRITE;
if (node->left()->AsBinaryOperation() != NULL &&
node->left()->AsBinaryOperation()->ResultOverwriteAllowed()) {
overwrite_mode = OVERWRITE_LEFT;
} else if (node->right()->AsBinaryOperation() != NULL &&
node->right()->AsBinaryOperation()->ResultOverwriteAllowed()) {
overwrite_mode = OVERWRITE_RIGHT;
}
if (node->left()->IsTrivial()) {
Load(node->right());
Result right = frame_->Pop();
frame_->Push(node->left());
frame_->Push(&right);
} else {
Load(node->left());
Load(node->right());
}
GenericBinaryOperation(node, overwrite_mode);
}
}
void CodeGenerator::VisitThisFunction(ThisFunction* node) {
ASSERT(!in_safe_int32_mode());
frame_->PushFunction();
}
void CodeGenerator::VisitCompareOperation(CompareOperation* node) {
ASSERT(!in_safe_int32_mode());
Comment cmnt(masm_, "[ CompareOperation");
bool left_already_loaded = false;
// Get the expressions from the node.
Expression* left = node->left();
Expression* right = node->right();
Token::Value op = node->op();
// To make typeof testing for natives implemented in JavaScript really
// efficient, we generate special code for expressions of the form:
// 'typeof <expression> == <string>'.
UnaryOperation* operation = left->AsUnaryOperation();
if ((op == Token::EQ || op == Token::EQ_STRICT) &&
(operation != NULL && operation->op() == Token::TYPEOF) &&
(right->AsLiteral() != NULL &&
right->AsLiteral()->handle()->IsString())) {
Handle<String> check(String::cast(*right->AsLiteral()->handle()));
// Load the operand and move it to a register.
LoadTypeofExpression(operation->expression());
Result answer = frame_->Pop();
answer.ToRegister();
if (check->Equals(Heap::number_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->true_target()->Branch(zero);
frame_->Spill(answer.reg());
__ mov(answer.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
__ cmp(answer.reg(), Factory::heap_number_map());
answer.Unuse();
destination()->Split(equal);
} else if (check->Equals(Heap::string_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
// It can be an undetectable string object.
Result temp = allocator()->Allocate();
ASSERT(temp.is_valid());
__ mov(temp.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
destination()->false_target()->Branch(not_zero);
__ CmpInstanceType(temp.reg(), FIRST_NONSTRING_TYPE);
temp.Unuse();
answer.Unuse();
destination()->Split(below);
} else if (check->Equals(Heap::boolean_symbol())) {
__ cmp(answer.reg(), Factory::true_value());
destination()->true_target()->Branch(equal);
__ cmp(answer.reg(), Factory::false_value());
answer.Unuse();
destination()->Split(equal);
} else if (check->Equals(Heap::undefined_symbol())) {
__ cmp(answer.reg(), Factory::undefined_value());
destination()->true_target()->Branch(equal);
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
// It can be an undetectable object.
frame_->Spill(answer.reg());
__ mov(answer.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
__ test_b(FieldOperand(answer.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
answer.Unuse();
destination()->Split(not_zero);
} else if (check->Equals(Heap::function_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
frame_->Spill(answer.reg());
__ CmpObjectType(answer.reg(), JS_FUNCTION_TYPE, answer.reg());
destination()->true_target()->Branch(equal);
// Regular expressions are callable so typeof == 'function'.
__ CmpInstanceType(answer.reg(), JS_REGEXP_TYPE);
answer.Unuse();
destination()->Split(equal);
} else if (check->Equals(Heap::object_symbol())) {
__ test(answer.reg(), Immediate(kSmiTagMask));
destination()->false_target()->Branch(zero);
__ cmp(answer.reg(), Factory::null_value());
destination()->true_target()->Branch(equal);
Result map = allocator()->Allocate();
ASSERT(map.is_valid());
// Regular expressions are typeof == 'function', not 'object'.
__ CmpObjectType(answer.reg(), JS_REGEXP_TYPE, map.reg());
destination()->false_target()->Branch(equal);
// It can be an undetectable object.
__ test_b(FieldOperand(map.reg(), Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
destination()->false_target()->Branch(not_zero);
// Do a range test for JSObject type. We can't use
// MacroAssembler::IsInstanceJSObjectType, because we are using a
// ControlDestination, so we copy its implementation here.
__ movzx_b(map.reg(), FieldOperand(map.reg(), Map::kInstanceTypeOffset));
__ sub(Operand(map.reg()), Immediate(FIRST_JS_OBJECT_TYPE));
__ cmp(map.reg(), LAST_JS_OBJECT_TYPE - FIRST_JS_OBJECT_TYPE);
answer.Unuse();
map.Unuse();
destination()->Split(below_equal);
} else {
// Uncommon case: typeof testing against a string literal that is
// never returned from the typeof operator.
answer.Unuse();
destination()->Goto(false);
}
return;
} else if (op == Token::LT &&
right->AsLiteral() != NULL &&
right->AsLiteral()->handle()->IsHeapNumber()) {
Handle<HeapNumber> check(HeapNumber::cast(*right->AsLiteral()->handle()));
if (check->value() == 2147483648.0) { // 0x80000000.
Load(left);
left_already_loaded = true;
Result lhs = frame_->Pop();
lhs.ToRegister();
__ test(lhs.reg(), Immediate(kSmiTagMask));
destination()->true_target()->Branch(zero); // All Smis are less.
Result scratch = allocator()->Allocate();
ASSERT(scratch.is_valid());
__ mov(scratch.reg(), FieldOperand(lhs.reg(), HeapObject::kMapOffset));
__ cmp(scratch.reg(), Factory::heap_number_map());
JumpTarget not_a_number;
not_a_number.Branch(not_equal, &lhs);
__ mov(scratch.reg(),
FieldOperand(lhs.reg(), HeapNumber::kExponentOffset));
__ cmp(Operand(scratch.reg()), Immediate(0xfff00000));
not_a_number.Branch(above_equal, &lhs); // It's a negative NaN or -Inf.
const uint32_t borderline_exponent =
(HeapNumber::kExponentBias + 31) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch.reg()), Immediate(borderline_exponent));
scratch.Unuse();
lhs.Unuse();
destination()->true_target()->Branch(less);
destination()->false_target()->Jump();
not_a_number.Bind(&lhs);
frame_->Push(&lhs);
}
}
Condition cc = no_condition;
bool strict = false;
switch (op) {
case Token::EQ_STRICT:
strict = true;
// Fall through
case Token::EQ:
cc = equal;
break;
case Token::LT:
cc = less;
break;
case Token::GT:
cc = greater;
break;
case Token::LTE:
cc = less_equal;
break;
case Token::GTE:
cc = greater_equal;
break;
case Token::IN: {
if (!left_already_loaded) Load(left);
Load(right);
Result answer = frame_->InvokeBuiltin(Builtins::IN, CALL_FUNCTION, 2);
frame_->Push(&answer); // push the result
return;
}
case Token::INSTANCEOF: {
if (!left_already_loaded) Load(left);
Load(right);
InstanceofStub stub;
Result answer = frame_->CallStub(&stub, 2);
answer.ToRegister();
__ test(answer.reg(), Operand(answer.reg()));
answer.Unuse();
destination()->Split(zero);
return;
}
default:
UNREACHABLE();
}
if (left->IsTrivial()) {
if (!left_already_loaded) {
Load(right);
Result right_result = frame_->Pop();
frame_->Push(left);
frame_->Push(&right_result);
} else {
Load(right);
}
} else {
if (!left_already_loaded) Load(left);
Load(right);
}
Comparison(node, cc, strict, destination());
}
#ifdef DEBUG
bool CodeGenerator::HasValidEntryRegisters() {
return (allocator()->count(eax) == (frame()->is_used(eax) ? 1 : 0))
&& (allocator()->count(ebx) == (frame()->is_used(ebx) ? 1 : 0))
&& (allocator()->count(ecx) == (frame()->is_used(ecx) ? 1 : 0))
&& (allocator()->count(edx) == (frame()->is_used(edx) ? 1 : 0))
&& (allocator()->count(edi) == (frame()->is_used(edi) ? 1 : 0));
}
#endif
// Emit a LoadIC call to get the value from receiver and leave it in
// dst.
class DeferredReferenceGetNamedValue: public DeferredCode {
public:
DeferredReferenceGetNamedValue(Register dst,
Register receiver,
Handle<String> name)
: dst_(dst), receiver_(receiver), name_(name) {
set_comment("[ DeferredReferenceGetNamedValue");
}
virtual void Generate();
Label* patch_site() { return &patch_site_; }
private:
Label patch_site_;
Register dst_;
Register receiver_;
Handle<String> name_;
};
void DeferredReferenceGetNamedValue::Generate() {
if (!receiver_.is(eax)) {
__ mov(eax, receiver_);
}
__ Set(ecx, Immediate(name_));
Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
__ call(ic, RelocInfo::CODE_TARGET);
// The call must be followed by a test eax instruction to indicate
// that the inobject property case was inlined.
//
// Store the delta to the map check instruction here in the test
// instruction. Use masm_-> instead of the __ macro since the
// latter can't return a value.
int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
// Here we use masm_-> instead of the __ macro because this is the
// instruction that gets patched and coverage code gets in the way.
masm_->test(eax, Immediate(-delta_to_patch_site));
__ IncrementCounter(&Counters::named_load_inline_miss, 1);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
class DeferredReferenceGetKeyedValue: public DeferredCode {
public:
explicit DeferredReferenceGetKeyedValue(Register dst,
Register receiver,
Register key)
: dst_(dst), receiver_(receiver), key_(key) {
set_comment("[ DeferredReferenceGetKeyedValue");
}
virtual void Generate();
Label* patch_site() { return &patch_site_; }
private:
Label patch_site_;
Register dst_;
Register receiver_;
Register key_;
};
void DeferredReferenceGetKeyedValue::Generate() {
if (!receiver_.is(eax)) {
// Register eax is available for key.
if (!key_.is(eax)) {
__ mov(eax, key_);
}
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
} else if (!key_.is(edx)) {
// Register edx is available for receiver.
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
if (!key_.is(eax)) {
__ mov(eax, key_);
}
} else {
__ xchg(edx, eax);
}
// Calculate the delta from the IC call instruction to the map check
// cmp instruction in the inlined version. This delta is stored in
// a test(eax, delta) instruction after the call so that we can find
// it in the IC initialization code and patch the cmp instruction.
// This means that we cannot allow test instructions after calls to
// KeyedLoadIC stubs in other places.
Handle<Code> ic(Builtins::builtin(Builtins::KeyedLoadIC_Initialize));
__ call(ic, RelocInfo::CODE_TARGET);
// The delta from the start of the map-compare instruction to the
// test instruction. We use masm_-> directly here instead of the __
// macro because the macro sometimes uses macro expansion to turn
// into something that can't return a value. This is encountered
// when doing generated code coverage tests.
int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
// Here we use masm_-> instead of the __ macro because this is the
// instruction that gets patched and coverage code gets in the way.
masm_->test(eax, Immediate(-delta_to_patch_site));
__ IncrementCounter(&Counters::keyed_load_inline_miss, 1);
if (!dst_.is(eax)) __ mov(dst_, eax);
}
class DeferredReferenceSetKeyedValue: public DeferredCode {
public:
DeferredReferenceSetKeyedValue(Register value,
Register key,
Register receiver,
Register scratch)
: value_(value),
key_(key),
receiver_(receiver),
scratch_(scratch) {
set_comment("[ DeferredReferenceSetKeyedValue");
}
virtual void Generate();
Label* patch_site() { return &patch_site_; }
private:
Register value_;
Register key_;
Register receiver_;
Register scratch_;
Label patch_site_;
};
void DeferredReferenceSetKeyedValue::Generate() {
__ IncrementCounter(&Counters::keyed_store_inline_miss, 1);
// Move value_ to eax, key_ to ecx, and receiver_ to edx.
Register old_value = value_;
// First, move value to eax.
if (!value_.is(eax)) {
if (key_.is(eax)) {
// Move key_ out of eax, preferably to ecx.
if (!value_.is(ecx) && !receiver_.is(ecx)) {
__ mov(ecx, key_);
key_ = ecx;
} else {
__ mov(scratch_, key_);
key_ = scratch_;
}
}
if (receiver_.is(eax)) {
// Move receiver_ out of eax, preferably to edx.
if (!value_.is(edx) && !key_.is(edx)) {
__ mov(edx, receiver_);
receiver_ = edx;
} else {
// Both moves to scratch are from eax, also, no valid path hits both.
__ mov(scratch_, receiver_);
receiver_ = scratch_;
}
}
__ mov(eax, value_);
value_ = eax;
}
// Now value_ is in eax. Move the other two to the right positions.
// We do not update the variables key_ and receiver_ to ecx and edx.
if (key_.is(ecx)) {
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
} else if (key_.is(edx)) {
if (receiver_.is(ecx)) {
__ xchg(edx, ecx);
} else {
__ mov(ecx, key_);
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
}
} else { // Key is not in edx or ecx.
if (!receiver_.is(edx)) {
__ mov(edx, receiver_);
}
__ mov(ecx, key_);
}
// Call the IC stub.
Handle<Code> ic(Builtins::builtin(Builtins::KeyedStoreIC_Initialize));
__ call(ic, RelocInfo::CODE_TARGET);
// The delta from the start of the map-compare instruction to the
// test instruction. We use masm_-> directly here instead of the
// __ macro because the macro sometimes uses macro expansion to turn
// into something that can't return a value. This is encountered
// when doing generated code coverage tests.
int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
// Here we use masm_-> instead of the __ macro because this is the
// instruction that gets patched and coverage code gets in the way.
masm_->test(eax, Immediate(-delta_to_patch_site));
// Restore value (returned from store IC) register.
if (!old_value.is(eax)) __ mov(old_value, eax);
}
Result CodeGenerator::EmitNamedLoad(Handle<String> name, bool is_contextual) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Result result;
// Do not inline the inobject property case for loads from the global
// object. Also do not inline for unoptimized code. This saves time in
// the code generator. Unoptimized code is toplevel code or code that is
// not in a loop.
if (is_contextual || scope()->is_global_scope() || loop_nesting() == 0) {
Comment cmnt(masm(), "[ Load from named Property");
frame()->Push(name);
RelocInfo::Mode mode = is_contextual
? RelocInfo::CODE_TARGET_CONTEXT
: RelocInfo::CODE_TARGET;
result = frame()->CallLoadIC(mode);
// A test eax instruction following the call signals that the inobject
// property case was inlined. Ensure that there is not a test eax
// instruction here.
__ nop();
} else {
// Inline the inobject property case.
Comment cmnt(masm(), "[ Inlined named property load");
Result receiver = frame()->Pop();
receiver.ToRegister();
result = allocator()->Allocate();
ASSERT(result.is_valid());
DeferredReferenceGetNamedValue* deferred =
new DeferredReferenceGetNamedValue(result.reg(), receiver.reg(), name);
// Check that the receiver is a heap object.
__ test(receiver.reg(), Immediate(kSmiTagMask));
deferred->Branch(zero);
__ bind(deferred->patch_site());
// This is the map check instruction that will be patched (so we can't
// use the double underscore macro that may insert instructions).
// Initially use an invalid map to force a failure.
masm()->cmp(FieldOperand(receiver.reg(), HeapObject::kMapOffset),
Immediate(Factory::null_value()));
// This branch is always a forwards branch so it's always a fixed size
// which allows the assert below to succeed and patching to work.
deferred->Branch(not_equal);
// The delta from the patch label to the load offset must be statically
// known.
ASSERT(masm()->SizeOfCodeGeneratedSince(deferred->patch_site()) ==
LoadIC::kOffsetToLoadInstruction);
// The initial (invalid) offset has to be large enough to force a 32-bit
// instruction encoding to allow patching with an arbitrary offset. Use
// kMaxInt (minus kHeapObjectTag).
int offset = kMaxInt;
masm()->mov(result.reg(), FieldOperand(receiver.reg(), offset));
__ IncrementCounter(&Counters::named_load_inline, 1);
deferred->BindExit();
}
ASSERT(frame()->height() == original_height - 1);
return result;
}
Result CodeGenerator::EmitNamedStore(Handle<String> name, bool is_contextual) {
#ifdef DEBUG
int expected_height = frame()->height() - (is_contextual ? 1 : 2);
#endif
Result result = frame()->CallStoreIC(name, is_contextual);
ASSERT_EQ(expected_height, frame()->height());
return result;
}
Result CodeGenerator::EmitKeyedLoad() {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Result result;
// Inline array load code if inside of a loop. We do not know the
// receiver map yet, so we initially generate the code with a check
// against an invalid map. In the inline cache code, we patch the map
// check if appropriate.
if (loop_nesting() > 0) {
Comment cmnt(masm_, "[ Inlined load from keyed Property");
// Use a fresh temporary to load the elements without destroying
// the receiver which is needed for the deferred slow case.
Result elements = allocator()->Allocate();
ASSERT(elements.is_valid());
Result key = frame_->Pop();
Result receiver = frame_->Pop();
key.ToRegister();
receiver.ToRegister();
// If key and receiver are shared registers on the frame, their values will
// be automatically saved and restored when going to deferred code.
// The result is in elements, which is guaranteed non-shared.
DeferredReferenceGetKeyedValue* deferred =
new DeferredReferenceGetKeyedValue(elements.reg(),
receiver.reg(),
key.reg());
__ test(receiver.reg(), Immediate(kSmiTagMask));
deferred->Branch(zero);
// Check that the receiver has the expected map.
// Initially, use an invalid map. The map is patched in the IC
// initialization code.
__ bind(deferred->patch_site());
// Use masm-> here instead of the double underscore macro since extra
// coverage code can interfere with the patching.
masm_->cmp(FieldOperand(receiver.reg(), HeapObject::kMapOffset),
Immediate(Factory::null_value()));
deferred->Branch(not_equal);
// Check that the key is a smi.
if (!key.is_smi()) {
__ test(key.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(key.reg());
}
// Get the elements array from the receiver and check that it
// is not a dictionary.
__ mov(elements.reg(),
FieldOperand(receiver.reg(), JSObject::kElementsOffset));
__ cmp(FieldOperand(elements.reg(), HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
deferred->Branch(not_equal);
// Check that the key is within bounds.
__ cmp(key.reg(),
FieldOperand(elements.reg(), FixedArray::kLengthOffset));
deferred->Branch(above_equal);
// Load and check that the result is not the hole.
// Key holds a smi.
ASSERT((kSmiTag == 0) && (kSmiTagSize == 1));
__ mov(elements.reg(),
FieldOperand(elements.reg(),
key.reg(),
times_2,
FixedArray::kHeaderSize));
result = elements;
__ cmp(Operand(result.reg()), Immediate(Factory::the_hole_value()));
deferred->Branch(equal);
__ IncrementCounter(&Counters::keyed_load_inline, 1);
deferred->BindExit();
} else {
Comment cmnt(masm_, "[ Load from keyed Property");
result = frame_->CallKeyedLoadIC(RelocInfo::CODE_TARGET);
// Make sure that we do not have a test instruction after the
// call. A test instruction after the call is used to
// indicate that we have generated an inline version of the
// keyed load. The explicit nop instruction is here because
// the push that follows might be peep-hole optimized away.
__ nop();
}
ASSERT(frame()->height() == original_height - 2);
return result;
}
Result CodeGenerator::EmitKeyedStore(StaticType* key_type) {
#ifdef DEBUG
int original_height = frame()->height();
#endif
Result result;
// Generate inlined version of the keyed store if the code is in a loop
// and the key is likely to be a smi.
if (loop_nesting() > 0 && key_type->IsLikelySmi()) {
Comment cmnt(masm(), "[ Inlined store to keyed Property");
// Get the receiver, key and value into registers.
result = frame()->Pop();
Result key = frame()->Pop();
Result receiver = frame()->Pop();
Result tmp = allocator_->Allocate();
ASSERT(tmp.is_valid());
Result tmp2 = allocator_->Allocate();
ASSERT(tmp2.is_valid());
// Determine whether the value is a constant before putting it in a
// register.
bool value_is_constant = result.is_constant();
// Make sure that value, key and receiver are in registers.
result.ToRegister();
key.ToRegister();
receiver.ToRegister();
DeferredReferenceSetKeyedValue* deferred =
new DeferredReferenceSetKeyedValue(result.reg(),
key.reg(),
receiver.reg(),
tmp.reg());
// Check that the receiver is not a smi.
__ test(receiver.reg(), Immediate(kSmiTagMask));
deferred->Branch(zero);
// Check that the key is a smi.
if (!key.is_smi()) {
__ test(key.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(key.reg());
}
// Check that the receiver is a JSArray.
__ CmpObjectType(receiver.reg(), JS_ARRAY_TYPE, tmp.reg());
deferred->Branch(not_equal);
// Check that the key is within bounds. Both the key and the length of
// the JSArray are smis. Use unsigned comparison to handle negative keys.
__ cmp(key.reg(),
FieldOperand(receiver.reg(), JSArray::kLengthOffset));
deferred->Branch(above_equal);
// Get the elements array from the receiver and check that it is not a
// dictionary.
__ mov(tmp.reg(),
FieldOperand(receiver.reg(), JSArray::kElementsOffset));
// Check whether it is possible to omit the write barrier. If the elements
// array is in new space or the value written is a smi we can safely update
// the elements array without write barrier.
Label in_new_space;
__ InNewSpace(tmp.reg(), tmp2.reg(), equal, &in_new_space);
if (!value_is_constant) {
__ test(result.reg(), Immediate(kSmiTagMask));
deferred->Branch(not_zero);
}
__ bind(&in_new_space);
// Bind the deferred code patch site to be able to locate the fixed
// array map comparison. When debugging, we patch this comparison to
// always fail so that we will hit the IC call in the deferred code
// which will allow the debugger to break for fast case stores.
__ bind(deferred->patch_site());
__ cmp(FieldOperand(tmp.reg(), HeapObject::kMapOffset),
Immediate(Factory::fixed_array_map()));
deferred->Branch(not_equal);
// Store the value.
__ mov(FixedArrayElementOperand(tmp.reg(), key.reg()), result.reg());
__ IncrementCounter(&Counters::keyed_store_inline, 1);
deferred->BindExit();
} else {
result = frame()->CallKeyedStoreIC();
// Make sure that we do not have a test instruction after the
// call. A test instruction after the call is used to
// indicate that we have generated an inline version of the
// keyed store.
__ nop();
}
ASSERT(frame()->height() == original_height - 3);
return result;
}
#undef __
#define __ ACCESS_MASM(masm)
static void CheckTwoForSminess(MacroAssembler* masm,
Register left, Register right, Register scratch,
TypeInfo left_info, TypeInfo right_info,
DeferredInlineBinaryOperation* deferred) {
if (left.is(right)) {
if (!left_info.IsSmi()) {
__ test(left, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left);
}
} else if (!left_info.IsSmi()) {
if (!right_info.IsSmi()) {
__ mov(scratch, left);
__ or_(scratch, Operand(right));
__ test(scratch, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
__ test(left, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
if (FLAG_debug_code) __ AbortIfNotSmi(right);
}
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(left);
if (!right_info.IsSmi()) {
__ test(right, Immediate(kSmiTagMask));
deferred->Branch(not_zero);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(right);
}
}
}
Handle<String> Reference::GetName() {
ASSERT(type_ == NAMED);
Property* property = expression_->AsProperty();
if (property == NULL) {
// Global variable reference treated as a named property reference.
VariableProxy* proxy = expression_->AsVariableProxy();
ASSERT(proxy->AsVariable() != NULL);
ASSERT(proxy->AsVariable()->is_global());
return proxy->name();
} else {
Literal* raw_name = property->key()->AsLiteral();
ASSERT(raw_name != NULL);
return Handle<String>::cast(raw_name->handle());
}
}
void Reference::GetValue() {
ASSERT(!cgen_->in_spilled_code());
ASSERT(cgen_->HasValidEntryRegisters());
ASSERT(!is_illegal());
MacroAssembler* masm = cgen_->masm();
// Record the source position for the property load.
Property* property = expression_->AsProperty();
if (property != NULL) {
cgen_->CodeForSourcePosition(property->position());
}
switch (type_) {
case SLOT: {
Comment cmnt(masm, "[ Load from Slot");
Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
ASSERT(slot != NULL);
cgen_->LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
if (!persist_after_get_) set_unloaded();
break;
}
case NAMED: {
Variable* var = expression_->AsVariableProxy()->AsVariable();
bool is_global = var != NULL;
ASSERT(!is_global || var->is_global());
if (persist_after_get_) cgen_->frame()->Dup();
Result result = cgen_->EmitNamedLoad(GetName(), is_global);
if (!persist_after_get_) set_unloaded();
cgen_->frame()->Push(&result);
break;
}
case KEYED: {
if (persist_after_get_) {
cgen_->frame()->PushElementAt(1);
cgen_->frame()->PushElementAt(1);
}
Result value = cgen_->EmitKeyedLoad();
cgen_->frame()->Push(&value);
if (!persist_after_get_) set_unloaded();
break;
}
default:
UNREACHABLE();
}
}
void Reference::TakeValue() {
// For non-constant frame-allocated slots, we invalidate the value in the
// slot. For all others, we fall back on GetValue.
ASSERT(!cgen_->in_spilled_code());
ASSERT(!is_illegal());
if (type_ != SLOT) {
GetValue();
return;
}
Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
ASSERT(slot != NULL);
if (slot->type() == Slot::LOOKUP ||
slot->type() == Slot::CONTEXT ||
slot->var()->mode() == Variable::CONST ||
slot->is_arguments()) {
GetValue();
return;
}
// Only non-constant, frame-allocated parameters and locals can
// reach here. Be careful not to use the optimizations for arguments
// object access since it may not have been initialized yet.
ASSERT(!slot->is_arguments());
if (slot->type() == Slot::PARAMETER) {
cgen_->frame()->TakeParameterAt(slot->index());
} else {
ASSERT(slot->type() == Slot::LOCAL);
cgen_->frame()->TakeLocalAt(slot->index());
}
ASSERT(persist_after_get_);
// Do not unload the reference, because it is used in SetValue.
}
void Reference::SetValue(InitState init_state) {
ASSERT(cgen_->HasValidEntryRegisters());
ASSERT(!is_illegal());
MacroAssembler* masm = cgen_->masm();
switch (type_) {
case SLOT: {
Comment cmnt(masm, "[ Store to Slot");
Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
ASSERT(slot != NULL);
cgen_->StoreToSlot(slot, init_state);
set_unloaded();
break;
}
case NAMED: {
Comment cmnt(masm, "[ Store to named Property");
Result answer = cgen_->EmitNamedStore(GetName(), false);
cgen_->frame()->Push(&answer);
set_unloaded();
break;
}
case KEYED: {
Comment cmnt(masm, "[ Store to keyed Property");
Property* property = expression()->AsProperty();
ASSERT(property != NULL);
Result answer = cgen_->EmitKeyedStore(property->key()->type());
cgen_->frame()->Push(&answer);
set_unloaded();
break;
}
case UNLOADED:
case ILLEGAL:
UNREACHABLE();
}
}
void FastNewClosureStub::Generate(MacroAssembler* masm) {
// Create a new closure from the given function info in new
// space. Set the context to the current context in esi.
Label gc;
__ AllocateInNewSpace(JSFunction::kSize, eax, ebx, ecx, &gc, TAG_OBJECT);
// Get the function info from the stack.
__ mov(edx, Operand(esp, 1 * kPointerSize));
// Compute the function map in the current global context and set that
// as the map of the allocated object.
__ mov(ecx, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
__ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalContextOffset));
__ mov(ecx, Operand(ecx, Context::SlotOffset(Context::FUNCTION_MAP_INDEX)));
__ mov(FieldOperand(eax, JSObject::kMapOffset), ecx);
// Initialize the rest of the function. We don't have to update the
// write barrier because the allocated object is in new space.
__ mov(ebx, Immediate(Factory::empty_fixed_array()));
__ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ebx);
__ mov(FieldOperand(eax, JSObject::kElementsOffset), ebx);
__ mov(FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset),
Immediate(Factory::the_hole_value()));
__ mov(FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset), edx);
__ mov(FieldOperand(eax, JSFunction::kContextOffset), esi);
__ mov(FieldOperand(eax, JSFunction::kLiteralsOffset), ebx);
// Return and remove the on-stack parameter.
__ ret(1 * kPointerSize);
// Create a new closure through the slower runtime call.
__ bind(&gc);
__ pop(ecx); // Temporarily remove return address.
__ pop(edx);
__ push(esi);
__ push(edx);
__ push(ecx); // Restore return address.
__ TailCallRuntime(Runtime::kNewClosure, 2, 1);
}
void FastNewContextStub::Generate(MacroAssembler* masm) {
// Try to allocate the context in new space.
Label gc;
int length = slots_ + Context::MIN_CONTEXT_SLOTS;
__ AllocateInNewSpace((length * kPointerSize) + FixedArray::kHeaderSize,
eax, ebx, ecx, &gc, TAG_OBJECT);
// Get the function from the stack.
__ mov(ecx, Operand(esp, 1 * kPointerSize));
// Setup the object header.
__ mov(FieldOperand(eax, HeapObject::kMapOffset), Factory::context_map());
__ mov(FieldOperand(eax, Context::kLengthOffset),
Immediate(Smi::FromInt(length)));
// Setup the fixed slots.
__ xor_(ebx, Operand(ebx)); // Set to NULL.
__ mov(Operand(eax, Context::SlotOffset(Context::CLOSURE_INDEX)), ecx);
__ mov(Operand(eax, Context::SlotOffset(Context::FCONTEXT_INDEX)), eax);
__ mov(Operand(eax, Context::SlotOffset(Context::PREVIOUS_INDEX)), ebx);
__ mov(Operand(eax, Context::SlotOffset(Context::EXTENSION_INDEX)), ebx);
// Copy the global object from the surrounding context. We go through the
// context in the function (ecx) to match the allocation behavior we have
// in the runtime system (see Heap::AllocateFunctionContext).
__ mov(ebx, FieldOperand(ecx, JSFunction::kContextOffset));
__ mov(ebx, Operand(ebx, Context::SlotOffset(Context::GLOBAL_INDEX)));
__ mov(Operand(eax, Context::SlotOffset(Context::GLOBAL_INDEX)), ebx);
// Initialize the rest of the slots to undefined.
__ mov(ebx, Factory::undefined_value());
for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) {
__ mov(Operand(eax, Context::SlotOffset(i)), ebx);
}
// Return and remove the on-stack parameter.
__ mov(esi, Operand(eax));
__ ret(1 * kPointerSize);
// Need to collect. Call into runtime system.
__ bind(&gc);
__ TailCallRuntime(Runtime::kNewContext, 1, 1);
}
void FastCloneShallowArrayStub::Generate(MacroAssembler* masm) {
// Stack layout on entry:
//
// [esp + kPointerSize]: constant elements.
// [esp + (2 * kPointerSize)]: literal index.
// [esp + (3 * kPointerSize)]: literals array.
// All sizes here are multiples of kPointerSize.
int elements_size = (length_ > 0) ? FixedArray::SizeFor(length_) : 0;
int size = JSArray::kSize + elements_size;
// Load boilerplate object into ecx and check if we need to create a
// boilerplate.
Label slow_case;
__ mov(ecx, Operand(esp, 3 * kPointerSize));
__ mov(eax, Operand(esp, 2 * kPointerSize));
ASSERT((kPointerSize == 4) && (kSmiTagSize == 1) && (kSmiTag == 0));
__ mov(ecx, CodeGenerator::FixedArrayElementOperand(ecx, eax));
__ cmp(ecx, Factory::undefined_value());
__ j(equal, &slow_case);
// Allocate both the JS array and the elements array in one big
// allocation. This avoids multiple limit checks.
__ AllocateInNewSpace(size, eax, ebx, edx, &slow_case, TAG_OBJECT);
// Copy the JS array part.
for (int i = 0; i < JSArray::kSize; i += kPointerSize) {
if ((i != JSArray::kElementsOffset) || (length_ == 0)) {
__ mov(ebx, FieldOperand(ecx, i));
__ mov(FieldOperand(eax, i), ebx);
}
}
if (length_ > 0) {
// Get hold of the elements array of the boilerplate and setup the
// elements pointer in the resulting object.
__ mov(ecx, FieldOperand(ecx, JSArray::kElementsOffset));
__ lea(edx, Operand(eax, JSArray::kSize));
__ mov(FieldOperand(eax, JSArray::kElementsOffset), edx);
// Copy the elements array.
for (int i = 0; i < elements_size; i += kPointerSize) {
__ mov(ebx, FieldOperand(ecx, i));
__ mov(FieldOperand(edx, i), ebx);
}
}
// Return and remove the on-stack parameters.
__ ret(3 * kPointerSize);
__ bind(&slow_case);
__ TailCallRuntime(Runtime::kCreateArrayLiteralShallow, 3, 1);
}
// NOTE: The stub does not handle the inlined cases (Smis, Booleans, undefined).
void ToBooleanStub::Generate(MacroAssembler* masm) {
Label false_result, true_result, not_string;
__ mov(eax, Operand(esp, 1 * kPointerSize));
// 'null' => false.
__ cmp(eax, Factory::null_value());
__ j(equal, &false_result);
// Get the map and type of the heap object.
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(edx, Map::kInstanceTypeOffset));
// Undetectable => false.
__ test_b(FieldOperand(edx, Map::kBitFieldOffset),
1 << Map::kIsUndetectable);
__ j(not_zero, &false_result);
// JavaScript object => true.
__ CmpInstanceType(edx, FIRST_JS_OBJECT_TYPE);
__ j(above_equal, &true_result);
// String value => false iff empty.
__ CmpInstanceType(edx, FIRST_NONSTRING_TYPE);
__ j(above_equal, ¬_string);
ASSERT(kSmiTag == 0);
__ cmp(FieldOperand(eax, String::kLengthOffset), Immediate(0));
__ j(zero, &false_result);
__ jmp(&true_result);
__ bind(¬_string);
// HeapNumber => false iff +0, -0, or NaN.
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &true_result);
__ fldz();
__ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ FCmp();
__ j(zero, &false_result);
// Fall through to |true_result|.
// Return 1/0 for true/false in eax.
__ bind(&true_result);
__ mov(eax, 1);
__ ret(1 * kPointerSize);
__ bind(&false_result);
__ mov(eax, 0);
__ ret(1 * kPointerSize);
}
void GenericBinaryOpStub::GenerateCall(
MacroAssembler* masm,
Register left,
Register right) {
if (!ArgsInRegistersSupported()) {
// Pass arguments on the stack.
__ push(left);
__ push(right);
} else {
// The calling convention with registers is left in edx and right in eax.
Register left_arg = edx;
Register right_arg = eax;
if (!(left.is(left_arg) && right.is(right_arg))) {
if (left.is(right_arg) && right.is(left_arg)) {
if (IsOperationCommutative()) {
SetArgsReversed();
} else {
__ xchg(left, right);
}
} else if (left.is(left_arg)) {
__ mov(right_arg, right);
} else if (right.is(right_arg)) {
__ mov(left_arg, left);
} else if (left.is(right_arg)) {
if (IsOperationCommutative()) {
__ mov(left_arg, right);
SetArgsReversed();
} else {
// Order of moves important to avoid destroying left argument.
__ mov(left_arg, left);
__ mov(right_arg, right);
}
} else if (right.is(left_arg)) {
if (IsOperationCommutative()) {
__ mov(right_arg, left);
SetArgsReversed();
} else {
// Order of moves important to avoid destroying right argument.
__ mov(right_arg, right);
__ mov(left_arg, left);
}
} else {
// Order of moves is not important.
__ mov(left_arg, left);
__ mov(right_arg, right);
}
}
// Update flags to indicate that arguments are in registers.
SetArgsInRegisters();
__ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
}
// Call the stub.
__ CallStub(this);
}
void GenericBinaryOpStub::GenerateCall(
MacroAssembler* masm,
Register left,
Smi* right) {
if (!ArgsInRegistersSupported()) {
// Pass arguments on the stack.
__ push(left);
__ push(Immediate(right));
} else {
// The calling convention with registers is left in edx and right in eax.
Register left_arg = edx;
Register right_arg = eax;
if (left.is(left_arg)) {
__ mov(right_arg, Immediate(right));
} else if (left.is(right_arg) && IsOperationCommutative()) {
__ mov(left_arg, Immediate(right));
SetArgsReversed();
} else {
// For non-commutative operations, left and right_arg might be
// the same register. Therefore, the order of the moves is
// important here in order to not overwrite left before moving
// it to left_arg.
__ mov(left_arg, left);
__ mov(right_arg, Immediate(right));
}
// Update flags to indicate that arguments are in registers.
SetArgsInRegisters();
__ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
}
// Call the stub.
__ CallStub(this);
}
void GenericBinaryOpStub::GenerateCall(
MacroAssembler* masm,
Smi* left,
Register right) {
if (!ArgsInRegistersSupported()) {
// Pass arguments on the stack.
__ push(Immediate(left));
__ push(right);
} else {
// The calling convention with registers is left in edx and right in eax.
Register left_arg = edx;
Register right_arg = eax;
if (right.is(right_arg)) {
__ mov(left_arg, Immediate(left));
} else if (right.is(left_arg) && IsOperationCommutative()) {
__ mov(right_arg, Immediate(left));
SetArgsReversed();
} else {
// For non-commutative operations, right and left_arg might be
// the same register. Therefore, the order of the moves is
// important here in order to not overwrite right before moving
// it to right_arg.
__ mov(right_arg, right);
__ mov(left_arg, Immediate(left));
}
// Update flags to indicate that arguments are in registers.
SetArgsInRegisters();
__ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
}
// Call the stub.
__ CallStub(this);
}
Result GenericBinaryOpStub::GenerateCall(MacroAssembler* masm,
VirtualFrame* frame,
Result* left,
Result* right) {
if (ArgsInRegistersSupported()) {
SetArgsInRegisters();
return frame->CallStub(this, left, right);
} else {
frame->Push(left);
frame->Push(right);
return frame->CallStub(this, 2);
}
}
void GenericBinaryOpStub::GenerateSmiCode(MacroAssembler* masm, Label* slow) {
// 1. Move arguments into edx, eax except for DIV and MOD, which need the
// dividend in eax and edx free for the division. Use eax, ebx for those.
Comment load_comment(masm, "-- Load arguments");
Register left = edx;
Register right = eax;
if (op_ == Token::DIV || op_ == Token::MOD) {
left = eax;
right = ebx;
if (HasArgsInRegisters()) {
__ mov(ebx, eax);
__ mov(eax, edx);
}
}
if (!HasArgsInRegisters()) {
__ mov(right, Operand(esp, 1 * kPointerSize));
__ mov(left, Operand(esp, 2 * kPointerSize));
}
if (static_operands_type_.IsSmi()) {
if (FLAG_debug_code) {
__ AbortIfNotSmi(left);
__ AbortIfNotSmi(right);
}
if (op_ == Token::BIT_OR) {
__ or_(right, Operand(left));
GenerateReturn(masm);
return;
} else if (op_ == Token::BIT_AND) {
__ and_(right, Operand(left));
GenerateReturn(masm);
return;
} else if (op_ == Token::BIT_XOR) {
__ xor_(right, Operand(left));
GenerateReturn(masm);
return;
}
}
// 2. Prepare the smi check of both operands by oring them together.
Comment smi_check_comment(masm, "-- Smi check arguments");
Label not_smis;
Register combined = ecx;
ASSERT(!left.is(combined) && !right.is(combined));
switch (op_) {
case Token::BIT_OR:
// Perform the operation into eax and smi check the result. Preserve
// eax in case the result is not a smi.
ASSERT(!left.is(ecx) && !right.is(ecx));
__ mov(ecx, right);
__ or_(right, Operand(left)); // Bitwise or is commutative.
combined = right;
break;
case Token::BIT_XOR:
case Token::BIT_AND:
case Token::ADD:
case Token::SUB:
case Token::MUL:
case Token::DIV:
case Token::MOD:
__ mov(combined, right);
__ or_(combined, Operand(left));
break;
case Token::SHL:
case Token::SAR:
case Token::SHR:
// Move the right operand into ecx for the shift operation, use eax
// for the smi check register.
ASSERT(!left.is(ecx) && !right.is(ecx));
__ mov(ecx, right);
__ or_(right, Operand(left));
combined = right;
break;
default:
break;
}
// 3. Perform the smi check of the operands.
ASSERT(kSmiTag == 0); // Adjust zero check if not the case.
__ test(combined, Immediate(kSmiTagMask));
__ j(not_zero, ¬_smis, not_taken);
// 4. Operands are both smis, perform the operation leaving the result in
// eax and check the result if necessary.
Comment perform_smi(masm, "-- Perform smi operation");
Label use_fp_on_smis;
switch (op_) {
case Token::BIT_OR:
// Nothing to do.
break;
case Token::BIT_XOR:
ASSERT(right.is(eax));
__ xor_(right, Operand(left)); // Bitwise xor is commutative.
break;
case Token::BIT_AND:
ASSERT(right.is(eax));
__ and_(right, Operand(left)); // Bitwise and is commutative.
break;
case Token::SHL:
// Remove tags from operands (but keep sign).
__ SmiUntag(left);
__ SmiUntag(ecx);
// Perform the operation.
__ shl_cl(left);
// Check that the *signed* result fits in a smi.
__ cmp(left, 0xc0000000);
__ j(sign, &use_fp_on_smis, not_taken);
// Tag the result and store it in register eax.
__ SmiTag(left);
__ mov(eax, left);
break;
case Token::SAR:
// Remove tags from operands (but keep sign).
__ SmiUntag(left);
__ SmiUntag(ecx);
// Perform the operation.
__ sar_cl(left);
// Tag the result and store it in register eax.
__ SmiTag(left);
__ mov(eax, left);
break;
case Token::SHR:
// Remove tags from operands (but keep sign).
__ SmiUntag(left);
__ SmiUntag(ecx);
// Perform the operation.
__ shr_cl(left);
// Check that the *unsigned* result fits in a smi.
// Neither of the two high-order bits can be set:
// - 0x80000000: high bit would be lost when smi tagging.
// - 0x40000000: this number would convert to negative when
// Smi tagging these two cases can only happen with shifts
// by 0 or 1 when handed a valid smi.
__ test(left, Immediate(0xc0000000));
__ j(not_zero, slow, not_taken);
// Tag the result and store it in register eax.
__ SmiTag(left);
__ mov(eax, left);
break;
case Token::ADD:
ASSERT(right.is(eax));
__ add(right, Operand(left)); // Addition is commutative.
__ j(overflow, &use_fp_on_smis, not_taken);
break;
case Token::SUB:
__ sub(left, Operand(right));
__ j(overflow, &use_fp_on_smis, not_taken);
__ mov(eax, left);
break;
case Token::MUL:
// If the smi tag is 0 we can just leave the tag on one operand.
ASSERT(kSmiTag == 0); // Adjust code below if not the case.
// We can't revert the multiplication if the result is not a smi
// so save the right operand.
__ mov(ebx, right);
// Remove tag from one of the operands (but keep sign).
__ SmiUntag(right);
// Do multiplication.
__ imul(right, Operand(left)); // Multiplication is commutative.
__ j(overflow, &use_fp_on_smis, not_taken);
// Check for negative zero result. Use combined = left | right.
__ NegativeZeroTest(right, combined, &use_fp_on_smis);
break;
case Token::DIV:
// We can't revert the division if the result is not a smi so
// save the left operand.
__ mov(edi, left);
// Check for 0 divisor.
__ test(right, Operand(right));
__ j(zero, &use_fp_on_smis, not_taken);
// Sign extend left into edx:eax.
ASSERT(left.is(eax));
__ cdq();
// Divide edx:eax by right.
__ idiv(right);
// Check for the corner case of dividing the most negative smi by
// -1. We cannot use the overflow flag, since it is not set by idiv
// instruction.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ cmp(eax, 0x40000000);
__ j(equal, &use_fp_on_smis);
// Check for negative zero result. Use combined = left | right.
__ NegativeZeroTest(eax, combined, &use_fp_on_smis);
// Check that the remainder is zero.
__ test(edx, Operand(edx));
__ j(not_zero, &use_fp_on_smis);
// Tag the result and store it in register eax.
__ SmiTag(eax);
break;
case Token::MOD:
// Check for 0 divisor.
__ test(right, Operand(right));
__ j(zero, ¬_smis, not_taken);
// Sign extend left into edx:eax.
ASSERT(left.is(eax));
__ cdq();
// Divide edx:eax by right.
__ idiv(right);
// Check for negative zero result. Use combined = left | right.
__ NegativeZeroTest(edx, combined, slow);
// Move remainder to register eax.
__ mov(eax, edx);
break;
default:
UNREACHABLE();
}
// 5. Emit return of result in eax.
GenerateReturn(masm);
// 6. For some operations emit inline code to perform floating point
// operations on known smis (e.g., if the result of the operation
// overflowed the smi range).
switch (op_) {
case Token::SHL: {
Comment perform_float(masm, "-- Perform float operation on smis");
__ bind(&use_fp_on_smis);
// Result we want is in left == edx, so we can put the allocated heap
// number in eax.
__ AllocateHeapNumber(eax, ecx, ebx, slow);
// Store the result in the HeapNumber and return.
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
__ cvtsi2sd(xmm0, Operand(left));
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
} else {
// It's OK to overwrite the right argument on the stack because we
// are about to return.
__ mov(Operand(esp, 1 * kPointerSize), left);
__ fild_s(Operand(esp, 1 * kPointerSize));
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
}
GenerateReturn(masm);
break;
}
case Token::ADD:
case Token::SUB:
case Token::MUL:
case Token::DIV: {
Comment perform_float(masm, "-- Perform float operation on smis");
__ bind(&use_fp_on_smis);
// Restore arguments to edx, eax.
switch (op_) {
case Token::ADD:
// Revert right = right + left.
__ sub(right, Operand(left));
break;
case Token::SUB:
// Revert left = left - right.
__ add(left, Operand(right));
break;
case Token::MUL:
// Right was clobbered but a copy is in ebx.
__ mov(right, ebx);
break;
case Token::DIV:
// Left was clobbered but a copy is in edi. Right is in ebx for
// division.
__ mov(edx, edi);
__ mov(eax, right);
break;
default: UNREACHABLE();
break;
}
__ AllocateHeapNumber(ecx, ebx, no_reg, slow);
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
FloatingPointHelper::LoadSSE2Smis(masm, ebx);
switch (op_) {
case Token::ADD: __ addsd(xmm0, xmm1); break;
case Token::SUB: __ subsd(xmm0, xmm1); break;
case Token::MUL: __ mulsd(xmm0, xmm1); break;
case Token::DIV: __ divsd(xmm0, xmm1); break;
default: UNREACHABLE();
}
__ movdbl(FieldOperand(ecx, HeapNumber::kValueOffset), xmm0);
} else { // SSE2 not available, use FPU.
FloatingPointHelper::LoadFloatSmis(masm, ebx);
switch (op_) {
case Token::ADD: __ faddp(1); break;
case Token::SUB: __ fsubp(1); break;
case Token::MUL: __ fmulp(1); break;
case Token::DIV: __ fdivp(1); break;
default: UNREACHABLE();
}
__ fstp_d(FieldOperand(ecx, HeapNumber::kValueOffset));
}
__ mov(eax, ecx);
GenerateReturn(masm);
break;
}
default:
break;
}
// 7. Non-smi operands, fall out to the non-smi code with the operands in
// edx and eax.
Comment done_comment(masm, "-- Enter non-smi code");
__ bind(¬_smis);
switch (op_) {
case Token::BIT_OR:
case Token::SHL:
case Token::SAR:
case Token::SHR:
// Right operand is saved in ecx and eax was destroyed by the smi
// check.
__ mov(eax, ecx);
break;
case Token::DIV:
case Token::MOD:
// Operands are in eax, ebx at this point.
__ mov(edx, eax);
__ mov(eax, ebx);
break;
default:
break;
}
}
void GenericBinaryOpStub::Generate(MacroAssembler* masm) {
Label call_runtime;
__ IncrementCounter(&Counters::generic_binary_stub_calls, 1);
// Generate fast case smi code if requested. This flag is set when the fast
// case smi code is not generated by the caller. Generating it here will speed
// up common operations.
if (ShouldGenerateSmiCode()) {
GenerateSmiCode(masm, &call_runtime);
} else if (op_ != Token::MOD) { // MOD goes straight to runtime.
if (!HasArgsInRegisters()) {
GenerateLoadArguments(masm);
}
}
// Floating point case.
if (ShouldGenerateFPCode()) {
switch (op_) {
case Token::ADD:
case Token::SUB:
case Token::MUL:
case Token::DIV: {
if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
HasSmiCodeInStub()) {
// Execution reaches this point when the first non-smi argument occurs
// (and only if smi code is generated). This is the right moment to
// patch to HEAP_NUMBERS state. The transition is attempted only for
// the four basic operations. The stub stays in the DEFAULT state
// forever for all other operations (also if smi code is skipped).
GenerateTypeTransition(masm);
}
Label not_floats;
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
if (static_operands_type_.IsNumber()) {
if (FLAG_debug_code) {
// Assert at runtime that inputs are only numbers.
__ AbortIfNotNumber(edx);
__ AbortIfNotNumber(eax);
}
if (static_operands_type_.IsSmi()) {
if (FLAG_debug_code) {
__ AbortIfNotSmi(edx);
__ AbortIfNotSmi(eax);
}
FloatingPointHelper::LoadSSE2Smis(masm, ecx);
} else {
FloatingPointHelper::LoadSSE2Operands(masm);
}
} else {
FloatingPointHelper::LoadSSE2Operands(masm, &call_runtime);
}
switch (op_) {
case Token::ADD: __ addsd(xmm0, xmm1); break;
case Token::SUB: __ subsd(xmm0, xmm1); break;
case Token::MUL: __ mulsd(xmm0, xmm1); break;
case Token::DIV: __ divsd(xmm0, xmm1); break;
default: UNREACHABLE();
}
GenerateHeapResultAllocation(masm, &call_runtime);
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
GenerateReturn(masm);
} else { // SSE2 not available, use FPU.
if (static_operands_type_.IsNumber()) {
if (FLAG_debug_code) {
// Assert at runtime that inputs are only numbers.
__ AbortIfNotNumber(edx);
__ AbortIfNotNumber(eax);
}
} else {
FloatingPointHelper::CheckFloatOperands(masm, &call_runtime, ebx);
}
FloatingPointHelper::LoadFloatOperands(
masm,
ecx,
FloatingPointHelper::ARGS_IN_REGISTERS);
switch (op_) {
case Token::ADD: __ faddp(1); break;
case Token::SUB: __ fsubp(1); break;
case Token::MUL: __ fmulp(1); break;
case Token::DIV: __ fdivp(1); break;
default: UNREACHABLE();
}
Label after_alloc_failure;
GenerateHeapResultAllocation(masm, &after_alloc_failure);
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
GenerateReturn(masm);
__ bind(&after_alloc_failure);
__ ffree();
__ jmp(&call_runtime);
}
__ bind(¬_floats);
if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
!HasSmiCodeInStub()) {
// Execution reaches this point when the first non-number argument
// occurs (and only if smi code is skipped from the stub, otherwise
// the patching has already been done earlier in this case branch).
// Try patching to STRINGS for ADD operation.
if (op_ == Token::ADD) {
GenerateTypeTransition(masm);
}
}
break;
}
case Token::MOD: {
// For MOD we go directly to runtime in the non-smi case.
break;
}
case Token::BIT_OR:
case Token::BIT_AND:
case Token::BIT_XOR:
case Token::SAR:
case Token::SHL:
case Token::SHR: {
Label non_smi_result;
FloatingPointHelper::LoadAsIntegers(masm,
static_operands_type_,
use_sse3_,
&call_runtime);
switch (op_) {
case Token::BIT_OR: __ or_(eax, Operand(ecx)); break;
case Token::BIT_AND: __ and_(eax, Operand(ecx)); break;
case Token::BIT_XOR: __ xor_(eax, Operand(ecx)); break;
case Token::SAR: __ sar_cl(eax); break;
case Token::SHL: __ shl_cl(eax); break;
case Token::SHR: __ shr_cl(eax); break;
default: UNREACHABLE();
}
if (op_ == Token::SHR) {
// Check if result is non-negative and fits in a smi.
__ test(eax, Immediate(0xc0000000));
__ j(not_zero, &call_runtime);
} else {
// Check if result fits in a smi.
__ cmp(eax, 0xc0000000);
__ j(negative, &non_smi_result);
}
// Tag smi result and return.
__ SmiTag(eax);
GenerateReturn(masm);
// All ops except SHR return a signed int32 that we load in
// a HeapNumber.
if (op_ != Token::SHR) {
__ bind(&non_smi_result);
// Allocate a heap number if needed.
__ mov(ebx, Operand(eax)); // ebx: result
Label skip_allocation;
switch (mode_) {
case OVERWRITE_LEFT:
case OVERWRITE_RIGHT:
// If the operand was an object, we skip the
// allocation of a heap number.
__ mov(eax, Operand(esp, mode_ == OVERWRITE_RIGHT ?
1 * kPointerSize : 2 * kPointerSize));
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &skip_allocation, not_taken);
// Fall through!
case NO_OVERWRITE:
__ AllocateHeapNumber(eax, ecx, edx, &call_runtime);
__ bind(&skip_allocation);
break;
default: UNREACHABLE();
}
// Store the result in the HeapNumber and return.
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
__ cvtsi2sd(xmm0, Operand(ebx));
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
} else {
__ mov(Operand(esp, 1 * kPointerSize), ebx);
__ fild_s(Operand(esp, 1 * kPointerSize));
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
}
GenerateReturn(masm);
}
break;
}
default: UNREACHABLE(); break;
}
}
// If all else fails, use the runtime system to get the correct
// result. If arguments was passed in registers now place them on the
// stack in the correct order below the return address.
__ bind(&call_runtime);
if (HasArgsInRegisters()) {
GenerateRegisterArgsPush(masm);
}
switch (op_) {
case Token::ADD: {
// Test for string arguments before calling runtime.
Label not_strings, not_string1, string1, string1_smi2;
// If this stub has already generated FP-specific code then the arguments
// are already in edx, eax
if (!ShouldGenerateFPCode() && !HasArgsInRegisters()) {
GenerateLoadArguments(masm);
}
// Registers containing left and right operands respectively.
Register lhs, rhs;
if (HasArgsReversed()) {
lhs = eax;
rhs = edx;
} else {
lhs = edx;
rhs = eax;
}
// Test if first argument is a string.
__ test(lhs, Immediate(kSmiTagMask));
__ j(zero, ¬_string1);
__ CmpObjectType(lhs, FIRST_NONSTRING_TYPE, ecx);
__ j(above_equal, ¬_string1);
// First argument is a string, test second.
__ test(rhs, Immediate(kSmiTagMask));
__ j(zero, &string1_smi2);
__ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, ecx);
__ j(above_equal, &string1);
// First and second argument are strings. Jump to the string add stub.
StringAddStub string_add_stub(NO_STRING_CHECK_IN_STUB);
__ TailCallStub(&string_add_stub);
__ bind(&string1_smi2);
// First argument is a string, second is a smi. Try to lookup the number
// string for the smi in the number string cache.
NumberToStringStub::GenerateLookupNumberStringCache(
masm, rhs, edi, ebx, ecx, true, &string1);
// Replace second argument on stack and tailcall string add stub to make
// the result.
__ mov(Operand(esp, 1 * kPointerSize), edi);
__ TailCallStub(&string_add_stub);
// Only first argument is a string.
__ bind(&string1);
__ InvokeBuiltin(Builtins::STRING_ADD_LEFT, JUMP_FUNCTION);
// First argument was not a string, test second.
__ bind(¬_string1);
__ test(rhs, Immediate(kSmiTagMask));
__ j(zero, ¬_strings);
__ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, ecx);
__ j(above_equal, ¬_strings);
// Only second argument is a string.
__ InvokeBuiltin(Builtins::STRING_ADD_RIGHT, JUMP_FUNCTION);
__ bind(¬_strings);
// Neither argument is a string.
__ InvokeBuiltin(Builtins::ADD, JUMP_FUNCTION);
break;
}
case Token::SUB:
__ InvokeBuiltin(Builtins::SUB, JUMP_FUNCTION);
break;
case Token::MUL:
__ InvokeBuiltin(Builtins::MUL, JUMP_FUNCTION);
break;
case Token::DIV:
__ InvokeBuiltin(Builtins::DIV, JUMP_FUNCTION);
break;
case Token::MOD:
__ InvokeBuiltin(Builtins::MOD, JUMP_FUNCTION);
break;
case Token::BIT_OR:
__ InvokeBuiltin(Builtins::BIT_OR, JUMP_FUNCTION);
break;
case Token::BIT_AND:
__ InvokeBuiltin(Builtins::BIT_AND, JUMP_FUNCTION);
break;
case Token::BIT_XOR:
__ InvokeBuiltin(Builtins::BIT_XOR, JUMP_FUNCTION);
break;
case Token::SAR:
__ InvokeBuiltin(Builtins::SAR, JUMP_FUNCTION);
break;
case Token::SHL:
__ InvokeBuiltin(Builtins::SHL, JUMP_FUNCTION);
break;
case Token::SHR:
__ InvokeBuiltin(Builtins::SHR, JUMP_FUNCTION);
break;
default:
UNREACHABLE();
}
}
void GenericBinaryOpStub::GenerateHeapResultAllocation(MacroAssembler* masm,
Label* alloc_failure) {
Label skip_allocation;
OverwriteMode mode = mode_;
if (HasArgsReversed()) {
if (mode == OVERWRITE_RIGHT) {
mode = OVERWRITE_LEFT;
} else if (mode == OVERWRITE_LEFT) {
mode = OVERWRITE_RIGHT;
}
}
switch (mode) {
case OVERWRITE_LEFT: {
// If the argument in edx is already an object, we skip the
// allocation of a heap number.
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &skip_allocation, not_taken);
// Allocate a heap number for the result. Keep eax and edx intact
// for the possible runtime call.
__ AllocateHeapNumber(ebx, ecx, no_reg, alloc_failure);
// Now edx can be overwritten losing one of the arguments as we are
// now done and will not need it any more.
__ mov(edx, Operand(ebx));
__ bind(&skip_allocation);
// Use object in edx as a result holder
__ mov(eax, Operand(edx));
break;
}
case OVERWRITE_RIGHT:
// If the argument in eax is already an object, we skip the
// allocation of a heap number.
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &skip_allocation, not_taken);
// Fall through!
case NO_OVERWRITE:
// Allocate a heap number for the result. Keep eax and edx intact
// for the possible runtime call.
__ AllocateHeapNumber(ebx, ecx, no_reg, alloc_failure);
// Now eax can be overwritten losing one of the arguments as we are
// now done and will not need it any more.
__ mov(eax, ebx);
__ bind(&skip_allocation);
break;
default: UNREACHABLE();
}
}
void GenericBinaryOpStub::GenerateLoadArguments(MacroAssembler* masm) {
// If arguments are not passed in registers read them from the stack.
ASSERT(!HasArgsInRegisters());
__ mov(eax, Operand(esp, 1 * kPointerSize));
__ mov(edx, Operand(esp, 2 * kPointerSize));
}
void GenericBinaryOpStub::GenerateReturn(MacroAssembler* masm) {
// If arguments are not passed in registers remove them from the stack before
// returning.
if (!HasArgsInRegisters()) {
__ ret(2 * kPointerSize); // Remove both operands
} else {
__ ret(0);
}
}
void GenericBinaryOpStub::GenerateRegisterArgsPush(MacroAssembler* masm) {
ASSERT(HasArgsInRegisters());
__ pop(ecx);
if (HasArgsReversed()) {
__ push(eax);
__ push(edx);
} else {
__ push(edx);
__ push(eax);
}
__ push(ecx);
}
void GenericBinaryOpStub::GenerateTypeTransition(MacroAssembler* masm) {
Label get_result;
// Keep a copy of operands on the stack and make sure they are also in
// edx, eax.
if (HasArgsInRegisters()) {
GenerateRegisterArgsPush(masm);
} else {
GenerateLoadArguments(masm);
}
// Internal frame is necessary to handle exceptions properly.
__ EnterInternalFrame();
// Push arguments on stack if the stub expects them there.
if (!HasArgsInRegisters()) {
__ push(edx);
__ push(eax);
}
// Call the stub proper to get the result in eax.
__ call(&get_result);
__ LeaveInternalFrame();
__ pop(ecx); // Return address.
// Left and right arguments are now on top.
// Push the operation result. The tail call to BinaryOp_Patch will
// return it to the original caller.
__ push(eax);
// Push this stub's key. Although the operation and the type info are
// encoded into the key, the encoding is opaque, so push them too.
__ push(Immediate(Smi::FromInt(MinorKey())));
__ push(Immediate(Smi::FromInt(op_)));
__ push(Immediate(Smi::FromInt(runtime_operands_type_)));
__ push(ecx); // Return address.
// Patch the caller to an appropriate specialized stub
// and return the operation result.
__ TailCallExternalReference(
ExternalReference(IC_Utility(IC::kBinaryOp_Patch)),
6,
1);
// The entry point for the result calculation is assumed to be immediately
// after this sequence.
__ bind(&get_result);
}
Handle<Code> GetBinaryOpStub(int key, BinaryOpIC::TypeInfo type_info) {
GenericBinaryOpStub stub(key, type_info);
return stub.GetCode();
}
void TranscendentalCacheStub::Generate(MacroAssembler* masm) {
// Input on stack:
// esp[4]: argument (should be number).
// esp[0]: return address.
// Test that eax is a number.
Label runtime_call;
Label runtime_call_clear_stack;
Label input_not_smi;
Label loaded;
__ mov(eax, Operand(esp, kPointerSize));
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &input_not_smi);
// Input is a smi. Untag and load it onto the FPU stack.
// Then load the low and high words of the double into ebx, edx.
ASSERT_EQ(1, kSmiTagSize);
__ sar(eax, 1);
__ sub(Operand(esp), Immediate(2 * kPointerSize));
__ mov(Operand(esp, 0), eax);
__ fild_s(Operand(esp, 0));
__ fst_d(Operand(esp, 0));
__ pop(edx);
__ pop(ebx);
__ jmp(&loaded);
__ bind(&input_not_smi);
// Check if input is a HeapNumber.
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(Operand(ebx), Immediate(Factory::heap_number_map()));
__ j(not_equal, &runtime_call);
// Input is a HeapNumber. Push it on the FPU stack and load its
// low and high words into ebx, edx.
__ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ mov(edx, FieldOperand(eax, HeapNumber::kExponentOffset));
__ mov(ebx, FieldOperand(eax, HeapNumber::kMantissaOffset));
__ bind(&loaded);
// ST[0] == double value
// ebx = low 32 bits of double value
// edx = high 32 bits of double value
// Compute hash:
// h = (low ^ high); h ^= h >> 16; h ^= h >> 8; h = h & (cacheSize - 1);
__ mov(ecx, ebx);
__ xor_(ecx, Operand(edx));
__ mov(eax, ecx);
__ sar(eax, 16);
__ xor_(ecx, Operand(eax));
__ mov(eax, ecx);
__ sar(eax, 8);
__ xor_(ecx, Operand(eax));
ASSERT(IsPowerOf2(TranscendentalCache::kCacheSize));
__ and_(Operand(ecx), Immediate(TranscendentalCache::kCacheSize - 1));
// ST[0] == double value.
// ebx = low 32 bits of double value.
// edx = high 32 bits of double value.
// ecx = TranscendentalCache::hash(double value).
__ mov(eax,
Immediate(ExternalReference::transcendental_cache_array_address()));
// Eax points to cache array.
__ mov(eax, Operand(eax, type_ * sizeof(TranscendentalCache::caches_[0])));
// Eax points to the cache for the type type_.
// If NULL, the cache hasn't been initialized yet, so go through runtime.
__ test(eax, Operand(eax));
__ j(zero, &runtime_call_clear_stack);
#ifdef DEBUG
// Check that the layout of cache elements match expectations.
{ TranscendentalCache::Element test_elem[2];
char* elem_start = reinterpret_cast<char*>(&test_elem[0]);
char* elem2_start = reinterpret_cast<char*>(&test_elem[1]);
char* elem_in0 = reinterpret_cast<char*>(&(test_elem[0].in[0]));
char* elem_in1 = reinterpret_cast<char*>(&(test_elem[0].in[1]));
char* elem_out = reinterpret_cast<char*>(&(test_elem[0].output));
CHECK_EQ(12, elem2_start - elem_start); // Two uint_32's and a pointer.
CHECK_EQ(0, elem_in0 - elem_start);
CHECK_EQ(kIntSize, elem_in1 - elem_start);
CHECK_EQ(2 * kIntSize, elem_out - elem_start);
}
#endif
// Find the address of the ecx'th entry in the cache, i.e., &eax[ecx*12].
__ lea(ecx, Operand(ecx, ecx, times_2, 0));
__ lea(ecx, Operand(eax, ecx, times_4, 0));
// Check if cache matches: Double value is stored in uint32_t[2] array.
Label cache_miss;
__ cmp(ebx, Operand(ecx, 0));
__ j(not_equal, &cache_miss);
__ cmp(edx, Operand(ecx, kIntSize));
__ j(not_equal, &cache_miss);
// Cache hit!
__ mov(eax, Operand(ecx, 2 * kIntSize));
__ fstp(0);
__ ret(kPointerSize);
__ bind(&cache_miss);
// Update cache with new value.
// We are short on registers, so use no_reg as scratch.
// This gives slightly larger code.
__ AllocateHeapNumber(eax, edi, no_reg, &runtime_call_clear_stack);
GenerateOperation(masm);
__ mov(Operand(ecx, 0), ebx);
__ mov(Operand(ecx, kIntSize), edx);
__ mov(Operand(ecx, 2 * kIntSize), eax);
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ ret(kPointerSize);
__ bind(&runtime_call_clear_stack);
__ fstp(0);
__ bind(&runtime_call);
__ TailCallExternalReference(ExternalReference(RuntimeFunction()), 1, 1);
}
Runtime::FunctionId TranscendentalCacheStub::RuntimeFunction() {
switch (type_) {
// Add more cases when necessary.
case TranscendentalCache::SIN: return Runtime::kMath_sin;
case TranscendentalCache::COS: return Runtime::kMath_cos;
default:
UNIMPLEMENTED();
return Runtime::kAbort;
}
}
void TranscendentalCacheStub::GenerateOperation(MacroAssembler* masm) {
// Only free register is edi.
Label done;
ASSERT(type_ == TranscendentalCache::SIN ||
type_ == TranscendentalCache::COS);
// More transcendental types can be added later.
// Both fsin and fcos require arguments in the range +/-2^63 and
// return NaN for infinities and NaN. They can share all code except
// the actual fsin/fcos operation.
Label in_range;
// If argument is outside the range -2^63..2^63, fsin/cos doesn't
// work. We must reduce it to the appropriate range.
__ mov(edi, edx);
__ and_(Operand(edi), Immediate(0x7ff00000)); // Exponent only.
int supported_exponent_limit =
(63 + HeapNumber::kExponentBias) << HeapNumber::kExponentShift;
__ cmp(Operand(edi), Immediate(supported_exponent_limit));
__ j(below, &in_range, taken);
// Check for infinity and NaN. Both return NaN for sin.
__ cmp(Operand(edi), Immediate(0x7ff00000));
Label non_nan_result;
__ j(not_equal, &non_nan_result, taken);
// Input is +/-Infinity or NaN. Result is NaN.
__ fstp(0);
// NaN is represented by 0x7ff8000000000000.
__ push(Immediate(0x7ff80000));
__ push(Immediate(0));
__ fld_d(Operand(esp, 0));
__ add(Operand(esp), Immediate(2 * kPointerSize));
__ jmp(&done);
__ bind(&non_nan_result);
// Use fpmod to restrict argument to the range +/-2*PI.
__ mov(edi, eax); // Save eax before using fnstsw_ax.
__ fldpi();
__ fadd(0);
__ fld(1);
// FPU Stack: input, 2*pi, input.
{
Label no_exceptions;
__ fwait();
__ fnstsw_ax();
// Clear if Illegal Operand or Zero Division exceptions are set.
__ test(Operand(eax), Immediate(5));
__ j(zero, &no_exceptions);
__ fnclex();
__ bind(&no_exceptions);
}
// Compute st(0) % st(1)
{
Label partial_remainder_loop;
__ bind(&partial_remainder_loop);
__ fprem1();
__ fwait();
__ fnstsw_ax();
__ test(Operand(eax), Immediate(0x400 /* C2 */));
// If C2 is set, computation only has partial result. Loop to
// continue computation.
__ j(not_zero, &partial_remainder_loop);
}
// FPU Stack: input, 2*pi, input % 2*pi
__ fstp(2);
__ fstp(0);
__ mov(eax, edi); // Restore eax (allocated HeapNumber pointer).
// FPU Stack: input % 2*pi
__ bind(&in_range);
switch (type_) {
case TranscendentalCache::SIN:
__ fsin();
break;
case TranscendentalCache::COS:
__ fcos();
break;
default:
UNREACHABLE();
}
__ bind(&done);
}
// Get the integer part of a heap number. Surprisingly, all this bit twiddling
// is faster than using the built-in instructions on floating point registers.
// Trashes edi and ebx. Dest is ecx. Source cannot be ecx or one of the
// trashed registers.
void IntegerConvert(MacroAssembler* masm,
Register source,
TypeInfo type_info,
bool use_sse3,
Label* conversion_failure) {
ASSERT(!source.is(ecx) && !source.is(edi) && !source.is(ebx));
Label done, right_exponent, normal_exponent;
Register scratch = ebx;
Register scratch2 = edi;
if (type_info.IsInteger32() && CpuFeatures::IsEnabled(SSE2)) {
CpuFeatures::Scope scope(SSE2);
__ cvttsd2si(ecx, FieldOperand(source, HeapNumber::kValueOffset));
return;
}
if (!type_info.IsInteger32() || !use_sse3) {
// Get exponent word.
__ mov(scratch, FieldOperand(source, HeapNumber::kExponentOffset));
// Get exponent alone in scratch2.
__ mov(scratch2, scratch);
__ and_(scratch2, HeapNumber::kExponentMask);
}
if (use_sse3) {
CpuFeatures::Scope scope(SSE3);
if (!type_info.IsInteger32()) {
// Check whether the exponent is too big for a 64 bit signed integer.
static const uint32_t kTooBigExponent =
(HeapNumber::kExponentBias + 63) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch2), Immediate(kTooBigExponent));
__ j(greater_equal, conversion_failure);
}
// Load x87 register with heap number.
__ fld_d(FieldOperand(source, HeapNumber::kValueOffset));
// Reserve space for 64 bit answer.
__ sub(Operand(esp), Immediate(sizeof(uint64_t))); // Nolint.
// Do conversion, which cannot fail because we checked the exponent.
__ fisttp_d(Operand(esp, 0));
__ mov(ecx, Operand(esp, 0)); // Load low word of answer into ecx.
__ add(Operand(esp), Immediate(sizeof(uint64_t))); // Nolint.
} else {
// Load ecx with zero. We use this either for the final shift or
// for the answer.
__ xor_(ecx, Operand(ecx));
// Check whether the exponent matches a 32 bit signed int that cannot be
// represented by a Smi. A non-smi 32 bit integer is 1.xxx * 2^30 so the
// exponent is 30 (biased). This is the exponent that we are fastest at and
// also the highest exponent we can handle here.
const uint32_t non_smi_exponent =
(HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch2), Immediate(non_smi_exponent));
// If we have a match of the int32-but-not-Smi exponent then skip some
// logic.
__ j(equal, &right_exponent);
// If the exponent is higher than that then go to slow case. This catches
// numbers that don't fit in a signed int32, infinities and NaNs.
__ j(less, &normal_exponent);
{
// Handle a big exponent. The only reason we have this code is that the
// >>> operator has a tendency to generate numbers with an exponent of 31.
const uint32_t big_non_smi_exponent =
(HeapNumber::kExponentBias + 31) << HeapNumber::kExponentShift;
__ cmp(Operand(scratch2), Immediate(big_non_smi_exponent));
__ j(not_equal, conversion_failure);
// We have the big exponent, typically from >>>. This means the number is
// in the range 2^31 to 2^32 - 1. Get the top bits of the mantissa.
__ mov(scratch2, scratch);
__ and_(scratch2, HeapNumber::kMantissaMask);
// Put back the implicit 1.
__ or_(scratch2, 1 << HeapNumber::kExponentShift);
// Shift up the mantissa bits to take up the space the exponent used to
// take. We just orred in the implicit bit so that took care of one and
// we want to use the full unsigned range so we subtract 1 bit from the
// shift distance.
const int big_shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 1;
__ shl(scratch2, big_shift_distance);
// Get the second half of the double.
__ mov(ecx, FieldOperand(source, HeapNumber::kMantissaOffset));
// Shift down 21 bits to get the most significant 11 bits or the low
// mantissa word.
__ shr(ecx, 32 - big_shift_distance);
__ or_(ecx, Operand(scratch2));
// We have the answer in ecx, but we may need to negate it.
__ test(scratch, Operand(scratch));
__ j(positive, &done);
__ neg(ecx);
__ jmp(&done);
}
__ bind(&normal_exponent);
// Exponent word in scratch, exponent part of exponent word in scratch2.
// Zero in ecx.
// We know the exponent is smaller than 30 (biased). If it is less than
// 0 (biased) then the number is smaller in magnitude than 1.0 * 2^0, ie
// it rounds to zero.
const uint32_t zero_exponent =
(HeapNumber::kExponentBias + 0) << HeapNumber::kExponentShift;
__ sub(Operand(scratch2), Immediate(zero_exponent));
// ecx already has a Smi zero.
__ j(less, &done);
// We have a shifted exponent between 0 and 30 in scratch2.
__ shr(scratch2, HeapNumber::kExponentShift);
__ mov(ecx, Immediate(30));
__ sub(ecx, Operand(scratch2));
__ bind(&right_exponent);
// Here ecx is the shift, scratch is the exponent word.
// Get the top bits of the mantissa.
__ and_(scratch, HeapNumber::kMantissaMask);
// Put back the implicit 1.
__ or_(scratch, 1 << HeapNumber::kExponentShift);
// Shift up the mantissa bits to take up the space the exponent used to
// take. We have kExponentShift + 1 significant bits int he low end of the
// word. Shift them to the top bits.
const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
__ shl(scratch, shift_distance);
// Get the second half of the double. For some exponents we don't
// actually need this because the bits get shifted out again, but
// it's probably slower to test than just to do it.
__ mov(scratch2, FieldOperand(source, HeapNumber::kMantissaOffset));
// Shift down 22 bits to get the most significant 10 bits or the low
// mantissa word.
__ shr(scratch2, 32 - shift_distance);
__ or_(scratch2, Operand(scratch));
// Move down according to the exponent.
__ shr_cl(scratch2);
// Now the unsigned answer is in scratch2. We need to move it to ecx and
// we may need to fix the sign.
Label negative;
__ xor_(ecx, Operand(ecx));
__ cmp(ecx, FieldOperand(source, HeapNumber::kExponentOffset));
__ j(greater, &negative);
__ mov(ecx, scratch2);
__ jmp(&done);
__ bind(&negative);
__ sub(ecx, Operand(scratch2));
__ bind(&done);
}
}
// Input: edx, eax are the left and right objects of a bit op.
// Output: eax, ecx are left and right integers for a bit op.
void FloatingPointHelper::LoadNumbersAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* conversion_failure) {
// Check float operands.
Label arg1_is_object, check_undefined_arg1;
Label arg2_is_object, check_undefined_arg2;
Label load_arg2, done;
if (!type_info.IsDouble()) {
if (!type_info.IsSmi()) {
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &arg1_is_object);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(edx);
}
__ SmiUntag(edx);
__ jmp(&load_arg2);
}
__ bind(&arg1_is_object);
// Get the untagged integer version of the edx heap number in ecx.
IntegerConvert(masm, edx, type_info, use_sse3, conversion_failure);
__ mov(edx, ecx);
// Here edx has the untagged integer, eax has a Smi or a heap number.
__ bind(&load_arg2);
if (!type_info.IsDouble()) {
// Test if arg2 is a Smi.
if (!type_info.IsSmi()) {
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &arg2_is_object);
} else {
if (FLAG_debug_code) __ AbortIfNotSmi(eax);
}
__ SmiUntag(eax);
__ mov(ecx, eax);
__ jmp(&done);
}
__ bind(&arg2_is_object);
// Get the untagged integer version of the eax heap number in ecx.
IntegerConvert(masm, eax, type_info, use_sse3, conversion_failure);
__ bind(&done);
__ mov(eax, edx);
}
// Input: edx, eax are the left and right objects of a bit op.
// Output: eax, ecx are left and right integers for a bit op.
void FloatingPointHelper::LoadUnknownsAsIntegers(MacroAssembler* masm,
bool use_sse3,
Label* conversion_failure) {
// Check float operands.
Label arg1_is_object, check_undefined_arg1;
Label arg2_is_object, check_undefined_arg2;
Label load_arg2, done;
// Test if arg1 is a Smi.
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &arg1_is_object);
__ SmiUntag(edx);
__ jmp(&load_arg2);
// If the argument is undefined it converts to zero (ECMA-262, section 9.5).
__ bind(&check_undefined_arg1);
__ cmp(edx, Factory::undefined_value());
__ j(not_equal, conversion_failure);
__ mov(edx, Immediate(0));
__ jmp(&load_arg2);
__ bind(&arg1_is_object);
__ mov(ebx, FieldOperand(edx, HeapObject::kMapOffset));
__ cmp(ebx, Factory::heap_number_map());
__ j(not_equal, &check_undefined_arg1);
// Get the untagged integer version of the edx heap number in ecx.
IntegerConvert(masm,
edx,
TypeInfo::Unknown(),
use_sse3,
conversion_failure);
__ mov(edx, ecx);
// Here edx has the untagged integer, eax has a Smi or a heap number.
__ bind(&load_arg2);
// Test if arg2 is a Smi.
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &arg2_is_object);
__ SmiUntag(eax);
__ mov(ecx, eax);
__ jmp(&done);
// If the argument is undefined it converts to zero (ECMA-262, section 9.5).
__ bind(&check_undefined_arg2);
__ cmp(eax, Factory::undefined_value());
__ j(not_equal, conversion_failure);
__ mov(ecx, Immediate(0));
__ jmp(&done);
__ bind(&arg2_is_object);
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(ebx, Factory::heap_number_map());
__ j(not_equal, &check_undefined_arg2);
// Get the untagged integer version of the eax heap number in ecx.
IntegerConvert(masm,
eax,
TypeInfo::Unknown(),
use_sse3,
conversion_failure);
__ bind(&done);
__ mov(eax, edx);
}
void FloatingPointHelper::LoadAsIntegers(MacroAssembler* masm,
TypeInfo type_info,
bool use_sse3,
Label* conversion_failure) {
if (type_info.IsNumber()) {
LoadNumbersAsIntegers(masm, type_info, use_sse3, conversion_failure);
} else {
LoadUnknownsAsIntegers(masm, use_sse3, conversion_failure);
}
}
void FloatingPointHelper::LoadFloatOperand(MacroAssembler* masm,
Register number) {
Label load_smi, done;
__ test(number, Immediate(kSmiTagMask));
__ j(zero, &load_smi, not_taken);
__ fld_d(FieldOperand(number, HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&load_smi);
__ SmiUntag(number);
__ push(number);
__ fild_s(Operand(esp, 0));
__ pop(number);
__ bind(&done);
}
void FloatingPointHelper::LoadSSE2Operands(MacroAssembler* masm) {
Label load_smi_edx, load_eax, load_smi_eax, done;
// Load operand in edx into xmm0.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &load_smi_edx, not_taken); // Argument in edx is a smi.
__ movdbl(xmm0, FieldOperand(edx, HeapNumber::kValueOffset));
__ bind(&load_eax);
// Load operand in eax into xmm1.
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &load_smi_eax, not_taken); // Argument in eax is a smi.
__ movdbl(xmm1, FieldOperand(eax, HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&load_smi_edx);
__ SmiUntag(edx); // Untag smi before converting to float.
__ cvtsi2sd(xmm0, Operand(edx));
__ SmiTag(edx); // Retag smi for heap number overwriting test.
__ jmp(&load_eax);
__ bind(&load_smi_eax);
__ SmiUntag(eax); // Untag smi before converting to float.
__ cvtsi2sd(xmm1, Operand(eax));
__ SmiTag(eax); // Retag smi for heap number overwriting test.
__ bind(&done);
}
void FloatingPointHelper::LoadSSE2Operands(MacroAssembler* masm,
Label* not_numbers) {
Label load_smi_edx, load_eax, load_smi_eax, load_float_eax, done;
// Load operand in edx into xmm0, or branch to not_numbers.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &load_smi_edx, not_taken); // Argument in edx is a smi.
__ cmp(FieldOperand(edx, HeapObject::kMapOffset), Factory::heap_number_map());
__ j(not_equal, not_numbers); // Argument in edx is not a number.
__ movdbl(xmm0, FieldOperand(edx, HeapNumber::kValueOffset));
__ bind(&load_eax);
// Load operand in eax into xmm1, or branch to not_numbers.
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &load_smi_eax, not_taken); // Argument in eax is a smi.
__ cmp(FieldOperand(eax, HeapObject::kMapOffset), Factory::heap_number_map());
__ j(equal, &load_float_eax);
__ jmp(not_numbers); // Argument in eax is not a number.
__ bind(&load_smi_edx);
__ SmiUntag(edx); // Untag smi before converting to float.
__ cvtsi2sd(xmm0, Operand(edx));
__ SmiTag(edx); // Retag smi for heap number overwriting test.
__ jmp(&load_eax);
__ bind(&load_smi_eax);
__ SmiUntag(eax); // Untag smi before converting to float.
__ cvtsi2sd(xmm1, Operand(eax));
__ SmiTag(eax); // Retag smi for heap number overwriting test.
__ jmp(&done);
__ bind(&load_float_eax);
__ movdbl(xmm1, FieldOperand(eax, HeapNumber::kValueOffset));
__ bind(&done);
}
void FloatingPointHelper::LoadSSE2Smis(MacroAssembler* masm,
Register scratch) {
const Register left = edx;
const Register right = eax;
__ mov(scratch, left);
ASSERT(!scratch.is(right)); // We're about to clobber scratch.
__ SmiUntag(scratch);
__ cvtsi2sd(xmm0, Operand(scratch));
__ mov(scratch, right);
__ SmiUntag(scratch);
__ cvtsi2sd(xmm1, Operand(scratch));
}
void FloatingPointHelper::LoadFloatOperands(MacroAssembler* masm,
Register scratch,
ArgLocation arg_location) {
Label load_smi_1, load_smi_2, done_load_1, done;
if (arg_location == ARGS_IN_REGISTERS) {
__ mov(scratch, edx);
} else {
__ mov(scratch, Operand(esp, 2 * kPointerSize));
}
__ test(scratch, Immediate(kSmiTagMask));
__ j(zero, &load_smi_1, not_taken);
__ fld_d(FieldOperand(scratch, HeapNumber::kValueOffset));
__ bind(&done_load_1);
if (arg_location == ARGS_IN_REGISTERS) {
__ mov(scratch, eax);
} else {
__ mov(scratch, Operand(esp, 1 * kPointerSize));
}
__ test(scratch, Immediate(kSmiTagMask));
__ j(zero, &load_smi_2, not_taken);
__ fld_d(FieldOperand(scratch, HeapNumber::kValueOffset));
__ jmp(&done);
__ bind(&load_smi_1);
__ SmiUntag(scratch);
__ push(scratch);
__ fild_s(Operand(esp, 0));
__ pop(scratch);
__ jmp(&done_load_1);
__ bind(&load_smi_2);
__ SmiUntag(scratch);
__ push(scratch);
__ fild_s(Operand(esp, 0));
__ pop(scratch);
__ bind(&done);
}
void FloatingPointHelper::LoadFloatSmis(MacroAssembler* masm,
Register scratch) {
const Register left = edx;
const Register right = eax;
__ mov(scratch, left);
ASSERT(!scratch.is(right)); // We're about to clobber scratch.
__ SmiUntag(scratch);
__ push(scratch);
__ fild_s(Operand(esp, 0));
__ mov(scratch, right);
__ SmiUntag(scratch);
__ mov(Operand(esp, 0), scratch);
__ fild_s(Operand(esp, 0));
__ pop(scratch);
}
void FloatingPointHelper::CheckFloatOperands(MacroAssembler* masm,
Label* non_float,
Register scratch) {
Label test_other, done;
// Test if both operands are floats or smi -> scratch=k_is_float;
// Otherwise scratch = k_not_float.
__ test(edx, Immediate(kSmiTagMask));
__ j(zero, &test_other, not_taken); // argument in edx is OK
__ mov(scratch, FieldOperand(edx, HeapObject::kMapOffset));
__ cmp(scratch, Factory::heap_number_map());
__ j(not_equal, non_float); // argument in edx is not a number -> NaN
__ bind(&test_other);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &done); // argument in eax is OK
__ mov(scratch, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(scratch, Factory::heap_number_map());
__ j(not_equal, non_float); // argument in eax is not a number -> NaN
// Fall-through: Both operands are numbers.
__ bind(&done);
}
void GenericUnaryOpStub::Generate(MacroAssembler* masm) {
Label slow, done;
if (op_ == Token::SUB) {
// Check whether the value is a smi.
Label try_float;
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &try_float, not_taken);
// Go slow case if the value of the expression is zero
// to make sure that we switch between 0 and -0.
__ test(eax, Operand(eax));
__ j(zero, &slow, not_taken);
// The value of the expression is a smi that is not zero. Try
// optimistic subtraction '0 - value'.
Label undo;
__ mov(edx, Operand(eax));
__ Set(eax, Immediate(0));
__ sub(eax, Operand(edx));
__ j(overflow, &undo, not_taken);
// If result is a smi we are done.
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &done, taken);
// Restore eax and go slow case.
__ bind(&undo);
__ mov(eax, Operand(edx));
__ jmp(&slow);
// Try floating point case.
__ bind(&try_float);
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &slow);
if (overwrite_) {
__ mov(edx, FieldOperand(eax, HeapNumber::kExponentOffset));
__ xor_(edx, HeapNumber::kSignMask); // Flip sign.
__ mov(FieldOperand(eax, HeapNumber::kExponentOffset), edx);
} else {
__ mov(edx, Operand(eax));
// edx: operand
__ AllocateHeapNumber(eax, ebx, ecx, &undo);
// eax: allocated 'empty' number
__ mov(ecx, FieldOperand(edx, HeapNumber::kExponentOffset));
__ xor_(ecx, HeapNumber::kSignMask); // Flip sign.
__ mov(FieldOperand(eax, HeapNumber::kExponentOffset), ecx);
__ mov(ecx, FieldOperand(edx, HeapNumber::kMantissaOffset));
__ mov(FieldOperand(eax, HeapNumber::kMantissaOffset), ecx);
}
} else if (op_ == Token::BIT_NOT) {
// Check if the operand is a heap number.
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &slow, not_taken);
// Convert the heap number in eax to an untagged integer in ecx.
IntegerConvert(masm,
eax,
TypeInfo::Unknown(),
CpuFeatures::IsSupported(SSE3),
&slow);
// Do the bitwise operation and check if the result fits in a smi.
Label try_float;
__ not_(ecx);
__ cmp(ecx, 0xc0000000);
__ j(sign, &try_float, not_taken);
// Tag the result as a smi and we're done.
ASSERT(kSmiTagSize == 1);
__ lea(eax, Operand(ecx, times_2, kSmiTag));
__ jmp(&done);
// Try to store the result in a heap number.
__ bind(&try_float);
if (!overwrite_) {
// Allocate a fresh heap number, but don't overwrite eax until
// we're sure we can do it without going through the slow case
// that needs the value in eax.
__ AllocateHeapNumber(ebx, edx, edi, &slow);
__ mov(eax, Operand(ebx));
}
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
__ cvtsi2sd(xmm0, Operand(ecx));
__ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
} else {
__ push(ecx);
__ fild_s(Operand(esp, 0));
__ pop(ecx);
__ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
}
} else {
UNIMPLEMENTED();
}
// Return from the stub.
__ bind(&done);
__ StubReturn(1);
// Handle the slow case by jumping to the JavaScript builtin.
__ bind(&slow);
__ pop(ecx); // pop return address.
__ push(eax);
__ push(ecx); // push return address
switch (op_) {
case Token::SUB:
__ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_FUNCTION);
break;
case Token::BIT_NOT:
__ InvokeBuiltin(Builtins::BIT_NOT, JUMP_FUNCTION);
break;
default:
UNREACHABLE();
}
}
void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
// The key is in edx and the parameter count is in eax.
// The displacement is used for skipping the frame pointer on the
// stack. It is the offset of the last parameter (if any) relative
// to the frame pointer.
static const int kDisplacement = 1 * kPointerSize;
// Check that the key is a smi.
Label slow;
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &slow, not_taken);
// Check if the calling frame is an arguments adaptor frame.
Label adaptor;
__ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ mov(ecx, Operand(ebx, StandardFrameConstants::kContextOffset));
__ cmp(Operand(ecx), Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &adaptor);
// Check index against formal parameters count limit passed in
// through register eax. Use unsigned comparison to get negative
// check for free.
__ cmp(edx, Operand(eax));
__ j(above_equal, &slow, not_taken);
// Read the argument from the stack and return it.
ASSERT(kSmiTagSize == 1 && kSmiTag == 0); // shifting code depends on this
__ lea(ebx, Operand(ebp, eax, times_2, 0));
__ neg(edx);
__ mov(eax, Operand(ebx, edx, times_2, kDisplacement));
__ ret(0);
// Arguments adaptor case: Check index against actual arguments
// limit found in the arguments adaptor frame. Use unsigned
// comparison to get negative check for free.
__ bind(&adaptor);
__ mov(ecx, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ cmp(edx, Operand(ecx));
__ j(above_equal, &slow, not_taken);
// Read the argument from the stack and return it.
ASSERT(kSmiTagSize == 1 && kSmiTag == 0); // shifting code depends on this
__ lea(ebx, Operand(ebx, ecx, times_2, 0));
__ neg(edx);
__ mov(eax, Operand(ebx, edx, times_2, kDisplacement));
__ ret(0);
// Slow-case: Handle non-smi or out-of-bounds access to arguments
// by calling the runtime system.
__ bind(&slow);
__ pop(ebx); // Return address.
__ push(edx);
__ push(ebx);
__ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
}
void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
// esp[0] : return address
// esp[4] : number of parameters
// esp[8] : receiver displacement
// esp[16] : function
// The displacement is used for skipping the return address and the
// frame pointer on the stack. It is the offset of the last
// parameter (if any) relative to the frame pointer.
static const int kDisplacement = 2 * kPointerSize;
// Check if the calling frame is an arguments adaptor frame.
Label adaptor_frame, try_allocate, runtime;
__ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
__ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
__ cmp(Operand(ecx), Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &adaptor_frame);
// Get the length from the frame.
__ mov(ecx, Operand(esp, 1 * kPointerSize));
__ jmp(&try_allocate);
// Patch the arguments.length and the parameters pointer.
__ bind(&adaptor_frame);
__ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ mov(Operand(esp, 1 * kPointerSize), ecx);
__ lea(edx, Operand(edx, ecx, times_2, kDisplacement));
__ mov(Operand(esp, 2 * kPointerSize), edx);
// Try the new space allocation. Start out with computing the size of
// the arguments object and the elements array.
Label add_arguments_object;
__ bind(&try_allocate);
__ test(ecx, Operand(ecx));
__ j(zero, &add_arguments_object);
__ lea(ecx, Operand(ecx, times_2, FixedArray::kHeaderSize));
__ bind(&add_arguments_object);
__ add(Operand(ecx), Immediate(Heap::kArgumentsObjectSize));
// Do the allocation of both objects in one go.
__ AllocateInNewSpace(ecx, eax, edx, ebx, &runtime, TAG_OBJECT);
// Get the arguments boilerplate from the current (global) context.
int offset = Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
__ mov(edi, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
__ mov(edi, FieldOperand(edi, GlobalObject::kGlobalContextOffset));
__ mov(edi, Operand(edi, offset));
// Copy the JS object part.
for (int i = 0; i < JSObject::kHeaderSize; i += kPointerSize) {
__ mov(ebx, FieldOperand(edi, i));
__ mov(FieldOperand(eax, i), ebx);
}
// Setup the callee in-object property.
ASSERT(Heap::arguments_callee_index == 0);
__ mov(ebx, Operand(esp, 3 * kPointerSize));
__ mov(FieldOperand(eax, JSObject::kHeaderSize), ebx);
// Get the length (smi tagged) and set that as an in-object property too.
ASSERT(Heap::arguments_length_index == 1);
__ mov(ecx, Operand(esp, 1 * kPointerSize));
__ mov(FieldOperand(eax, JSObject::kHeaderSize + kPointerSize), ecx);
// If there are no actual arguments, we're done.
Label done;
__ test(ecx, Operand(ecx));
__ j(zero, &done);
// Get the parameters pointer from the stack.
__ mov(edx, Operand(esp, 2 * kPointerSize));
// Setup the elements pointer in the allocated arguments object and
// initialize the header in the elements fixed array.
__ lea(edi, Operand(eax, Heap::kArgumentsObjectSize));
__ mov(FieldOperand(eax, JSObject::kElementsOffset), edi);
__ mov(FieldOperand(edi, FixedArray::kMapOffset),
Immediate(Factory::fixed_array_map()));
__ mov(FieldOperand(edi, FixedArray::kLengthOffset), ecx);
// Untag the length for the loop below.
__ SmiUntag(ecx);
// Copy the fixed array slots.
Label loop;
__ bind(&loop);
__ mov(ebx, Operand(edx, -1 * kPointerSize)); // Skip receiver.
__ mov(FieldOperand(edi, FixedArray::kHeaderSize), ebx);
__ add(Operand(edi), Immediate(kPointerSize));
__ sub(Operand(edx), Immediate(kPointerSize));
__ dec(ecx);
__ j(not_zero, &loop);
// Return and remove the on-stack parameters.
__ bind(&done);
__ ret(3 * kPointerSize);
// Do the runtime call to allocate the arguments object.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
}
void RegExpExecStub::Generate(MacroAssembler* masm) {
// Just jump directly to runtime if native RegExp is not selected at compile
// time or if regexp entry in generated code is turned off runtime switch or
// at compilation.
#ifdef V8_INTERPRETED_REGEXP
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
#else // V8_INTERPRETED_REGEXP
if (!FLAG_regexp_entry_native) {
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
return;
}
// Stack frame on entry.
// esp[0]: return address
// esp[4]: last_match_info (expected JSArray)
// esp[8]: previous index
// esp[12]: subject string
// esp[16]: JSRegExp object
static const int kLastMatchInfoOffset = 1 * kPointerSize;
static const int kPreviousIndexOffset = 2 * kPointerSize;
static const int kSubjectOffset = 3 * kPointerSize;
static const int kJSRegExpOffset = 4 * kPointerSize;
Label runtime, invoke_regexp;
// Ensure that a RegExp stack is allocated.
ExternalReference address_of_regexp_stack_memory_address =
ExternalReference::address_of_regexp_stack_memory_address();
ExternalReference address_of_regexp_stack_memory_size =
ExternalReference::address_of_regexp_stack_memory_size();
__ mov(ebx, Operand::StaticVariable(address_of_regexp_stack_memory_size));
__ test(ebx, Operand(ebx));
__ j(zero, &runtime, not_taken);
// Check that the first argument is a JSRegExp object.
__ mov(eax, Operand(esp, kJSRegExpOffset));
ASSERT_EQ(0, kSmiTag);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
__ CmpObjectType(eax, JS_REGEXP_TYPE, ecx);
__ j(not_equal, &runtime);
// Check that the RegExp has been compiled (data contains a fixed array).
__ mov(ecx, FieldOperand(eax, JSRegExp::kDataOffset));
if (FLAG_debug_code) {
__ test(ecx, Immediate(kSmiTagMask));
__ Check(not_zero, "Unexpected type for RegExp data, FixedArray expected");
__ CmpObjectType(ecx, FIXED_ARRAY_TYPE, ebx);
__ Check(equal, "Unexpected type for RegExp data, FixedArray expected");
}
// ecx: RegExp data (FixedArray)
// Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
__ mov(ebx, FieldOperand(ecx, JSRegExp::kDataTagOffset));
__ cmp(Operand(ebx), Immediate(Smi::FromInt(JSRegExp::IRREGEXP)));
__ j(not_equal, &runtime);
// ecx: RegExp data (FixedArray)
// Check that the number of captures fit in the static offsets vector buffer.
__ mov(edx, FieldOperand(ecx, JSRegExp::kIrregexpCaptureCountOffset));
// Calculate number of capture registers (number_of_captures + 1) * 2. This
// uses the asumption that smis are 2 * their untagged value.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
__ add(Operand(edx), Immediate(2)); // edx was a smi.
// Check that the static offsets vector buffer is large enough.
__ cmp(edx, OffsetsVector::kStaticOffsetsVectorSize);
__ j(above, &runtime);
// ecx: RegExp data (FixedArray)
// edx: Number of capture registers
// Check that the second argument is a string.
__ mov(eax, Operand(esp, kSubjectOffset));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
__ j(NegateCondition(is_string), &runtime);
// Get the length of the string to ebx.
__ mov(ebx, FieldOperand(eax, String::kLengthOffset));
// ebx: Length of subject string as a smi
// ecx: RegExp data (FixedArray)
// edx: Number of capture registers
// Check that the third argument is a positive smi less than the subject
// string length. A negative value will be greater (unsigned comparison).
__ mov(eax, Operand(esp, kPreviousIndexOffset));
__ test(eax, Immediate(kSmiTagMask));
__ j(not_zero, &runtime);
__ cmp(eax, Operand(ebx));
__ j(above_equal, &runtime);
// ecx: RegExp data (FixedArray)
// edx: Number of capture registers
// Check that the fourth object is a JSArray object.
__ mov(eax, Operand(esp, kLastMatchInfoOffset));
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
__ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
__ j(not_equal, &runtime);
// Check that the JSArray is in fast case.
__ mov(ebx, FieldOperand(eax, JSArray::kElementsOffset));
__ mov(eax, FieldOperand(ebx, HeapObject::kMapOffset));
__ cmp(eax, Factory::fixed_array_map());
__ j(not_equal, &runtime);
// Check that the last match info has space for the capture registers and the
// additional information.
__ mov(eax, FieldOperand(ebx, FixedArray::kLengthOffset));
__ SmiUntag(eax);
__ add(Operand(edx), Immediate(RegExpImpl::kLastMatchOverhead));
__ cmp(edx, Operand(eax));
__ j(greater, &runtime);
// ecx: RegExp data (FixedArray)
// Check the representation and encoding of the subject string.
Label seq_ascii_string, seq_two_byte_string, check_code;
__ mov(eax, Operand(esp, kSubjectOffset));
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
// First check for flat two-byte string.
__ test_b(Operand(ebx),
kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
ASSERT_EQ(0, kStringTag | kSeqStringTag | kTwoByteStringTag);
__ j(zero, &seq_two_byte_string);
// Any other flat string must be a flat ascii string.
__ test_b(Operand(ebx), kIsNotStringMask | kStringRepresentationMask);
__ j(zero, &seq_ascii_string);
// Check for flat cons string.
// If this is a string, and not an external string, it is a cons string.
// A flat cons string is a cons string where the second part is the empty
// string. In that case the subject string is just the first part of the cons
// string. Also in this case the first part of the cons string is known to be
// a sequential string or an external string.
ASSERT(kExternalStringTag !=0);
ASSERT_EQ(0, kConsStringTag & kExternalStringTag);
__ test_b(Operand(ebx), kIsNotStringMask | kExternalStringTag);
__ j(not_zero, &runtime);
// String is a cons string.
__ cmp(FieldOperand(eax, ConsString::kSecondOffset),
Factory::empty_string());
__ j(not_equal, &runtime);
__ mov(eax, FieldOperand(eax, ConsString::kFirstOffset));
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
// String is a cons string with empty second part.
// eax: first part of cons string.
// ebx: map of first part of cons string.
// Is first part a flat two byte string?
__ test_b(FieldOperand(ebx, Map::kInstanceTypeOffset),
kStringRepresentationMask | kStringEncodingMask);
ASSERT_EQ(0, kSeqStringTag | kTwoByteStringTag);
__ j(zero, &seq_two_byte_string);
// Any other flat string must be ascii.
__ test_b(FieldOperand(ebx, Map::kInstanceTypeOffset),
kStringRepresentationMask);
__ j(not_zero, &runtime);
__ bind(&seq_ascii_string);
// eax: subject string (flat ascii)
// ecx: RegExp data (FixedArray)
__ mov(edx, FieldOperand(ecx, JSRegExp::kDataAsciiCodeOffset));
__ Set(edi, Immediate(1)); // Type is ascii.
__ jmp(&check_code);
__ bind(&seq_two_byte_string);
// eax: subject string (flat two byte)
// ecx: RegExp data (FixedArray)
__ mov(edx, FieldOperand(ecx, JSRegExp::kDataUC16CodeOffset));
__ Set(edi, Immediate(0)); // Type is two byte.
__ bind(&check_code);
// Check that the irregexp code has been generated for the actual string
// encoding. If it has, the field contains a code object otherwise it contains
// the hole.
__ CmpObjectType(edx, CODE_TYPE, ebx);
__ j(not_equal, &runtime);
// eax: subject string
// edx: code
// edi: encoding of subject string (1 if ascii, 0 if two_byte);
// Load used arguments before starting to push arguments for call to native
// RegExp code to avoid handling changing stack height.
__ mov(ebx, Operand(esp, kPreviousIndexOffset));
__ SmiUntag(ebx); // Previous index from smi.
// eax: subject string
// ebx: previous index
// edx: code
// edi: encoding of subject string (1 if ascii 0 if two_byte);
// All checks done. Now push arguments for native regexp code.
__ IncrementCounter(&Counters::regexp_entry_native, 1);
static const int kRegExpExecuteArguments = 7;
__ PrepareCallCFunction(kRegExpExecuteArguments, ecx);
// Argument 7: Indicate that this is a direct call from JavaScript.
__ mov(Operand(esp, 6 * kPointerSize), Immediate(1));
// Argument 6: Start (high end) of backtracking stack memory area.
__ mov(ecx, Operand::StaticVariable(address_of_regexp_stack_memory_address));
__ add(ecx, Operand::StaticVariable(address_of_regexp_stack_memory_size));
__ mov(Operand(esp, 5 * kPointerSize), ecx);
// Argument 5: static offsets vector buffer.
__ mov(Operand(esp, 4 * kPointerSize),
Immediate(ExternalReference::address_of_static_offsets_vector()));
// Argument 4: End of string data
// Argument 3: Start of string data
Label setup_two_byte, setup_rest;
__ test(edi, Operand(edi));
__ mov(edi, FieldOperand(eax, String::kLengthOffset));
__ j(zero, &setup_two_byte);
__ SmiUntag(edi);
__ lea(ecx, FieldOperand(eax, edi, times_1, SeqAsciiString::kHeaderSize));
__ mov(Operand(esp, 3 * kPointerSize), ecx); // Argument 4.
__ lea(ecx, FieldOperand(eax, ebx, times_1, SeqAsciiString::kHeaderSize));
__ mov(Operand(esp, 2 * kPointerSize), ecx); // Argument 3.
__ jmp(&setup_rest);
__ bind(&setup_two_byte);
ASSERT(kSmiTag == 0 && kSmiTagSize == 1); // edi is smi (powered by 2).
__ lea(ecx, FieldOperand(eax, edi, times_1, SeqTwoByteString::kHeaderSize));
__ mov(Operand(esp, 3 * kPointerSize), ecx); // Argument 4.
__ lea(ecx, FieldOperand(eax, ebx, times_2, SeqTwoByteString::kHeaderSize));
__ mov(Operand(esp, 2 * kPointerSize), ecx); // Argument 3.
__ bind(&setup_rest);
// Argument 2: Previous index.
__ mov(Operand(esp, 1 * kPointerSize), ebx);
// Argument 1: Subject string.
__ mov(Operand(esp, 0 * kPointerSize), eax);
// Locate the code entry and call it.
__ add(Operand(edx), Immediate(Code::kHeaderSize - kHeapObjectTag));
__ CallCFunction(edx, kRegExpExecuteArguments);
// Check the result.
Label success;
__ cmp(eax, NativeRegExpMacroAssembler::SUCCESS);
__ j(equal, &success, taken);
Label failure;
__ cmp(eax, NativeRegExpMacroAssembler::FAILURE);
__ j(equal, &failure, taken);
__ cmp(eax, NativeRegExpMacroAssembler::EXCEPTION);
// If not exception it can only be retry. Handle that in the runtime system.
__ j(not_equal, &runtime);
// Result must now be exception. If there is no pending exception already a
// stack overflow (on the backtrack stack) was detected in RegExp code but
// haven't created the exception yet. Handle that in the runtime system.
// TODO(592): Rerunning the RegExp to get the stack overflow exception.
ExternalReference pending_exception(Top::k_pending_exception_address);
__ mov(eax,
Operand::StaticVariable(ExternalReference::the_hole_value_location()));
__ cmp(eax, Operand::StaticVariable(pending_exception));
__ j(equal, &runtime);
__ bind(&failure);
// For failure and exception return null.
__ mov(Operand(eax), Factory::null_value());
__ ret(4 * kPointerSize);
// Load RegExp data.
__ bind(&success);
__ mov(eax, Operand(esp, kJSRegExpOffset));
__ mov(ecx, FieldOperand(eax, JSRegExp::kDataOffset));
__ mov(edx, FieldOperand(ecx, JSRegExp::kIrregexpCaptureCountOffset));
// Calculate number of capture registers (number_of_captures + 1) * 2.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
__ add(Operand(edx), Immediate(2)); // edx was a smi.
// edx: Number of capture registers
// Load last_match_info which is still known to be a fast case JSArray.
__ mov(eax, Operand(esp, kLastMatchInfoOffset));
__ mov(ebx, FieldOperand(eax, JSArray::kElementsOffset));
// ebx: last_match_info backing store (FixedArray)
// edx: number of capture registers
// Store the capture count.
__ SmiTag(edx); // Number of capture registers to smi.
__ mov(FieldOperand(ebx, RegExpImpl::kLastCaptureCountOffset), edx);
__ SmiUntag(edx); // Number of capture registers back from smi.
// Store last subject and last input.
__ mov(eax, Operand(esp, kSubjectOffset));
__ mov(FieldOperand(ebx, RegExpImpl::kLastSubjectOffset), eax);
__ mov(ecx, ebx);
__ RecordWrite(ecx, RegExpImpl::kLastSubjectOffset, eax, edi);
__ mov(eax, Operand(esp, kSubjectOffset));
__ mov(FieldOperand(ebx, RegExpImpl::kLastInputOffset), eax);
__ mov(ecx, ebx);
__ RecordWrite(ecx, RegExpImpl::kLastInputOffset, eax, edi);
// Get the static offsets vector filled by the native regexp code.
ExternalReference address_of_static_offsets_vector =
ExternalReference::address_of_static_offsets_vector();
__ mov(ecx, Immediate(address_of_static_offsets_vector));
// ebx: last_match_info backing store (FixedArray)
// ecx: offsets vector
// edx: number of capture registers
Label next_capture, done;
// Capture register counter starts from number of capture registers and
// counts down until wraping after zero.
__ bind(&next_capture);
__ sub(Operand(edx), Immediate(1));
__ j(negative, &done);
// Read the value from the static offsets vector buffer.
__ mov(edi, Operand(ecx, edx, times_int_size, 0));
__ SmiTag(edi);
// Store the smi value in the last match info.
__ mov(FieldOperand(ebx,
edx,
times_pointer_size,
RegExpImpl::kFirstCaptureOffset),
edi);
__ jmp(&next_capture);
__ bind(&done);
// Return last match info.
__ mov(eax, Operand(esp, kLastMatchInfoOffset));
__ ret(4 * kPointerSize);
// Do the runtime call to execute the regexp.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
#endif // V8_INTERPRETED_REGEXP
}
void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm,
Register object,
Register result,
Register scratch1,
Register scratch2,
bool object_is_smi,
Label* not_found) {
// Use of registers. Register result is used as a temporary.
Register number_string_cache = result;
Register mask = scratch1;
Register scratch = scratch2;
// Load the number string cache.
ExternalReference roots_address = ExternalReference::roots_address();
__ mov(scratch, Immediate(Heap::kNumberStringCacheRootIndex));
__ mov(number_string_cache,
Operand::StaticArray(scratch, times_pointer_size, roots_address));
// Make the hash mask from the length of the number string cache. It
// contains two elements (number and string) for each cache entry.
__ mov(mask, FieldOperand(number_string_cache, FixedArray::kLengthOffset));
__ shr(mask, kSmiTagSize + 1); // Untag length and divide it by two.
__ sub(Operand(mask), Immediate(1)); // Make mask.
// Calculate the entry in the number string cache. The hash value in the
// number string cache for smis is just the smi value, and the hash for
// doubles is the xor of the upper and lower words. See
// Heap::GetNumberStringCache.
Label smi_hash_calculated;
Label load_result_from_cache;
if (object_is_smi) {
__ mov(scratch, object);
__ SmiUntag(scratch);
} else {
Label not_smi, hash_calculated;
ASSERT(kSmiTag == 0);
__ test(object, Immediate(kSmiTagMask));
__ j(not_zero, ¬_smi);
__ mov(scratch, object);
__ SmiUntag(scratch);
__ jmp(&smi_hash_calculated);
__ bind(¬_smi);
__ cmp(FieldOperand(object, HeapObject::kMapOffset),
Factory::heap_number_map());
__ j(not_equal, not_found);
ASSERT_EQ(8, kDoubleSize);
__ mov(scratch, FieldOperand(object, HeapNumber::kValueOffset));
__ xor_(scratch, FieldOperand(object, HeapNumber::kValueOffset + 4));
// Object is heap number and hash is now in scratch. Calculate cache index.
__ and_(scratch, Operand(mask));
Register index = scratch;
Register probe = mask;
__ mov(probe,
FieldOperand(number_string_cache,
index,
times_twice_pointer_size,
FixedArray::kHeaderSize));
__ test(probe, Immediate(kSmiTagMask));
__ j(zero, not_found);
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope fscope(SSE2);
__ movdbl(xmm0, FieldOperand(object, HeapNumber::kValueOffset));
__ movdbl(xmm1, FieldOperand(probe, HeapNumber::kValueOffset));
__ comisd(xmm0, xmm1);
} else {
__ fld_d(FieldOperand(object, HeapNumber::kValueOffset));
__ fld_d(FieldOperand(probe, HeapNumber::kValueOffset));
__ FCmp();
}
__ j(parity_even, not_found); // Bail out if NaN is involved.
__ j(not_equal, not_found); // The cache did not contain this value.
__ jmp(&load_result_from_cache);
}
__ bind(&smi_hash_calculated);
// Object is smi and hash is now in scratch. Calculate cache index.
__ and_(scratch, Operand(mask));
Register index = scratch;
// Check if the entry is the smi we are looking for.
__ cmp(object,
FieldOperand(number_string_cache,
index,
times_twice_pointer_size,
FixedArray::kHeaderSize));
__ j(not_equal, not_found);
// Get the result from the cache.
__ bind(&load_result_from_cache);
__ mov(result,
FieldOperand(number_string_cache,
index,
times_twice_pointer_size,
FixedArray::kHeaderSize + kPointerSize));
__ IncrementCounter(&Counters::number_to_string_native, 1);
}
void NumberToStringStub::Generate(MacroAssembler* masm) {
Label runtime;
__ mov(ebx, Operand(esp, kPointerSize));
// Generate code to lookup number in the number string cache.
GenerateLookupNumberStringCache(masm, ebx, eax, ecx, edx, false, &runtime);
__ ret(1 * kPointerSize);
__ bind(&runtime);
// Handle number to string in the runtime system if not found in the cache.
__ TailCallRuntime(Runtime::kNumberToStringSkipCache, 1, 1);
}
static int NegativeComparisonResult(Condition cc) {
ASSERT(cc != equal);
ASSERT((cc == less) || (cc == less_equal)
|| (cc == greater) || (cc == greater_equal));
return (cc == greater || cc == greater_equal) ? LESS : GREATER;
}
void CompareStub::Generate(MacroAssembler* masm) {
Label call_builtin, done;
// NOTICE! This code is only reached after a smi-fast-case check, so
// it is certain that at least one operand isn't a smi.
// Identical objects can be compared fast, but there are some tricky cases
// for NaN and undefined.
{
Label not_identical;
__ cmp(eax, Operand(edx));
__ j(not_equal, ¬_identical);
if (cc_ != equal) {
// Check for undefined. undefined OP undefined is false even though
// undefined == undefined.
Label check_for_nan;
__ cmp(edx, Factory::undefined_value());
__ j(not_equal, &check_for_nan);
__ Set(eax, Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
__ ret(0);
__ bind(&check_for_nan);
}
// Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
// so we do the second best thing - test it ourselves.
// Note: if cc_ != equal, never_nan_nan_ is not used.
if (never_nan_nan_ && (cc_ == equal)) {
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(0);
} else {
Label return_equal;
Label heap_number;
// If it's not a heap number, then return equal.
__ cmp(FieldOperand(edx, HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
__ j(equal, &heap_number);
__ bind(&return_equal);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(0);
__ bind(&heap_number);
// It is a heap number, so return non-equal if it's NaN and equal if
// it's not NaN.
// The representation of NaN values has all exponent bits (52..62) set,
// and not all mantissa bits (0..51) clear.
// We only accept QNaNs, which have bit 51 set.
// Read top bits of double representation (second word of value).
// Value is a QNaN if value & kQuietNaNMask == kQuietNaNMask, i.e.,
// all bits in the mask are set. We only need to check the word
// that contains the exponent and high bit of the mantissa.
ASSERT_NE(0, (kQuietNaNHighBitsMask << 1) & 0x80000000u);
__ mov(edx, FieldOperand(edx, HeapNumber::kExponentOffset));
__ xor_(eax, Operand(eax));
// Shift value and mask so kQuietNaNHighBitsMask applies to topmost
// bits.
__ add(edx, Operand(edx));
__ cmp(edx, kQuietNaNHighBitsMask << 1);
if (cc_ == equal) {
ASSERT_NE(1, EQUAL);
__ setcc(above_equal, eax);
__ ret(0);
} else {
Label nan;
__ j(above_equal, &nan);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(0);
__ bind(&nan);
__ Set(eax, Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
__ ret(0);
}
}
__ bind(¬_identical);
}
if (cc_ == equal) { // Both strict and non-strict.
Label slow; // Fallthrough label.
// If we're doing a strict equality comparison, we don't have to do
// type conversion, so we generate code to do fast comparison for objects
// and oddballs. Non-smi numbers and strings still go through the usual
// slow-case code.
if (strict_) {
// If either is a Smi (we know that not both are), then they can only
// be equal if the other is a HeapNumber. If so, use the slow case.
{
Label not_smis;
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(0, Smi::FromInt(0));
__ mov(ecx, Immediate(kSmiTagMask));
__ and_(ecx, Operand(eax));
__ test(ecx, Operand(edx));
__ j(not_zero, ¬_smis);
// One operand is a smi.
// Check whether the non-smi is a heap number.
ASSERT_EQ(1, kSmiTagMask);
// ecx still holds eax & kSmiTag, which is either zero or one.
__ sub(Operand(ecx), Immediate(0x01));
__ mov(ebx, edx);
__ xor_(ebx, Operand(eax));
__ and_(ebx, Operand(ecx)); // ebx holds either 0 or eax ^ edx.
__ xor_(ebx, Operand(eax));
// if eax was smi, ebx is now edx, else eax.
// Check if the non-smi operand is a heap number.
__ cmp(FieldOperand(ebx, HeapObject::kMapOffset),
Immediate(Factory::heap_number_map()));
// If heap number, handle it in the slow case.
__ j(equal, &slow);
// Return non-equal (ebx is not zero)
__ mov(eax, ebx);
__ ret(0);
__ bind(¬_smis);
}
// If either operand is a JSObject or an oddball value, then they are not
// equal since their pointers are different
// There is no test for undetectability in strict equality.
// Get the type of the first operand.
// If the first object is a JS object, we have done pointer comparison.
Label first_non_object;
ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
__ j(below, &first_non_object);
// Return non-zero (eax is not zero)
Label return_not_equal;
ASSERT(kHeapObjectTag != 0);
__ bind(&return_not_equal);
__ ret(0);
__ bind(&first_non_object);
// Check for oddballs: true, false, null, undefined.
__ CmpInstanceType(ecx, ODDBALL_TYPE);
__ j(equal, &return_not_equal);
__ CmpObjectType(edx, FIRST_JS_OBJECT_TYPE, ecx);
__ j(above_equal, &return_not_equal);
// Check for oddballs: true, false, null, undefined.
__ CmpInstanceType(ecx, ODDBALL_TYPE);
__ j(equal, &return_not_equal);
// Fall through to the general case.
}
__ bind(&slow);
}
// Push arguments below the return address.
__ pop(ecx);
__ push(eax);
__ push(edx);
__ push(ecx);
// Generate the number comparison code.
if (include_number_compare_) {
Label non_number_comparison;
Label unordered;
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope use_sse2(SSE2);
CpuFeatures::Scope use_cmov(CMOV);
FloatingPointHelper::LoadSSE2Operands(masm, &non_number_comparison);
__ comisd(xmm0, xmm1);
// Don't base result on EFLAGS when a NaN is involved.
__ j(parity_even, &unordered, not_taken);
// Return a result of -1, 0, or 1, based on EFLAGS.
__ mov(eax, 0); // equal
__ mov(ecx, Immediate(Smi::FromInt(1)));
__ cmov(above, eax, Operand(ecx));
__ mov(ecx, Immediate(Smi::FromInt(-1)));
__ cmov(below, eax, Operand(ecx));
__ ret(2 * kPointerSize);
} else {
FloatingPointHelper::CheckFloatOperands(
masm, &non_number_comparison, ebx);
FloatingPointHelper::LoadFloatOperands(masm, ecx);
__ FCmp();
// Don't base result on EFLAGS when a NaN is involved.
__ j(parity_even, &unordered, not_taken);
Label below_label, above_label;
// Return a result of -1, 0, or 1, based on EFLAGS. In all cases remove
// two arguments from the stack as they have been pushed in preparation
// of a possible runtime call.
__ j(below, &below_label, not_taken);
__ j(above, &above_label, not_taken);
__ xor_(eax, Operand(eax));
__ ret(2 * kPointerSize);
__ bind(&below_label);
__ mov(eax, Immediate(Smi::FromInt(-1)));
__ ret(2 * kPointerSize);
__ bind(&above_label);
__ mov(eax, Immediate(Smi::FromInt(1)));
__ ret(2 * kPointerSize);
}
// If one of the numbers was NaN, then the result is always false.
// The cc is never not-equal.
__ bind(&unordered);
ASSERT(cc_ != not_equal);
if (cc_ == less || cc_ == less_equal) {
__ mov(eax, Immediate(Smi::FromInt(1)));
} else {
__ mov(eax, Immediate(Smi::FromInt(-1)));
}
__ ret(2 * kPointerSize); // eax, edx were pushed
// The number comparison code did not provide a valid result.
__ bind(&non_number_comparison);
}
// Fast negative check for symbol-to-symbol equality.
Label check_for_strings;
if (cc_ == equal) {
BranchIfNonSymbol(masm, &check_for_strings, eax, ecx);
BranchIfNonSymbol(masm, &check_for_strings, edx, ecx);
// We've already checked for object identity, so if both operands
// are symbols they aren't equal. Register eax already holds a
// non-zero value, which indicates not equal, so just return.
__ ret(2 * kPointerSize);
}
__ bind(&check_for_strings);
__ JumpIfNotBothSequentialAsciiStrings(edx, eax, ecx, ebx, &call_builtin);
// Inline comparison of ascii strings.
StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
edx,
eax,
ecx,
ebx,
edi);
#ifdef DEBUG
__ Abort("Unexpected fall-through from string comparison");
#endif
__ bind(&call_builtin);
// must swap argument order
__ pop(ecx);
__ pop(edx);
__ pop(eax);
__ push(edx);
__ push(eax);
// Figure out which native to call and setup the arguments.
Builtins::JavaScript builtin;
if (cc_ == equal) {
builtin = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
} else {
builtin = Builtins::COMPARE;
__ push(Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
}
// Restore return address on the stack.
__ push(ecx);
// Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ InvokeBuiltin(builtin, JUMP_FUNCTION);
}
void CompareStub::BranchIfNonSymbol(MacroAssembler* masm,
Label* label,
Register object,
Register scratch) {
__ test(object, Immediate(kSmiTagMask));
__ j(zero, label);
__ mov(scratch, FieldOperand(object, HeapObject::kMapOffset));
__ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
__ and_(scratch, kIsSymbolMask | kIsNotStringMask);
__ cmp(scratch, kSymbolTag | kStringTag);
__ j(not_equal, label);
}
void StackCheckStub::Generate(MacroAssembler* masm) {
// Because builtins always remove the receiver from the stack, we
// have to fake one to avoid underflowing the stack. The receiver
// must be inserted below the return address on the stack so we
// temporarily store that in a register.
__ pop(eax);
__ push(Immediate(Smi::FromInt(0)));
__ push(eax);
// Do tail-call to runtime routine.
__ TailCallRuntime(Runtime::kStackGuard, 1, 1);
}
void CallFunctionStub::Generate(MacroAssembler* masm) {
Label slow;
// If the receiver might be a value (string, number or boolean) check for this
// and box it if it is.
if (ReceiverMightBeValue()) {
// Get the receiver from the stack.
// +1 ~ return address
Label receiver_is_value, receiver_is_js_object;
__ mov(eax, Operand(esp, (argc_ + 1) * kPointerSize));
// Check if receiver is a smi (which is a number value).
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &receiver_is_value, not_taken);
// Check if the receiver is a valid JS object.
__ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, edi);
__ j(above_equal, &receiver_is_js_object);
// Call the runtime to box the value.
__ bind(&receiver_is_value);
__ EnterInternalFrame();
__ push(eax);
__ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
__ LeaveInternalFrame();
__ mov(Operand(esp, (argc_ + 1) * kPointerSize), eax);
__ bind(&receiver_is_js_object);
}
// Get the function to call from the stack.
// +2 ~ receiver, return address
__ mov(edi, Operand(esp, (argc_ + 2) * kPointerSize));
// Check that the function really is a JavaScript function.
__ test(edi, Immediate(kSmiTagMask));
__ j(zero, &slow, not_taken);
// Goto slow case if we do not have a function.
__ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
__ j(not_equal, &slow, not_taken);
// Fast-case: Just invoke the function.
ParameterCount actual(argc_);
__ InvokeFunction(edi, actual, JUMP_FUNCTION);
// Slow-case: Non-function called.
__ bind(&slow);
// CALL_NON_FUNCTION expects the non-function callee as receiver (instead
// of the original receiver from the call site).
__ mov(Operand(esp, (argc_ + 1) * kPointerSize), edi);
__ Set(eax, Immediate(argc_));
__ Set(ebx, Immediate(0));
__ GetBuiltinEntry(edx, Builtins::CALL_NON_FUNCTION);
Handle<Code> adaptor(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
__ jmp(adaptor, RelocInfo::CODE_TARGET);
}
void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
// eax holds the exception.
// Adjust this code if not the case.
ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
// Drop the sp to the top of the handler.
ExternalReference handler_address(Top::k_handler_address);
__ mov(esp, Operand::StaticVariable(handler_address));
// Restore next handler and frame pointer, discard handler state.
ASSERT(StackHandlerConstants::kNextOffset == 0);
__ pop(Operand::StaticVariable(handler_address));
ASSERT(StackHandlerConstants::kFPOffset == 1 * kPointerSize);
__ pop(ebp);
__ pop(edx); // Remove state.
// Before returning we restore the context from the frame pointer if
// not NULL. The frame pointer is NULL in the exception handler of
// a JS entry frame.
__ xor_(esi, Operand(esi)); // Tentatively set context pointer to NULL.
Label skip;
__ cmp(ebp, 0);
__ j(equal, &skip, not_taken);
__ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
__ bind(&skip);
ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
__ ret(0);
}
// If true, a Handle<T> passed by value is passed and returned by
// using the location_ field directly. If false, it is passed and
// returned as a pointer to a handle.
#ifdef USING_BSD_ABI
static const bool kPassHandlesDirectly = true;
#else
static const bool kPassHandlesDirectly = false;
#endif
void ApiGetterEntryStub::Generate(MacroAssembler* masm) {
Label get_result;
Label prologue;
Label promote_scheduled_exception;
__ EnterApiExitFrame(ExitFrame::MODE_NORMAL, kStackSpace, kArgc);
ASSERT_EQ(kArgc, 4);
if (kPassHandlesDirectly) {
// When handles as passed directly we don't have to allocate extra
// space for and pass an out parameter.
__ mov(Operand(esp, 0 * kPointerSize), ebx); // name.
__ mov(Operand(esp, 1 * kPointerSize), eax); // arguments pointer.
} else {
// The function expects three arguments to be passed but we allocate
// four to get space for the output cell. The argument slots are filled
// as follows:
//
// 3: output cell
// 2: arguments pointer
// 1: name
// 0: pointer to the output cell
//
// Note that this is one more "argument" than the function expects
// so the out cell will have to be popped explicitly after returning
// from the function.
__ mov(Operand(esp, 1 * kPointerSize), ebx); // name.
__ mov(Operand(esp, 2 * kPointerSize), eax); // arguments pointer.
__ mov(ebx, esp);
__ add(Operand(ebx), Immediate(3 * kPointerSize));
__ mov(Operand(esp, 0 * kPointerSize), ebx); // output
__ mov(Operand(esp, 3 * kPointerSize), Immediate(0)); // out cell.
}
// Call the api function!
__ call(fun()->address(), RelocInfo::RUNTIME_ENTRY);
// Check if the function scheduled an exception.
ExternalReference scheduled_exception_address =
ExternalReference::scheduled_exception_address();
__ cmp(Operand::StaticVariable(scheduled_exception_address),
Immediate(Factory::the_hole_value()));
__ j(not_equal, &promote_scheduled_exception, not_taken);
if (!kPassHandlesDirectly) {
// The returned value is a pointer to the handle holding the result.
// Dereference this to get to the location.
__ mov(eax, Operand(eax, 0));
}
// Check if the result handle holds 0
__ test(eax, Operand(eax));
__ j(not_zero, &get_result, taken);
// It was zero; the result is undefined.
__ mov(eax, Factory::undefined_value());
__ jmp(&prologue);
// It was non-zero. Dereference to get the result value.
__ bind(&get_result);
__ mov(eax, Operand(eax, 0));
__ bind(&prologue);
__ LeaveExitFrame(ExitFrame::MODE_NORMAL);
__ ret(0);
__ bind(&promote_scheduled_exception);
__ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
}
void CEntryStub::GenerateCore(MacroAssembler* masm,
Label* throw_normal_exception,
Label* throw_termination_exception,
Label* throw_out_of_memory_exception,
bool do_gc,
bool always_allocate_scope,
int /* alignment_skew */) {
// eax: result parameter for PerformGC, if any
// ebx: pointer to C function (C callee-saved)
// ebp: frame pointer (restored after C call)
// esp: stack pointer (restored after C call)
// edi: number of arguments including receiver (C callee-saved)
// esi: pointer to the first argument (C callee-saved)
// Result returned in eax, or eax+edx if result_size_ is 2.
// Check stack alignment.
if (FLAG_debug_code) {
__ CheckStackAlignment();
}
if (do_gc) {
// Pass failure code returned from last attempt as first argument to
// PerformGC. No need to use PrepareCallCFunction/CallCFunction here as the
// stack alignment is known to be correct. This function takes one argument
// which is passed on the stack, and we know that the stack has been
// prepared to pass at least one argument.
__ mov(Operand(esp, 0 * kPointerSize), eax); // Result.
__ call(FUNCTION_ADDR(Runtime::PerformGC), RelocInfo::RUNTIME_ENTRY);
}
ExternalReference scope_depth =
ExternalReference::heap_always_allocate_scope_depth();
if (always_allocate_scope) {
__ inc(Operand::StaticVariable(scope_depth));
}
// Call C function.
__ mov(Operand(esp, 0 * kPointerSize), edi); // argc.
__ mov(Operand(esp, 1 * kPointerSize), esi); // argv.
__ call(Operand(ebx));
// Result is in eax or edx:eax - do not destroy these registers!
if (always_allocate_scope) {
__ dec(Operand::StaticVariable(scope_depth));
}
// Make sure we're not trying to return 'the hole' from the runtime
// call as this may lead to crashes in the IC code later.
if (FLAG_debug_code) {
Label okay;
__ cmp(eax, Factory::the_hole_value());
__ j(not_equal, &okay);
__ int3();
__ bind(&okay);
}
// Check for failure result.
Label failure_returned;
ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
__ lea(ecx, Operand(eax, 1));
// Lower 2 bits of ecx are 0 iff eax has failure tag.
__ test(ecx, Immediate(kFailureTagMask));
__ j(zero, &failure_returned, not_taken);
// Exit the JavaScript to C++ exit frame.
__ LeaveExitFrame(mode_);
__ ret(0);
// Handling of failure.
__ bind(&failure_returned);
Label retry;
// If the returned exception is RETRY_AFTER_GC continue at retry label
ASSERT(Failure::RETRY_AFTER_GC == 0);
__ test(eax, Immediate(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
__ j(zero, &retry, taken);
// Special handling of out of memory exceptions.
__ cmp(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
__ j(equal, throw_out_of_memory_exception);
// Retrieve the pending exception and clear the variable.
ExternalReference pending_exception_address(Top::k_pending_exception_address);
__ mov(eax, Operand::StaticVariable(pending_exception_address));
__ mov(edx,
Operand::StaticVariable(ExternalReference::the_hole_value_location()));
__ mov(Operand::StaticVariable(pending_exception_address), edx);
// Special handling of termination exceptions which are uncatchable
// by javascript code.
__ cmp(eax, Factory::termination_exception());
__ j(equal, throw_termination_exception);
// Handle normal exception.
__ jmp(throw_normal_exception);
// Retry.
__ bind(&retry);
}
void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
UncatchableExceptionType type) {
// Adjust this code if not the case.
ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
// Drop sp to the top stack handler.
ExternalReference handler_address(Top::k_handler_address);
__ mov(esp, Operand::StaticVariable(handler_address));
// Unwind the handlers until the ENTRY handler is found.
Label loop, done;
__ bind(&loop);
// Load the type of the current stack handler.
const int kStateOffset = StackHandlerConstants::kStateOffset;
__ cmp(Operand(esp, kStateOffset), Immediate(StackHandler::ENTRY));
__ j(equal, &done);
// Fetch the next handler in the list.
const int kNextOffset = StackHandlerConstants::kNextOffset;
__ mov(esp, Operand(esp, kNextOffset));
__ jmp(&loop);
__ bind(&done);
// Set the top handler address to next handler past the current ENTRY handler.
ASSERT(StackHandlerConstants::kNextOffset == 0);
__ pop(Operand::StaticVariable(handler_address));
if (type == OUT_OF_MEMORY) {
// Set external caught exception to false.
ExternalReference external_caught(Top::k_external_caught_exception_address);
__ mov(eax, false);
__ mov(Operand::StaticVariable(external_caught), eax);
// Set pending exception and eax to out of memory exception.
ExternalReference pending_exception(Top::k_pending_exception_address);
__ mov(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
__ mov(Operand::StaticVariable(pending_exception), eax);
}
// Clear the context pointer.
__ xor_(esi, Operand(esi));
// Restore fp from handler and discard handler state.
ASSERT(StackHandlerConstants::kFPOffset == 1 * kPointerSize);
__ pop(ebp);
__ pop(edx); // State.
ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
__ ret(0);
}
void CEntryStub::Generate(MacroAssembler* masm) {
// eax: number of arguments including receiver
// ebx: pointer to C function (C callee-saved)
// ebp: frame pointer (restored after C call)
// esp: stack pointer (restored after C call)
// esi: current context (C callee-saved)
// edi: JS function of the caller (C callee-saved)
// NOTE: Invocations of builtins may return failure objects instead
// of a proper result. The builtin entry handles this by performing
// a garbage collection and retrying the builtin (twice).
// Enter the exit frame that transitions from JavaScript to C++.
__ EnterExitFrame(mode_);
// eax: result parameter for PerformGC, if any (setup below)
// ebx: pointer to builtin function (C callee-saved)
// ebp: frame pointer (restored after C call)
// esp: stack pointer (restored after C call)
// edi: number of arguments including receiver (C callee-saved)
// esi: argv pointer (C callee-saved)
Label throw_normal_exception;
Label throw_termination_exception;
Label throw_out_of_memory_exception;
// Call into the runtime system.
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
false,
false);
// Do space-specific GC and retry runtime call.
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
true,
false);
// Do full GC and retry runtime call one final time.
Failure* failure = Failure::InternalError();
__ mov(eax, Immediate(reinterpret_cast<int32_t>(failure)));
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
true,
true);
__ bind(&throw_out_of_memory_exception);
GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
__ bind(&throw_termination_exception);
GenerateThrowUncatchable(masm, TERMINATION);
__ bind(&throw_normal_exception);
GenerateThrowTOS(masm);
}
void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
Label invoke, exit;
#ifdef ENABLE_LOGGING_AND_PROFILING
Label not_outermost_js, not_outermost_js_2;
#endif
// Setup frame.
__ push(ebp);
__ mov(ebp, Operand(esp));
// Push marker in two places.
int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
__ push(Immediate(Smi::FromInt(marker))); // context slot
__ push(Immediate(Smi::FromInt(marker))); // function slot
// Save callee-saved registers (C calling conventions).
__ push(edi);
__ push(esi);
__ push(ebx);
// Save copies of the top frame descriptor on the stack.
ExternalReference c_entry_fp(Top::k_c_entry_fp_address);
__ push(Operand::StaticVariable(c_entry_fp));
#ifdef ENABLE_LOGGING_AND_PROFILING
// If this is the outermost JS call, set js_entry_sp value.
ExternalReference js_entry_sp(Top::k_js_entry_sp_address);
__ cmp(Operand::StaticVariable(js_entry_sp), Immediate(0));
__ j(not_equal, ¬_outermost_js);
__ mov(Operand::StaticVariable(js_entry_sp), ebp);
__ bind(¬_outermost_js);
#endif
// Call a faked try-block that does the invoke.
__ call(&invoke);
// Caught exception: Store result (exception) in the pending
// exception field in the JSEnv and return a failure sentinel.
ExternalReference pending_exception(Top::k_pending_exception_address);
__ mov(Operand::StaticVariable(pending_exception), eax);
__ mov(eax, reinterpret_cast<int32_t>(Failure::Exception()));
__ jmp(&exit);
// Invoke: Link this frame into the handler chain.
__ bind(&invoke);
__ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
// Clear any pending exceptions.
__ mov(edx,
Operand::StaticVariable(ExternalReference::the_hole_value_location()));
__ mov(Operand::StaticVariable(pending_exception), edx);
// Fake a receiver (NULL).
__ push(Immediate(0)); // receiver
// Invoke the function by calling through JS entry trampoline
// builtin and pop the faked function when we return. Notice that we
// cannot store a reference to the trampoline code directly in this
// stub, because the builtin stubs may not have been generated yet.
if (is_construct) {
ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
__ mov(edx, Immediate(construct_entry));
} else {
ExternalReference entry(Builtins::JSEntryTrampoline);
__ mov(edx, Immediate(entry));
}
__ mov(edx, Operand(edx, 0)); // deref address
__ lea(edx, FieldOperand(edx, Code::kHeaderSize));
__ call(Operand(edx));
// Unlink this frame from the handler chain.
__ pop(Operand::StaticVariable(ExternalReference(Top::k_handler_address)));
// Pop next_sp.
__ add(Operand(esp), Immediate(StackHandlerConstants::kSize - kPointerSize));
#ifdef ENABLE_LOGGING_AND_PROFILING
// If current EBP value is the same as js_entry_sp value, it means that
// the current function is the outermost.
__ cmp(ebp, Operand::StaticVariable(js_entry_sp));
__ j(not_equal, ¬_outermost_js_2);
__ mov(Operand::StaticVariable(js_entry_sp), Immediate(0));
__ bind(¬_outermost_js_2);
#endif
// Restore the top frame descriptor from the stack.
__ bind(&exit);
__ pop(Operand::StaticVariable(ExternalReference(Top::k_c_entry_fp_address)));
// Restore callee-saved registers (C calling conventions).
__ pop(ebx);
__ pop(esi);
__ pop(edi);
__ add(Operand(esp), Immediate(2 * kPointerSize)); // remove markers
// Restore frame pointer and return.
__ pop(ebp);
__ ret(0);
}
void InstanceofStub::Generate(MacroAssembler* masm) {
// Get the object - go slow case if it's a smi.
Label slow;
__ mov(eax, Operand(esp, 2 * kPointerSize)); // 2 ~ return address, function
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &slow, not_taken);
// Check that the left hand is a JS object.
__ IsObjectJSObjectType(eax, eax, edx, &slow);
// Get the prototype of the function.
__ mov(edx, Operand(esp, 1 * kPointerSize)); // 1 ~ return address
// edx is function, eax is map.
// Look up the function and the map in the instanceof cache.
Label miss;
ExternalReference roots_address = ExternalReference::roots_address();
__ mov(ecx, Immediate(Heap::kInstanceofCacheFunctionRootIndex));
__ cmp(edx, Operand::StaticArray(ecx, times_pointer_size, roots_address));
__ j(not_equal, &miss);
__ mov(ecx, Immediate(Heap::kInstanceofCacheMapRootIndex));
__ cmp(eax, Operand::StaticArray(ecx, times_pointer_size, roots_address));
__ j(not_equal, &miss);
__ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
__ mov(eax, Operand::StaticArray(ecx, times_pointer_size, roots_address));
__ ret(2 * kPointerSize);
__ bind(&miss);
__ TryGetFunctionPrototype(edx, ebx, ecx, &slow);
// Check that the function prototype is a JS object.
__ test(ebx, Immediate(kSmiTagMask));
__ j(zero, &slow, not_taken);
__ IsObjectJSObjectType(ebx, ecx, ecx, &slow);
// Register mapping:
// eax is object map.
// edx is function.
// ebx is function prototype.
__ mov(ecx, Immediate(Heap::kInstanceofCacheMapRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
__ mov(ecx, Immediate(Heap::kInstanceofCacheFunctionRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), edx);
__ mov(ecx, FieldOperand(eax, Map::kPrototypeOffset));
// Loop through the prototype chain looking for the function prototype.
Label loop, is_instance, is_not_instance;
__ bind(&loop);
__ cmp(ecx, Operand(ebx));
__ j(equal, &is_instance);
__ cmp(Operand(ecx), Immediate(Factory::null_value()));
__ j(equal, &is_not_instance);
__ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
__ mov(ecx, FieldOperand(ecx, Map::kPrototypeOffset));
__ jmp(&loop);
__ bind(&is_instance);
__ Set(eax, Immediate(0));
__ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
__ ret(2 * kPointerSize);
__ bind(&is_not_instance);
__ Set(eax, Immediate(Smi::FromInt(1)));
__ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
__ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
__ ret(2 * kPointerSize);
// Slow-case: Go through the JavaScript implementation.
__ bind(&slow);
__ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
}
int CompareStub::MinorKey() {
// Encode the three parameters in a unique 16 bit value. To avoid duplicate
// stubs the never NaN NaN condition is only taken into account if the
// condition is equals.
ASSERT(static_cast<unsigned>(cc_) < (1 << 13));
return ConditionField::encode(static_cast<unsigned>(cc_))
| StrictField::encode(strict_)
| NeverNanNanField::encode(cc_ == equal ? never_nan_nan_ : false)
| IncludeNumberCompareField::encode(include_number_compare_);
}
// Unfortunately you have to run without snapshots to see most of these
// names in the profile since most compare stubs end up in the snapshot.
const char* CompareStub::GetName() {
if (name_ != NULL) return name_;
const int kMaxNameLength = 100;
name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
if (name_ == NULL) return "OOM";
const char* cc_name;
switch (cc_) {
case less: cc_name = "LT"; break;
case greater: cc_name = "GT"; break;
case less_equal: cc_name = "LE"; break;
case greater_equal: cc_name = "GE"; break;
case equal: cc_name = "EQ"; break;
case not_equal: cc_name = "NE"; break;
default: cc_name = "UnknownCondition"; break;
}
const char* strict_name = "";
if (strict_ && (cc_ == equal || cc_ == not_equal)) {
strict_name = "_STRICT";
}
const char* never_nan_nan_name = "";
if (never_nan_nan_ && (cc_ == equal || cc_ == not_equal)) {
never_nan_nan_name = "_NO_NAN";
}
const char* include_number_compare_name = "";
if (!include_number_compare_) {
include_number_compare_name = "_NO_NUMBER";
}
OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
"CompareStub_%s%s%s%s",
cc_name,
strict_name,
never_nan_nan_name,
include_number_compare_name);
return name_;
}
// -------------------------------------------------------------------------
// StringCharCodeAtGenerator
void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
Label flat_string;
Label ascii_string;
Label got_char_code;
// If the receiver is a smi trigger the non-string case.
ASSERT(kSmiTag == 0);
__ test(object_, Immediate(kSmiTagMask));
__ j(zero, receiver_not_string_);
// Fetch the instance type of the receiver into result register.
__ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
__ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
// If the receiver is not a string trigger the non-string case.
__ test(result_, Immediate(kIsNotStringMask));
__ j(not_zero, receiver_not_string_);
// If the index is non-smi trigger the non-smi case.
ASSERT(kSmiTag == 0);
__ test(index_, Immediate(kSmiTagMask));
__ j(not_zero, &index_not_smi_);
// Put smi-tagged index into scratch register.
__ mov(scratch_, index_);
__ bind(&got_smi_index_);
// Check for index out of range.
__ cmp(scratch_, FieldOperand(object_, String::kLengthOffset));
__ j(above_equal, index_out_of_range_);
// We need special handling for non-flat strings.
ASSERT(kSeqStringTag == 0);
__ test(result_, Immediate(kStringRepresentationMask));
__ j(zero, &flat_string);
// Handle non-flat strings.
__ test(result_, Immediate(kIsConsStringMask));
__ j(zero, &call_runtime_);
// ConsString.
// Check whether the right hand side is the empty string (i.e. if
// this is really a flat string in a cons string). If that is not
// the case we would rather go to the runtime system now to flatten
// the string.
__ cmp(FieldOperand(object_, ConsString::kSecondOffset),
Immediate(Factory::empty_string()));
__ j(not_equal, &call_runtime_);
// Get the first of the two strings and load its instance type.
__ mov(object_, FieldOperand(object_, ConsString::kFirstOffset));
__ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
__ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
// If the first cons component is also non-flat, then go to runtime.
ASSERT(kSeqStringTag == 0);
__ test(result_, Immediate(kStringRepresentationMask));
__ j(not_zero, &call_runtime_);
// Check for 1-byte or 2-byte string.
__ bind(&flat_string);
ASSERT(kAsciiStringTag != 0);
__ test(result_, Immediate(kStringEncodingMask));
__ j(not_zero, &ascii_string);
// 2-byte string.
// Load the 2-byte character code into the result register.
ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ movzx_w(result_, FieldOperand(object_,
scratch_, times_1, // Scratch is smi-tagged.
SeqTwoByteString::kHeaderSize));
__ jmp(&got_char_code);
// ASCII string.
// Load the byte into the result register.
__ bind(&ascii_string);
__ SmiUntag(scratch_);
__ movzx_b(result_, FieldOperand(object_,
scratch_, times_1,
SeqAsciiString::kHeaderSize));
__ bind(&got_char_code);
__ SmiTag(result_);
__ bind(&exit_);
}
void StringCharCodeAtGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
__ Abort("Unexpected fallthrough to CharCodeAt slow case");
// Index is not a smi.
__ bind(&index_not_smi_);
// If index is a heap number, try converting it to an integer.
__ CheckMap(index_, Factory::heap_number_map(), index_not_number_, true);
call_helper.BeforeCall(masm);
__ push(object_);
__ push(index_);
__ push(index_); // Consumed by runtime conversion function.
if (index_flags_ == STRING_INDEX_IS_NUMBER) {
__ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
} else {
ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
// NumberToSmi discards numbers that are not exact integers.
__ CallRuntime(Runtime::kNumberToSmi, 1);
}
if (!scratch_.is(eax)) {
// Save the conversion result before the pop instructions below
// have a chance to overwrite it.
__ mov(scratch_, eax);
}
__ pop(index_);
__ pop(object_);
// Reload the instance type.
__ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
__ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
call_helper.AfterCall(masm);
// If index is still not a smi, it must be out of range.
ASSERT(kSmiTag == 0);
__ test(scratch_, Immediate(kSmiTagMask));
__ j(not_zero, index_out_of_range_);
// Otherwise, return to the fast path.
__ jmp(&got_smi_index_);
// Call runtime. We get here when the receiver is a string and the
// index is a number, but the code of getting the actual character
// is too complex (e.g., when the string needs to be flattened).
__ bind(&call_runtime_);
call_helper.BeforeCall(masm);
__ push(object_);
__ push(index_);
__ CallRuntime(Runtime::kStringCharCodeAt, 2);
if (!result_.is(eax)) {
__ mov(result_, eax);
}
call_helper.AfterCall(masm);
__ jmp(&exit_);
__ Abort("Unexpected fallthrough from CharCodeAt slow case");
}
// -------------------------------------------------------------------------
// StringCharFromCodeGenerator
void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
// Fast case of Heap::LookupSingleCharacterStringFromCode.
ASSERT(kSmiTag == 0);
ASSERT(kSmiShiftSize == 0);
ASSERT(IsPowerOf2(String::kMaxAsciiCharCode + 1));
__ test(code_,
Immediate(kSmiTagMask |
((~String::kMaxAsciiCharCode) << kSmiTagSize)));
__ j(not_zero, &slow_case_, not_taken);
__ Set(result_, Immediate(Factory::single_character_string_cache()));
ASSERT(kSmiTag == 0);
ASSERT(kSmiTagSize == 1);
ASSERT(kSmiShiftSize == 0);
// At this point code register contains smi tagged ascii char code.
__ mov(result_, FieldOperand(result_,
code_, times_half_pointer_size,
FixedArray::kHeaderSize));
__ cmp(result_, Factory::undefined_value());
__ j(equal, &slow_case_, not_taken);
__ bind(&exit_);
}
void StringCharFromCodeGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
__ Abort("Unexpected fallthrough to CharFromCode slow case");
__ bind(&slow_case_);
call_helper.BeforeCall(masm);
__ push(code_);
__ CallRuntime(Runtime::kCharFromCode, 1);
if (!result_.is(eax)) {
__ mov(result_, eax);
}
call_helper.AfterCall(masm);
__ jmp(&exit_);
__ Abort("Unexpected fallthrough from CharFromCode slow case");
}
// -------------------------------------------------------------------------
// StringCharAtGenerator
void StringCharAtGenerator::GenerateFast(MacroAssembler* masm) {
char_code_at_generator_.GenerateFast(masm);
char_from_code_generator_.GenerateFast(masm);
}
void StringCharAtGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
char_code_at_generator_.GenerateSlow(masm, call_helper);
char_from_code_generator_.GenerateSlow(masm, call_helper);
}
void StringAddStub::Generate(MacroAssembler* masm) {
Label string_add_runtime;
// Load the two arguments.
__ mov(eax, Operand(esp, 2 * kPointerSize)); // First argument.
__ mov(edx, Operand(esp, 1 * kPointerSize)); // Second argument.
// Make sure that both arguments are strings if not known in advance.
if (string_check_) {
__ mov(ecx, eax);
__ and_(Operand(ecx), edx);
__ test(ecx, Immediate(kSmiTagMask));
__ j(zero, &string_add_runtime);
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
__ mov(ebx, FieldOperand(edx, HeapObject::kMapOffset));
__ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
__ or_(Operand(ecx), ebx);
__ test_b(Operand(ecx), kIsNotStringMask);
__ j(not_zero, &string_add_runtime);
}
// Both arguments are strings.
// eax: first string
// edx: second string
// Check if either of the strings are empty. In that case return the other.
Label second_not_zero_length, both_not_zero_length;
__ mov(ecx, FieldOperand(edx, String::kLengthOffset));
ASSERT(kSmiTag == 0);
__ test(ecx, Operand(ecx));
__ j(not_zero, &second_not_zero_length);
// Second string is empty, result is first string which is already in eax.
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
__ bind(&second_not_zero_length);
__ mov(ebx, FieldOperand(eax, String::kLengthOffset));
ASSERT(kSmiTag == 0);
__ test(ebx, Operand(ebx));
__ j(not_zero, &both_not_zero_length);
// First string is empty, result is second string which is in edx.
__ mov(eax, edx);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
// Both strings are non-empty.
// eax: first string
// ebx: length of first string as a smi
// ecx: length of second string as a smi
// edx: second string
// Look at the length of the result of adding the two strings.
Label make_two_character_string, longer_than_two,
make_flat_string, make_flat_ascii_string, make_flat_non_ascii_string;
__ bind(&both_not_zero_length);
__ add(ebx, Operand(ecx));
ASSERT(Smi::kMaxValue == String::kMaxLength);
// Handle exceptionally long strings in the runtime system.
__ j(overflow, &string_add_runtime);
// Use the runtime system when adding two one character strings, as it
// contains optimizations for this specific case using the symbol table.
__ cmp(Operand(ebx), Immediate(Smi::FromInt(2)));
__ j(not_equal, &longer_than_two);
// Check that both strings are non-external ascii strings.
__ JumpIfNotBothSequentialAsciiStrings(eax, edx, ebx, ecx,
&string_add_runtime);
// Get the two characters forming the sub string.
__ movzx_b(ebx, FieldOperand(eax, SeqAsciiString::kHeaderSize));
__ movzx_b(ecx, FieldOperand(edx, SeqAsciiString::kHeaderSize));
// Try to lookup two character string in symbol table. If it is not found
// just allocate a new one.
StringHelper::GenerateTwoCharacterSymbolTableProbe(
masm, ebx, ecx, eax, edx, edi, &make_two_character_string);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
__ bind(&make_two_character_string);
__ Set(ebx, Immediate(Smi::FromInt(2)));
__ jmp(&make_flat_ascii_string);
__ bind(&longer_than_two);
// Check if resulting string will be flat.
__ cmp(Operand(ebx), Immediate(Smi::FromInt(String::kMinNonFlatLength)));
__ j(below, &make_flat_string);
// If result is not supposed to be flat allocate a cons string object. If both
// strings are ascii the result is an ascii cons string.
Label non_ascii, allocated;
__ mov(edi, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(edi, Map::kInstanceTypeOffset));
__ mov(edi, FieldOperand(edx, HeapObject::kMapOffset));
__ movzx_b(edi, FieldOperand(edi, Map::kInstanceTypeOffset));
__ and_(ecx, Operand(edi));
ASSERT(kStringEncodingMask == kAsciiStringTag);
__ test(ecx, Immediate(kAsciiStringTag));
__ j(zero, &non_ascii);
// Allocate an acsii cons string.
__ AllocateAsciiConsString(ecx, edi, no_reg, &string_add_runtime);
__ bind(&allocated);
// Fill the fields of the cons string.
if (FLAG_debug_code) __ AbortIfNotSmi(ebx);
__ mov(FieldOperand(ecx, ConsString::kLengthOffset), ebx);
__ mov(FieldOperand(ecx, ConsString::kHashFieldOffset),
Immediate(String::kEmptyHashField));
__ mov(FieldOperand(ecx, ConsString::kFirstOffset), eax);
__ mov(FieldOperand(ecx, ConsString::kSecondOffset), edx);
__ mov(eax, ecx);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
__ bind(&non_ascii);
// Allocate a two byte cons string.
__ AllocateConsString(ecx, edi, no_reg, &string_add_runtime);
__ jmp(&allocated);
// Handle creating a flat result. Branch to runtime if either string
// is external or if they are not both ascii or both two-byte.
// Otherwise branch to ascii case or two-byte case.
// eax: first string
// ebx: length of resulting flat string as a smi
// edx: second string
__ bind(&make_flat_string);
__ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(edi, FieldOperand(ecx, Map::kInstanceTypeOffset));
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
__ or_(ecx, Operand(edi));
ASSERT(kExternalStringTag !=0);
ASSERT_EQ(0, kConsStringTag & kExternalStringTag);
ASSERT_EQ(0, kSeqStringTag & kExternalStringTag);
ASSERT_EQ(0, kTwoByteStringTag);
__ test_b(Operand(ecx), kExternalStringTag | kStringEncodingMask);
__ j(zero, &make_flat_non_ascii_string); // Neither is ascii or external.
__ test_b(Operand(ecx), kExternalStringTag);
__ j(not_zero, &string_add_runtime); // One or both is external.
// At this point, neither is external, and at least one is ascii.
// Check that both are ascii, by computing mask & first type & second type.
__ and_(edi, kStringEncodingMask);
__ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
__ test_b(edi, FieldOperand(ecx, Map::kInstanceTypeOffset));
ASSERT(kAsciiStringTag != 0);
__ j(zero, &string_add_runtime);
__ bind(&make_flat_ascii_string);
// Both strings are ascii strings. As they are short they are both flat.
// Create a flat ascii result.
// ebx: length of resulting flat string as a smi
__ SmiUntag(ebx);
__ AllocateAsciiString(eax, ebx, ecx, edx, edi, &string_add_runtime);
// eax: result string
__ mov(ecx, eax);
// Locate first character of result.
__ add(Operand(ecx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// Load first argument and locate first character.
__ mov(edx, Operand(esp, 2 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: first character of result
// edx: first char of first argument
// edi: length of first argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, true);
// Load second argument and locate first character.
__ mov(edx, Operand(esp, 1 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: next character of result
// edx: first char of second argument
// edi: length of second argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, true);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
// Both strings are two-byte strings. As they are short they are both flat.
// Create a flat two byte result.
// ebx: length of resulting flat string as a smi
__ bind(&make_flat_non_ascii_string);
// Both strings are two byte strings. As they are short they are both
// flat.
__ SmiUntag(ebx);
__ AllocateTwoByteString(eax, ebx, ecx, edx, edi, &string_add_runtime);
// eax: result string
__ mov(ecx, eax);
// Locate first character of result.
__ add(Operand(ecx),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// Load first argument and locate first character.
__ mov(edx, Operand(esp, 2 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: first character of result
// edx: first char of first argument
// edi: length of first argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, false);
// Load second argument and locate first character.
__ mov(edx, Operand(esp, 1 * kPointerSize));
__ mov(edi, FieldOperand(edx, String::kLengthOffset));
__ SmiUntag(edi);
__ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// eax: result string
// ecx: next character of result
// edx: first char of second argument
// edi: length of second argument
StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, false);
__ IncrementCounter(&Counters::string_add_native, 1);
__ ret(2 * kPointerSize);
// Just jump to runtime to add the two strings.
__ bind(&string_add_runtime);
__ TailCallRuntime(Runtime::kStringAdd, 2, 1);
}
void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
Register dest,
Register src,
Register count,
Register scratch,
bool ascii) {
Label loop;
__ bind(&loop);
// This loop just copies one character at a time, as it is only used for very
// short strings.
if (ascii) {
__ mov_b(scratch, Operand(src, 0));
__ mov_b(Operand(dest, 0), scratch);
__ add(Operand(src), Immediate(1));
__ add(Operand(dest), Immediate(1));
} else {
__ mov_w(scratch, Operand(src, 0));
__ mov_w(Operand(dest, 0), scratch);
__ add(Operand(src), Immediate(2));
__ add(Operand(dest), Immediate(2));
}
__ sub(Operand(count), Immediate(1));
__ j(not_zero, &loop);
}
void StringHelper::GenerateCopyCharactersREP(MacroAssembler* masm,
Register dest,
Register src,
Register count,
Register scratch,
bool ascii) {
// Copy characters using rep movs of doublewords. Align destination on 4 byte
// boundary before starting rep movs. Copy remaining characters after running
// rep movs.
ASSERT(dest.is(edi)); // rep movs destination
ASSERT(src.is(esi)); // rep movs source
ASSERT(count.is(ecx)); // rep movs count
ASSERT(!scratch.is(dest));
ASSERT(!scratch.is(src));
ASSERT(!scratch.is(count));
// Nothing to do for zero characters.
Label done;
__ test(count, Operand(count));
__ j(zero, &done);
// Make count the number of bytes to copy.
if (!ascii) {
__ shl(count, 1);
}
// Don't enter the rep movs if there are less than 4 bytes to copy.
Label last_bytes;
__ test(count, Immediate(~3));
__ j(zero, &last_bytes);
// Copy from edi to esi using rep movs instruction.
__ mov(scratch, count);
__ sar(count, 2); // Number of doublewords to copy.
__ cld();
__ rep_movs();
// Find number of bytes left.
__ mov(count, scratch);
__ and_(count, 3);
// Check if there are more bytes to copy.
__ bind(&last_bytes);
__ test(count, Operand(count));
__ j(zero, &done);
// Copy remaining characters.
Label loop;
__ bind(&loop);
__ mov_b(scratch, Operand(src, 0));
__ mov_b(Operand(dest, 0), scratch);
__ add(Operand(src), Immediate(1));
__ add(Operand(dest), Immediate(1));
__ sub(Operand(count), Immediate(1));
__ j(not_zero, &loop);
__ bind(&done);
}
void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
Register c1,
Register c2,
Register scratch1,
Register scratch2,
Register scratch3,
Label* not_found) {
// Register scratch3 is the general scratch register in this function.
Register scratch = scratch3;
// Make sure that both characters are not digits as such strings has a
// different hash algorithm. Don't try to look for these in the symbol table.
Label not_array_index;
__ mov(scratch, c1);
__ sub(Operand(scratch), Immediate(static_cast<int>('0')));
__ cmp(Operand(scratch), Immediate(static_cast<int>('9' - '0')));
__ j(above, ¬_array_index);
__ mov(scratch, c2);
__ sub(Operand(scratch), Immediate(static_cast<int>('0')));
__ cmp(Operand(scratch), Immediate(static_cast<int>('9' - '0')));
__ j(below_equal, not_found);
__ bind(¬_array_index);
// Calculate the two character string hash.
Register hash = scratch1;
GenerateHashInit(masm, hash, c1, scratch);
GenerateHashAddCharacter(masm, hash, c2, scratch);
GenerateHashGetHash(masm, hash, scratch);
// Collect the two characters in a register.
Register chars = c1;
__ shl(c2, kBitsPerByte);
__ or_(chars, Operand(c2));
// chars: two character string, char 1 in byte 0 and char 2 in byte 1.
// hash: hash of two character string.
// Load the symbol table.
Register symbol_table = c2;
ExternalReference roots_address = ExternalReference::roots_address();
__ mov(scratch, Immediate(Heap::kSymbolTableRootIndex));
__ mov(symbol_table,
Operand::StaticArray(scratch, times_pointer_size, roots_address));
// Calculate capacity mask from the symbol table capacity.
Register mask = scratch2;
__ mov(mask, FieldOperand(symbol_table, SymbolTable::kCapacityOffset));
__ SmiUntag(mask);
__ sub(Operand(mask), Immediate(1));
// Registers
// chars: two character string, char 1 in byte 0 and char 2 in byte 1.
// hash: hash of two character string
// symbol_table: symbol table
// mask: capacity mask
// scratch: -
// Perform a number of probes in the symbol table.
static const int kProbes = 4;
Label found_in_symbol_table;
Label next_probe[kProbes], next_probe_pop_mask[kProbes];
for (int i = 0; i < kProbes; i++) {
// Calculate entry in symbol table.
__ mov(scratch, hash);
if (i > 0) {
__ add(Operand(scratch), Immediate(SymbolTable::GetProbeOffset(i)));
}
__ and_(scratch, Operand(mask));
// Load the entry from the symble table.
Register candidate = scratch; // Scratch register contains candidate.
ASSERT_EQ(1, SymbolTable::kEntrySize);
__ mov(candidate,
FieldOperand(symbol_table,
scratch,
times_pointer_size,
SymbolTable::kElementsStartOffset));
// If entry is undefined no string with this hash can be found.
__ cmp(candidate, Factory::undefined_value());
__ j(equal, not_found);
// If length is not 2 the string is not a candidate.
__ cmp(FieldOperand(candidate, String::kLengthOffset),
Immediate(Smi::FromInt(2)));
__ j(not_equal, &next_probe[i]);
// As we are out of registers save the mask on the stack and use that
// register as a temporary.
__ push(mask);
Register temp = mask;
// Check that the candidate is a non-external ascii string.
__ mov(temp, FieldOperand(candidate, HeapObject::kMapOffset));
__ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
__ JumpIfInstanceTypeIsNotSequentialAscii(
temp, temp, &next_probe_pop_mask[i]);
// Check if the two characters match.
__ mov(temp, FieldOperand(candidate, SeqAsciiString::kHeaderSize));
__ and_(temp, 0x0000ffff);
__ cmp(chars, Operand(temp));
__ j(equal, &found_in_symbol_table);
__ bind(&next_probe_pop_mask[i]);
__ pop(mask);
__ bind(&next_probe[i]);
}
// No matching 2 character string found by probing.
__ jmp(not_found);
// Scratch register contains result when we fall through to here.
Register result = scratch;
__ bind(&found_in_symbol_table);
__ pop(mask); // Pop temporally saved mask from the stack.
if (!result.is(eax)) {
__ mov(eax, result);
}
}
void StringHelper::GenerateHashInit(MacroAssembler* masm,
Register hash,
Register character,
Register scratch) {
// hash = character + (character << 10);
__ mov(hash, character);
__ shl(hash, 10);
__ add(hash, Operand(character));
// hash ^= hash >> 6;
__ mov(scratch, hash);
__ sar(scratch, 6);
__ xor_(hash, Operand(scratch));
}
void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
Register hash,
Register character,
Register scratch) {
// hash += character;
__ add(hash, Operand(character));
// hash += hash << 10;
__ mov(scratch, hash);
__ shl(scratch, 10);
__ add(hash, Operand(scratch));
// hash ^= hash >> 6;
__ mov(scratch, hash);
__ sar(scratch, 6);
__ xor_(hash, Operand(scratch));
}
void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
Register hash,
Register scratch) {
// hash += hash << 3;
__ mov(scratch, hash);
__ shl(scratch, 3);
__ add(hash, Operand(scratch));
// hash ^= hash >> 11;
__ mov(scratch, hash);
__ sar(scratch, 11);
__ xor_(hash, Operand(scratch));
// hash += hash << 15;
__ mov(scratch, hash);
__ shl(scratch, 15);
__ add(hash, Operand(scratch));
// if (hash == 0) hash = 27;
Label hash_not_zero;
__ test(hash, Operand(hash));
__ j(not_zero, &hash_not_zero);
__ mov(hash, Immediate(27));
__ bind(&hash_not_zero);
}
void SubStringStub::Generate(MacroAssembler* masm) {
Label runtime;
// Stack frame on entry.
// esp[0]: return address
// esp[4]: to
// esp[8]: from
// esp[12]: string
// Make sure first argument is a string.
__ mov(eax, Operand(esp, 3 * kPointerSize));
ASSERT_EQ(0, kSmiTag);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, &runtime);
Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
__ j(NegateCondition(is_string), &runtime);
// eax: string
// ebx: instance type
// Calculate length of sub string using the smi values.
Label result_longer_than_two;
__ mov(ecx, Operand(esp, 1 * kPointerSize)); // To index.
__ test(ecx, Immediate(kSmiTagMask));
__ j(not_zero, &runtime);
__ mov(edx, Operand(esp, 2 * kPointerSize)); // From index.
__ test(edx, Immediate(kSmiTagMask));
__ j(not_zero, &runtime);
__ sub(ecx, Operand(edx));
// Special handling of sub-strings of length 1 and 2. One character strings
// are handled in the runtime system (looked up in the single character
// cache). Two character strings are looked for in the symbol cache.
__ SmiUntag(ecx); // Result length is no longer smi.
__ cmp(ecx, 2);
__ j(greater, &result_longer_than_two);
__ j(less, &runtime);
// Sub string of length 2 requested.
// eax: string
// ebx: instance type
// ecx: sub string length (value is 2)
// edx: from index (smi)
__ JumpIfInstanceTypeIsNotSequentialAscii(ebx, ebx, &runtime);
// Get the two characters forming the sub string.
__ SmiUntag(edx); // From index is no longer smi.
__ movzx_b(ebx, FieldOperand(eax, edx, times_1, SeqAsciiString::kHeaderSize));
__ movzx_b(ecx,
FieldOperand(eax, edx, times_1, SeqAsciiString::kHeaderSize + 1));
// Try to lookup two character string in symbol table.
Label make_two_character_string;
StringHelper::GenerateTwoCharacterSymbolTableProbe(
masm, ebx, ecx, eax, edx, edi, &make_two_character_string);
__ ret(3 * kPointerSize);
__ bind(&make_two_character_string);
// Setup registers for allocating the two character string.
__ mov(eax, Operand(esp, 3 * kPointerSize));
__ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
__ Set(ecx, Immediate(2));
__ bind(&result_longer_than_two);
// eax: string
// ebx: instance type
// ecx: result string length
// Check for flat ascii string
Label non_ascii_flat;
__ JumpIfInstanceTypeIsNotSequentialAscii(ebx, ebx, &non_ascii_flat);
// Allocate the result.
__ AllocateAsciiString(eax, ecx, ebx, edx, edi, &runtime);
// eax: result string
// ecx: result string length
__ mov(edx, esi); // esi used by following code.
// Locate first character of result.
__ mov(edi, eax);
__ add(Operand(edi), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
// Load string argument and locate character of sub string start.
__ mov(esi, Operand(esp, 3 * kPointerSize));
__ add(Operand(esi), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
__ mov(ebx, Operand(esp, 2 * kPointerSize)); // from
__ SmiUntag(ebx);
__ add(esi, Operand(ebx));
// eax: result string
// ecx: result length
// edx: original value of esi
// edi: first character of result
// esi: character of sub string start
StringHelper::GenerateCopyCharactersREP(masm, edi, esi, ecx, ebx, true);
__ mov(esi, edx); // Restore esi.
__ IncrementCounter(&Counters::sub_string_native, 1);
__ ret(3 * kPointerSize);
__ bind(&non_ascii_flat);
// eax: string
// ebx: instance type & kStringRepresentationMask | kStringEncodingMask
// ecx: result string length
// Check for flat two byte string
__ cmp(ebx, kSeqStringTag | kTwoByteStringTag);
__ j(not_equal, &runtime);
// Allocate the result.
__ AllocateTwoByteString(eax, ecx, ebx, edx, edi, &runtime);
// eax: result string
// ecx: result string length
__ mov(edx, esi); // esi used by following code.
// Locate first character of result.
__ mov(edi, eax);
__ add(Operand(edi),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// Load string argument and locate character of sub string start.
__ mov(esi, Operand(esp, 3 * kPointerSize));
__ add(Operand(esi),
Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
__ mov(ebx, Operand(esp, 2 * kPointerSize)); // from
// As from is a smi it is 2 times the value which matches the size of a two
// byte character.
ASSERT_EQ(0, kSmiTag);
ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
__ add(esi, Operand(ebx));
// eax: result string
// ecx: result length
// edx: original value of esi
// edi: first character of result
// esi: character of sub string start
StringHelper::GenerateCopyCharactersREP(masm, edi, esi, ecx, ebx, false);
__ mov(esi, edx); // Restore esi.
__ IncrementCounter(&Counters::sub_string_native, 1);
__ ret(3 * kPointerSize);
// Just jump to runtime to create the sub string.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kSubString, 3, 1);
}
void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
Register left,
Register right,
Register scratch1,
Register scratch2,
Register scratch3) {
Label result_not_equal;
Label result_greater;
Label compare_lengths;
__ IncrementCounter(&Counters::string_compare_native, 1);
// Find minimum length.
Label left_shorter;
__ mov(scratch1, FieldOperand(left, String::kLengthOffset));
__ mov(scratch3, scratch1);
__ sub(scratch3, FieldOperand(right, String::kLengthOffset));
Register length_delta = scratch3;
__ j(less_equal, &left_shorter);
// Right string is shorter. Change scratch1 to be length of right string.
__ sub(scratch1, Operand(length_delta));
__ bind(&left_shorter);
Register min_length = scratch1;
// If either length is zero, just compare lengths.
__ test(min_length, Operand(min_length));
__ j(zero, &compare_lengths);
// Change index to run from -min_length to -1 by adding min_length
// to string start. This means that loop ends when index reaches zero,
// which doesn't need an additional compare.
__ SmiUntag(min_length);
__ lea(left,
FieldOperand(left,
min_length, times_1,
SeqAsciiString::kHeaderSize));
__ lea(right,
FieldOperand(right,
min_length, times_1,
SeqAsciiString::kHeaderSize));
__ neg(min_length);
Register index = min_length; // index = -min_length;
{
// Compare loop.
Label loop;
__ bind(&loop);
// Compare characters.
__ mov_b(scratch2, Operand(left, index, times_1, 0));
__ cmpb(scratch2, Operand(right, index, times_1, 0));
__ j(not_equal, &result_not_equal);
__ add(Operand(index), Immediate(1));
__ j(not_zero, &loop);
}
// Compare lengths - strings up to min-length are equal.
__ bind(&compare_lengths);
__ test(length_delta, Operand(length_delta));
__ j(not_zero, &result_not_equal);
// Result is EQUAL.
ASSERT_EQ(0, EQUAL);
ASSERT_EQ(0, kSmiTag);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ ret(2 * kPointerSize);
__ bind(&result_not_equal);
__ j(greater, &result_greater);
// Result is LESS.
__ Set(eax, Immediate(Smi::FromInt(LESS)));
__ ret(2 * kPointerSize);
// Result is GREATER.
__ bind(&result_greater);
__ Set(eax, Immediate(Smi::FromInt(GREATER)));
__ ret(2 * kPointerSize);
}
void StringCompareStub::Generate(MacroAssembler* masm) {
Label runtime;
// Stack frame on entry.
// esp[0]: return address
// esp[4]: right string
// esp[8]: left string
__ mov(edx, Operand(esp, 2 * kPointerSize)); // left
__ mov(eax, Operand(esp, 1 * kPointerSize)); // right
Label not_same;
__ cmp(edx, Operand(eax));
__ j(not_equal, ¬_same);
ASSERT_EQ(0, EQUAL);
ASSERT_EQ(0, kSmiTag);
__ Set(eax, Immediate(Smi::FromInt(EQUAL)));
__ IncrementCounter(&Counters::string_compare_native, 1);
__ ret(2 * kPointerSize);
__ bind(¬_same);
// Check that both objects are sequential ascii strings.
__ JumpIfNotBothSequentialAsciiStrings(edx, eax, ecx, ebx, &runtime);
// Compare flat ascii strings.
GenerateCompareFlatAsciiStrings(masm, edx, eax, ecx, ebx, edi);
// Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kStringCompare, 2, 1);
}
#undef __
#define __ masm.
MemCopyFunction CreateMemCopyFunction() {
size_t actual_size;
byte* buffer = static_cast<byte*>(OS::Allocate(Assembler::kMinimalBufferSize,
&actual_size,
true));
CHECK(buffer);
HandleScope handles;
MacroAssembler masm(buffer, static_cast<int>(actual_size));
// Generated code is put into a fixed, unmovable, buffer, and not into
// the V8 heap. We can't, and don't, refer to any relocatable addresses
// (e.g. the JavaScript nan-object).
// 32-bit C declaration function calls pass arguments on stack.
// Stack layout:
// esp[12]: Third argument, size.
// esp[8]: Second argument, source pointer.
// esp[4]: First argument, destination pointer.
// esp[0]: return address
const int kDestinationOffset = 1 * kPointerSize;
const int kSourceOffset = 2 * kPointerSize;
const int kSizeOffset = 3 * kPointerSize;
int stack_offset = 0; // Update if we change the stack height.
if (FLAG_debug_code) {
__ cmp(Operand(esp, kSizeOffset + stack_offset),
Immediate(kMinComplexMemCopy));
Label ok;
__ j(greater_equal, &ok);
__ int3();
__ bind(&ok);
}
if (CpuFeatures::IsSupported(SSE2)) {
CpuFeatures::Scope enable(SSE2);
__ push(edi);
__ push(esi);
stack_offset += 2 * kPointerSize;
Register dst = edi;
Register src = esi;
Register count = ecx;
__ mov(dst, Operand(esp, stack_offset + kDestinationOffset));
__ mov(src, Operand(esp, stack_offset + kSourceOffset));
__ mov(count, Operand(esp, stack_offset + kSizeOffset));
__ movdqu(xmm0, Operand(src, 0));
__ movdqu(Operand(dst, 0), xmm0);
__ mov(edx, dst);
__ and_(edx, 0xF);
__ neg(edx);
__ add(Operand(edx), Immediate(16));
__ add(dst, Operand(edx));
__ add(src, Operand(edx));
__ sub(Operand(count), edx);
// edi is now aligned. Check if esi is also aligned.
Label unaligned_source;
__ test(Operand(src), Immediate(0x0F));
__ j(not_zero, &unaligned_source);
{
__ IncrementCounter(&Counters::memcopy_aligned, 1);
// Copy loop for aligned source and destination.
__ mov(edx, count);
Register loop_count = ecx;
Register count = edx;
__ shr(loop_count, 5);
{
// Main copy loop.
Label loop;
__ bind(&loop);
__ prefetch(Operand(src, 0x20), 1);
__ movdqa(xmm0, Operand(src, 0x00));
__ movdqa(xmm1, Operand(src, 0x10));
__ add(Operand(src), Immediate(0x20));
__ movdqa(Operand(dst, 0x00), xmm0);
__ movdqa(Operand(dst, 0x10), xmm1);
__ add(Operand(dst), Immediate(0x20));
__ dec(loop_count);
__ j(not_zero, &loop);
}
// At most 31 bytes to copy.
Label move_less_16;
__ test(Operand(count), Immediate(0x10));
__ j(zero, &move_less_16);
__ movdqa(xmm0, Operand(src, 0));
__ add(Operand(src), Immediate(0x10));
__ movdqa(Operand(dst, 0), xmm0);
__ add(Operand(dst), Immediate(0x10));
__ bind(&move_less_16);
// At most 15 bytes to copy. Copy 16 bytes at end of string.
__ and_(count, 0xF);
__ movdqu(xmm0, Operand(src, count, times_1, -0x10));
__ movdqu(Operand(dst, count, times_1, -0x10), xmm0);
__ pop(esi);
__ pop(edi);
__ ret(0);
}
__ Align(16);
{
// Copy loop for unaligned source and aligned destination.
// If source is not aligned, we can't read it as efficiently.
__ bind(&unaligned_source);
__ IncrementCounter(&Counters::memcopy_unaligned, 1);
__ mov(edx, ecx);
Register loop_count = ecx;
Register count = edx;
__ shr(loop_count, 5);
{
// Main copy loop
Label loop;
__ bind(&loop);
__ prefetch(Operand(src, 0x20), 1);
__ movdqu(xmm0, Operand(src, 0x00));
__ movdqu(xmm1, Operand(src, 0x10));
__ add(Operand(src), Immediate(0x20));
__ movdqa(Operand(dst, 0x00), xmm0);
__ movdqa(Operand(dst, 0x10), xmm1);
__ add(Operand(dst), Immediate(0x20));
__ dec(loop_count);
__ j(not_zero, &loop);
}
// At most 31 bytes to copy.
Label move_less_16;
__ test(Operand(count), Immediate(0x10));
__ j(zero, &move_less_16);
__ movdqu(xmm0, Operand(src, 0));
__ add(Operand(src), Immediate(0x10));
__ movdqa(Operand(dst, 0), xmm0);
__ add(Operand(dst), Immediate(0x10));
__ bind(&move_less_16);
// At most 15 bytes to copy. Copy 16 bytes at end of string.
__ and_(count, 0x0F);
__ movdqu(xmm0, Operand(src, count, times_1, -0x10));
__ movdqu(Operand(dst, count, times_1, -0x10), xmm0);
__ pop(esi);
__ pop(edi);
__ ret(0);
}
} else {
__ IncrementCounter(&Counters::memcopy_noxmm, 1);
// SSE2 not supported. Unlikely to happen in practice.
__ push(edi);
__ push(esi);
stack_offset += 2 * kPointerSize;
__ cld();
Register dst = edi;
Register src = esi;
Register count = ecx;
__ mov(dst, Operand(esp, stack_offset + kDestinationOffset));
__ mov(src, Operand(esp, stack_offset + kSourceOffset));
__ mov(count, Operand(esp, stack_offset + kSizeOffset));
// Copy the first word.
__ mov(eax, Operand(src, 0));
__ mov(Operand(dst, 0), eax);
// Increment src,dstso that dst is aligned.
__ mov(edx, dst);
__ and_(edx, 0x03);
__ neg(edx);
__ add(Operand(edx), Immediate(4)); // edx = 4 - (dst & 3)
__ add(dst, Operand(edx));
__ add(src, Operand(edx));
__ sub(Operand(count), edx);
// edi is now aligned, ecx holds number of remaning bytes to copy.
__ mov(edx, count);
count = edx;
__ shr(ecx, 2); // Make word count instead of byte count.
__ rep_movs();
// At most 3 bytes left to copy. Copy 4 bytes at end of string.
__ and_(count, 3);
__ mov(eax, Operand(src, count, times_1, -4));
__ mov(Operand(dst, count, times_1, -4), eax);
__ pop(esi);
__ pop(edi);
__ ret(0);
}
CodeDesc desc;
masm.GetCode(&desc);
// Call the function from C++.
return FUNCTION_CAST<MemCopyFunction>(buffer);
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_IA32
|
/* Copyright (C) 2003 MySQL 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; either version 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <getarg.h>
#include <BaseString.hpp>
#include <Parser.hpp>
#include <NdbOut.hpp>
#include <Properties.hpp>
#include <NdbAutoPtr.hpp>
#include "run-test.hpp"
#include <SysLogHandler.hpp>
#include <FileLogHandler.hpp>
#include <mgmapi.h>
#include "CpcClient.hpp"
/**
psuedo code for run-test.bin
define autotest_wrapper process at each host
start ndb-processes
for each testcase
do
start mysqld processes
start replication processes
start test programs
wait until test program finished or max time passed
stop test program
stop replication processes
stop mysqld processes
write report data-file
if test failed and ! last test
restart ndb processes
drop all tables created by test
done
stop ndb processes
undefined wrapper processes
*/
/** Global variables */
static const char progname[] = "ndb_atrt";
static const char * g_gather_progname = "atrt-gather-result.sh";
static const char * g_analyze_progname = "atrt-analyze-result.sh";
static const char * g_clear_progname = "atrt-clear-result.sh";
static const char * g_setup_progname = "atrt-setup.sh";
static const char * g_setup_path = 0;
static const char * g_process_config_filename = "d.txt";
static const char * g_log_filename = 0;
static const char * g_test_case_filename = 0;
static const char * g_report_filename = 0;
static const char * g_default_user = 0;
static const char * g_default_base_dir = 0;
static int g_default_base_port = 0;
static int g_report = 0;
static int g_verbosity = 0;
static FILE * g_report_file = 0;
static FILE * g_test_case_file = stdin;
Logger g_logger;
atrt_config g_config;
static int g_mode_bench = 0;
static int g_mode_regression = 0;
static int g_mode_interactive = 0;
static int g_mode = 0;
static
struct getargs args[] = {
{ "process-config", 0, arg_string, &g_process_config_filename, 0, 0 },
{ "setup-path", 0, arg_string, &g_setup_path, 0, 0 },
{ 0, 'v', arg_counter, &g_verbosity, 0, 0 },
{ "log-file", 0, arg_string, &g_log_filename, 0, 0 },
{ "testcase-file", 'f', arg_string, &g_test_case_filename, 0, 0 },
{ 0, 'R', arg_flag, &g_report, 0, 0 },
{ "report-file", 0, arg_string, &g_report_filename, 0, 0 },
{ "interactive", 'i', arg_flag, &g_mode_interactive, 0, 0 },
{ "regression", 'r', arg_flag, &g_mode_regression, 0, 0 },
{ "bench", 'b', arg_flag, &g_mode_bench, 0, 0 },
};
const int arg_count = 10;
int
main(int argc, const char ** argv){
bool restart = true;
int lineno = 1;
int test_no = 1;
const int p_ndb = atrt_process::NDB_MGM | atrt_process::NDB_DB;
const int p_servers = atrt_process::MYSQL_SERVER | atrt_process::NDB_REP;
const int p_clients = atrt_process::MYSQL_CLIENT | atrt_process::NDB_API;
g_logger.setCategory(progname);
g_logger.enable(Logger::LL_ALL);
g_logger.createConsoleHandler();
if(!parse_args(argc, argv))
goto end;
g_logger.info("Starting...");
if(!setup_config(g_config))
goto end;
g_logger.info("Connecting to hosts");
if(!connect_hosts(g_config))
goto end;
if(!setup_hosts(g_config))
goto end;
if(!start_processes(g_config, atrt_process::NDB_MGM))
goto end;
if(!connect_ndb_mgm(g_config)){
goto end;
}
/**
* Main loop
*/
while(!feof(g_test_case_file)){
/**
* Do we need to restart ndb
*/
if(restart){
g_logger.info("(Re)starting ndb processes");
if(!stop_processes(g_config, atrt_process::NDB_DB))
goto end;
if(!wait_ndb(g_config, NDB_MGM_NODE_STATUS_NO_CONTACT))
goto end;
if(!start_processes(g_config, atrt_process::NDB_DB))
goto end;
if(!wait_ndb(g_config, NDB_MGM_NODE_STATUS_STARTED))
goto end;
g_logger.info("Ndb start completed");
}
const int start_line = lineno;
atrt_testcase test_case;
if(!read_test_case(g_test_case_file, test_case, lineno))
goto end;
g_logger.info("#%d - %s %s",
test_no,
test_case.m_command.c_str(), test_case.m_args.c_str());
// Assign processes to programs
if(!setup_test_case(g_config, test_case))
goto end;
if(!start_processes(g_config, p_servers))
goto end;
if(!start_processes(g_config, p_clients))
goto end;
int result = 0;
const time_t start = time(0);
time_t now = start;
do {
if(!update_status(g_config, atrt_process::ALL))
goto end;
int count = 0;
if((count = is_running(g_config, p_ndb)) != 2){
result = ERR_NDB_FAILED;
break;
}
if((count = is_running(g_config, p_servers)) != 2){
result = ERR_SERVERS_FAILED;
break;
}
if((count = is_running(g_config, p_clients)) == 0){
break;
}
now = time(0);
if(now > (start + test_case.m_max_time)){
result = ERR_MAX_TIME_ELAPSED;
break;
}
sleep(1);
} while(true);
const time_t elapsed = time(0) - start;
if(!stop_processes(g_config, p_clients))
goto end;
if(!stop_processes(g_config, p_servers))
goto end;
if(!gather_result(g_config, &result))
goto end;
g_logger.info("#%d %s(%d)",
test_no,
(result == 0 ? "OK" : "FAILED"), result);
if(g_report_file != 0){
fprintf(g_report_file, "%s %s ; %d ; %d ; %d\n",
test_case.m_command.c_str(),
test_case.m_args.c_str(),
test_no, result, elapsed);
fflush(g_report_file);
}
if(g_mode_bench || (g_mode_regression && result)){
BaseString tmp;
tmp.assfmt("result.%d", test_no);
if(rename("result", tmp.c_str()) != 0){
g_logger.critical("Failed to rename %s as %s",
"result", tmp.c_str());
goto end;
}
}
if(g_mode_interactive && result){
g_logger.info
("Encountered failed test in interactive mode - terminating");
break;
}
if(result != 0){
restart = true;
} else {
restart = false;
}
test_no++;
}
end:
if(g_report_file != 0){
fclose(g_report_file);
g_report_file = 0;
}
if(g_test_case_file != 0 && g_test_case_file != stdin){
fclose(g_test_case_file);
g_test_case_file = 0;
}
stop_processes(g_config, atrt_process::ALL);
return 0;
}
bool
parse_args(int argc, const char** argv){
int optind = 0;
if(getarg(args, arg_count, argc, argv, &optind)) {
arg_printusage(args, arg_count, progname, "");
return false;
}
if(g_log_filename != 0){
g_logger.removeConsoleHandler();
g_logger.addHandler(new FileLogHandler(g_log_filename));
}
{
int tmp = Logger::LL_WARNING - g_verbosity;
tmp = (tmp < Logger::LL_DEBUG ? Logger::LL_DEBUG : tmp);
g_logger.disable(Logger::LL_ALL);
g_logger.enable((Logger::LoggerLevel)tmp, Logger::LL_ALERT);
}
if(!g_process_config_filename){
g_logger.critical("Process config not specified!");
return false;
}
if(!g_setup_path){
char buf[1024];
if(getcwd(buf, sizeof(buf))){
g_setup_path = strdup(buf);
g_logger.info("Setup path not specified, using %s", buf);
} else {
g_logger.critical("Setup path not specified!\n");
return false;
}
}
if(g_report & !g_report_filename){
g_report_filename = "report.txt";
}
if(g_report_filename){
g_report_file = fopen(g_report_filename, "w");
if(g_report_file == 0){
g_logger.critical("Unable to create report file: %s", g_report_filename);
return false;
}
}
if(g_test_case_filename){
g_test_case_file = fopen(g_test_case_filename, "r");
if(g_test_case_file == 0){
g_logger.critical("Unable to open file: %s", g_test_case_filename);
return false;
}
}
int sum = g_mode_interactive + g_mode_regression + g_mode_bench;
if(sum == 0){
g_mode_interactive = 1;
}
if(sum > 1){
g_logger.critical
("Only one of bench/regression/interactive can be specified");
return false;
}
g_default_user = strdup(getenv("USER"));
return true;
}
static
atrt_host *
find(const BaseString& host, Vector<atrt_host> & hosts){
for(size_t i = 0; i<hosts.size(); i++){
if(hosts[i].m_hostname == host){
return &hosts[i];
}
}
return 0;
}
bool
setup_config(atrt_config& config){
FILE * f = fopen(g_process_config_filename, "r");
if(!f){
g_logger.critical("Failed to open process config file: %s",
g_process_config_filename);
return false;
}
bool result = true;
int lineno = 0;
char buf[2048];
while(fgets(buf, 2048, f)){
lineno++;
BaseString tmp(buf);
tmp.trim(" \t\n\r");
if(tmp.length() == 0 || tmp == "" || tmp.c_str()[0] == '#')
continue;
Vector<BaseString> split1;
if(tmp.split(split1, ":", 2) != 2){
g_logger.warning("Invalid line %d in %s - ignoring",
lineno, g_process_config_filename);
continue;
}
if(split1[0].trim() == "basedir"){
g_default_base_dir = strdup(split1[1].trim().c_str());
continue;
}
if(split1[0].trim() == "baseport"){
g_default_base_port = atoi(split1[1].trim().c_str());
continue;
}
if(split1[0].trim() == "user"){
g_default_user = strdup(split1[1].trim().c_str());
continue;
}
Vector<BaseString> hosts;
if(split1[1].trim().split(hosts) <= 0){
g_logger.warning("Invalid line %d in %s - ignoring",
lineno, g_process_config_filename);
}
// 1 - Check hosts
for(size_t i = 0; i<hosts.size(); i++){
Vector<BaseString> tmp;
hosts[i].split(tmp, ":");
BaseString hostname = tmp[0].trim();
BaseString base_dir;
if(tmp.size() >= 2)
base_dir = tmp[1];
else if(g_default_base_dir == 0){
g_logger.critical("Basedir not specified...");
return false;
}
atrt_host * host_ptr;
if((host_ptr = find(hostname, config.m_hosts)) == 0){
atrt_host host;
host.m_index = config.m_hosts.size();
host.m_cpcd = new SimpleCpcClient(hostname.c_str(), 1234);
host.m_base_dir = (base_dir.empty() ? g_default_base_dir : base_dir);
host.m_user = g_default_user;
host.m_hostname = hostname.c_str();
config.m_hosts.push_back(host);
} else {
if(!base_dir.empty() && (base_dir == host_ptr->m_base_dir)){
g_logger.critical("Inconsistent base dir definition for host %s"
", \"%s\" != \"%s\"", hostname.c_str(),
base_dir.c_str(), host_ptr->m_base_dir.c_str());
return false;
}
}
}
for(size_t i = 0; i<hosts.size(); i++){
BaseString & tmp = hosts[i];
atrt_host * host = find(tmp, config.m_hosts);
const int index = config.m_processes.size() + 1;
atrt_process proc;
proc.m_index = index;
proc.m_host = host;
proc.m_proc.m_id = -1;
proc.m_proc.m_type = "temporary";
proc.m_proc.m_owner = "atrt";
proc.m_proc.m_group = "group";
proc.m_proc.m_cwd.assign(host->m_base_dir).append("/run/");
proc.m_proc.m_env.assign("LD_LIBRARY_PATH=").append(host->m_base_dir).append("/lib");
proc.m_proc.m_stdout = "log.out";
proc.m_proc.m_stderr = "2>&1";
proc.m_proc.m_runas = proc.m_host->m_user;
proc.m_proc.m_ulimit = "c:unlimited";
proc.m_hostname = proc.m_host->m_hostname;
proc.m_ndb_mgm_port = g_default_base_port;
if(split1[0] == "mgm"){
proc.m_type = atrt_process::NDB_MGM;
proc.m_proc.m_name.assfmt("%d-%s", index, "ndb_mgm");
proc.m_proc.m_path.assign(host->m_base_dir).append("/bin/mgmtsrvr");
proc.m_proc.m_args = "-n -c initconfig.txt";
proc.m_proc.m_cwd.appfmt("%d.ndb_mgm", index);
} else if(split1[0] == "ndb"){
proc.m_type = atrt_process::NDB_DB;
proc.m_proc.m_name.assfmt("%d-%s", index, "ndb_db");
proc.m_proc.m_path.assign(host->m_base_dir).append("/bin/ndb");
proc.m_proc.m_args = "-i -n";
proc.m_proc.m_cwd.appfmt("%d.ndb_db", index);
} else if(split1[0] == "api"){
proc.m_type = atrt_process::NDB_API;
proc.m_proc.m_name.assfmt("%d-%s", index, "ndb_api");
proc.m_proc.m_path = "";
proc.m_proc.m_args = "";
proc.m_proc.m_cwd.appfmt("%d.ndb_api", index);
} else {
g_logger.critical("%s:%d: Unhandled process type: %s",
g_process_config_filename, lineno,
split1[0].c_str());
result = false;
goto end;
}
config.m_processes.push_back(proc);
}
}
end:
fclose(f);
return result;
}
bool
connect_hosts(atrt_config& config){
for(size_t i = 0; i<config.m_hosts.size(); i++){
if(config.m_hosts[i].m_cpcd->connect() != 0){
g_logger.error("Unable to connect to cpc %s:%d",
config.m_hosts[i].m_cpcd->getHost(),
config.m_hosts[i].m_cpcd->getPort());
return false;
}
g_logger.debug("Connected to %s:%d",
config.m_hosts[i].m_cpcd->getHost(),
config.m_hosts[i].m_cpcd->getPort());
}
return true;
}
bool
connect_ndb_mgm(atrt_process & proc){
NdbMgmHandle handle = ndb_mgm_create_handle();
if(handle == 0){
g_logger.critical("Unable to create mgm handle");
return false;
}
BaseString tmp = proc.m_hostname;
tmp.appfmt(":%d", proc.m_ndb_mgm_port);
time_t start = time(0);
const time_t max_connect_time = 30;
do {
if(ndb_mgm_connect(handle, tmp.c_str()) != -1){
proc.m_ndb_mgm_handle = handle;
return true;
}
sleep(1);
} while(time(0) < (start + max_connect_time));
g_logger.critical("Unable to connect to ndb mgm %s", tmp.c_str());
return false;
}
bool
connect_ndb_mgm(atrt_config& config){
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((proc.m_type & atrt_process::NDB_MGM) != 0){
if(!connect_ndb_mgm(proc)){
return false;
}
}
}
return true;
}
static int remap(int i){
if(i == NDB_MGM_NODE_STATUS_NO_CONTACT) return NDB_MGM_NODE_STATUS_UNKNOWN;
if(i == NDB_MGM_NODE_STATUS_UNKNOWN) return NDB_MGM_NODE_STATUS_NO_CONTACT;
return i;
}
bool
wait_ndb(atrt_config& config, int goal){
goal = remap(goal);
/**
* Get mgm handle for cluster
*/
NdbMgmHandle handle = 0;
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((proc.m_type & atrt_process::NDB_MGM) != 0){
handle = proc.m_ndb_mgm_handle;
break;
}
}
if(handle == 0){
g_logger.critical("Unable to find mgm handle");
return false;
}
if(goal == NDB_MGM_NODE_STATUS_STARTED){
/**
* 1) wait NOT_STARTED
* 2) send start
* 3) wait STARTED
*/
if(!wait_ndb(config, NDB_MGM_NODE_STATUS_NOT_STARTED))
return false;
ndb_mgm_start(handle, 0, 0);
}
struct ndb_mgm_cluster_state * state;
time_t now = time(0);
time_t end = now + 360;
int min = remap(NDB_MGM_NODE_STATUS_NO_CONTACT);
int min2 = goal;
while(now < end){
/**
* 1) retreive current state
*/
state = ndb_mgm_get_status(handle);
if(state == 0){
g_logger.critical("Unable to poll db state");
return false;
}
NdbAutoPtr<void> tmp(state);
min2 = goal;
for(int i = 0; i<state->no_of_nodes; i++){
if(state->node_states[i].node_type == NDB_MGM_NODE_TYPE_NDB){
const int s = remap(state->node_states[i].node_status);
min2 = (min2 < s ? min2 : s );
if(s < remap(NDB_MGM_NODE_STATUS_NO_CONTACT) ||
s > NDB_MGM_NODE_STATUS_STARTED){
g_logger.critical("Strange DB status during start: %d %d", i, min2);
return false;
}
}
}
if(min2 < min){
g_logger.critical("wait ndb failed %d %d %d", min, min2, goal);
return false;
}
if(min2 == goal){
return true;
break;
}
min = min2;
now = time(0);
}
g_logger.critical("wait ndb timed out %d %d %d", min, min2, goal);
return false;
}
bool
start_process(atrt_process & proc){
if(proc.m_proc.m_id != -1){
g_logger.critical("starting already started process: %d", proc.m_index);
return false;
}
BaseString path = proc.m_proc.m_cwd.substr(proc.m_host->m_base_dir.length()+BaseString("/run").length());
BaseString tmp = g_setup_progname;
tmp.appfmt(" %s %s/%s/ %s",
proc.m_host->m_hostname.c_str(),
g_setup_path,
path.c_str(),
proc.m_proc.m_cwd.c_str());
const int r1 = system(tmp.c_str());
if(r1 != 0){
g_logger.critical("Failed to setup process");
return false;
}
{
Properties reply;
if(proc.m_host->m_cpcd->define_process(proc.m_proc, reply) != 0){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to define process: %s", msg.c_str());
return false;
}
}
{
Properties reply;
if(proc.m_host->m_cpcd->start_process(proc.m_proc.m_id, reply) != 0){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to start process: %s", msg.c_str());
return false;
}
}
return true;
}
bool
start_processes(atrt_config& config, int types){
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((types & proc.m_type) != 0){
if(!start_process(proc)){
return false;
}
}
}
return true;
}
bool
stop_process(atrt_process & proc){
if(proc.m_proc.m_id == -1){
return true;
}
{
Properties reply;
if(proc.m_host->m_cpcd->stop_process(proc.m_proc.m_id, reply) != 0){
Uint32 status;
reply.get("status", &status);
if(status != 4){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to stop process: %s(%d)", msg.c_str(), status);
return false;
}
}
}
{
Properties reply;
if(proc.m_host->m_cpcd->undefine_process(proc.m_proc.m_id, reply) != 0){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to undefine process: %s", msg.c_str());
return false;
}
proc.m_proc.m_id = -1;
}
return true;
}
bool
stop_processes(atrt_config& config, int types){
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((types & proc.m_type) != 0){
if(!stop_process(proc)){
return false;
}
}
}
return true;
}
bool
update_status(atrt_config& config, int){
Vector<Vector<SimpleCpcClient::Process> > m_procs;
Vector<SimpleCpcClient::Process> dummy;
m_procs.fill(config.m_hosts.size(), dummy);
for(size_t i = 0; i<config.m_hosts.size(); i++){
Properties p;
config.m_hosts[i].m_cpcd->list_processes(m_procs[i], p);
}
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
Vector<SimpleCpcClient::Process> & h_procs = m_procs[proc.m_host->m_index];
bool found = false;
for(size_t j = 0; j<h_procs.size(); j++){
if(proc.m_proc.m_id == h_procs[j].m_id){
found = true;
proc.m_proc.m_status = h_procs[j].m_status;
break;
}
}
if(!found){
g_logger.error("update_status: not found");
return false;
}
}
return true;
}
int
is_running(atrt_config& config, int types){
int found = 0, running = 0;
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((types & proc.m_type) != 0){
found++;
if(proc.m_proc.m_status == "running")
running++;
}
}
if(found == running)
return 2;
if(running == 0)
return 0;
return 1;
}
int
insert(const char * pair, Properties & p){
BaseString tmp(pair);
tmp.trim(" \t\n\r");
Vector<BaseString> split;
tmp.split(split, ":=", 2);
if(split.size() != 2)
return -1;
p.put(split[0].trim().c_str(), split[1].trim().c_str());
return 0;
}
bool
read_test_case(FILE * file, atrt_testcase& tc, int& line){
Properties p;
int elements = 0;
char buf[1024];
while(!feof(file)){
if(!fgets(buf, 1024, file))
break;
line++;
BaseString tmp = buf;
if(tmp.length() > 0 && tmp.c_str()[0] == '#')
continue;
if(insert(tmp.c_str(), p) != 0)
break;
elements++;
}
if(elements == 0){
if(file == stdin){
BaseString tmp(buf);
tmp.trim(" \t\n\r");
Vector<BaseString> split;
tmp.split(split, " ", 2);
tc.m_command = split[0];
if(split.size() == 2)
tc.m_args = split[1];
else
tc.m_args = "";
tc.m_max_time = 60000;
return true;
}
return false;
}
if(!p.get("cmd", tc.m_command)){
g_logger.critical("Invalid test file: cmd is missing near line: %d", line);
return false;
}
if(!p.get("args", tc.m_args))
tc.m_args = "";
const char * mt = 0;
if(!p.get("max-time", &mt))
tc.m_max_time = 60000;
else
tc.m_max_time = atoi(mt);
return true;
}
bool
setup_test_case(atrt_config& config, const atrt_testcase& tc){
const int r1 = system(g_clear_progname);
if(r1 != 0){
g_logger.critical("Failed to clear result");
return false;
}
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if(proc.m_type == atrt_process::NDB_API){
proc.m_proc.m_path.assign(proc.m_host->m_base_dir).append("/bin/").append(tc.m_command);
proc.m_proc.m_args.assign(tc.m_args);
return true;
}
}
return false;
}
bool
gather_result(atrt_config& config, int * result){
BaseString tmp = g_gather_progname;
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
tmp.appfmt(" %s:%s",
proc.m_hostname.c_str(),
proc.m_proc.m_cwd.c_str());
}
const int r1 = system(tmp.c_str());
if(r1 != 0){
g_logger.critical("Failed to gather result");
return false;
}
const int r2 = system(g_analyze_progname);
if(r2 == -1 || r2 == (127 << 8)){
g_logger.critical("Failed to analyze results");
return false;
}
* result = r2 ;
return true;
}
bool
setup_hosts(atrt_config& config){
const int r1 = system(g_clear_progname);
if(r1 != 0){
g_logger.critical("Failed to clear result");
return false;
}
for(size_t i = 0; i<config.m_hosts.size(); i++){
BaseString tmp = g_setup_progname;
tmp.appfmt(" %s %s/ %s/run",
config.m_hosts[i].m_hostname.c_str(),
g_setup_path,
config.m_hosts[i].m_base_dir.c_str());
const int r1 = system(tmp.c_str());
if(r1 != 0){
g_logger.critical("Failed to setup %s",
config.m_hosts[i].m_hostname.c_str());
return false;
}
}
return true;
}
Update atrt to use new names of binaries
/* Copyright (C) 2003 MySQL 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; either version 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <getarg.h>
#include <BaseString.hpp>
#include <Parser.hpp>
#include <NdbOut.hpp>
#include <Properties.hpp>
#include <NdbAutoPtr.hpp>
#include "run-test.hpp"
#include <SysLogHandler.hpp>
#include <FileLogHandler.hpp>
#include <mgmapi.h>
#include "CpcClient.hpp"
/**
psuedo code for run-test.bin
define autotest_wrapper process at each host
start ndb-processes
for each testcase
do
start mysqld processes
start replication processes
start test programs
wait until test program finished or max time passed
stop test program
stop replication processes
stop mysqld processes
write report data-file
if test failed and ! last test
restart ndb processes
drop all tables created by test
done
stop ndb processes
undefined wrapper processes
*/
/** Global variables */
static const char progname[] = "ndb_atrt";
static const char * g_gather_progname = "atrt-gather-result.sh";
static const char * g_analyze_progname = "atrt-analyze-result.sh";
static const char * g_clear_progname = "atrt-clear-result.sh";
static const char * g_setup_progname = "atrt-setup.sh";
static const char * g_setup_path = 0;
static const char * g_process_config_filename = "d.txt";
static const char * g_log_filename = 0;
static const char * g_test_case_filename = 0;
static const char * g_report_filename = 0;
static const char * g_default_user = 0;
static const char * g_default_base_dir = 0;
static int g_default_base_port = 0;
static int g_report = 0;
static int g_verbosity = 0;
static FILE * g_report_file = 0;
static FILE * g_test_case_file = stdin;
Logger g_logger;
atrt_config g_config;
static int g_mode_bench = 0;
static int g_mode_regression = 0;
static int g_mode_interactive = 0;
static int g_mode = 0;
static
struct getargs args[] = {
{ "process-config", 0, arg_string, &g_process_config_filename, 0, 0 },
{ "setup-path", 0, arg_string, &g_setup_path, 0, 0 },
{ 0, 'v', arg_counter, &g_verbosity, 0, 0 },
{ "log-file", 0, arg_string, &g_log_filename, 0, 0 },
{ "testcase-file", 'f', arg_string, &g_test_case_filename, 0, 0 },
{ 0, 'R', arg_flag, &g_report, 0, 0 },
{ "report-file", 0, arg_string, &g_report_filename, 0, 0 },
{ "interactive", 'i', arg_flag, &g_mode_interactive, 0, 0 },
{ "regression", 'r', arg_flag, &g_mode_regression, 0, 0 },
{ "bench", 'b', arg_flag, &g_mode_bench, 0, 0 },
};
const int arg_count = 10;
int
main(int argc, const char ** argv){
bool restart = true;
int lineno = 1;
int test_no = 1;
const int p_ndb = atrt_process::NDB_MGM | atrt_process::NDB_DB;
const int p_servers = atrt_process::MYSQL_SERVER | atrt_process::NDB_REP;
const int p_clients = atrt_process::MYSQL_CLIENT | atrt_process::NDB_API;
g_logger.setCategory(progname);
g_logger.enable(Logger::LL_ALL);
g_logger.createConsoleHandler();
if(!parse_args(argc, argv))
goto end;
g_logger.info("Starting...");
if(!setup_config(g_config))
goto end;
g_logger.info("Connecting to hosts");
if(!connect_hosts(g_config))
goto end;
if(!setup_hosts(g_config))
goto end;
if(!start_processes(g_config, atrt_process::NDB_MGM))
goto end;
if(!connect_ndb_mgm(g_config)){
goto end;
}
/**
* Main loop
*/
while(!feof(g_test_case_file)){
/**
* Do we need to restart ndb
*/
if(restart){
g_logger.info("(Re)starting ndb processes");
if(!stop_processes(g_config, atrt_process::NDB_DB))
goto end;
if(!wait_ndb(g_config, NDB_MGM_NODE_STATUS_NO_CONTACT))
goto end;
if(!start_processes(g_config, atrt_process::NDB_DB))
goto end;
if(!wait_ndb(g_config, NDB_MGM_NODE_STATUS_STARTED))
goto end;
g_logger.info("Ndb start completed");
}
const int start_line = lineno;
atrt_testcase test_case;
if(!read_test_case(g_test_case_file, test_case, lineno))
goto end;
g_logger.info("#%d - %s %s",
test_no,
test_case.m_command.c_str(), test_case.m_args.c_str());
// Assign processes to programs
if(!setup_test_case(g_config, test_case))
goto end;
if(!start_processes(g_config, p_servers))
goto end;
if(!start_processes(g_config, p_clients))
goto end;
int result = 0;
const time_t start = time(0);
time_t now = start;
do {
if(!update_status(g_config, atrt_process::ALL))
goto end;
int count = 0;
if((count = is_running(g_config, p_ndb)) != 2){
result = ERR_NDB_FAILED;
break;
}
if((count = is_running(g_config, p_servers)) != 2){
result = ERR_SERVERS_FAILED;
break;
}
if((count = is_running(g_config, p_clients)) == 0){
break;
}
now = time(0);
if(now > (start + test_case.m_max_time)){
result = ERR_MAX_TIME_ELAPSED;
break;
}
sleep(1);
} while(true);
const time_t elapsed = time(0) - start;
if(!stop_processes(g_config, p_clients))
goto end;
if(!stop_processes(g_config, p_servers))
goto end;
if(!gather_result(g_config, &result))
goto end;
g_logger.info("#%d %s(%d)",
test_no,
(result == 0 ? "OK" : "FAILED"), result);
if(g_report_file != 0){
fprintf(g_report_file, "%s %s ; %d ; %d ; %d\n",
test_case.m_command.c_str(),
test_case.m_args.c_str(),
test_no, result, elapsed);
fflush(g_report_file);
}
if(g_mode_bench || (g_mode_regression && result)){
BaseString tmp;
tmp.assfmt("result.%d", test_no);
if(rename("result", tmp.c_str()) != 0){
g_logger.critical("Failed to rename %s as %s",
"result", tmp.c_str());
goto end;
}
}
if(g_mode_interactive && result){
g_logger.info
("Encountered failed test in interactive mode - terminating");
break;
}
if(result != 0){
restart = true;
} else {
restart = false;
}
test_no++;
}
end:
if(g_report_file != 0){
fclose(g_report_file);
g_report_file = 0;
}
if(g_test_case_file != 0 && g_test_case_file != stdin){
fclose(g_test_case_file);
g_test_case_file = 0;
}
stop_processes(g_config, atrt_process::ALL);
return 0;
}
bool
parse_args(int argc, const char** argv){
int optind = 0;
if(getarg(args, arg_count, argc, argv, &optind)) {
arg_printusage(args, arg_count, progname, "");
return false;
}
if(g_log_filename != 0){
g_logger.removeConsoleHandler();
g_logger.addHandler(new FileLogHandler(g_log_filename));
}
{
int tmp = Logger::LL_WARNING - g_verbosity;
tmp = (tmp < Logger::LL_DEBUG ? Logger::LL_DEBUG : tmp);
g_logger.disable(Logger::LL_ALL);
g_logger.enable((Logger::LoggerLevel)tmp, Logger::LL_ALERT);
}
if(!g_process_config_filename){
g_logger.critical("Process config not specified!");
return false;
}
if(!g_setup_path){
char buf[1024];
if(getcwd(buf, sizeof(buf))){
g_setup_path = strdup(buf);
g_logger.info("Setup path not specified, using %s", buf);
} else {
g_logger.critical("Setup path not specified!\n");
return false;
}
}
if(g_report & !g_report_filename){
g_report_filename = "report.txt";
}
if(g_report_filename){
g_report_file = fopen(g_report_filename, "w");
if(g_report_file == 0){
g_logger.critical("Unable to create report file: %s", g_report_filename);
return false;
}
}
if(g_test_case_filename){
g_test_case_file = fopen(g_test_case_filename, "r");
if(g_test_case_file == 0){
g_logger.critical("Unable to open file: %s", g_test_case_filename);
return false;
}
}
int sum = g_mode_interactive + g_mode_regression + g_mode_bench;
if(sum == 0){
g_mode_interactive = 1;
}
if(sum > 1){
g_logger.critical
("Only one of bench/regression/interactive can be specified");
return false;
}
g_default_user = strdup(getenv("USER"));
return true;
}
static
atrt_host *
find(const BaseString& host, Vector<atrt_host> & hosts){
for(size_t i = 0; i<hosts.size(); i++){
if(hosts[i].m_hostname == host){
return &hosts[i];
}
}
return 0;
}
bool
setup_config(atrt_config& config){
FILE * f = fopen(g_process_config_filename, "r");
if(!f){
g_logger.critical("Failed to open process config file: %s",
g_process_config_filename);
return false;
}
bool result = true;
int lineno = 0;
char buf[2048];
while(fgets(buf, 2048, f)){
lineno++;
BaseString tmp(buf);
tmp.trim(" \t\n\r");
if(tmp.length() == 0 || tmp == "" || tmp.c_str()[0] == '#')
continue;
Vector<BaseString> split1;
if(tmp.split(split1, ":", 2) != 2){
g_logger.warning("Invalid line %d in %s - ignoring",
lineno, g_process_config_filename);
continue;
}
if(split1[0].trim() == "basedir"){
g_default_base_dir = strdup(split1[1].trim().c_str());
continue;
}
if(split1[0].trim() == "baseport"){
g_default_base_port = atoi(split1[1].trim().c_str());
continue;
}
if(split1[0].trim() == "user"){
g_default_user = strdup(split1[1].trim().c_str());
continue;
}
Vector<BaseString> hosts;
if(split1[1].trim().split(hosts) <= 0){
g_logger.warning("Invalid line %d in %s - ignoring",
lineno, g_process_config_filename);
}
// 1 - Check hosts
for(size_t i = 0; i<hosts.size(); i++){
Vector<BaseString> tmp;
hosts[i].split(tmp, ":");
BaseString hostname = tmp[0].trim();
BaseString base_dir;
if(tmp.size() >= 2)
base_dir = tmp[1];
else if(g_default_base_dir == 0){
g_logger.critical("Basedir not specified...");
return false;
}
atrt_host * host_ptr;
if((host_ptr = find(hostname, config.m_hosts)) == 0){
atrt_host host;
host.m_index = config.m_hosts.size();
host.m_cpcd = new SimpleCpcClient(hostname.c_str(), 1234);
host.m_base_dir = (base_dir.empty() ? g_default_base_dir : base_dir);
host.m_user = g_default_user;
host.m_hostname = hostname.c_str();
config.m_hosts.push_back(host);
} else {
if(!base_dir.empty() && (base_dir == host_ptr->m_base_dir)){
g_logger.critical("Inconsistent base dir definition for host %s"
", \"%s\" != \"%s\"", hostname.c_str(),
base_dir.c_str(), host_ptr->m_base_dir.c_str());
return false;
}
}
}
BaseString connect_string;
for(size_t i = 0; i<hosts.size(); i++){
BaseString & tmp = hosts[i];
atrt_host * host = find(tmp, config.m_hosts);
BaseString & dir = host->m_base_dir;
const int index = config.m_processes.size() + 1;
atrt_process proc;
proc.m_index = index;
proc.m_host = host;
proc.m_proc.m_id = -1;
proc.m_proc.m_type = "temporary";
proc.m_proc.m_owner = "atrt";
proc.m_proc.m_group = "group";
proc.m_proc.m_cwd.assign(dir).append("/run/");
proc.m_proc.m_env.assfmt("LD_LIBRARY_PATH=%s/lib/mysql", dir.c_str());
proc.m_proc.m_stdout = "log.out";
proc.m_proc.m_stderr = "2>&1";
proc.m_proc.m_runas = proc.m_host->m_user;
proc.m_proc.m_ulimit = "c:unlimited";
proc.m_hostname = proc.m_host->m_hostname;
proc.m_ndb_mgm_port = g_default_base_port;
if(split1[0] == "mgm"){
proc.m_type = atrt_process::NDB_MGM;
proc.m_proc.m_name.assfmt("%d-%s", index, "ndb_mgmd");
proc.m_proc.m_path.assign(dir).append("/libexec/ndb_mgmd");
proc.m_proc.m_args = "-n -c initconfig.txt";
proc.m_proc.m_cwd.appfmt("%d.ndb_mgmd", index);
connect_string.appfmt(";host=%s:%d",
proc.m_hostname.c_str(), proc.m_ndb_mgm_port);
} else if(split1[0] == "ndb"){
proc.m_type = atrt_process::NDB_DB;
proc.m_proc.m_name.assfmt("%d-%s", index, "ndbd");
proc.m_proc.m_path.assign(dir).append("/libexec/ndbd");
proc.m_proc.m_args = "-i -n";
proc.m_proc.m_cwd.appfmt("%d.ndbd", index);
} else if(split1[0] == "api"){
proc.m_type = atrt_process::NDB_API;
proc.m_proc.m_name.assfmt("%d-%s", index, "ndb_api");
proc.m_proc.m_path = "";
proc.m_proc.m_args = "";
proc.m_proc.m_cwd.appfmt("%d.ndb_api", index);
} else {
g_logger.critical("%s:%d: Unhandled process type: %s",
g_process_config_filename, lineno,
split1[0].c_str());
result = false;
goto end;
}
config.m_processes.push_back(proc);
}
// Setup connect string
for(size_t i = 0; i<config.m_processes.size(); i++){
config.m_processes[i].m_proc.m_env.appfmt(" NDB_CONNECTSTRING=nodeid=%d%s",
i+1, connect_string.c_str());
}
}
end:
fclose(f);
return result;
}
bool
connect_hosts(atrt_config& config){
for(size_t i = 0; i<config.m_hosts.size(); i++){
if(config.m_hosts[i].m_cpcd->connect() != 0){
g_logger.error("Unable to connect to cpc %s:%d",
config.m_hosts[i].m_cpcd->getHost(),
config.m_hosts[i].m_cpcd->getPort());
return false;
}
g_logger.debug("Connected to %s:%d",
config.m_hosts[i].m_cpcd->getHost(),
config.m_hosts[i].m_cpcd->getPort());
}
return true;
}
bool
connect_ndb_mgm(atrt_process & proc){
NdbMgmHandle handle = ndb_mgm_create_handle();
if(handle == 0){
g_logger.critical("Unable to create mgm handle");
return false;
}
BaseString tmp = proc.m_hostname;
tmp.appfmt(":%d", proc.m_ndb_mgm_port);
time_t start = time(0);
const time_t max_connect_time = 30;
do {
if(ndb_mgm_connect(handle, tmp.c_str()) != -1){
proc.m_ndb_mgm_handle = handle;
return true;
}
sleep(1);
} while(time(0) < (start + max_connect_time));
g_logger.critical("Unable to connect to ndb mgm %s", tmp.c_str());
return false;
}
bool
connect_ndb_mgm(atrt_config& config){
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((proc.m_type & atrt_process::NDB_MGM) != 0){
if(!connect_ndb_mgm(proc)){
return false;
}
}
}
return true;
}
static int remap(int i){
if(i == NDB_MGM_NODE_STATUS_NO_CONTACT) return NDB_MGM_NODE_STATUS_UNKNOWN;
if(i == NDB_MGM_NODE_STATUS_UNKNOWN) return NDB_MGM_NODE_STATUS_NO_CONTACT;
return i;
}
bool
wait_ndb(atrt_config& config, int goal){
goal = remap(goal);
/**
* Get mgm handle for cluster
*/
NdbMgmHandle handle = 0;
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((proc.m_type & atrt_process::NDB_MGM) != 0){
handle = proc.m_ndb_mgm_handle;
break;
}
}
if(handle == 0){
g_logger.critical("Unable to find mgm handle");
return false;
}
if(goal == NDB_MGM_NODE_STATUS_STARTED){
/**
* 1) wait NOT_STARTED
* 2) send start
* 3) wait STARTED
*/
if(!wait_ndb(config, NDB_MGM_NODE_STATUS_NOT_STARTED))
return false;
ndb_mgm_start(handle, 0, 0);
}
struct ndb_mgm_cluster_state * state;
time_t now = time(0);
time_t end = now + 360;
int min = remap(NDB_MGM_NODE_STATUS_NO_CONTACT);
int min2 = goal;
while(now < end){
/**
* 1) retreive current state
*/
state = ndb_mgm_get_status(handle);
if(state == 0){
g_logger.critical("Unable to poll db state");
return false;
}
NdbAutoPtr<void> tmp(state);
min2 = goal;
for(int i = 0; i<state->no_of_nodes; i++){
if(state->node_states[i].node_type == NDB_MGM_NODE_TYPE_NDB){
const int s = remap(state->node_states[i].node_status);
min2 = (min2 < s ? min2 : s );
if(s < remap(NDB_MGM_NODE_STATUS_NO_CONTACT) ||
s > NDB_MGM_NODE_STATUS_STARTED){
g_logger.critical("Strange DB status during start: %d %d", i, min2);
return false;
}
}
}
if(min2 < min){
g_logger.critical("wait ndb failed %d %d %d", min, min2, goal);
return false;
}
if(min2 == goal){
return true;
break;
}
min = min2;
now = time(0);
}
g_logger.critical("wait ndb timed out %d %d %d", min, min2, goal);
return false;
}
bool
start_process(atrt_process & proc){
if(proc.m_proc.m_id != -1){
g_logger.critical("starting already started process: %d", proc.m_index);
return false;
}
BaseString path = proc.m_proc.m_cwd.substr(proc.m_host->m_base_dir.length()+BaseString("/run").length());
BaseString tmp = g_setup_progname;
tmp.appfmt(" %s %s/%s/ %s",
proc.m_host->m_hostname.c_str(),
g_setup_path,
path.c_str(),
proc.m_proc.m_cwd.c_str());
const int r1 = system(tmp.c_str());
if(r1 != 0){
g_logger.critical("Failed to setup process");
return false;
}
{
Properties reply;
if(proc.m_host->m_cpcd->define_process(proc.m_proc, reply) != 0){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to define process: %s", msg.c_str());
return false;
}
}
{
Properties reply;
if(proc.m_host->m_cpcd->start_process(proc.m_proc.m_id, reply) != 0){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to start process: %s", msg.c_str());
return false;
}
}
return true;
}
bool
start_processes(atrt_config& config, int types){
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((types & proc.m_type) != 0){
if(!start_process(proc)){
return false;
}
}
}
return true;
}
bool
stop_process(atrt_process & proc){
if(proc.m_proc.m_id == -1){
return true;
}
{
Properties reply;
if(proc.m_host->m_cpcd->stop_process(proc.m_proc.m_id, reply) != 0){
Uint32 status;
reply.get("status", &status);
if(status != 4){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to stop process: %s(%d)", msg.c_str(), status);
return false;
}
}
}
{
Properties reply;
if(proc.m_host->m_cpcd->undefine_process(proc.m_proc.m_id, reply) != 0){
BaseString msg;
reply.get("errormessage", msg);
g_logger.error("Unable to undefine process: %s", msg.c_str());
return false;
}
proc.m_proc.m_id = -1;
}
return true;
}
bool
stop_processes(atrt_config& config, int types){
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((types & proc.m_type) != 0){
if(!stop_process(proc)){
return false;
}
}
}
return true;
}
bool
update_status(atrt_config& config, int){
Vector<Vector<SimpleCpcClient::Process> > m_procs;
Vector<SimpleCpcClient::Process> dummy;
m_procs.fill(config.m_hosts.size(), dummy);
for(size_t i = 0; i<config.m_hosts.size(); i++){
Properties p;
config.m_hosts[i].m_cpcd->list_processes(m_procs[i], p);
}
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
Vector<SimpleCpcClient::Process> & h_procs = m_procs[proc.m_host->m_index];
bool found = false;
for(size_t j = 0; j<h_procs.size(); j++){
if(proc.m_proc.m_id == h_procs[j].m_id){
found = true;
proc.m_proc.m_status = h_procs[j].m_status;
break;
}
}
if(!found){
g_logger.error("update_status: not found");
return false;
}
}
return true;
}
int
is_running(atrt_config& config, int types){
int found = 0, running = 0;
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if((types & proc.m_type) != 0){
found++;
if(proc.m_proc.m_status == "running")
running++;
}
}
if(found == running)
return 2;
if(running == 0)
return 0;
return 1;
}
int
insert(const char * pair, Properties & p){
BaseString tmp(pair);
tmp.trim(" \t\n\r");
Vector<BaseString> split;
tmp.split(split, ":=", 2);
if(split.size() != 2)
return -1;
p.put(split[0].trim().c_str(), split[1].trim().c_str());
return 0;
}
bool
read_test_case(FILE * file, atrt_testcase& tc, int& line){
Properties p;
int elements = 0;
char buf[1024];
while(!feof(file)){
if(!fgets(buf, 1024, file))
break;
line++;
BaseString tmp = buf;
if(tmp.length() > 0 && tmp.c_str()[0] == '#')
continue;
if(insert(tmp.c_str(), p) != 0)
break;
elements++;
}
if(elements == 0){
if(file == stdin){
BaseString tmp(buf);
tmp.trim(" \t\n\r");
Vector<BaseString> split;
tmp.split(split, " ", 2);
tc.m_command = split[0];
if(split.size() == 2)
tc.m_args = split[1];
else
tc.m_args = "";
tc.m_max_time = 60000;
return true;
}
return false;
}
if(!p.get("cmd", tc.m_command)){
g_logger.critical("Invalid test file: cmd is missing near line: %d", line);
return false;
}
if(!p.get("args", tc.m_args))
tc.m_args = "";
const char * mt = 0;
if(!p.get("max-time", &mt))
tc.m_max_time = 60000;
else
tc.m_max_time = atoi(mt);
return true;
}
bool
setup_test_case(atrt_config& config, const atrt_testcase& tc){
const int r1 = system(g_clear_progname);
if(r1 != 0){
g_logger.critical("Failed to clear result");
return false;
}
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
if(proc.m_type == atrt_process::NDB_API){
proc.m_proc.m_path.assign(proc.m_host->m_base_dir).append("/bin/").append(tc.m_command);
proc.m_proc.m_args.assign(tc.m_args);
return true;
}
}
return false;
}
bool
gather_result(atrt_config& config, int * result){
BaseString tmp = g_gather_progname;
for(size_t i = 0; i<config.m_processes.size(); i++){
atrt_process & proc = config.m_processes[i];
tmp.appfmt(" %s:%s",
proc.m_hostname.c_str(),
proc.m_proc.m_cwd.c_str());
}
const int r1 = system(tmp.c_str());
if(r1 != 0){
g_logger.critical("Failed to gather result");
return false;
}
const int r2 = system(g_analyze_progname);
if(r2 == -1 || r2 == (127 << 8)){
g_logger.critical("Failed to analyze results");
return false;
}
* result = r2 ;
return true;
}
bool
setup_hosts(atrt_config& config){
const int r1 = system(g_clear_progname);
if(r1 != 0){
g_logger.critical("Failed to clear result");
return false;
}
for(size_t i = 0; i<config.m_hosts.size(); i++){
BaseString tmp = g_setup_progname;
tmp.appfmt(" %s %s/ %s/run",
config.m_hosts[i].m_hostname.c_str(),
g_setup_path,
config.m_hosts[i].m_base_dir.c_str());
const int r1 = system(tmp.c_str());
if(r1 != 0){
g_logger.critical("Failed to setup %s",
config.m_hosts[i].m_hostname.c_str());
return false;
}
}
return true;
}
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This 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. See file COPYING.
*
*/
#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;
#include "config.h"
#include "mon/MonMap.h"
#include "mon/MonClient.h"
#include "msg/SimpleMessenger.h"
#include "messages/MMonCommand.h"
#include "messages/MMonCommandAck.h"
#include "common/Timer.h"
#include "common/common_init.h"
#ifndef DARWIN
#include <envz.h>
#endif // DARWIN
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
extern "C" {
#include <histedit.h>
}
Mutex lock("ceph.cc lock");
Cond cond;
SimpleMessenger *messenger = 0;
SafeTimer timer(lock);
MonClient mc;
const char *outfile = 0;
// sync command
vector<string> pending_cmd;
bufferlist pending_bl;
bool reply;
string reply_rs;
int reply_rc;
bufferlist reply_bl;
entity_inst_t reply_from;
Context *resend_event = 0;
// observe (push)
#include "mon/PGMap.h"
#include "osd/OSDMap.h"
#include "mds/MDSMap.h"
#include "include/LogEntry.h"
#include "include/ClassLibrary.h"
#include "mon/mon_types.h"
#include "messages/MMonObserve.h"
#include "messages/MMonObserveNotify.h"
int observe = 0;
bool one_shot = false;
static PGMap pgmap;
static MDSMap mdsmap;
static OSDMap osdmap;
static set<int> registered, seen;
version_t map_ver[PAXOS_NUM];
version_t last_seen_version = 0;
void handle_observe(MMonObserve *observe)
{
dout(1) << observe->get_source() << " -> " << get_paxos_name(observe->machine_id)
<< " registered" << dendl;
lock.Lock();
registered.insert(observe->machine_id);
lock.Unlock();
delete observe;
}
void handle_notify(MMonObserveNotify *notify)
{
dout(1) << notify->get_source() << " -> " << get_paxos_name(notify->machine_id)
<< " v" << notify->ver
<< (notify->is_latest ? " (latest)" : "")
<< dendl;
if (ceph_fsid_compare(¬ify->fsid, &mc.monmap.fsid)) {
dout(0) << notify->get_source_inst() << " notify fsid " << notify->fsid << " != " << mc.monmap.fsid << dendl;
delete notify;
return;
}
if (map_ver[notify->machine_id] >= notify->ver)
return;
switch (notify->machine_id) {
case PAXOS_PGMAP:
{
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
pgmap.decode(p);
} else {
PGMap::Incremental inc;
inc.decode(p);
pgmap.apply_incremental(inc);
}
dout(0) << " pg " << pgmap << dendl;
break;
}
case PAXOS_MDSMAP:
mdsmap.decode(notify->bl);
dout(0) << " mds " << mdsmap << dendl;
break;
case PAXOS_OSDMAP:
{
if (notify->is_latest) {
osdmap.decode(notify->bl);
} else {
OSDMap::Incremental inc(notify->bl);
osdmap.apply_incremental(inc);
}
dout(0) << " osd " << osdmap << dendl;
}
break;
case PAXOS_LOG:
{
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
LogSummary summary;
::decode(summary, p);
// show last log message
if (!summary.tail.empty())
dout(0) << " log " << summary.tail.back() << dendl;
} else {
LogEntry le;
__u8 v;
::decode(v, p);
while (!p.end()) {
le.decode(p);
dout(0) << " log " << le << dendl;
}
}
break;
}
case PAXOS_CLASS:
{
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
ClassLibrary list;
::decode(list, p);
// show the first class info
map<string, ClassVersionMap>::iterator mapiter = list.library_map.begin();
if (mapiter != list.library_map.end()) {
ClassVersionMap& map = mapiter->second;
tClassVersionMap::iterator iter = map.begin();
if (iter != map.end())
dout(0) << " class " << iter->second << dendl;
}
} else {
ClassInfo info;
__u8 v;
::decode(v, p);
while (!p.end()) {
info.decode(p);
dout(0) << " class " << info << dendl;
}
}
break;
}
case PAXOS_AUTH:
{
#if 0
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
KeyServerData data;
::decode(data, p);
dout(0) << " auth " << dendl;
} else {
while (!p.end()) {
AuthMonitor::Incremental inc;
inc.decode(p);
dout(0) << " auth " << inc.name.to_str() << dendl;
}
}
#endif
/* ignoring auth incremental.. don't want to decode it */
break;
}
case PAXOS_MONMAP:
{
mc.monmap.decode(notify->bl);
dout(0) << " mon " << mc.monmap << dendl;
}
break;
default:
dout(0) << " ignoring unknown machine id " << notify->machine_id << dendl;
}
map_ver[notify->machine_id] = notify->ver;
// have we seen them all?
seen.insert(notify->machine_id);
if (one_shot && seen.size() == PAXOS_NUM) {
messenger->shutdown();
}
delete notify;
}
static void send_observe_requests();
class C_ObserverRefresh : public Context {
public:
bool newmon;
C_ObserverRefresh(bool n) : newmon(n) {}
void finish(int r) {
send_observe_requests();
}
};
static void send_observe_requests()
{
dout(1) << "send_observe_requests " << dendl;
bool sent = false;
for (int i=0; i<PAXOS_NUM; i++) {
MMonObserve *m = new MMonObserve(mc.monmap.fsid, i, map_ver[i]);
dout(1) << "mon" << " <- observe " << get_paxos_name(i) << dendl;
mc.send_mon_message(m);
sent = true;
}
registered.clear();
float seconds = g_conf.paxos_observer_timeout/2;
dout(1) << " refresh after " << seconds << " with same mon" << dendl;
timer.add_event_after(seconds, new C_ObserverRefresh(false));
}
// watch (poll)
int watch = 0;
enum { OSD, MON, MDS, CLIENT, LAST };
int which = 0;
int same = 0;
const char *prefix[4] = { "mds", "osd", "pg", "client" };
map<string,string> status;
int lines = 0;
// refresh every second
void get_status(bool newmon=false);
struct C_Refresh : public Context {
void finish(int r) {
get_status(true);
}
};
Context *event = 0;
void get_status(bool newmon)
{
vector<string> vcmd(2);
vcmd[0] = prefix[which];
vcmd[1] = "stat";
MMonCommand *m = new MMonCommand(mc.monmap.fsid, last_seen_version);
m->cmd.swap(vcmd);
mc.send_mon_message(m);
event = new C_Refresh;
timer.add_event_after(.2, event);
}
void handle_ack(MMonCommandAck *ack)
{
if (watch) {
lock.Lock();
which++;
which = which % LAST;
if (ack->version > last_seen_version)
last_seen_version = ack->version;
string w = ack->cmd[0];
if (ack->rs != status[w]) {
status[w] = ack->rs;
generic_dout(0) << w << " " << status[w] << dendl;
lines++;
if (lines > 20) {
generic_dout(0) << dendl;
for (map<string,string>::iterator p = status.begin(); p != status.end(); p++)
generic_dout(0) << p->first << " " << p->second << dendl;
generic_dout(0) << dendl;
lines = 0;
}
if (event)
timer.cancel_event(event);
get_status();
}
lock.Unlock();
} else {
lock.Lock();
reply = true;
reply_from = ack->get_source_inst();
reply_rs = ack->rs;
reply_rc = ack->r;
reply_bl = ack->get_data();
cond.Signal();
if (resend_event) {
timer.cancel_event(resend_event);
resend_event = 0;
}
lock.Unlock();
}
delete ack;
}
void send_command()
{
MMonCommand *m = new MMonCommand(mc.monmap.fsid, last_seen_version);
m->cmd = pending_cmd;
m->get_data() = pending_bl;
generic_dout(0) << "mon" << " <- " << pending_cmd << dendl;
mc.send_mon_message(m);
}
class Admin : public Dispatcher {
bool ms_dispatch(Message *m) {
switch (m->get_type()) {
case MSG_MON_COMMAND_ACK:
handle_ack((MMonCommandAck*)m);
break;
case MSG_MON_OBSERVE_NOTIFY:
handle_notify((MMonObserveNotify *)m);
break;
case MSG_MON_OBSERVE:
handle_observe((MMonObserve *)m);
break;
case CEPH_MSG_MON_MAP:
delete m;
break;
default:
return false;
}
return true;
}
void ms_handle_connect(Connection *con) {
if (con->get_peer_type() == CEPH_ENTITY_TYPE_MON) {
lock.Lock();
if (observe)
send_observe_requests();
if (pending_cmd.size())
send_command();
lock.Unlock();
}
}
bool ms_handle_reset(Connection *con) { return false; }
void ms_handle_remote_reset(Connection *con) {}
} dispatcher;
int do_command(vector<string>& cmd, bufferlist& bl, string& rs, bufferlist& rbl)
{
Mutex::Locker l(lock);
pending_cmd = cmd;
pending_bl = bl;
reply = false;
send_command();
while (!reply)
cond.Wait(lock);
rs = rs;
rbl = reply_bl;
generic_dout(0) << reply_from.name << " -> '"
<< reply_rs << "' (" << reply_rc << ")"
<< dendl;
return reply_rc;
}
void usage()
{
cerr << "usage: ceph [options] [commands]" << std::endl;
cerr << "If no commands are specified, enter interactive mode.\n";
cerr << "Commands:" << std::endl;
cerr << " stop -- cleanly shut down file system" << std::endl
<< " (osd|pg|mds) stat -- get monitor subsystem status" << std::endl
<< " ..." << std::endl;
cerr << "Options:" << std::endl;
cerr << " -i infile\n";
cerr << " -o outfile\n";
cerr << " specify input or output file (for certain commands)\n";
cerr << " -s or --status\n";
cerr << " print current system status\n";
cerr << " -w or --watch\n";
cerr << " watch system status changes in real time (push)\n";
cerr << " -p or --poll\n";
cerr << " watch system status changes in real time (poll)\n";
generic_client_usage();
}
const char *cli_prompt(EditLine *e) {
return "ceph> ";
}
int do_cli()
{
/* emacs style */
EditLine *el = el_init("ceph", stdin, stdout, stderr);
el_set(el, EL_PROMPT, &cli_prompt);
el_set(el, EL_EDITOR, "emacs");
History *myhistory = history_init();
if (myhistory == 0) {
fprintf(stderr, "history could not be initialized\n");
return 1;
}
HistEvent ev;
/* Set the size of the history */
history(myhistory, &ev, H_SETSIZE, 800);
/* This sets up the call back functions for history functionality */
el_set(el, EL_HIST, history, myhistory);
Tokenizer *tok = tok_init(NULL);
bufferlist in;
while (1) {
int count; // # chars read
const char *line = el_gets(el, &count);
if (!count) {
cout << "quit" << std::endl;
break;
}
//cout << "typed '" << line << "'" << std::endl;
if (strcmp(line, "quit\n") == 0)
break;
history(myhistory, &ev, H_ENTER, line);
int argc;
const char **argv;
tok_str(tok, line, &argc, &argv);
tok_reset(tok);
vector<string> cmd;
const char *infile = 0;
const char *outfile = 0;
for (int i=0; i<argc; i++) {
if (strcmp(argv[i], ">") == 0 && i < argc-1) {
outfile = argv[++i];
continue;
}
if (argv[i][0] == '>') {
outfile = argv[i] + 1;
while (*outfile == ' ') outfile++;
continue;
}
if (strcmp(argv[i], "<") == 0 && i < argc-1) {
infile = argv[++i];
continue;
}
if (argv[i][0] == '<') {
infile = argv[i] + 1;
while (*infile == ' ') infile++;
continue;
}
cmd.push_back(argv[i]);
}
if (cmd.empty())
continue;
if (cmd.size() == 1 && cmd[0] == "print") {
cout << "----" << std::endl;
write(1, in.c_str(), in.length());
cout << "---- (" << in.length() << " bytes)" << std::endl;
continue;
}
//cout << "cmd is " << cmd << std::endl;
bufferlist out;
if (infile) {
if (out.read_file(infile) == 0) {
cout << "read " << out.length() << " from " << infile << std::endl;
} else {
char buf[80];
cerr << "couldn't read from " << infile << ": " << strerror_r(errno, buf, sizeof(buf)) << std::endl;
continue;
}
}
in.clear();
string rs;
do_command(cmd, out, rs, in);
if (in.length()) {
if (outfile) {
if (strcmp(outfile, "-") == 0) {
cout << "----" << std::endl;
write(1, in.c_str(), in.length());
cout << "---- (" << in.length() << " bytes)" << std::endl;
} else {
in.write_file(outfile);
cout << "wrote " << in.length() << " to " << outfile << std::endl;
}
} else {
cout << "got " << in.length() << " byte payload; 'print' to dump to terminal, or add '>-' to command." << std::endl;
}
}
}
history_end(myhistory);
el_end(el);
return 0;
}
int main(int argc, const char **argv, const char *envp[])
{
DEFINE_CONF_VARS(usage);
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
ceph_set_default_id("admin");
common_init(args, "ceph", false, true);
vec_to_argv(args, argc, argv);
srand(getpid());
// default to 'admin' user
if (!g_conf.id || !g_conf.id[0])
g_conf.id = strdup("admin");
char *fname;
bufferlist indata;
vector<const char*> nargs;
FOR_EACH_ARG(args) {
if (CONF_ARG_EQ("out_file", 'o')) {
CONF_SAFE_SET_ARG_VAL(&outfile, OPT_STR);
} else if (CONF_ARG_EQ("in_data", 'i')) {
CONF_SAFE_SET_ARG_VAL(&fname, OPT_STR);
int fd = ::open(fname, O_RDONLY);
struct stat st;
if (::fstat(fd, &st) == 0) {
indata.push_back(buffer::create(st.st_size));
indata.zero();
::read(fd, indata.c_str(), st.st_size);
::close(fd);
cout << "read " << st.st_size << " bytes from " << args[i] << std::endl;
}
} else if (CONF_ARG_EQ("status", 's')) {
CONF_SAFE_SET_ARG_VAL(&observe, OPT_BOOL);
one_shot = true;
} else if (CONF_ARG_EQ("watch", 'w')) {
CONF_SAFE_SET_ARG_VAL(&observe, OPT_BOOL);
} else if (CONF_ARG_EQ("poll", 'p')) {
CONF_SAFE_SET_ARG_VAL(&watch, OPT_BOOL);
} else if (CONF_ARG_EQ("help", 'h')) {
usage();
} else if (args[i][0] == '-' && nargs.empty()) {
cerr << "unrecognized option " << args[i] << std::endl;
usage();
} else
nargs.push_back(args[i]);
}
// build command
vector<string> vcmd;
string cmd;
if (!watch) {
for (unsigned i=0; i<nargs.size(); i++) {
if (i) cmd += " ";
cmd += nargs[i];
vcmd.push_back(string(nargs[i]));
}
}
// get monmap
if (mc.build_initial_monmap() < 0)
return -1;
// start up network
messenger = new SimpleMessenger();
messenger->register_entity(entity_name_t::CLIENT());
messenger->add_dispatcher_head(&dispatcher);
messenger->start();
mc.set_messenger(messenger);
mc.init();
if (mc.authenticate() < 0) {
cerr << "unable to authenticate as " << *g_conf.entity_name << std::endl;
return -1;
}
if (mc.get_monmap() < 0) {
cerr << "unable to get monmap" << std::endl;
return -1;
}
if (watch) {
lock.Lock();
get_status();
lock.Unlock();
}
if (observe) {
lock.Lock();
send_observe_requests();
lock.Unlock();
}
if (!watch && !observe) {
if (vcmd.size()) {
string rs;
bufferlist odata;
do_command(vcmd, indata, rs, odata);
int len = odata.length();
if (len) {
if (outfile) {
if (strcmp(outfile, "-") == 0) {
::write(1, odata.c_str(), len);
} else {
odata.write_file(outfile);
}
generic_dout(0) << "wrote " << len << " byte payload to " << outfile << dendl;
} else {
generic_dout(0) << "got " << len << " byte payload, discarding (specify -o <outfile)" << dendl;
}
}
} else {
// interactive mode
do_cli();
}
messenger->shutdown();
}
// wait for messenger to finish
messenger->wait();
messenger->destroy();
return 0;
}
ceph: drop (broken) poll mode (use -w instead)
It wasn't working anyway.
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This 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. See file COPYING.
*
*/
#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;
#include "config.h"
#include "mon/MonMap.h"
#include "mon/MonClient.h"
#include "msg/SimpleMessenger.h"
#include "messages/MMonCommand.h"
#include "messages/MMonCommandAck.h"
#include "common/Timer.h"
#include "common/common_init.h"
#ifndef DARWIN
#include <envz.h>
#endif // DARWIN
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
extern "C" {
#include <histedit.h>
}
Mutex lock("ceph.cc lock");
Cond cond;
SimpleMessenger *messenger = 0;
SafeTimer timer(lock);
MonClient mc;
const char *outfile = 0;
// sync command
vector<string> pending_cmd;
bufferlist pending_bl;
bool reply;
string reply_rs;
int reply_rc;
bufferlist reply_bl;
entity_inst_t reply_from;
Context *resend_event = 0;
// observe (push)
#include "mon/PGMap.h"
#include "osd/OSDMap.h"
#include "mds/MDSMap.h"
#include "include/LogEntry.h"
#include "include/ClassLibrary.h"
#include "mon/mon_types.h"
#include "messages/MMonObserve.h"
#include "messages/MMonObserveNotify.h"
int observe = 0;
bool one_shot = false;
static PGMap pgmap;
static MDSMap mdsmap;
static OSDMap osdmap;
static set<int> registered, seen;
version_t map_ver[PAXOS_NUM];
version_t last_seen_version = 0;
void handle_observe(MMonObserve *observe)
{
dout(1) << observe->get_source() << " -> " << get_paxos_name(observe->machine_id)
<< " registered" << dendl;
lock.Lock();
registered.insert(observe->machine_id);
lock.Unlock();
delete observe;
}
void handle_notify(MMonObserveNotify *notify)
{
dout(1) << notify->get_source() << " -> " << get_paxos_name(notify->machine_id)
<< " v" << notify->ver
<< (notify->is_latest ? " (latest)" : "")
<< dendl;
if (ceph_fsid_compare(¬ify->fsid, &mc.monmap.fsid)) {
dout(0) << notify->get_source_inst() << " notify fsid " << notify->fsid << " != " << mc.monmap.fsid << dendl;
delete notify;
return;
}
if (map_ver[notify->machine_id] >= notify->ver)
return;
switch (notify->machine_id) {
case PAXOS_PGMAP:
{
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
pgmap.decode(p);
} else {
PGMap::Incremental inc;
inc.decode(p);
pgmap.apply_incremental(inc);
}
dout(0) << " pg " << pgmap << dendl;
break;
}
case PAXOS_MDSMAP:
mdsmap.decode(notify->bl);
dout(0) << " mds " << mdsmap << dendl;
break;
case PAXOS_OSDMAP:
{
if (notify->is_latest) {
osdmap.decode(notify->bl);
} else {
OSDMap::Incremental inc(notify->bl);
osdmap.apply_incremental(inc);
}
dout(0) << " osd " << osdmap << dendl;
}
break;
case PAXOS_LOG:
{
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
LogSummary summary;
::decode(summary, p);
// show last log message
if (!summary.tail.empty())
dout(0) << " log " << summary.tail.back() << dendl;
} else {
LogEntry le;
__u8 v;
::decode(v, p);
while (!p.end()) {
le.decode(p);
dout(0) << " log " << le << dendl;
}
}
break;
}
case PAXOS_CLASS:
{
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
ClassLibrary list;
::decode(list, p);
// show the first class info
map<string, ClassVersionMap>::iterator mapiter = list.library_map.begin();
if (mapiter != list.library_map.end()) {
ClassVersionMap& map = mapiter->second;
tClassVersionMap::iterator iter = map.begin();
if (iter != map.end())
dout(0) << " class " << iter->second << dendl;
}
} else {
ClassInfo info;
__u8 v;
::decode(v, p);
while (!p.end()) {
info.decode(p);
dout(0) << " class " << info << dendl;
}
}
break;
}
case PAXOS_AUTH:
{
#if 0
bufferlist::iterator p = notify->bl.begin();
if (notify->is_latest) {
KeyServerData data;
::decode(data, p);
dout(0) << " auth " << dendl;
} else {
while (!p.end()) {
AuthMonitor::Incremental inc;
inc.decode(p);
dout(0) << " auth " << inc.name.to_str() << dendl;
}
}
#endif
/* ignoring auth incremental.. don't want to decode it */
break;
}
case PAXOS_MONMAP:
{
mc.monmap.decode(notify->bl);
dout(0) << " mon " << mc.monmap << dendl;
}
break;
default:
dout(0) << " ignoring unknown machine id " << notify->machine_id << dendl;
}
map_ver[notify->machine_id] = notify->ver;
// have we seen them all?
seen.insert(notify->machine_id);
if (one_shot && seen.size() == PAXOS_NUM) {
messenger->shutdown();
}
delete notify;
}
static void send_observe_requests();
class C_ObserverRefresh : public Context {
public:
bool newmon;
C_ObserverRefresh(bool n) : newmon(n) {}
void finish(int r) {
send_observe_requests();
}
};
static void send_observe_requests()
{
dout(1) << "send_observe_requests " << dendl;
bool sent = false;
for (int i=0; i<PAXOS_NUM; i++) {
MMonObserve *m = new MMonObserve(mc.monmap.fsid, i, map_ver[i]);
dout(1) << "mon" << " <- observe " << get_paxos_name(i) << dendl;
mc.send_mon_message(m);
sent = true;
}
registered.clear();
float seconds = g_conf.paxos_observer_timeout/2;
dout(1) << " refresh after " << seconds << " with same mon" << dendl;
timer.add_event_after(seconds, new C_ObserverRefresh(false));
}
int lines = 0;
void handle_ack(MMonCommandAck *ack)
{
lock.Lock();
reply = true;
reply_from = ack->get_source_inst();
reply_rs = ack->rs;
reply_rc = ack->r;
reply_bl = ack->get_data();
cond.Signal();
if (resend_event) {
timer.cancel_event(resend_event);
resend_event = 0;
}
lock.Unlock();
delete ack;
}
void send_command()
{
MMonCommand *m = new MMonCommand(mc.monmap.fsid, last_seen_version);
m->cmd = pending_cmd;
m->get_data() = pending_bl;
generic_dout(0) << "mon" << " <- " << pending_cmd << dendl;
mc.send_mon_message(m);
}
class Admin : public Dispatcher {
bool ms_dispatch(Message *m) {
switch (m->get_type()) {
case MSG_MON_COMMAND_ACK:
handle_ack((MMonCommandAck*)m);
break;
case MSG_MON_OBSERVE_NOTIFY:
handle_notify((MMonObserveNotify *)m);
break;
case MSG_MON_OBSERVE:
handle_observe((MMonObserve *)m);
break;
case CEPH_MSG_MON_MAP:
delete m;
break;
default:
return false;
}
return true;
}
void ms_handle_connect(Connection *con) {
if (con->get_peer_type() == CEPH_ENTITY_TYPE_MON) {
lock.Lock();
if (observe)
send_observe_requests();
if (pending_cmd.size())
send_command();
lock.Unlock();
}
}
bool ms_handle_reset(Connection *con) { return false; }
void ms_handle_remote_reset(Connection *con) {}
} dispatcher;
int do_command(vector<string>& cmd, bufferlist& bl, string& rs, bufferlist& rbl)
{
Mutex::Locker l(lock);
pending_cmd = cmd;
pending_bl = bl;
reply = false;
send_command();
while (!reply)
cond.Wait(lock);
rs = rs;
rbl = reply_bl;
generic_dout(0) << reply_from.name << " -> '"
<< reply_rs << "' (" << reply_rc << ")"
<< dendl;
return reply_rc;
}
void usage()
{
cerr << "usage: ceph [options] [commands]" << std::endl;
cerr << "If no commands are specified, enter interactive mode.\n";
cerr << "Commands:" << std::endl;
cerr << " stop -- cleanly shut down file system" << std::endl
<< " (osd|pg|mds) stat -- get monitor subsystem status" << std::endl
<< " ..." << std::endl;
cerr << "Options:" << std::endl;
cerr << " -i infile\n";
cerr << " -o outfile\n";
cerr << " specify input or output file (for certain commands)\n";
cerr << " -s or --status\n";
cerr << " print current system status\n";
cerr << " -w or --watch\n";
cerr << " watch system status changes in real time (push)\n";
generic_client_usage();
}
const char *cli_prompt(EditLine *e) {
return "ceph> ";
}
int do_cli()
{
/* emacs style */
EditLine *el = el_init("ceph", stdin, stdout, stderr);
el_set(el, EL_PROMPT, &cli_prompt);
el_set(el, EL_EDITOR, "emacs");
History *myhistory = history_init();
if (myhistory == 0) {
fprintf(stderr, "history could not be initialized\n");
return 1;
}
HistEvent ev;
/* Set the size of the history */
history(myhistory, &ev, H_SETSIZE, 800);
/* This sets up the call back functions for history functionality */
el_set(el, EL_HIST, history, myhistory);
Tokenizer *tok = tok_init(NULL);
bufferlist in;
while (1) {
int count; // # chars read
const char *line = el_gets(el, &count);
if (!count) {
cout << "quit" << std::endl;
break;
}
//cout << "typed '" << line << "'" << std::endl;
if (strcmp(line, "quit\n") == 0)
break;
history(myhistory, &ev, H_ENTER, line);
int argc;
const char **argv;
tok_str(tok, line, &argc, &argv);
tok_reset(tok);
vector<string> cmd;
const char *infile = 0;
const char *outfile = 0;
for (int i=0; i<argc; i++) {
if (strcmp(argv[i], ">") == 0 && i < argc-1) {
outfile = argv[++i];
continue;
}
if (argv[i][0] == '>') {
outfile = argv[i] + 1;
while (*outfile == ' ') outfile++;
continue;
}
if (strcmp(argv[i], "<") == 0 && i < argc-1) {
infile = argv[++i];
continue;
}
if (argv[i][0] == '<') {
infile = argv[i] + 1;
while (*infile == ' ') infile++;
continue;
}
cmd.push_back(argv[i]);
}
if (cmd.empty())
continue;
if (cmd.size() == 1 && cmd[0] == "print") {
cout << "----" << std::endl;
write(1, in.c_str(), in.length());
cout << "---- (" << in.length() << " bytes)" << std::endl;
continue;
}
//cout << "cmd is " << cmd << std::endl;
bufferlist out;
if (infile) {
if (out.read_file(infile) == 0) {
cout << "read " << out.length() << " from " << infile << std::endl;
} else {
char buf[80];
cerr << "couldn't read from " << infile << ": " << strerror_r(errno, buf, sizeof(buf)) << std::endl;
continue;
}
}
in.clear();
string rs;
do_command(cmd, out, rs, in);
if (in.length()) {
if (outfile) {
if (strcmp(outfile, "-") == 0) {
cout << "----" << std::endl;
write(1, in.c_str(), in.length());
cout << "---- (" << in.length() << " bytes)" << std::endl;
} else {
in.write_file(outfile);
cout << "wrote " << in.length() << " to " << outfile << std::endl;
}
} else {
cout << "got " << in.length() << " byte payload; 'print' to dump to terminal, or add '>-' to command." << std::endl;
}
}
}
history_end(myhistory);
el_end(el);
return 0;
}
int main(int argc, const char **argv, const char *envp[])
{
DEFINE_CONF_VARS(usage);
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
ceph_set_default_id("admin");
common_init(args, "ceph", false, true);
vec_to_argv(args, argc, argv);
srand(getpid());
// default to 'admin' user
if (!g_conf.id || !g_conf.id[0])
g_conf.id = strdup("admin");
char *fname;
bufferlist indata;
vector<const char*> nargs;
FOR_EACH_ARG(args) {
if (CONF_ARG_EQ("out_file", 'o')) {
CONF_SAFE_SET_ARG_VAL(&outfile, OPT_STR);
} else if (CONF_ARG_EQ("in_data", 'i')) {
CONF_SAFE_SET_ARG_VAL(&fname, OPT_STR);
int fd = ::open(fname, O_RDONLY);
struct stat st;
if (::fstat(fd, &st) == 0) {
indata.push_back(buffer::create(st.st_size));
indata.zero();
::read(fd, indata.c_str(), st.st_size);
::close(fd);
cout << "read " << st.st_size << " bytes from " << args[i] << std::endl;
}
} else if (CONF_ARG_EQ("status", 's')) {
CONF_SAFE_SET_ARG_VAL(&observe, OPT_BOOL);
one_shot = true;
} else if (CONF_ARG_EQ("watch", 'w')) {
CONF_SAFE_SET_ARG_VAL(&observe, OPT_BOOL);
} else if (CONF_ARG_EQ("help", 'h')) {
usage();
} else if (args[i][0] == '-' && nargs.empty()) {
cerr << "unrecognized option " << args[i] << std::endl;
usage();
} else
nargs.push_back(args[i]);
}
// build command
vector<string> vcmd;
string cmd;
for (unsigned i=0; i<nargs.size(); i++) {
if (i) cmd += " ";
cmd += nargs[i];
vcmd.push_back(string(nargs[i]));
}
// get monmap
if (mc.build_initial_monmap() < 0)
return -1;
// start up network
messenger = new SimpleMessenger();
messenger->register_entity(entity_name_t::CLIENT());
messenger->add_dispatcher_head(&dispatcher);
messenger->start();
mc.set_messenger(messenger);
mc.init();
if (mc.authenticate() < 0) {
cerr << "unable to authenticate as " << *g_conf.entity_name << std::endl;
return -1;
}
if (mc.get_monmap() < 0) {
cerr << "unable to get monmap" << std::endl;
return -1;
}
if (observe) {
lock.Lock();
send_observe_requests();
lock.Unlock();
} else {
if (vcmd.size()) {
string rs;
bufferlist odata;
do_command(vcmd, indata, rs, odata);
int len = odata.length();
if (len) {
if (outfile) {
if (strcmp(outfile, "-") == 0) {
::write(1, odata.c_str(), len);
} else {
odata.write_file(outfile);
}
generic_dout(0) << "wrote " << len << " byte payload to " << outfile << dendl;
} else {
generic_dout(0) << "got " << len << " byte payload, discarding (specify -o <outfile)" << dendl;
}
}
} else {
// interactive mode
do_cli();
}
messenger->shutdown();
}
// wait for messenger to finish
messenger->wait();
messenger->destroy();
return 0;
}
|
#include <ctime>
#include <iostream>
#include <thread>
#include <functional>
#include <vector>
#include <cassert>
#include <map>
#include <string>
#include <sstream>
#include <mutex>
// nanomsg for tcp communication
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>
// characters
#include "utf8.hh"
using Timestamp = std::time_t;
using Alias = std::string;
using Key = std::string;
using Value = std::string;
using NumBytes = std::uint64_t;
//------------------------------------------------------------------------------
// Status
//------------------------------------------------------------------------------
enum Status {
OK=0,
ALIAS_ALREADY_EXISTS=1,
ALIAS_DOESNT_EXIST=2,
UTF8_PARSING_ERROR=3,
KEY_NOT_FOUND=4,
NOT_IMPLEMENTED=5,
NEXT_TOKEN_EMPTY=6,
INSERT_REQUEST_INVALID=7,
GET_REQUEST_INVALID=8,
REMOVE_REQUEST_INVALID=9
};
static const char *status_messages[] {
"OK",
"ALIAS_ALREADY_EXISTS",
"ALIAS_DOESNT_EXIST"
"UTF8_PARSING_ERROR",
"KEY_NOT_FOUND",
"NOT_IMPLEMENTED",
"NEXT_TOKEN_EMPTY",
"INSERT_REQUEST_INVALID",
"GET_REQUEST_INVALID",
"REMOVE_REQUEST_INVALID"
};
//------------------------------------------------------------------------------
// Entry
//------------------------------------------------------------------------------
template<typename T>
struct Expected {
Expected() = default;
Expected(T object): _object(object), _status(OK) {}
Expected(Status not_ok_status): _status(not_ok_status) { assert(not_ok_status!=OK); }
Status status () const { return _status; }
T& get () { assert(status() == OK); return _object; }
T& operator *() { return get(); }
operator bool() const { return _status == OK; }
T _object;
Status _status;
};
//------------------------------------------------------------------------------
// Item
//------------------------------------------------------------------------------
struct Item {
struct Iter {
using iter_t = typename std::map<Key,Value>::const_iterator;
Iter() = default;
Iter(const Item& i);
bool next();
const Key& key() const { return _result->first; }
const Value& value() const { return _result->second; }
iter_t _result;
iter_t _current;
iter_t _end;
};
Item() = default;
Item(const Alias& alias): _alias(alias) {}
Timestamp insertion_time() const { return _insertion_time; }
Timestamp removal_time() const { return _removal_time; }
Item& insertion_time(Timestamp t) { _insertion_time=t; return *this; }
Item& removal_time(Timestamp t) { _removal_time=t; return *this; }
Expected<Value> get(const Key& key) noexcept;
void set(const Key& key, const Value& value) noexcept;
Iter iter() const { return Iter(*this); }
const Alias& alias() const { return _alias; }
Alias _alias;
Timestamp _insertion_time { 0 }; // we assume 0 is undefined for now
Timestamp _removal_time { 0 };
std::map<Key, Value> _dictionary;
};
Item::Iter::Iter(const Item& item):
_current(item._dictionary.cbegin()),
_end(item._dictionary.cend())
{}
bool Item::Iter::next() {
if (_current == _end)
return false;
else {
_result = _current;
++_current;
return true;
}
}
Expected<Value> Item::get(const Key& key) noexcept {
auto it = _dictionary.find(key);
if (it != _dictionary.end()) {
return Expected<Value>(it->second);
}
else {
return Expected<Value>(KEY_NOT_FOUND);
}
}
void Item::set(const Key& key, const Value& value) noexcept {
_dictionary[key] = value;
}
//------------------------------------------------------------------------------
// Collection
//------------------------------------------------------------------------------
//
// Collection of dictionaries with an alias identifier
//
struct Collection {
struct Iter {
using iter_t = typename std::map<Alias,std::unique_ptr<Item>>::const_iterator;
Iter() = default;
Iter(const Collection& c);
const Item* next();
iter_t _current;
iter_t _end;
};
Expected<Item*> insert(const Alias& alias);
bool remove(const Alias& alias);
Item* get(const Alias& alias);
Iter iter() { return Iter(*this); }
// doesn't need to be very efficient
std::map<Alias, std::unique_ptr<Item>> _current_items;
std::vector<std::unique_ptr<Item>> _removed_items;
std::mutex mutex;
};
Collection::Iter::Iter(const Collection& col):
_current(col._current_items.cbegin()),
_end(col._current_items.cend())
{}
const Item* Collection::Iter::next() {
if (_current == _end)
return nullptr;
else {
auto result = _current->second.get();
++_current;
return result;
}
}
bool Collection::remove(const Alias& alias) {
auto it = _current_items.find(alias);
if (it == _current_items.end()) {
return false;
}
else {
_current_items.erase(it);
return true;
}
}
Expected<Item*> Collection::insert(const Alias& alias) {
auto it = _current_items.find(alias);
if (it == _current_items.end()) {
auto new_item = new Item(alias);
new_item->insertion_time(std::time(0)); // get current timestamp
_current_items[alias] = std::unique_ptr<Item>(new_item);
return Expected<Item*>(new_item);
}
else {
return Expected<Item*>(ALIAS_ALREADY_EXISTS);
}
}
Item* Collection::get(const Alias& alias) {
auto it = _current_items.find(alias);
if (it == _current_items.end()) {
return nullptr;
}
else {
return it->second.get();
}
}
Collection& collection() {
static Collection collection;
return collection;
}
//------------------------------------------------------------------------------
// MemoryBlock
//------------------------------------------------------------------------------
struct MemoryBlock {
MemoryBlock() = default;
MemoryBlock(const char* begin, const char* end): _begin(begin), _end(end) {}
NumBytes size() const { return _end - _begin; }
const char* begin() const { return _begin; }
const char* end() const { return _end; }
const char* _begin { nullptr };
const char* _end { nullptr };
};
//------------------------------------------------------------------------------
// Request
//------------------------------------------------------------------------------
enum RequestType { REQUEST_NONE=0, REQUEST_INSERT=1, REQUEST_REMOVE=2, REQUEST_GET=3 };
static const char *request_strings[] { "none", "insert", "remove", "get" };
static const int MIN_REQUEST = 1;
static const int MAX_REQUEST = 3;
struct Request {
Request() = default;
Request(RequestType type, const MemoryBlock& params): _type(type), _params(params) {}
RequestType type() const { return _type; }
const char* type_string() const { return request_strings[_type]; }
const MemoryBlock& params() const { return _params; }
RequestType _type { REQUEST_NONE };
MemoryBlock _params;
};
//------------------------------------------------------------------------------
// Token
//------------------------------------------------------------------------------
// This is strongly coupled with the next_token function.
struct Token {
Token() = default;
Token(const char* begin, const char* end, const char* next):
_begin(begin), _end(end), _next(next)
{}
//
// assuming a null terminated string in st
// compare with the string from [_begin,_end)
//
bool operator==(const char* st) const;
Token& lstrip(utf8::CodePoint p); // left strip
const char* begin() const { return _begin; };
const char* end() const { return _end; };
const char* next() const { return _next; };
const char* _begin { nullptr };
const char* _end { nullptr };
const char* _next { nullptr };
};
bool Token::operator==(const char* st) const {
auto i = _begin;
auto j = st;
while (i < _end && *j != 0 && *i == *j) {
++i;
++j;
}
return (*j == 0 && i == _end);
}
Token& Token::lstrip(utf8::CodePoint symbol) {
auto it = _begin;
utf8::Next n;
while ( (n = utf8::next(_begin,_end)) ) {
if (*n == symbol) {
it = n.next();
}
else {
break;
}
}
_begin = it;
return *this;
}
Expected<Token> next_token(const char* begin, const char* end, utf8::CodePoint delim) {
if (begin == end)
return Expected<Token>(NEXT_TOKEN_EMPTY);
auto it = begin;
utf8::Next n;
while ( (n = utf8::next(it,end)) ) {
if (*n == delim) {
return Expected<Token>(Token(begin,it,it+1));
}
else {
it = n.next();
}
}
if (n.done()) {
return Expected<Token>(Token(begin,it,end));
}
else {
return Expected<Token>(UTF8_PARSING_ERROR);
}
}
std::vector<Token> tokenize(const char* begin, const char* end, utf8::CodePoint delim) {
std::vector<Token> tokens;
auto it = begin;
while (true) {
auto et = next_token(it,end,'|');
if (et) {
auto &tok = et.get();
tokens.push_back(tok);
it = tok.next();
}
else {
break;
}
}
return tokens;
}
//------------------------------------------------------------------------------
// parse request
//------------------------------------------------------------------------------
Request parse_request_type(const MemoryBlock& block) {
//
// service request comes as
// <sevice-name>[|<params>]
//
auto et = next_token(block.begin(), block.end(), '|');
if (et) {
auto &t = *et;
for (auto i=MIN_REQUEST;i<=MAX_REQUEST;++i) {
if (t == request_strings[i]) {
return Request( static_cast<RequestType>(i),
MemoryBlock(t.end() == block.end() ? block.end() : t.end()+1, block.end()) );
}
}
}
return Request(REQUEST_NONE, block);
}
using Handler = std::function<void(const MemoryBlock& params, std::ostream& ostream)>;
void write_status_and_statusmsg(std::ostream &os, Status status) {
os << status << '|' << status_messages[status];
}
void none_handler(const MemoryBlock& params, std::ostream& ostream) {
write_status_and_statusmsg(ostream, NOT_IMPLEMENTED);
}
void remove_handler(const MemoryBlock& params, std::ostream& ostream) {
auto tokens = tokenize(params.begin(), params.end(), '|');
// parse alias name
if (tokens.size() == 1) {
auto &col = collection();
std::lock_guard<std::mutex> lock(col.mutex);
auto &tok = tokens.at(0);
auto ok = col.remove(std::string(tok.begin(),tok.end()));
if (ok) {
write_status_and_statusmsg(ostream, OK);
}
else {
write_status_and_statusmsg(ostream, ALIAS_DOESNT_EXIST);
}
}
else {
write_status_and_statusmsg(ostream, REMOVE_REQUEST_INVALID);
}
}
void insert_handler(const MemoryBlock& params, std::ostream& ostream) {
auto tokens = tokenize(params.begin(), params.end(), '|');
// parse alias name
if (tokens.size()) {
auto &col = collection();
std::lock_guard<std::mutex> lock(col.mutex);
auto &token = tokens.at(0);
auto eitem = col.insert(std::string(token.begin(),token.end()));
if (eitem) {
auto item = *eitem;
for (auto i=1;i<tokens.size()-1;i+=2) {
auto &tkey = tokens.at(i);
auto &tval = tokens.at(i+1);
item->set(std::string(tkey.begin(),tkey.end()),
std::string(tval.begin(),tval.end()));
}
write_status_and_statusmsg(ostream, OK);
return;
}
else {
write_status_and_statusmsg(ostream, eitem.status());
return;
}
}
write_status_and_statusmsg(ostream, INSERT_REQUEST_INVALID);
}
void get_handler(const MemoryBlock& params, std::ostream& ostream) {
auto tokens = tokenize(params.begin(), params.end(), '|');
//
// get
// get|latency
//
// return all the current elements of the collection:
//
// alias1|key1_1|value1_1|key1_2|value1_2|...|key1_n|value1_n\n
// alias2|key2_1|value2_1|key2_2|value2_2|...|key2_n|value2_n\n
// ...
// alias2|key2_1|value2_1|key2_2|value2_2|...|key2_n|value2_n\n
//
if (tokens.size() == 0) {
auto &col = collection();
// @todo replace with shared mutex
std::lock_guard<std::mutex> lock(col.mutex);
ostream << OK << '|';
auto iter = collection().iter();
const Item* item = nullptr;
while( (item = iter.next())) {
ostream << item->alias();
auto iter_dict = item->iter();
while (iter_dict.next()) {
ostream << '|' << iter_dict.key() << '|' << iter_dict.value();
}
ostream << '\n';
}
}
else if (tokens.size() == 1) {
auto &col = collection();
// @todo replace with shared mutex
std::lock_guard<std::mutex> lock(col.mutex);
auto alias = tokens.at(0);
auto item = col.get(std::string(alias.begin(),alias.end()));
if (item) {
ostream << OK << '|';
ostream << item->alias();
auto iter_dict = item->iter();
while (iter_dict.next()) {
ostream << '|' << iter_dict.key() << '|' << iter_dict.value();
}
ostream << '\n';
return;
}
else {
write_status_and_statusmsg(ostream,ALIAS_DOESNT_EXIST);
return;
}
}
else {
write_status_and_statusmsg(ostream,GET_REQUEST_INVALID);
}
}
std::vector<Handler> _handlers { none_handler, insert_handler, remove_handler, get_handler };
// worker thread to process requests in "parallel"
void worker(int worker_id)
{
auto socket = nn_socket(AF_SP, NN_REP);
assert(socket>= 0);
auto endpoint = nn_connect(socket, "inproc://test");
assert(endpoint >= 0);
char buf [1024*1024]; // 1M per thread (don't expect messages larger than 1M)
std::stringstream ss;
while (1) {
auto received_bytes = nn_recv (socket, buf, sizeof(buf), 0);
assert(received_bytes >= 0);
// parse reqeuest
auto request = parse_request_type(MemoryBlock(buf,buf + received_bytes));
//
// @todo: to avoid copying...
// move the back-end to a custom implementation
//
ss.str("");
ss.clear();
std::cerr << "[" << worker_id << "] received request '" << std::string(buf,buf+received_bytes) << "' ---> " << request.type_string() << std::endl;
// process request
_handlers[request.type()](request.params(), ss);
// inneficient!!
auto st = ss.str();
std::cerr << "[" << worker_id << "] response: '" << st << "'" << std::endl;
auto sent_bytes = nn_send(socket, st.c_str(), st.length(), 0);
assert(sent_bytes == st.length());
}
nn_shutdown(socket,endpoint);
}
// redirect requests to worker threads
int main(int argc, char** argv) {
int port = 29999;
if (argc > 1) {
try {
port = std::stoi(argv[1]);
}
catch(...) {
assert(0 && "invalid port number");
}
}
std::stringstream ss;
ss << "tcp://127.0.0.1:" << port;
auto server = ss.str();
auto frontend_socket = nn_socket(AF_SP_RAW, NN_REP);
assert(frontend_socket >= 0);
int option = 0;
nn_setsockopt(frontend_socket,NN_SOL_SOCKET,NN_IPV4ONLY,&option,sizeof(option));
auto frontend_endpoint = nn_bind(frontend_socket, server.c_str());
assert(frontend_endpoint >= 0);
auto backend_socket = nn_socket(AF_SP_RAW, NN_REQ);
assert(backend_socket >= 0);
auto backend_endpoint = nn_bind(backend_socket, "inproc://test");
assert(backend_endpoint >= 0);
// start three worker threads
std::thread t1(worker, 1);
std::thread t2(worker, 2);
std::thread t3(worker, 3);
std::string version = "0.0.1-2015.11.10";
std::cerr << "nanocube-registry v." << version << std::endl;
std::cerr << "Listening on port " << port << "..." << std::endl;
auto exit_status = nn_device(frontend_socket, backend_socket);
nn_shutdown(frontend_socket,frontend_endpoint);
nn_shutdown(backend_socket,backend_endpoint);
return 0;
}
binding to *:port instead of 127.0.0.1:port
#include <ctime>
#include <iostream>
#include <thread>
#include <functional>
#include <vector>
#include <cassert>
#include <map>
#include <string>
#include <sstream>
#include <mutex>
// nanomsg for tcp communication
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>
// characters
#include "utf8.hh"
using Timestamp = std::time_t;
using Alias = std::string;
using Key = std::string;
using Value = std::string;
using NumBytes = std::uint64_t;
//------------------------------------------------------------------------------
// Status
//------------------------------------------------------------------------------
enum Status {
OK=0,
ALIAS_ALREADY_EXISTS=1,
ALIAS_DOESNT_EXIST=2,
UTF8_PARSING_ERROR=3,
KEY_NOT_FOUND=4,
NOT_IMPLEMENTED=5,
NEXT_TOKEN_EMPTY=6,
INSERT_REQUEST_INVALID=7,
GET_REQUEST_INVALID=8,
REMOVE_REQUEST_INVALID=9
};
static const char *status_messages[] {
"OK",
"ALIAS_ALREADY_EXISTS",
"ALIAS_DOESNT_EXIST"
"UTF8_PARSING_ERROR",
"KEY_NOT_FOUND",
"NOT_IMPLEMENTED",
"NEXT_TOKEN_EMPTY",
"INSERT_REQUEST_INVALID",
"GET_REQUEST_INVALID",
"REMOVE_REQUEST_INVALID"
};
//------------------------------------------------------------------------------
// Entry
//------------------------------------------------------------------------------
template<typename T>
struct Expected {
Expected() = default;
Expected(T object): _object(object), _status(OK) {}
Expected(Status not_ok_status): _status(not_ok_status) { assert(not_ok_status!=OK); }
Status status () const { return _status; }
T& get () { assert(status() == OK); return _object; }
T& operator *() { return get(); }
operator bool() const { return _status == OK; }
T _object;
Status _status;
};
//------------------------------------------------------------------------------
// Item
//------------------------------------------------------------------------------
struct Item {
struct Iter {
using iter_t = typename std::map<Key,Value>::const_iterator;
Iter() = default;
Iter(const Item& i);
bool next();
const Key& key() const { return _result->first; }
const Value& value() const { return _result->second; }
iter_t _result;
iter_t _current;
iter_t _end;
};
Item() = default;
Item(const Alias& alias): _alias(alias) {}
Timestamp insertion_time() const { return _insertion_time; }
Timestamp removal_time() const { return _removal_time; }
Item& insertion_time(Timestamp t) { _insertion_time=t; return *this; }
Item& removal_time(Timestamp t) { _removal_time=t; return *this; }
Expected<Value> get(const Key& key) noexcept;
void set(const Key& key, const Value& value) noexcept;
Iter iter() const { return Iter(*this); }
const Alias& alias() const { return _alias; }
Alias _alias;
Timestamp _insertion_time { 0 }; // we assume 0 is undefined for now
Timestamp _removal_time { 0 };
std::map<Key, Value> _dictionary;
};
Item::Iter::Iter(const Item& item):
_current(item._dictionary.cbegin()),
_end(item._dictionary.cend())
{}
bool Item::Iter::next() {
if (_current == _end)
return false;
else {
_result = _current;
++_current;
return true;
}
}
Expected<Value> Item::get(const Key& key) noexcept {
auto it = _dictionary.find(key);
if (it != _dictionary.end()) {
return Expected<Value>(it->second);
}
else {
return Expected<Value>(KEY_NOT_FOUND);
}
}
void Item::set(const Key& key, const Value& value) noexcept {
_dictionary[key] = value;
}
//------------------------------------------------------------------------------
// Collection
//------------------------------------------------------------------------------
//
// Collection of dictionaries with an alias identifier
//
struct Collection {
struct Iter {
using iter_t = typename std::map<Alias,std::unique_ptr<Item>>::const_iterator;
Iter() = default;
Iter(const Collection& c);
const Item* next();
iter_t _current;
iter_t _end;
};
Expected<Item*> insert(const Alias& alias);
bool remove(const Alias& alias);
Item* get(const Alias& alias);
Iter iter() { return Iter(*this); }
// doesn't need to be very efficient
std::map<Alias, std::unique_ptr<Item>> _current_items;
std::vector<std::unique_ptr<Item>> _removed_items;
std::mutex mutex;
};
Collection::Iter::Iter(const Collection& col):
_current(col._current_items.cbegin()),
_end(col._current_items.cend())
{}
const Item* Collection::Iter::next() {
if (_current == _end)
return nullptr;
else {
auto result = _current->second.get();
++_current;
return result;
}
}
bool Collection::remove(const Alias& alias) {
auto it = _current_items.find(alias);
if (it == _current_items.end()) {
return false;
}
else {
_current_items.erase(it);
return true;
}
}
Expected<Item*> Collection::insert(const Alias& alias) {
auto it = _current_items.find(alias);
if (it == _current_items.end()) {
auto new_item = new Item(alias);
new_item->insertion_time(std::time(0)); // get current timestamp
_current_items[alias] = std::unique_ptr<Item>(new_item);
return Expected<Item*>(new_item);
}
else {
return Expected<Item*>(ALIAS_ALREADY_EXISTS);
}
}
Item* Collection::get(const Alias& alias) {
auto it = _current_items.find(alias);
if (it == _current_items.end()) {
return nullptr;
}
else {
return it->second.get();
}
}
Collection& collection() {
static Collection collection;
return collection;
}
//------------------------------------------------------------------------------
// MemoryBlock
//------------------------------------------------------------------------------
struct MemoryBlock {
MemoryBlock() = default;
MemoryBlock(const char* begin, const char* end): _begin(begin), _end(end) {}
NumBytes size() const { return _end - _begin; }
const char* begin() const { return _begin; }
const char* end() const { return _end; }
const char* _begin { nullptr };
const char* _end { nullptr };
};
//------------------------------------------------------------------------------
// Request
//------------------------------------------------------------------------------
enum RequestType { REQUEST_NONE=0, REQUEST_INSERT=1, REQUEST_REMOVE=2, REQUEST_GET=3 };
static const char *request_strings[] { "none", "insert", "remove", "get" };
static const int MIN_REQUEST = 1;
static const int MAX_REQUEST = 3;
struct Request {
Request() = default;
Request(RequestType type, const MemoryBlock& params): _type(type), _params(params) {}
RequestType type() const { return _type; }
const char* type_string() const { return request_strings[_type]; }
const MemoryBlock& params() const { return _params; }
RequestType _type { REQUEST_NONE };
MemoryBlock _params;
};
//------------------------------------------------------------------------------
// Token
//------------------------------------------------------------------------------
// This is strongly coupled with the next_token function.
struct Token {
Token() = default;
Token(const char* begin, const char* end, const char* next):
_begin(begin), _end(end), _next(next)
{}
//
// assuming a null terminated string in st
// compare with the string from [_begin,_end)
//
bool operator==(const char* st) const;
Token& lstrip(utf8::CodePoint p); // left strip
const char* begin() const { return _begin; };
const char* end() const { return _end; };
const char* next() const { return _next; };
const char* _begin { nullptr };
const char* _end { nullptr };
const char* _next { nullptr };
};
bool Token::operator==(const char* st) const {
auto i = _begin;
auto j = st;
while (i < _end && *j != 0 && *i == *j) {
++i;
++j;
}
return (*j == 0 && i == _end);
}
Token& Token::lstrip(utf8::CodePoint symbol) {
auto it = _begin;
utf8::Next n;
while ( (n = utf8::next(_begin,_end)) ) {
if (*n == symbol) {
it = n.next();
}
else {
break;
}
}
_begin = it;
return *this;
}
Expected<Token> next_token(const char* begin, const char* end, utf8::CodePoint delim) {
if (begin == end)
return Expected<Token>(NEXT_TOKEN_EMPTY);
auto it = begin;
utf8::Next n;
while ( (n = utf8::next(it,end)) ) {
if (*n == delim) {
return Expected<Token>(Token(begin,it,it+1));
}
else {
it = n.next();
}
}
if (n.done()) {
return Expected<Token>(Token(begin,it,end));
}
else {
return Expected<Token>(UTF8_PARSING_ERROR);
}
}
std::vector<Token> tokenize(const char* begin, const char* end, utf8::CodePoint delim) {
std::vector<Token> tokens;
auto it = begin;
while (true) {
auto et = next_token(it,end,'|');
if (et) {
auto &tok = et.get();
tokens.push_back(tok);
it = tok.next();
}
else {
break;
}
}
return tokens;
}
//------------------------------------------------------------------------------
// parse request
//------------------------------------------------------------------------------
Request parse_request_type(const MemoryBlock& block) {
//
// service request comes as
// <sevice-name>[|<params>]
//
auto et = next_token(block.begin(), block.end(), '|');
if (et) {
auto &t = *et;
for (auto i=MIN_REQUEST;i<=MAX_REQUEST;++i) {
if (t == request_strings[i]) {
return Request( static_cast<RequestType>(i),
MemoryBlock(t.end() == block.end() ? block.end() : t.end()+1, block.end()) );
}
}
}
return Request(REQUEST_NONE, block);
}
using Handler = std::function<void(const MemoryBlock& params, std::ostream& ostream)>;
void write_status_and_statusmsg(std::ostream &os, Status status) {
os << status << '|' << status_messages[status];
}
void none_handler(const MemoryBlock& params, std::ostream& ostream) {
write_status_and_statusmsg(ostream, NOT_IMPLEMENTED);
}
void remove_handler(const MemoryBlock& params, std::ostream& ostream) {
auto tokens = tokenize(params.begin(), params.end(), '|');
// parse alias name
if (tokens.size() == 1) {
auto &col = collection();
std::lock_guard<std::mutex> lock(col.mutex);
auto &tok = tokens.at(0);
auto ok = col.remove(std::string(tok.begin(),tok.end()));
if (ok) {
write_status_and_statusmsg(ostream, OK);
}
else {
write_status_and_statusmsg(ostream, ALIAS_DOESNT_EXIST);
}
}
else {
write_status_and_statusmsg(ostream, REMOVE_REQUEST_INVALID);
}
}
void insert_handler(const MemoryBlock& params, std::ostream& ostream) {
auto tokens = tokenize(params.begin(), params.end(), '|');
// parse alias name
if (tokens.size()) {
auto &col = collection();
std::lock_guard<std::mutex> lock(col.mutex);
auto &token = tokens.at(0);
auto eitem = col.insert(std::string(token.begin(),token.end()));
if (eitem) {
auto item = *eitem;
for (auto i=1;i<tokens.size()-1;i+=2) {
auto &tkey = tokens.at(i);
auto &tval = tokens.at(i+1);
item->set(std::string(tkey.begin(),tkey.end()),
std::string(tval.begin(),tval.end()));
}
write_status_and_statusmsg(ostream, OK);
return;
}
else {
write_status_and_statusmsg(ostream, eitem.status());
return;
}
}
write_status_and_statusmsg(ostream, INSERT_REQUEST_INVALID);
}
void get_handler(const MemoryBlock& params, std::ostream& ostream) {
auto tokens = tokenize(params.begin(), params.end(), '|');
//
// get
// get|latency
//
// return all the current elements of the collection:
//
// alias1|key1_1|value1_1|key1_2|value1_2|...|key1_n|value1_n\n
// alias2|key2_1|value2_1|key2_2|value2_2|...|key2_n|value2_n\n
// ...
// alias2|key2_1|value2_1|key2_2|value2_2|...|key2_n|value2_n\n
//
if (tokens.size() == 0) {
auto &col = collection();
// @todo replace with shared mutex
std::lock_guard<std::mutex> lock(col.mutex);
ostream << OK << '|';
auto iter = collection().iter();
const Item* item = nullptr;
while( (item = iter.next())) {
ostream << item->alias();
auto iter_dict = item->iter();
while (iter_dict.next()) {
ostream << '|' << iter_dict.key() << '|' << iter_dict.value();
}
ostream << '\n';
}
}
else if (tokens.size() == 1) {
auto &col = collection();
// @todo replace with shared mutex
std::lock_guard<std::mutex> lock(col.mutex);
auto alias = tokens.at(0);
auto item = col.get(std::string(alias.begin(),alias.end()));
if (item) {
ostream << OK << '|';
ostream << item->alias();
auto iter_dict = item->iter();
while (iter_dict.next()) {
ostream << '|' << iter_dict.key() << '|' << iter_dict.value();
}
ostream << '\n';
return;
}
else {
write_status_and_statusmsg(ostream,ALIAS_DOESNT_EXIST);
return;
}
}
else {
write_status_and_statusmsg(ostream,GET_REQUEST_INVALID);
}
}
std::vector<Handler> _handlers { none_handler, insert_handler, remove_handler, get_handler };
// worker thread to process requests in "parallel"
void worker(int worker_id)
{
auto socket = nn_socket(AF_SP, NN_REP);
assert(socket>= 0);
auto endpoint = nn_connect(socket, "inproc://test");
assert(endpoint >= 0);
char buf [1024*1024]; // 1M per thread (don't expect messages larger than 1M)
std::stringstream ss;
while (1) {
auto received_bytes = nn_recv (socket, buf, sizeof(buf), 0);
assert(received_bytes >= 0);
// parse reqeuest
auto request = parse_request_type(MemoryBlock(buf,buf + received_bytes));
//
// @todo: to avoid copying...
// move the back-end to a custom implementation
//
ss.str("");
ss.clear();
std::cerr << "[" << worker_id << "] received request '" << std::string(buf,buf+received_bytes) << "' ---> " << request.type_string() << std::endl;
// process request
_handlers[request.type()](request.params(), ss);
// inneficient!!
auto st = ss.str();
std::cerr << "[" << worker_id << "] response: '" << st << "'" << std::endl;
auto sent_bytes = nn_send(socket, st.c_str(), st.length(), 0);
assert(sent_bytes == st.length());
}
nn_shutdown(socket,endpoint);
}
// redirect requests to worker threads
int main(int argc, char** argv) {
int port = 29999;
if (argc > 1) {
try {
port = std::stoi(argv[1]);
}
catch(...) {
assert(0 && "invalid port number");
}
}
std::stringstream ss;
ss << "tcp://*:" << port;
auto server = ss.str();
auto frontend_socket = nn_socket(AF_SP_RAW, NN_REP);
assert(frontend_socket >= 0);
auto frontend_endpoint = nn_bind(frontend_socket, server.c_str());
assert(frontend_endpoint >= 0);
auto backend_socket = nn_socket(AF_SP_RAW, NN_REQ);
assert(backend_socket >= 0);
auto backend_endpoint = nn_bind(backend_socket, "inproc://test");
assert(backend_endpoint >= 0);
// start three worker threads
std::thread t1(worker, 1);
std::thread t2(worker, 2);
std::thread t3(worker, 3);
std::string version = "0.0.1-2015.11.10";
std::cerr << "nanocube-registry v." << version << std::endl;
std::cerr << "Listening on port " << port << "..." << std::endl;
auto exit_status = nn_device(frontend_socket, backend_socket);
nn_shutdown(frontend_socket,frontend_endpoint);
nn_shutdown(backend_socket,backend_endpoint);
return 0;
}
|
/*
* AbstractView_EventConsumption.cpp
*
* Copyright (C) 2020 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "mmcore/view/AbstractView_EventConsumption.h"
#include "Framebuffer_Events.h"
#include "KeyboardMouse_Events.h"
#include "Window_Events.h"
#include <chrono>
namespace megamol {
namespace core {
namespace view {
using namespace megamol::frontend_resources;
// shorthand notation to unpack a FrontendResource to some type.
// if the type is present in the resource is made available as an 'events' variable in the if statemtnt.
// note that when using this macro there is no visible opening bracket { for the if statements because it is hidden inside the macro
#define GET_RESOURCE(TYPENAME) \
{ \
TYPENAME const& events = resource.getResource<TYPENAME>();
void view_consume_keyboard_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
GET_RESOURCE(KeyboardEvents)//{
for (auto& e : events.key_events)
view.OnKey(std::get<0>(e), std::get<1>(e), std::get<2>(e));
for (auto& e : events.codepoint_events)
view.OnChar(e);
}
}
void view_consume_mouse_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
GET_RESOURCE(MouseEvents)//{
for (auto& e : events.buttons_events)
view.OnMouseButton(std::get<0>(e), std::get<1>(e), std::get<2>(e));
for (auto& e : events.position_events)
view.OnMouseMove(std::get<0>(e), std::get<1>(e));
for (auto& e : events.scroll_events)
view.OnMouseScroll(std::get<0>(e), std::get<1>(e));
//for (auto& e: events.enter_events) {}
}
}
void view_consume_window_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
GET_RESOURCE(WindowEvents)//{
events.is_focused_events;
}
}
// this is a weird place to measure passed program time, but we do it here so we satisfy _mmcRenderViewContext and nobody else needs to know
static std::chrono::high_resolution_clock::time_point render_view_context_timer_start;
void view_poke_rendering(AbstractView& view, megamol::frontend_resources::RenderInput const& render_input, megamol::frontend_resources::ImageWrapper& result_image) {
static bool started_timer = false;
if (!started_timer) {
render_view_context_timer_start = std::chrono::high_resolution_clock::now();
started_timer = true;
}
const auto render = [&]() {
const double instanceTime = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - render_view_context_timer_start)
.count() / static_cast<double>(1000);
const double time = view.DefaultTime(instanceTime);
result_image = view.Render(time, instanceTime);
};
render();
}
std::vector<std::string> get_view_runtime_resources_requests() {
return {"ViewRenderInput", "KeyboardEvents", "MouseEvents", "WindowEvents"};
}
bool view_rendering_execution(
void* module_ptr
, std::vector<megamol::frontend::FrontendResource> const& resources
, megamol::frontend_resources::ImageWrapper& result_image
) {
megamol::core::view::AbstractView* view_ptr =
dynamic_cast<megamol::core::view::AbstractView*>(static_cast<megamol::core::Module*>(module_ptr));
if (!view_ptr) {
std::cout << "error. module is not a view module. could not use as rendering entry point." << std::endl;
return false;
}
megamol::core::view::AbstractView& view = *view_ptr;
// resources are in order of initial requests from get_view_runtime_resources_requests()
megamol::core::view::view_consume_keyboard_events(view, resources[1]);
megamol::core::view::view_consume_mouse_events(view, resources[2]);
megamol::core::view::view_consume_window_events(view, resources[3]);
megamol::core::view::view_poke_rendering(view, resources[0].getResource<megamol::frontend_resources::RenderInput>(), result_image);
return true;
}
} /* end namespace view */
} /* end namespace core */
} /* end namespace megamol */
AbstractView EventConsumption uses RenderInput resolution
/*
* AbstractView_EventConsumption.cpp
*
* Copyright (C) 2020 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "mmcore/view/AbstractView_EventConsumption.h"
#include "Framebuffer_Events.h"
#include "KeyboardMouse_Events.h"
#include "Window_Events.h"
#include <chrono>
namespace megamol {
namespace core {
namespace view {
using namespace megamol::frontend_resources;
// shorthand notation to unpack a FrontendResource to some type.
// if the type is present in the resource is made available as an 'events' variable in the if statemtnt.
// note that when using this macro there is no visible opening bracket { for the if statements because it is hidden inside the macro
#define GET_RESOURCE(TYPENAME) \
{ \
TYPENAME const& events = resource.getResource<TYPENAME>();
void view_consume_keyboard_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
GET_RESOURCE(KeyboardEvents)//{
for (auto& e : events.key_events)
view.OnKey(std::get<0>(e), std::get<1>(e), std::get<2>(e));
for (auto& e : events.codepoint_events)
view.OnChar(e);
}
}
void view_consume_mouse_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
GET_RESOURCE(MouseEvents)//{
for (auto& e : events.buttons_events)
view.OnMouseButton(std::get<0>(e), std::get<1>(e), std::get<2>(e));
for (auto& e : events.position_events)
view.OnMouseMove(std::get<0>(e), std::get<1>(e));
for (auto& e : events.scroll_events)
view.OnMouseScroll(std::get<0>(e), std::get<1>(e));
//for (auto& e: events.enter_events) {}
}
}
void view_consume_window_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
GET_RESOURCE(WindowEvents)//{
events.is_focused_events;
}
}
// this is a weird place to measure passed program time, but we do it here so we satisfy _mmcRenderViewContext and nobody else needs to know
static std::chrono::high_resolution_clock::time_point render_view_context_timer_start;
void view_poke_rendering(AbstractView& view, megamol::frontend_resources::RenderInput const& render_input, megamol::frontend_resources::ImageWrapper& result_image) {
static bool started_timer = false;
if (!started_timer) {
render_view_context_timer_start = std::chrono::high_resolution_clock::now();
started_timer = true;
}
const double instanceTime_sec = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - render_view_context_timer_start)
.count() / static_cast<double>(1000);
const double time_sec = view.DefaultTime(instanceTime_sec);
// copy render inputs from frontend so we can update time
auto renderinput = render_input;
renderinput.instanceTime_sec = instanceTime_sec;
renderinput.time_sec = time_sec;
view.Resize(renderinput.local_view_framebuffer_resolution.x, renderinput.local_view_framebuffer_resolution.y);
result_image = view.Render(renderinput.time_sec, renderinput.instanceTime_sec);
}
std::vector<std::string> get_view_runtime_resources_requests() {
return {"ViewRenderInput", "KeyboardEvents", "MouseEvents", "WindowEvents"};
}
bool view_rendering_execution(
void* module_ptr
, std::vector<megamol::frontend::FrontendResource> const& resources
, megamol::frontend_resources::ImageWrapper& result_image
) {
megamol::core::view::AbstractView* view_ptr =
dynamic_cast<megamol::core::view::AbstractView*>(static_cast<megamol::core::Module*>(module_ptr));
if (!view_ptr) {
std::cout << "error. module is not a view module. could not use as rendering entry point." << std::endl;
return false;
}
megamol::core::view::AbstractView& view = *view_ptr;
// resources are in order of initial requests from get_view_runtime_resources_requests()
megamol::core::view::view_consume_keyboard_events(view, resources[1]);
megamol::core::view::view_consume_mouse_events(view, resources[2]);
megamol::core::view::view_consume_window_events(view, resources[3]);
megamol::core::view::view_poke_rendering(view, resources[0].getResource<megamol::frontend_resources::RenderInput>(), result_image);
return true;
}
} /* end namespace view */
} /* end namespace core */
} /* end namespace megamol */
|
#include "slash/include/slash_string.h"
#include "slash/include/env.h"
#include "zgw_store.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <glog/logging.h>
namespace zgwstore {
ZgwStore::ZgwStore(const std::string& zp_table,const std::string& lock_name,
const int32_t lock_ttl, const std::string& redis_passwd) :
zp_table_(zp_table), zp_cli_(nullptr), redis_cli_(nullptr), redis_ip_(""),
redis_port_(-1), lock_name_(lock_name), lock_ttl_(lock_ttl),
redis_passwd_(redis_passwd), redis_error_(false) {
};
ZgwStore::~ZgwStore() {
if (zp_cli_ != nullptr) {
delete zp_cli_;
}
if (redis_cli_ != nullptr) {
redisFree(redis_cli_);
}
}
Status ZgwStore::Open(const std::vector<std::string>& zp_addrs,
const std::string& redis_addr, const std::string& zp_table,
const std::string& lock_name, const int32_t lock_ttl,
const std::string& redis_passwd, ZgwStore** store) {
*store = nullptr;
/*
* Connect to zeppelin
*/
if (zp_addrs.empty()) {
return Status::InvalidArgument("Invalid zeppelin addresses");
}
std::string t_ip;
int t_port = 0;
Status s;
libzp::Options zp_option;
for (auto& addr : zp_addrs) {
if (!slash::ParseIpPortString(addr, t_ip, t_port)) {
return Status::InvalidArgument("Invalid zeppelin address");
}
zp_option.meta_addr.push_back(libzp::Node(t_ip, t_port));
}
libzp::Cluster* zp_cli = new libzp::Cluster(zp_option);
s = zp_cli->Connect();
if (!s.ok()) {
delete zp_cli;
return Status::IOError("Failed to connect to zeppelin");
}
s = zp_cli->CreateTable(zp_table, 64);
if (!s.ok() && s.IsCorruption() &&
s.ToString() != "Corruption: Corruption: Already Exist") {
delete zp_cli;
return s;
}
/*
* Connect to redis
*/
if (!slash::ParseIpPortString(redis_addr, t_ip, t_port)) {
delete zp_cli;
return Status::InvalidArgument("Invalid zeppelin address");
}
redisContext* redis_cli;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
redis_cli = redisConnectWithTimeout(t_ip.c_str(), t_port, timeout);
if (redis_cli == NULL || redis_cli->err) {
delete zp_cli;
if (redis_cli) {
redisFree(redis_cli);
return Status::IOError("Failed to connect to redis");
} else {
return Status::Corruption("Connection error: can't allocate redis context");
}
}
if (!redis_passwd.empty()) {
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli,
"AUTH %s", redis_passwd.c_str()));
if (reply == NULL) {
delete zp_cli;
return Status::IOError("Failed to auth to redis");
}
if (std::string(reply->str) != "OK") {
freeReplyObject(reply);
delete zp_cli;
return Status::Corruption("Failed to auth to redis");
}
freeReplyObject(reply);
}
*store = new ZgwStore(zp_table, lock_name, lock_ttl, redis_passwd);
(*store)->InstallClients(zp_cli, redis_cli);
(*store)->set_redis_ip(t_ip);
(*store)->set_redis_port(t_port);
return Status::OK();
}
void ZgwStore::InstallClients(libzp::Cluster* zp_cli, redisContext* redis_cli) {
zp_cli_ = zp_cli;
redis_cli_ = redis_cli;
}
Status ZgwStore::BlockSet(const std::string& block_id, const std::string& block_content) {
return zp_cli_->Set(zp_table_, kZpBlockPrefix + block_id, block_content);
}
Status ZgwStore::BlockGet(const std::string& block_id, std::string* block_content) {
return zp_cli_->Get(zp_table_, kZpBlockPrefix + block_id, block_content);
}
Status ZgwStore::BlockDelete(const std::string& block_id) {
return zp_cli_->Delete(zp_table_, kZpBlockPrefix + block_id);
}
Status ZgwStore::BlockMGet(const std::vector<std::string>& block_ids,
std::map<std::string, std::string>* block_contents) {
std::vector<std::string> ids;
for(auto& id : block_ids) {
ids.push_back(kZpBlockPrefix + id);
}
return zp_cli_->Mget(zp_table_, ids, block_contents);
}
Status ZgwStore::BlockRef(const std::string& block_id) {
// Lock outside
std::string block_ref_s;
int ref;
Status s = zp_cli_->Get(zp_table_, kZpRefPrefix + block_id, &block_ref_s);
if (!s.ok()) {
if (s.IsNotFound()) {
ref = 0;
} else {
return s;
}
} else {
ref = std::atoi(block_ref_s.c_str());
}
ref++;
block_ref_s.assign(std::to_string(ref));
return zp_cli_->Set(zp_table_, kZpRefPrefix + block_id, block_ref_s);
}
Status ZgwStore::Lock() {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
redisReply *reply;
while (true) {
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SET zgw_lock %s NX PX %lu", lock_name_.c_str(), lock_ttl_));
if (reply == NULL) {
return HandleIOError("Lock");
}
if (reply->type == REDIS_REPLY_STATUS && !strcmp(reply->str, "OK")) {
freeReplyObject(reply);
break;
}
freeReplyObject(reply);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return Status::OK();
}
Status ZgwStore::UnLock() {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
std::string del_cmd = "if redis.call(\"get\", \"zgw_lock\") == \"" + lock_name_ + "\" "
"then "
"return redis.call(\"del\", \"zgw_lock\") "
"else "
"return 0 "
"end ";
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"EVAL %s %d", del_cmd.c_str(), 0));
if (reply == NULL) {
return HandleIOError("UnLock");
}
if (reply->integer == 1) {
// UnLock Success
} else if (reply->integer == 0) {
// The zgw_lock is held by other clients
// std::cout << "reply-int" << std::endl;
// redisReply* t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "GET zgw_lock"));
// std::cout <<t_reply->type << std::endl;
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::AddUser(const User& user, const bool override) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
s = Lock();
if (!s.ok()) {
return s;
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s %s", kZgwUserList.c_str(), user.display_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddUser::SISMEMBER ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 1 && !override) {
return HandleLogicError("User Already Exist", reply, true);
}
freeReplyObject(reply);
/*
* 3. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "DEL %s%s",
kZgwUserPrefix.c_str(), user.display_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 4. HMSET
*/
std::string hmset_cmd = "HMSET " + kZgwUserPrefix + user.display_name;
hmset_cmd += (" uid " + user.user_id);
hmset_cmd += (" name " + user.display_name);
for (auto& iter : user.key_pairs) {
hmset_cmd += (" " + iter.first + " " + iter.second);
}
reply = static_cast<redisReply*>(redisCommand(redis_cli_, hmset_cmd.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::HMSET");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddUser::HMSET ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_STATUS);
freeReplyObject(reply);
/*
* 4. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s %s", kZgwUserList.c_str(), user.display_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddUser::SADD ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0 && !override) {
return HandleLogicError("User Already Exist", reply, true);
}
freeReplyObject(reply);
/*
* 5. UnLock
*/
s = UnLock();
return s;
}
Status ZgwStore::ListUsers(std::vector<User>* users) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
users->clear();
/*
* 1. Get user list
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s", kZgwUserList.c_str()));
if (reply == NULL) {
return HandleIOError("ListUsers::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListUser::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through users to HGETALL
*/
redisReply* t_reply;
for (unsigned int i = 0; i < reply->elements; i++) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwUserPrefix.c_str(), reply->element[i]->str));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("ListUsers::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("ListUser::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
freeReplyObject(reply);
return HandleLogicError("ListUser::HGETALL: elements % 2 != 0", t_reply, false);
}
users->push_back(GenUserFromReply(t_reply));
freeReplyObject(t_reply);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::AddBucket(const Bucket& bucket, const bool need_lock,
const bool override) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), bucket.owner.c_str(),
bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::SISMEMBER ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 1 && !override) {
return HandleLogicError("Bucket Already Exist", reply, need_lock);
}
freeReplyObject(reply);
/*
* 3. EXISTS
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "EXISTS %s%s",
kZgwBucketPrefix.c_str(), bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::EXISTS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::EXISTS ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 1) {
return HandleLogicError("Bucket Already Exist [GLOBAL]", reply, need_lock);
}
assert(reply->integer == 0);
freeReplyObject(reply);
/*
* 4. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "DEL %s%s",
kZgwBucketPrefix.c_str(), bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 5. HMSET
*/
std::string hmset_cmd = "HMSET " + kZgwBucketPrefix + bucket.bucket_name;
hmset_cmd += (" name " + bucket.bucket_name);
hmset_cmd += " ctime %llu";
hmset_cmd += (" owner " + bucket.owner);
hmset_cmd += (" acl " + bucket.acl);
hmset_cmd += (" loc " + bucket.location);
hmset_cmd += " vol %lld";
hmset_cmd += " uvol %lld";
reply = static_cast<redisReply*>(redisCommand(redis_cli_, hmset_cmd.c_str(), bucket.create_time,
bucket.volumn, bucket.uploading_volumn));
if (reply == NULL) {
return HandleIOError("AddBucket::HMSET");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::HMSET ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_STATUS);
freeReplyObject(reply);
/*
* 6. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s%s %s", kZgwBucketListPrefix.c_str(), bucket.owner.c_str(),
bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::SADD ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0 && !override) {
return HandleLogicError("Bucket Already Exist", reply, need_lock);
}
freeReplyObject(reply);
/*
* 7. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::GetBucket(const std::string& user_name, const std::string& bucket_name,
Bucket* bucket) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("GetBucket::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetBucket::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* HGETALL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
freeReplyObject(reply);
return HandleIOError("GetBucket::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("GetBucket::HGETALL ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return HandleLogicError("Bucket Not Found", reply, true);
} else if (reply->elements % 2 != 0) {
return HandleLogicError("GetBucket::HGETALL: elements % 2 != 0", reply, false);
}
*bucket = GenBucketFromReply(reply);
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::DeleteBucket(const std::string& user_name, const std::string& bucket_name,
const bool need_lock) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteBucket::SISMEMBER ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesnt Exist", reply, need_lock);
}
freeReplyObject(reply);
/*
* 3. HGET
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGET %s%s vol",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::EXISTS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteBucket::EXISTS ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_STRING);
char* end;
if (std::strtoll(reply->str, &end, 10) != 0) {
return HandleLogicError("Bucket Vol IS NOT 0", reply, need_lock);
}
assert(reply->integer == 0);
freeReplyObject(reply);
/*
* 4. SCARD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SCARD %s%s", kZgwObjectListPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::SCARD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteBucket::SCARD ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer != 0) {
return HandleLogicError("Bucket Non Empty", reply, need_lock);
}
freeReplyObject(reply);
/*
* 5. SREM
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SREM %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::SREM");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 6. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "DEL %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 7. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::ListBuckets(const std::string& user_name, std::vector<Bucket>* buckets) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
buckets->clear();
/*
* 1. Get bucket list
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwBucketListPrefix.c_str(),
user_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListBuckets::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListBuckets::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through buckets to HGETALL
*/
redisReply* t_reply;
for (unsigned int i = 0; i < reply->elements; i++) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwBucketPrefix.c_str(), reply->element[i]->str));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("ListBuckets::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("ListBuckets::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
freeReplyObject(reply);
return HandleLogicError("ListBuckets::HGETALL: elements % 2 != 0", t_reply, false);
}
buckets->push_back(GenBucketFromReply(t_reply));
freeReplyObject(t_reply);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::ListBucketsName(const std::string& user_name, std::vector<std::string>* buckets_name) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
buckets_name->clear();
/*
* 1. Get bucket list
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwBucketListPrefix.c_str(),
user_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListBucketsName::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListBucketsName::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through buckets to push_back
*/
for (unsigned int i = 0; i < reply->elements; i++) {
buckets_name->push_back(reply->element[i]->str);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::MGetBuckets(const std::string& user_name, const std::vector<std::string> buckets_name,
std::vector<Bucket>* buckets) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
buckets->clear();
/*
* 1. Iterate through buckets to HGETALL
*/
redisReply* t_reply;
for (auto& bucket_name : buckets_name) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (t_reply == NULL) {
return HandleIOError("MGetBuckets::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("MGetBuckets::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
return HandleLogicError("MGetBuckets::HGETALL: elements % 2 != 0", t_reply, false);
}
buckets->push_back(GenBucketFromReply(t_reply));
freeReplyObject(t_reply);
}
return Status::OK();
}
Status ZgwStore::AllocateId(const std::string& user_name, const std::string& bucket_name,
const std::string& object_name, const int32_t block_nums, uint64_t* tail_id) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
s = Lock();
if (!s.ok()) {
return s;
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AllocateId::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::SISMEMBER ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, true);
}
freeReplyObject(reply);
/*
* 3. EXISTS
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "EXISTS %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AllocateId::EXISTS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::EXISTS ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket NOT Exists", reply, true);
}
assert(reply->integer == 1);
/*
* 4. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s%s %s%s", kZgwObjectListPrefix.c_str(), bucket_name.c_str(),
kZgwTempObjectNamePrefix.c_str(), object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AllocateId::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::SADD ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 5. INCRBY
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"INCRBY %s %d", kZgwIdGen.c_str(), block_nums));
if (reply == NULL) {
return HandleIOError("AllocateId::INCRBY");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::INCRBY ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
*tail_id = reply->integer;
freeReplyObject(reply);
/*
* 6. UnLock
*/
s = UnLock();
return s;
}
Status ZgwStore::AddObject(const Object& object, const bool need_lock) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. HGETALL
*/
redisReply *reply;
int64_t old_size = 0;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), object.bucket_name.c_str(),
object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::HGETALL ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements != 0) {
Object t_object = GenObjectFromReply(reply);
old_size = t_object.size;
redisReply* t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"LPUSH %s %s", kZgwDeletedList.c_str(), std::string(t_object.data_block +
"/" + std::to_string(slash::NowMicros())).c_str()));
if (t_reply == NULL) {
return HandleIOError("AddObject::LPUSH");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::LPUSH ret: " + std::string(reply->str), reply, need_lock);
}
assert(t_reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(t_reply);
}
freeReplyObject(reply);
/*
* 3. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"DEL %s%s_%s", kZgwObjectPrefix.c_str(), object.bucket_name.c_str(),
object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 4. HMSET
*/
std::string hmset_cmd = "HMSET " + kZgwObjectPrefix + object.bucket_name +
"_" + object.object_name;
hmset_cmd += (" bname " + object.bucket_name);
hmset_cmd += (" oname " + object.object_name);
hmset_cmd += (" etag " + object.etag);
hmset_cmd += " size %lld";
hmset_cmd += (" owner " + object.owner);
hmset_cmd += " lm %llu";
hmset_cmd += " class %d";
hmset_cmd += (" acl " + object.acl);
hmset_cmd += (" id " + object.upload_id);
hmset_cmd += (" block " + object.data_block);
reply = static_cast<redisReply*>(redisCommand(redis_cli_, hmset_cmd.c_str(), object.size,
object.last_modified, object.storage_class));
if (reply == NULL) {
return HandleIOError("AddObject::HMSET");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::HMSET ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_STATUS);
freeReplyObject(reply);
/*
* 5. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s%s %s", kZgwObjectListPrefix.c_str(), object.bucket_name.c_str(),
object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::SADD ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
// object already exists, update
}
freeReplyObject(reply);
/*
* 6. HINCRBY
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HINCRBY %s%s vol %lld", kZgwBucketPrefix.c_str(), object.bucket_name.c_str(),
object.size - old_size));
if (reply == NULL) {
return HandleIOError("AddObject::HINCRBY");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::HINCRBY ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
/*
* 7. SREM
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SREM %s%s %s%s", kZgwObjectListPrefix.c_str(), object.bucket_name.c_str(),
kZgwTempObjectNamePrefix.c_str(), object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::SREM");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 8. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::GetObject(const std::string& user_name, const std::string& bucket_name,
const std::string& object_name, Object* object) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("GetObject::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetObject::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* 2. HGETALL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("GetObject::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetObject::HGETALL ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return HandleLogicError("Object Not Found", reply, true);
} else if (reply->elements % 2 != 0) {
return HandleLogicError("GetObject::HGETALL: elements % 2 != 0", reply, false);
}
*object = GenObjectFromReply(reply);
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::DeleteObject(const std::string& user_name, const std::string& bucket_name,
const std::string& object_name, const bool need_lock) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. HGETALL
*/
redisReply *reply;
int64_t delta_size = 0;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteObject::HGETALL ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements != 0) {
Object t_object = GenObjectFromReply(reply);
delta_size = t_object.size;
redisReply* t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"LPUSH %s %s", kZgwDeletedList.c_str(), std::string(t_object.data_block +
"/" + std::to_string(slash::NowMicros())).c_str()));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("DeleteObject::LPUSH");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("DeleteObject::LPUSH ret: " + std::string(reply->str), reply, need_lock);
}
assert(t_reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(t_reply);
}
freeReplyObject(reply);
/*
* 3. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"DEL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 4. SREM
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SREM %s%s %s", kZgwObjectListPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::SREM");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteObject::SREM ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 5. HINCRBY
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HINCRBY %s%s vol %lld", kZgwBucketPrefix.c_str(), bucket_name.c_str(),
0 - delta_size));
if (reply == NULL) {
return HandleIOError("DeleteObject::HINCRBY");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteObject::HINCRBY ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
/*
* 6. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::ListObjects(const std::string& user_name, const std::string& bucket_name,
std::vector<Object>* objects) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* 2. Get object list
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwObjectListPrefix.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return Status::OK();
}
/*
* 3. Iterate through objects to HGETALL
*/
redisReply* t_reply;
for (unsigned int i = 0; i < reply->elements; i++) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
reply->element[i]->str));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("ListObjects::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("ListObjects::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
freeReplyObject(reply);
return HandleLogicError("ListObjects::HGETALL: elements % 2 != 0", t_reply, false);
}
objects->push_back(GenObjectFromReply(t_reply));
freeReplyObject(t_reply);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::ListObjectsName(const std::string& user_name, const std::string& bucket_name,
std::vector<std::string>* objects_name) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
objects_name->clear();
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjectsName::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjectsName::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* 2. Get object list (SSCAN)
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwObjectListPrefix.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return Status::OK();
}
std::string cursor = "0";
do {
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SSCAN %s%s %s", kZgwObjectListPrefix.c_str(),
bucket_name.c_str(), cursor.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SSCAN");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SSCAN ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
assert(reply->elements == 2);
assert(reply->element[0]->type == REDIS_REPLY_STRING);
assert(reply->element[1]->type == REDIS_REPLY_ARRAY);
cursor = reply->element[0]->str;
for (unsigned int i = 0; i < reply->element[1]->elements; i++) {
objects_name->push_back(reply->element[1]->element[i]->str);
}
freeReplyObject(reply);
} while (cursor != "0");
return Status::OK();
}
Status ZgwStore::MGetObjects(const std::string& user_name, const std::string& bucket_name,
const std::vector<std::string> objects_name, std::vector<Object>* objects) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
objects->clear();
/*
* 1. Iterate through objects to HGETALL
*/
redisReply* t_reply;
for (auto& object_name : objects_name) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (t_reply == NULL) {
return HandleIOError("MGetObjects::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("MGetObjects::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
return HandleLogicError("MGetObjects::HGETALL: elements % 2 != 0", t_reply, false);
}
objects->push_back(GenObjectFromReply(t_reply));
freeReplyObject(t_reply);
}
return Status::OK();
}
Status ZgwStore::AddMultiBlockSet(const std::string& bucket_name, const std::string& object_name,
const std::string& upload_id, const std::string& block_index) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SADD
*/
std::string redis_key = kZgwMultiBlockSetPrefix + bucket_name + "_" +
object_name + "_" + upload_id;
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s %s", redis_key.c_str(), block_index.c_str()));
if (reply == NULL) {
return HandleIOError("AddMultiBlockSet::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddMultiBlockSet::SADD ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("upload_id Already Exist", reply, false);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::GetMultiBlockSet(const std::string& bucket_name, const std::string& object_name,
const std::string& upload_id, std::vector<std::string>* block_indexs) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
block_indexs->clear();
/*
* 1. Get Block indexs
*/
std::string redis_key = kZgwMultiBlockSetPrefix + bucket_name + "_" +
object_name + "_" + upload_id;
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s", redis_key.c_str()));
if (reply == NULL) {
return HandleIOError("GetMultiBlockSet::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetMultiBlockSet::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through indexs to push_back
*/
for (unsigned int i = 0; i < reply->elements; i++) {
block_indexs->push_back(reply->element[i]->str);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::DeleteMultiBlockSet(const std::string& bucket_name, const std::string& object_name,
const std::string& upload_id) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. DEL
*/
std::string redis_key = kZgwMultiBlockSetPrefix + bucket_name + "_" +
object_name + "_" + upload_id;
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"DEL %s", redis_key.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteMultiBlockSet::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
return Status::OK();
}
bool ZgwStore::MaybeHandleRedisError() {
if (!redis_error_) {
return true;
}
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
LOG(WARNING) << "reconnect: " << redis_ip_ << ":" << redis_port_ << "," << redis_passwd_;
redis_cli_ = redisConnectWithTimeout(redis_ip_.c_str(), redis_port_, timeout);
if (redis_cli_ == NULL || redis_cli_->err) {
LOG(WARNING) << "redis_cli is null, error: " << (redis_cli_ != NULL) ? std::to_string(redis_cli_->err) : "";
if (redis_cli_) {
redisFree(redis_cli_);
}
return false;
}
if (!redis_passwd_.empty()) {
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"AUTH %s", redis_passwd_.c_str()));
if (reply == NULL) {
LOG(WARNING) << "reply is null";
return false;
}
if (std::string(reply->str) != "OK") {
LOG(WARNING) << "reply is not ok, type: " << reply->type << " str: " << reply->str;
freeReplyObject(reply);
return false;
}
freeReplyObject(reply);
}
redis_error_ = false;
return true;
}
Status ZgwStore::HandleIOError(const std::string& func_name) {
redisFree(redis_cli_);
redis_error_ = true;
return Status::IOError(func_name);
}
Status ZgwStore::HandleLogicError(const std::string& str_err, redisReply* reply,
const bool should_unlock) {
freeReplyObject(reply);
Status s;
if (should_unlock) {
s = UnLock();
return Status::Corruption(str_err + ", UnLock ret: " + s.ToString());
}
return Status::Corruption(str_err);
}
bool ZgwStore::CheckRedis() {
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"PING"));
if (reply != NULL &&
reply->type == REDIS_REPLY_STATUS &&
std::string(reply->str) == "PONG") {
return true;
}
if (reply == NULL) {
LOG(WARNING) << "CheckRedis reply is null";
} else {
LOG(WARNING) << "CheckRedis reply error: " << reply->type << ", " << reply->str;
}
redis_error_ = true;
return MaybeHandleRedisError();
}
User ZgwStore::GenUserFromReply(redisReply* reply) {
User user;
for (unsigned int i = 0; i < reply->elements; i++) {
if (std::string(reply->element[i]->str) == "uid") {
user.user_id = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "name") {
user.display_name = reply->element[++i]->str;
continue;
} else {
user.key_pairs.insert(std::pair<std::string, std::string>(reply->element[i]->str,
reply->element[i+1]->str));
i++;
continue;
}
}
return user;
}
Bucket ZgwStore::GenBucketFromReply(redisReply* reply) {
Bucket bucket;
char* end;
for (unsigned int i = 0; i < reply->elements; i++) {
if (std::string(reply->element[i]->str) == "name") {
bucket.bucket_name = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "ctime") {
bucket.create_time = std::strtoll(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "owner") {
bucket.owner = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "acl") {
bucket.acl = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "loc") {
bucket.location = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "vol") {
bucket.volumn = std::strtoull(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "uvol") {
bucket.uploading_volumn = std::strtoull(reply->element[++i]->str,
&end, 10);
}
}
return bucket;
}
Object ZgwStore::GenObjectFromReply(redisReply* reply) {
Object object;
char* end;
for (unsigned int i = 0; i < reply->elements; i++) {
if (std::string(reply->element[i]->str) == "bname") {
object.bucket_name = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "oname") {
object.object_name = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "etag") {
object.etag = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "size") {
object.size = std::strtoll(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "owner") {
object.owner = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "lm") {
object.last_modified = std::strtoull(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "class") {
object.storage_class = std::atoi(reply->element[++i]->str);
continue;
} else if (std::string(reply->element[i]->str) == "acl") {
object.acl = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "id") {
object.upload_id = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "block") {
object.data_block = reply->element[++i]->str;
}
}
return object;
}
}
remove SMEMBERS in ListObjectsName
#include "slash/include/slash_string.h"
#include "slash/include/env.h"
#include "zgw_store.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <glog/logging.h>
namespace zgwstore {
ZgwStore::ZgwStore(const std::string& zp_table,const std::string& lock_name,
const int32_t lock_ttl, const std::string& redis_passwd) :
zp_table_(zp_table), zp_cli_(nullptr), redis_cli_(nullptr), redis_ip_(""),
redis_port_(-1), lock_name_(lock_name), lock_ttl_(lock_ttl),
redis_passwd_(redis_passwd), redis_error_(false) {
};
ZgwStore::~ZgwStore() {
if (zp_cli_ != nullptr) {
delete zp_cli_;
}
if (redis_cli_ != nullptr) {
redisFree(redis_cli_);
}
}
Status ZgwStore::Open(const std::vector<std::string>& zp_addrs,
const std::string& redis_addr, const std::string& zp_table,
const std::string& lock_name, const int32_t lock_ttl,
const std::string& redis_passwd, ZgwStore** store) {
*store = nullptr;
/*
* Connect to zeppelin
*/
if (zp_addrs.empty()) {
return Status::InvalidArgument("Invalid zeppelin addresses");
}
std::string t_ip;
int t_port = 0;
Status s;
libzp::Options zp_option;
for (auto& addr : zp_addrs) {
if (!slash::ParseIpPortString(addr, t_ip, t_port)) {
return Status::InvalidArgument("Invalid zeppelin address");
}
zp_option.meta_addr.push_back(libzp::Node(t_ip, t_port));
}
libzp::Cluster* zp_cli = new libzp::Cluster(zp_option);
s = zp_cli->Connect();
if (!s.ok()) {
delete zp_cli;
return Status::IOError("Failed to connect to zeppelin");
}
s = zp_cli->CreateTable(zp_table, 64);
if (!s.ok() && s.IsCorruption() &&
s.ToString() != "Corruption: Corruption: Already Exist") {
delete zp_cli;
return s;
}
/*
* Connect to redis
*/
if (!slash::ParseIpPortString(redis_addr, t_ip, t_port)) {
delete zp_cli;
return Status::InvalidArgument("Invalid zeppelin address");
}
redisContext* redis_cli;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
redis_cli = redisConnectWithTimeout(t_ip.c_str(), t_port, timeout);
if (redis_cli == NULL || redis_cli->err) {
delete zp_cli;
if (redis_cli) {
redisFree(redis_cli);
return Status::IOError("Failed to connect to redis");
} else {
return Status::Corruption("Connection error: can't allocate redis context");
}
}
if (!redis_passwd.empty()) {
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli,
"AUTH %s", redis_passwd.c_str()));
if (reply == NULL) {
delete zp_cli;
return Status::IOError("Failed to auth to redis");
}
if (std::string(reply->str) != "OK") {
freeReplyObject(reply);
delete zp_cli;
return Status::Corruption("Failed to auth to redis");
}
freeReplyObject(reply);
}
*store = new ZgwStore(zp_table, lock_name, lock_ttl, redis_passwd);
(*store)->InstallClients(zp_cli, redis_cli);
(*store)->set_redis_ip(t_ip);
(*store)->set_redis_port(t_port);
return Status::OK();
}
void ZgwStore::InstallClients(libzp::Cluster* zp_cli, redisContext* redis_cli) {
zp_cli_ = zp_cli;
redis_cli_ = redis_cli;
}
Status ZgwStore::BlockSet(const std::string& block_id, const std::string& block_content) {
return zp_cli_->Set(zp_table_, kZpBlockPrefix + block_id, block_content);
}
Status ZgwStore::BlockGet(const std::string& block_id, std::string* block_content) {
return zp_cli_->Get(zp_table_, kZpBlockPrefix + block_id, block_content);
}
Status ZgwStore::BlockDelete(const std::string& block_id) {
return zp_cli_->Delete(zp_table_, kZpBlockPrefix + block_id);
}
Status ZgwStore::BlockMGet(const std::vector<std::string>& block_ids,
std::map<std::string, std::string>* block_contents) {
std::vector<std::string> ids;
for(auto& id : block_ids) {
ids.push_back(kZpBlockPrefix + id);
}
return zp_cli_->Mget(zp_table_, ids, block_contents);
}
Status ZgwStore::BlockRef(const std::string& block_id) {
// Lock outside
std::string block_ref_s;
int ref;
Status s = zp_cli_->Get(zp_table_, kZpRefPrefix + block_id, &block_ref_s);
if (!s.ok()) {
if (s.IsNotFound()) {
ref = 0;
} else {
return s;
}
} else {
ref = std::atoi(block_ref_s.c_str());
}
ref++;
block_ref_s.assign(std::to_string(ref));
return zp_cli_->Set(zp_table_, kZpRefPrefix + block_id, block_ref_s);
}
Status ZgwStore::Lock() {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
redisReply *reply;
while (true) {
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SET zgw_lock %s NX PX %lu", lock_name_.c_str(), lock_ttl_));
if (reply == NULL) {
return HandleIOError("Lock");
}
if (reply->type == REDIS_REPLY_STATUS && !strcmp(reply->str, "OK")) {
freeReplyObject(reply);
break;
}
freeReplyObject(reply);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return Status::OK();
}
Status ZgwStore::UnLock() {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
std::string del_cmd = "if redis.call(\"get\", \"zgw_lock\") == \"" + lock_name_ + "\" "
"then "
"return redis.call(\"del\", \"zgw_lock\") "
"else "
"return 0 "
"end ";
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"EVAL %s %d", del_cmd.c_str(), 0));
if (reply == NULL) {
return HandleIOError("UnLock");
}
if (reply->integer == 1) {
// UnLock Success
} else if (reply->integer == 0) {
// The zgw_lock is held by other clients
// std::cout << "reply-int" << std::endl;
// redisReply* t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "GET zgw_lock"));
// std::cout <<t_reply->type << std::endl;
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::AddUser(const User& user, const bool override) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
s = Lock();
if (!s.ok()) {
return s;
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s %s", kZgwUserList.c_str(), user.display_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddUser::SISMEMBER ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 1 && !override) {
return HandleLogicError("User Already Exist", reply, true);
}
freeReplyObject(reply);
/*
* 3. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "DEL %s%s",
kZgwUserPrefix.c_str(), user.display_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 4. HMSET
*/
std::string hmset_cmd = "HMSET " + kZgwUserPrefix + user.display_name;
hmset_cmd += (" uid " + user.user_id);
hmset_cmd += (" name " + user.display_name);
for (auto& iter : user.key_pairs) {
hmset_cmd += (" " + iter.first + " " + iter.second);
}
reply = static_cast<redisReply*>(redisCommand(redis_cli_, hmset_cmd.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::HMSET");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddUser::HMSET ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_STATUS);
freeReplyObject(reply);
/*
* 4. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s %s", kZgwUserList.c_str(), user.display_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddUser::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddUser::SADD ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0 && !override) {
return HandleLogicError("User Already Exist", reply, true);
}
freeReplyObject(reply);
/*
* 5. UnLock
*/
s = UnLock();
return s;
}
Status ZgwStore::ListUsers(std::vector<User>* users) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
users->clear();
/*
* 1. Get user list
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s", kZgwUserList.c_str()));
if (reply == NULL) {
return HandleIOError("ListUsers::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListUser::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through users to HGETALL
*/
redisReply* t_reply;
for (unsigned int i = 0; i < reply->elements; i++) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwUserPrefix.c_str(), reply->element[i]->str));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("ListUsers::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("ListUser::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
freeReplyObject(reply);
return HandleLogicError("ListUser::HGETALL: elements % 2 != 0", t_reply, false);
}
users->push_back(GenUserFromReply(t_reply));
freeReplyObject(t_reply);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::AddBucket(const Bucket& bucket, const bool need_lock,
const bool override) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), bucket.owner.c_str(),
bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::SISMEMBER ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 1 && !override) {
return HandleLogicError("Bucket Already Exist", reply, need_lock);
}
freeReplyObject(reply);
/*
* 3. EXISTS
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "EXISTS %s%s",
kZgwBucketPrefix.c_str(), bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::EXISTS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::EXISTS ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 1) {
return HandleLogicError("Bucket Already Exist [GLOBAL]", reply, need_lock);
}
assert(reply->integer == 0);
freeReplyObject(reply);
/*
* 4. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "DEL %s%s",
kZgwBucketPrefix.c_str(), bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 5. HMSET
*/
std::string hmset_cmd = "HMSET " + kZgwBucketPrefix + bucket.bucket_name;
hmset_cmd += (" name " + bucket.bucket_name);
hmset_cmd += " ctime %llu";
hmset_cmd += (" owner " + bucket.owner);
hmset_cmd += (" acl " + bucket.acl);
hmset_cmd += (" loc " + bucket.location);
hmset_cmd += " vol %lld";
hmset_cmd += " uvol %lld";
reply = static_cast<redisReply*>(redisCommand(redis_cli_, hmset_cmd.c_str(), bucket.create_time,
bucket.volumn, bucket.uploading_volumn));
if (reply == NULL) {
return HandleIOError("AddBucket::HMSET");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::HMSET ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_STATUS);
freeReplyObject(reply);
/*
* 6. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s%s %s", kZgwBucketListPrefix.c_str(), bucket.owner.c_str(),
bucket.bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddBucket::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddBucket::SADD ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0 && !override) {
return HandleLogicError("Bucket Already Exist", reply, need_lock);
}
freeReplyObject(reply);
/*
* 7. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::GetBucket(const std::string& user_name, const std::string& bucket_name,
Bucket* bucket) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("GetBucket::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetBucket::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* HGETALL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
freeReplyObject(reply);
return HandleIOError("GetBucket::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("GetBucket::HGETALL ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return HandleLogicError("Bucket Not Found", reply, true);
} else if (reply->elements % 2 != 0) {
return HandleLogicError("GetBucket::HGETALL: elements % 2 != 0", reply, false);
}
*bucket = GenBucketFromReply(reply);
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::DeleteBucket(const std::string& user_name, const std::string& bucket_name,
const bool need_lock) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteBucket::SISMEMBER ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesnt Exist", reply, need_lock);
}
freeReplyObject(reply);
/*
* 3. HGET
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGET %s%s vol",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::EXISTS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteBucket::EXISTS ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_STRING);
char* end;
if (std::strtoll(reply->str, &end, 10) != 0) {
return HandleLogicError("Bucket Vol IS NOT 0", reply, need_lock);
}
assert(reply->integer == 0);
freeReplyObject(reply);
/*
* 4. SCARD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SCARD %s%s", kZgwObjectListPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::SCARD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteBucket::SCARD ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer != 0) {
return HandleLogicError("Bucket Non Empty", reply, need_lock);
}
freeReplyObject(reply);
/*
* 5. SREM
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SREM %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::SREM");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 6. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "DEL %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteBucket::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 7. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::ListBuckets(const std::string& user_name, std::vector<Bucket>* buckets) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
buckets->clear();
/*
* 1. Get bucket list
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwBucketListPrefix.c_str(),
user_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListBuckets::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListBuckets::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through buckets to HGETALL
*/
redisReply* t_reply;
for (unsigned int i = 0; i < reply->elements; i++) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwBucketPrefix.c_str(), reply->element[i]->str));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("ListBuckets::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("ListBuckets::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
freeReplyObject(reply);
return HandleLogicError("ListBuckets::HGETALL: elements % 2 != 0", t_reply, false);
}
buckets->push_back(GenBucketFromReply(t_reply));
freeReplyObject(t_reply);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::ListBucketsName(const std::string& user_name, std::vector<std::string>* buckets_name) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
buckets_name->clear();
/*
* 1. Get bucket list
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwBucketListPrefix.c_str(),
user_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListBucketsName::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListBucketsName::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through buckets to push_back
*/
for (unsigned int i = 0; i < reply->elements; i++) {
buckets_name->push_back(reply->element[i]->str);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::MGetBuckets(const std::string& user_name, const std::vector<std::string> buckets_name,
std::vector<Bucket>* buckets) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
buckets->clear();
/*
* 1. Iterate through buckets to HGETALL
*/
redisReply* t_reply;
for (auto& bucket_name : buckets_name) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_, "HGETALL %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (t_reply == NULL) {
return HandleIOError("MGetBuckets::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("MGetBuckets::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
return HandleLogicError("MGetBuckets::HGETALL: elements % 2 != 0", t_reply, false);
}
buckets->push_back(GenBucketFromReply(t_reply));
freeReplyObject(t_reply);
}
return Status::OK();
}
Status ZgwStore::AllocateId(const std::string& user_name, const std::string& bucket_name,
const std::string& object_name, const int32_t block_nums, uint64_t* tail_id) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
s = Lock();
if (!s.ok()) {
return s;
}
/*
* 2. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AllocateId::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::SISMEMBER ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, true);
}
freeReplyObject(reply);
/*
* 3. EXISTS
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_, "EXISTS %s%s",
kZgwBucketPrefix.c_str(), bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("AllocateId::EXISTS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::EXISTS ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket NOT Exists", reply, true);
}
assert(reply->integer == 1);
/*
* 4. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s%s %s%s", kZgwObjectListPrefix.c_str(), bucket_name.c_str(),
kZgwTempObjectNamePrefix.c_str(), object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AllocateId::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::SADD ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 5. INCRBY
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"INCRBY %s %d", kZgwIdGen.c_str(), block_nums));
if (reply == NULL) {
return HandleIOError("AllocateId::INCRBY");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AllocateId::INCRBY ret: " + std::string(reply->str), reply, true);
}
assert(reply->type == REDIS_REPLY_INTEGER);
*tail_id = reply->integer;
freeReplyObject(reply);
/*
* 6. UnLock
*/
s = UnLock();
return s;
}
Status ZgwStore::AddObject(const Object& object, const bool need_lock) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. HGETALL
*/
redisReply *reply;
int64_t old_size = 0;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), object.bucket_name.c_str(),
object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::HGETALL ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements != 0) {
Object t_object = GenObjectFromReply(reply);
old_size = t_object.size;
redisReply* t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"LPUSH %s %s", kZgwDeletedList.c_str(), std::string(t_object.data_block +
"/" + std::to_string(slash::NowMicros())).c_str()));
if (t_reply == NULL) {
return HandleIOError("AddObject::LPUSH");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::LPUSH ret: " + std::string(reply->str), reply, need_lock);
}
assert(t_reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(t_reply);
}
freeReplyObject(reply);
/*
* 3. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"DEL %s%s_%s", kZgwObjectPrefix.c_str(), object.bucket_name.c_str(),
object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 4. HMSET
*/
std::string hmset_cmd = "HMSET " + kZgwObjectPrefix + object.bucket_name +
"_" + object.object_name;
hmset_cmd += (" bname " + object.bucket_name);
hmset_cmd += (" oname " + object.object_name);
hmset_cmd += (" etag " + object.etag);
hmset_cmd += " size %lld";
hmset_cmd += (" owner " + object.owner);
hmset_cmd += " lm %llu";
hmset_cmd += " class %d";
hmset_cmd += (" acl " + object.acl);
hmset_cmd += (" id " + object.upload_id);
hmset_cmd += (" block " + object.data_block);
reply = static_cast<redisReply*>(redisCommand(redis_cli_, hmset_cmd.c_str(), object.size,
object.last_modified, object.storage_class));
if (reply == NULL) {
return HandleIOError("AddObject::HMSET");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::HMSET ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_STATUS);
freeReplyObject(reply);
/*
* 5. SADD
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s%s %s", kZgwObjectListPrefix.c_str(), object.bucket_name.c_str(),
object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::SADD ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
// object already exists, update
}
freeReplyObject(reply);
/*
* 6. HINCRBY
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HINCRBY %s%s vol %lld", kZgwBucketPrefix.c_str(), object.bucket_name.c_str(),
object.size - old_size));
if (reply == NULL) {
return HandleIOError("AddObject::HINCRBY");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddObject::HINCRBY ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
/*
* 7. SREM
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SREM %s%s %s%s", kZgwObjectListPrefix.c_str(), object.bucket_name.c_str(),
kZgwTempObjectNamePrefix.c_str(), object.object_name.c_str()));
if (reply == NULL) {
return HandleIOError("AddObject::SREM");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 8. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::GetObject(const std::string& user_name, const std::string& bucket_name,
const std::string& object_name, Object* object) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("GetObject::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetObject::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* 2. HGETALL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("GetObject::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetObject::HGETALL ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return HandleLogicError("Object Not Found", reply, true);
} else if (reply->elements % 2 != 0) {
return HandleLogicError("GetObject::HGETALL: elements % 2 != 0", reply, false);
}
*object = GenObjectFromReply(reply);
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::DeleteObject(const std::string& user_name, const std::string& bucket_name,
const std::string& object_name, const bool need_lock) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. Lock
*/
Status s;
if (need_lock) {
s = Lock();
if (!s.ok()) {
return s;
}
}
/*
* 2. HGETALL
*/
redisReply *reply;
int64_t delta_size = 0;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::HGETALL");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteObject::HGETALL ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements != 0) {
Object t_object = GenObjectFromReply(reply);
delta_size = t_object.size;
redisReply* t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"LPUSH %s %s", kZgwDeletedList.c_str(), std::string(t_object.data_block +
"/" + std::to_string(slash::NowMicros())).c_str()));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("DeleteObject::LPUSH");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("DeleteObject::LPUSH ret: " + std::string(reply->str), reply, need_lock);
}
assert(t_reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(t_reply);
}
freeReplyObject(reply);
/*
* 3. DEL
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"DEL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 4. SREM
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SREM %s%s %s", kZgwObjectListPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteObject::SREM");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteObject::SREM ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
/*
* 5. HINCRBY
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HINCRBY %s%s vol %lld", kZgwBucketPrefix.c_str(), bucket_name.c_str(),
0 - delta_size));
if (reply == NULL) {
return HandleIOError("DeleteObject::HINCRBY");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("DeleteObject::HINCRBY ret: " + std::string(reply->str), reply, need_lock);
}
assert(reply->type == REDIS_REPLY_INTEGER);
/*
* 6. UnLock
*/
if (need_lock) {
s = UnLock();
}
return s;
}
Status ZgwStore::ListObjects(const std::string& user_name, const std::string& bucket_name,
std::vector<Object>* objects) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* 2. Get object list
*/
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s%s", kZgwObjectListPrefix.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
return Status::OK();
}
/*
* 3. Iterate through objects to HGETALL
*/
redisReply* t_reply;
for (unsigned int i = 0; i < reply->elements; i++) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
reply->element[i]->str));
if (t_reply == NULL) {
freeReplyObject(reply);
return HandleIOError("ListObjects::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
return HandleLogicError("ListObjects::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
freeReplyObject(reply);
return HandleLogicError("ListObjects::HGETALL: elements % 2 != 0", t_reply, false);
}
objects->push_back(GenObjectFromReply(t_reply));
freeReplyObject(t_reply);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::ListObjectsName(const std::string& user_name, const std::string& bucket_name,
std::vector<std::string>* objects_name) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
objects_name->clear();
/*
* 1. SISMEMBER
*/
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SISMEMBER %s%s %s", kZgwBucketListPrefix.c_str(), user_name.c_str(),
bucket_name.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjectsName::SISMEMBER");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjectsName::SISMEMBER ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("Bucket Doesn't Belong To This User", reply, false);
}
freeReplyObject(reply);
/*
* 2. Get object list (SSCAN)
*/
std::string cursor = "0";
do {
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SSCAN %s%s %s", kZgwObjectListPrefix.c_str(),
bucket_name.c_str(), cursor.c_str()));
if (reply == NULL) {
return HandleIOError("ListObjects::SSCAN");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("ListObjects::SSCAN ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
assert(reply->elements == 2);
assert(reply->element[0]->type == REDIS_REPLY_STRING);
assert(reply->element[1]->type == REDIS_REPLY_ARRAY);
cursor = reply->element[0]->str;
for (unsigned int i = 0; i < reply->element[1]->elements; i++) {
objects_name->push_back(reply->element[1]->element[i]->str);
}
freeReplyObject(reply);
} while (cursor != "0");
return Status::OK();
}
Status ZgwStore::MGetObjects(const std::string& user_name, const std::string& bucket_name,
const std::vector<std::string> objects_name, std::vector<Object>* objects) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
objects->clear();
/*
* 1. Iterate through objects to HGETALL
*/
redisReply* t_reply;
for (auto& object_name : objects_name) {
t_reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"HGETALL %s%s_%s", kZgwObjectPrefix.c_str(), bucket_name.c_str(),
object_name.c_str()));
if (t_reply == NULL) {
return HandleIOError("MGetObjects::HGETALL");
}
if (t_reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("MGetObjects::HGETALL ret: " + std::string(t_reply->str), t_reply, false);
}
assert(t_reply->type == REDIS_REPLY_ARRAY);
if (t_reply->elements == 0) {
continue;
} else if (t_reply->elements % 2 != 0) {
return HandleLogicError("MGetObjects::HGETALL: elements % 2 != 0", t_reply, false);
}
objects->push_back(GenObjectFromReply(t_reply));
freeReplyObject(t_reply);
}
return Status::OK();
}
Status ZgwStore::AddMultiBlockSet(const std::string& bucket_name, const std::string& object_name,
const std::string& upload_id, const std::string& block_index) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. SADD
*/
std::string redis_key = kZgwMultiBlockSetPrefix + bucket_name + "_" +
object_name + "_" + upload_id;
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SADD %s %s", redis_key.c_str(), block_index.c_str()));
if (reply == NULL) {
return HandleIOError("AddMultiBlockSet::SADD");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("AddMultiBlockSet::SADD ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_INTEGER);
if (reply->integer == 0) {
return HandleLogicError("upload_id Already Exist", reply, false);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::GetMultiBlockSet(const std::string& bucket_name, const std::string& object_name,
const std::string& upload_id, std::vector<std::string>* block_indexs) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
block_indexs->clear();
/*
* 1. Get Block indexs
*/
std::string redis_key = kZgwMultiBlockSetPrefix + bucket_name + "_" +
object_name + "_" + upload_id;
redisReply *reply;
reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"SMEMBERS %s", redis_key.c_str()));
if (reply == NULL) {
return HandleIOError("GetMultiBlockSet::SEMBMBERS");
}
if (reply->type == REDIS_REPLY_ERROR) {
return HandleLogicError("GetMultiBlockSet::SMEMBERS ret: " + std::string(reply->str), reply, false);
}
assert(reply->type == REDIS_REPLY_ARRAY);
if (reply->elements == 0) {
freeReplyObject(reply);
return Status::OK();
}
/*
* 2. Iterate through indexs to push_back
*/
for (unsigned int i = 0; i < reply->elements; i++) {
block_indexs->push_back(reply->element[i]->str);
}
freeReplyObject(reply);
return Status::OK();
}
Status ZgwStore::DeleteMultiBlockSet(const std::string& bucket_name, const std::string& object_name,
const std::string& upload_id) {
if (!MaybeHandleRedisError()) {
return Status::IOError("Reconnect");
}
if (!CheckRedis()) {
return Status::IOError("CheckRedis Failed");
}
/*
* 1. DEL
*/
std::string redis_key = kZgwMultiBlockSetPrefix + bucket_name + "_" +
object_name + "_" + upload_id;
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"DEL %s", redis_key.c_str()));
if (reply == NULL) {
return HandleIOError("DeleteMultiBlockSet::DEL");
}
assert(reply->type == REDIS_REPLY_INTEGER);
freeReplyObject(reply);
return Status::OK();
}
bool ZgwStore::MaybeHandleRedisError() {
if (!redis_error_) {
return true;
}
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
LOG(WARNING) << "reconnect: " << redis_ip_ << ":" << redis_port_ << "," << redis_passwd_;
redis_cli_ = redisConnectWithTimeout(redis_ip_.c_str(), redis_port_, timeout);
if (redis_cli_ == NULL || redis_cli_->err) {
LOG(WARNING) << "redis_cli is null, error: " << (redis_cli_ != NULL) ? std::to_string(redis_cli_->err) : "";
if (redis_cli_) {
redisFree(redis_cli_);
}
return false;
}
if (!redis_passwd_.empty()) {
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"AUTH %s", redis_passwd_.c_str()));
if (reply == NULL) {
LOG(WARNING) << "reply is null";
return false;
}
if (std::string(reply->str) != "OK") {
LOG(WARNING) << "reply is not ok, type: " << reply->type << " str: " << reply->str;
freeReplyObject(reply);
return false;
}
freeReplyObject(reply);
}
redis_error_ = false;
return true;
}
Status ZgwStore::HandleIOError(const std::string& func_name) {
redisFree(redis_cli_);
redis_error_ = true;
return Status::IOError(func_name);
}
Status ZgwStore::HandleLogicError(const std::string& str_err, redisReply* reply,
const bool should_unlock) {
freeReplyObject(reply);
Status s;
if (should_unlock) {
s = UnLock();
return Status::Corruption(str_err + ", UnLock ret: " + s.ToString());
}
return Status::Corruption(str_err);
}
bool ZgwStore::CheckRedis() {
redisReply* reply = static_cast<redisReply*>(redisCommand(redis_cli_,
"PING"));
if (reply != NULL &&
reply->type == REDIS_REPLY_STATUS &&
std::string(reply->str) == "PONG") {
return true;
}
if (reply == NULL) {
LOG(WARNING) << "CheckRedis reply is null";
} else {
LOG(WARNING) << "CheckRedis reply error: " << reply->type << ", " << reply->str;
}
redis_error_ = true;
return MaybeHandleRedisError();
}
User ZgwStore::GenUserFromReply(redisReply* reply) {
User user;
for (unsigned int i = 0; i < reply->elements; i++) {
if (std::string(reply->element[i]->str) == "uid") {
user.user_id = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "name") {
user.display_name = reply->element[++i]->str;
continue;
} else {
user.key_pairs.insert(std::pair<std::string, std::string>(reply->element[i]->str,
reply->element[i+1]->str));
i++;
continue;
}
}
return user;
}
Bucket ZgwStore::GenBucketFromReply(redisReply* reply) {
Bucket bucket;
char* end;
for (unsigned int i = 0; i < reply->elements; i++) {
if (std::string(reply->element[i]->str) == "name") {
bucket.bucket_name = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "ctime") {
bucket.create_time = std::strtoll(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "owner") {
bucket.owner = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "acl") {
bucket.acl = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "loc") {
bucket.location = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "vol") {
bucket.volumn = std::strtoull(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "uvol") {
bucket.uploading_volumn = std::strtoull(reply->element[++i]->str,
&end, 10);
}
}
return bucket;
}
Object ZgwStore::GenObjectFromReply(redisReply* reply) {
Object object;
char* end;
for (unsigned int i = 0; i < reply->elements; i++) {
if (std::string(reply->element[i]->str) == "bname") {
object.bucket_name = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "oname") {
object.object_name = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "etag") {
object.etag = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "size") {
object.size = std::strtoll(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "owner") {
object.owner = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "lm") {
object.last_modified = std::strtoull(reply->element[++i]->str,
&end, 10);
continue;
} else if (std::string(reply->element[i]->str) == "class") {
object.storage_class = std::atoi(reply->element[++i]->str);
continue;
} else if (std::string(reply->element[i]->str) == "acl") {
object.acl = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "id") {
object.upload_id = reply->element[++i]->str;
continue;
} else if (std::string(reply->element[i]->str) == "block") {
object.data_block = reply->element[++i]->str;
}
}
return object;
}
}
|
// Copyright (c) 2016 Jon Taylor
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "cli.h"
#include <sstream>
#include <unistd.h> // open and close
#include <sys/stat.h> // temp because we removed util
#include <fcntl.h> // temp removed util.h
#include <time.h>
#include "ecdsacrypto.h"
#include "functions/functions.h"
#include "wallet.h"
/**
* printCommands
*
* Description: Print a list of commands that are accepted.
*/
void CCLI::printCommands(){
std::cout << "Commands:\n" <<
" join - request membership in the network.\n" <<
" balance - print balance and transaction summary.\n" <<
" sent - print sent transaction list details.\n" <<
" received - print received transaction list details.\n" <<
" network - print network stats including currency and volumes.\n" <<
" send - send a payment to another user address.\n" <<
" receive - prints your public key address to have others send you payments.\n" <<
" advanced - more commands for admin and testing functions.\n" <<
" quit - shutdown the application.\n " << std::endl;
}
void CCLI::printAdvancedCommands(){
std::cout << " Advanced: \n" <<
" tests - Run tests to verify this build is functioning correctly.\n " <<
std::endl;
}
/**
* processUserInput
*
* Description: process user commands and print results
*/
void CCLI::processUserInput(){
bool running = true;
printCommands();
while(running){
std::cout << ">";
std::string command;
std::cin >> command;
if( command.find("join") != std::string::npos ){
CFunctions functions;
std::string privateKey;
std::string publicKey;
CWallet wallet;
bool e = wallet.fileExists("wallet.dat");
if(e != 0){
// Load wallet
wallet.read(privateKey, publicKey);
functions.parseBlockFile( publicKey );
}
if(functions.joined == true){
std::cout << "Allready joined network. \n" << std::endl;
} else {
std::cout << "Joining request sending... \n" << std::endl;
// TODO: send request or say allready sent.
}
// Print if pending or allready accepted.
} else if ( command.find("balance") != std::string::npos ){
CFunctions functions;
std::string privateKey;
std::string publicKey;
CWallet wallet;
bool e = wallet.fileExists("wallet.dat");
if(e != 0){
// Load wallet
wallet.read(privateKey, publicKey);
functions.parseBlockFile( publicKey );
std::cout << " Your balance: " << functions.balance << " sfr" << std::endl;
}
} else if ( command.find("sent") != std::string::npos ){
std::cout << "This feature is not implemented yet.\n" << std::endl;
} else if ( command.find("receive") != std::string::npos ){
std::cout << "This feature is not implemented yet.\n" << std::endl;
} else if ( command.find("send") != std::string::npos ){
std::cout << "Enter destination address: \n" << std::endl;
std::string destination_address;
std::cin >> destination_address;
std::cout << "Enter amount to send: \n" << std::endl;
std::string amount;
std::cin >> amount;
std::cout << "Sending " << amount << " to user: " << destination_address << " \n" << std::endl;
} else if ( command.find("network") != std::string::npos ){
CFunctions functions;
std::string privateKey;
std::string publicKey;
CWallet wallet;
bool e = wallet.fileExists("wallet.dat");
if(e != 0){
// Load wallet
wallet.read(privateKey, publicKey);
functions.parseBlockFile( publicKey );
std::cout << " Currency: " << functions.currency_circulation << " sfr" << std::endl;
}
// Block chain size?
// Active connections?
//std::cout << "This feature is not implemented yet.\n" << std::endl;
} else if ( command.find("quit") != std::string::npos ){
running = false;
} else if ( command.find("advanced") != std::string::npos ){
printAdvancedCommands();
} else if ( command.find("tests") != std::string::npos ){
CECDSACrypto ecdsa;
ecdsa.runTests();
} else {
printCommands();
}
}
}
send payment adds request to queue file.
// Copyright (c) 2016 Jon Taylor
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "cli.h"
#include <sstream>
#include <unistd.h> // open and close
#include <sys/stat.h> // temp because we removed util
#include <fcntl.h> // temp removed util.h
#include <time.h>
#include "ecdsacrypto.h"
#include "functions/functions.h"
#include "wallet.h"
/**
* printCommands
*
* Description: Print a list of commands that are accepted.
*/
void CCLI::printCommands(){
std::cout << "Commands:\n" <<
" join - request membership in the network.\n" <<
" balance - print balance and transaction summary.\n" <<
" sent - print sent transaction list details.\n" <<
" received - print received transaction list details.\n" <<
" network - print network stats including currency and volumes.\n" <<
" send - send a payment to another user address.\n" <<
" receive - prints your public key address to have others send you payments.\n" <<
" advanced - more commands for admin and testing functions.\n" <<
" quit - shutdown the application.\n " << std::endl;
}
void CCLI::printAdvancedCommands(){
std::cout << " Advanced: \n" <<
" tests - Run tests to verify this build is functioning correctly.\n " <<
std::endl;
}
/**
* processUserInput
*
* Description: process user commands and print results
*/
void CCLI::processUserInput(){
bool running = true;
CECDSACrypto ecdsa;
CFunctions functions;
std::string privateKey;
std::string publicKey;
CWallet wallet;
bool e = wallet.fileExists("wallet.dat");
if(e != 0){
// Load wallet
wallet.read(privateKey, publicKey);
functions.parseBlockFile(publicKey);
}
printCommands();
while(running){
std::cout << ">";
std::string command;
std::cin >> command;
if( command.find("join") != std::string::npos ){
//CFunctions functions;
//std::string privateKey;
//std::string publicKey;
//CWallet wallet;
//bool e = wallet.fileExists("wallet.dat");
//if(e != 0){
// Load wallet
//wallet.read(privateKey, publicKey);
functions.parseBlockFile( publicKey );
//}
if(functions.joined == true){
std::cout << "Allready joined network. \n" << std::endl;
} else {
std::cout << "Joining request sending... \n" << std::endl;
CFunctions::record_structure joinRecord;
time_t timev;
time(&timev);
std::stringstream ss;
ss << timev;
std::string ts = ss.str();
joinRecord.time = ts;
joinRecord.transaction_type = CFunctions::JOIN_NETWORK;
joinRecord.amount = 0.0;
joinRecord.sender_public_key = "";
joinRecord.recipient_public_key = publicKey;
std::string message_siganture = "";
ecdsa.SignMessage(privateKey, "" + publicKey, message_siganture);
joinRecord.message_signature = message_siganture;
functions.addToQueue( joinRecord );
// TODO: send request or say allready sent.
}
// Print if pending or allready accepted.
} else if ( command.find("balance") != std::string::npos ){
//CFunctions functions;
//std::string privateKey;
//std::string publicKey;
//CWallet wallet;
//bool e = wallet.fileExists("wallet.dat");
//if(e != 0){
// Load wallet
//wallet.read(privateKey, publicKey);
functions.parseBlockFile( publicKey );
std::cout << " Your balance: " << functions.balance << " sfr" << std::endl;
//}
} else if ( command.find("sent") != std::string::npos ){
std::cout << "This feature is not implemented yet.\n" << std::endl;
} else if ( command.find("receive") != std::string::npos ){
std::cout << "This feature is not implemented yet.\n" << std::endl;
} else if ( command.find("send") != std::string::npos ){
std::cout << "Enter destination address: \n" << std::endl;
std::string destination_address;
std::cin >> destination_address;
std::cout << "Enter amount to send: \n" << std::endl;
std::string amount;
std::cin >> amount;
std::cout << "Sending " << amount << " to user: " << destination_address << " \n" << std::endl;
double d_amount = ::atof(amount.c_str());
// TODO also check balance adjusted using sent requests in queue....
// TODO check destination address is an accepted user
if(d_amount > functions.balance ){
std::cout << "Insuficient balance. Unable to send transfer request. " << std::endl;
} else {
CFunctions::record_structure sendRecord;
time_t timev;
time(&timev);
std::stringstream ss;
ss << timev;
std::string ts = ss.str();
sendRecord.time = ts;
sendRecord.transaction_type = CFunctions::TRANSFER_CURRENCY;
sendRecord.amount = d_amount;
sendRecord.sender_public_key = publicKey;
sendRecord.recipient_public_key = publicKey;
std::string message_siganture = destination_address;
ecdsa.SignMessage(privateKey, "" + publicKey, message_siganture);
sendRecord.message_signature = message_siganture;
functions.addToQueue( sendRecord );
std::cout << "Sent transfer request. " << std::endl;
}
} else if ( command.find("network") != std::string::npos ){
CFunctions functions;
std::string privateKey;
std::string publicKey;
CWallet wallet;
bool e = wallet.fileExists("wallet.dat");
if(e != 0){
// Load wallet
wallet.read(privateKey, publicKey);
functions.parseBlockFile( publicKey );
std::cout << " Currency: " << functions.currency_circulation << " sfr" << std::endl;
}
// Block chain size?
std::cout << " Blockchain size: " << " 0MB" << std::endl;
std::cout << " Pending transactions: " << " 0" << std::endl;
// Active connections?
//std::cout << "This feature is not implemented yet.\n" << std::endl;
} else if ( command.find("quit") != std::string::npos ){
running = false;
} else if ( command.find("advanced") != std::string::npos ){
printAdvancedCommands();
} else if ( command.find("tests") != std::string::npos ){
CECDSACrypto ecdsa;
ecdsa.runTests();
} else {
printCommands();
}
}
}
|
/*
* Copyright (C) 2015-2018 Nagisa Sekiguchi
*
* 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 <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <poll.h>
#include <cstdlib>
#include <cstdarg>
#include <unordered_map>
#include <ydsh/ydsh.h>
#include "logger.h"
#include "cmd.h"
#include "core.h"
#include "constant.h"
#include "symbol_table.h"
#include "object.h"
#include "signals.h"
#include "misc/num.h"
#include "misc/files.h"
namespace ydsh {
// builtin command definition
static int builtin___gets(DSState &state, Array_Object &argvObj);
static int builtin___puts(DSState &state, Array_Object &argvObj);
static int builtin_cd(DSState &state, Array_Object &argvObj);
static int builtin_check_env(DSState &state, Array_Object &argvObj);
static int builtin_complete(DSState &state, Array_Object &argvObj);
static int builtin_echo(DSState &state, Array_Object &argvObj);
static int builtin_false(DSState &state, Array_Object &argvObj);
static int builtin_fg_bg(DSState &state, Array_Object &argvObj);
static int builtin_hash(DSState &state, Array_Object &argvObj);
static int builtin_help(DSState &state, Array_Object &argvObj);
static int builtin_history(DSState &state, Array_Object &argvObj);
static int builtin_kill(DSState &state, Array_Object &argvObj);
static int builtin_ps_intrp(DSState &state, Array_Object &argvObj);
static int builtin_pwd(DSState &state, Array_Object &argvObj);
static int builtin_read(DSState &state, Array_Object &argvObj);
static int builtin_setenv(DSState &state, Array_Object &argvObj);
static int builtin_test(DSState &state, Array_Object &argvObj);
static int builtin_true(DSState &state, Array_Object &argvObj);
static int builtin_unsetenv(DSState &state, Array_Object &argvObj);
const struct {
const char *commandName;
builtin_command_t cmd_ptr;
const char *usage;
const char *detail;
} builtinCommands[] {
{":", builtin_true, "",
" Null command. Always success (exit status is 0)."},
{"__gets", builtin___gets, "",
" Read standard input and write to standard output."},
{"__puts", builtin___puts, "[-1 arg1] [-2 arg2]",
" Print specified argument to standard output/error and print new line.\n"
" Options:\n"
" -1 print to standard output\n"
" -2 print to standard error"},
{"bg", builtin_fg_bg, "[job_spec ...]",
" Move jobs to the background.\n"
" If JOB_SPEC is not present, latest job is used."},
{"cd", builtin_cd, "[-LP] [dir]",
" Changing the current directory to DIR. The Environment variable\n"
" HOME is the default DIR. A null directory name is the same as\n"
" the current directory. If -L is specified, use logical directory \n"
" (with symbolic link). If -P is specified, use physical directory \n"
" (without symbolic link). Default is -L."},
{"check_env", builtin_check_env, "variable ...",
" Check existence of specified environmental variables.\n"
" If all of variables are exist and not empty string, exit with 0."},
{"command", nullptr, "[-pVv] command [arg ...]",
" Execute COMMAND with ARGS excepting user defined command.\n"
" If -p option is specified, search command from default PATH.\n"
" If -V or -v option are specified, print description of COMMAND.\n"
" -V option shows more detailed information."},
{"complete", builtin_complete, "line",
" Show completion candidates."},
{"echo", builtin_echo, "[-neE] [arg ...]",
" Print argument to standard output and print new line.\n"
" Options:\n"
" -n not print new line\n"
" -e interpret some escape sequence\n"
" \\\\ backslash\n"
" \\a bell\n"
" \\b backspace\n"
" \\c ignore subsequent string\n"
" \\e escape sequence\n"
" \\E escape sequence\n"
" \\f form feed\n"
" \\n newline\n"
" \\r carriage return\n"
" \\t horizontal tab\n"
" \\v vertical tab\n"
" \\0nnn N is octal number. NNN can be 0 to 3 number\n"
" \\xnn N is hex number. NN can be 1 to 2 number\n"
" -E disable escape sequence interpretation"},
{"eval", nullptr, "[args ...]",
" evaluate ARGS as command."},
{"exec", nullptr, "[-c] [-a name] file [args ...]",
" Execute FILE and replace this shell with specified program.\n"
" If FILE is not specified, the redirections take effect in this shell.\n"
" IF FILE execution fail, terminate this shell immediately\n"
" Options:\n"
" -c cleaner environmental variable\n"
" -a specify set program name(default is FILE)"},
{"exit", nullptr, "[n]",
" Exit the shell with a status of N. If N is omitted, the exit\n"
" status is $?."},
{"false", builtin_false, "",
" Always failure (exit status is 1)."},
{"fg", builtin_fg_bg, "[job_spec]",
" Move job to the foreground.\n"
" If JOB_SPEC is not present, latest job is used."},
{"hash", builtin_hash, "[-r] [command ...]",
" Cache file path of specified commands. If -r option is supplied,\n"
" removes specified command path (if not specified, remove all cache).\n"
" If option is not supplied, display all cached path."},
{"help", builtin_help, "[-s] [pattern ...]",
" Display helpful information about builtin commands."},
{"history", builtin_history, "[-c] [-d offset] or history [-rw] [file]",
" Display or manipulate history list.\n"
" Options:\n"
" -c clear the history list\n"
" -d offset delete the history entry at OFFSET\n"
"\n"
" -r read the history list from history file\n"
" -w write the history list to history file"},
{"kill", builtin_kill, "[-s signal] pid | jobspec ... or kill -l [signal...]",
" Send a signal to a process or job.\n"
" If signal is not specified, then SIGTERM is assumed.\n"
" Options:\n"
" -s sig send a signal. SIG is a signal name or signal number\n"
" -l list the signal names"},
{"ps_intrp", builtin_ps_intrp, "prompt",
" Interpret prompt string.\n"
" Escape Sequence:\n"
" \\a bell\n"
" \\d date\n"
" \\e escape sequence\n"
" \\h host name\n"
" \\H fully qualified host name\n"
" \\n newline\n"
" \\r carriage return\n"
" \\s base name of $0\n"
" \\t 24 hour notation (HH:MM:SS)\n"
" \\T 12 hour notation (HH:MM:SS)\n"
" \\@ 12 hour notation with AM/PM\n"
" \\u user name\n"
" \\v version\n"
" \\V version with patch level\n"
" \\w current directory\n"
" \\W base name of current directory($HOME is replaced by tilde)\n"
" \\$ # if uid is 0, otherwise $\n"
" \\\\ backslash\n"
" \\[ begin of unprintable sequence\n"
" \\] end of unprintable sequence\n"
" \\0nnn N is octal number. NNN can be 0 to 3 number\n"
" \\xnn N is hex number. NN can be 1 to 2 number"},
{"pwd", builtin_pwd, "[-LP]",
" Print the current working directory(absolute path).\n"
" If -L specified, print logical working directory.\n"
" If -P specified, print physical working directory\n"
" (without symbolic link). Default is -L."},
{"read", builtin_read, "[-r] [-p prompt] [-f field separator] [-u fd] [-t timeout] [name ...]",
" Read from standard input.\n"
" Options:\n"
" -r disable backslash escape\n"
" -p specify prompt string\n"
" -f specify field separator (if not, use IFS)\n"
" -s disable echo back\n"
" -u specify file descriptor\n"
" -t timeout set timeout second (only available if input fd is a tty)"},
{"set_env", builtin_setenv, "[name=env ...]",
" set environmental variables."},
{"test", builtin_test, "[expr]",
" Unary or Binary expressions.\n"
" If expression is true, return 0\n"
" If expression is false, return 1\n"
" If operand or operator is invalid, return 2\n"
"\n"
" String operators:\n"
" -z STRING check if string is empty\n"
" -n STRING\n"
" STRING check if string is not empty\n"
" STRING1 = STRING2\n"
" STRING1 == STRING2\n"
" check if strings are equal\n"
" STRING1 != STRING2\n"
" check if strings are not equal\n"
" STRING1 < STRING2\n"
" check if STRING1 is less than STRING2 with dictionary order\n"
" STRING1 > STRING2\n"
" check if STRING2 is greater than STRING2 with dictionary order\n"
" Integer operators:\n"
" INT1 -eq INT2 check if integers are equal\n"
" INT1 -ne INT2 check if integers are not equal\n"
" INT1 -lt INT2 check if INT1 is less than INT2\n"
" INT1 -gt INT2 check if INT1 is greater than INT2\n"
" INT1 -le INT2 check if INT1 is less than or equal to INT2\n"
" INT1 -ge INT2 check if INT1 is greater than or equal to INT2\n"
"\n"
" Integer value is signed int 64.\n"
"\n"
" File operators:\n"
" -a FILE\n"
" -e FILE check if file exists\n"
" -b FILE check if file is block device\n"
" -c FILE check if file is character device\n"
" -d FILE check if file is a directory\n"
" -f FILE check if file is a regular file\n"
" -g FILE check if file has set-group-id bit\n"
" -h FILE\n"
" -L FILE check if file is a symbolic link\n"
" -k FILE check if file has sticky bit\n"
" -p FILE check if file is a named pipe\n"
" -r FILE check if file is readable\n"
" -s FILE check if file is not empty\n"
" -S FILE check if file is a socket\n"
" -t FD check if file descriptor is a terminal\n"
" -u FILE check if file has set-user-id bit\n"
" -w FILE check if file is writable\n"
" -x FILE check if file is executable\n"
" -O FILE check if file is effectively owned by user\n"
" -G FILE check if file is effectively owned by group"},
{"true", builtin_true, "",
" Always success (exit status is 0)."},
{"unset_env", builtin_unsetenv, "[name ...]",
" unset environmental variables."},
};
unsigned int getBuiltinCommandSize() {
return arraySize(builtinCommands);
}
const char *getBuiltinCommandName(unsigned int index) {
assert(index < getBuiltinCommandSize());
return builtinCommands[index].commandName;
}
/**
* return null, if not found builtin command.
*/
builtin_command_t lookupBuiltinCommand(const char *commandName) {
/**
* builtin command name and index.
*/
static CStringHashMap<unsigned int> builtinMap;
if(builtinMap.empty()) {
for(unsigned int i = 0; i < arraySize(builtinCommands); i++) {
builtinMap.insert(std::make_pair(builtinCommands[i].commandName, i));
}
}
auto iter = builtinMap.find(commandName);
if(iter == builtinMap.end()) {
return nullptr;
}
return builtinCommands[iter->second].cmd_ptr;
}
static void printAllUsage(FILE *fp) {
for(const auto &e : builtinCommands) {
fprintf(fp, "%s %s\n", e.commandName, e.usage);
}
}
static bool startsWith(const char *prefix, const char *target) {
const unsigned int prefixSize = strlen(prefix);
const unsigned int targetSize = strlen(target);
return prefixSize <= targetSize && strncmp(prefix, target, prefixSize) == 0;
}
/**
* if not found command, return false.
*/
static bool printUsage(FILE *fp, const char *prefix, bool isShortHelp = true) {
bool matched = false;
for(const auto &e : builtinCommands) {
const char *cmdName = e.commandName;
if(startsWith(prefix, cmdName)) {
fprintf(fp, "%s: %s %s\n", cmdName, cmdName, e.usage);
if(!isShortHelp) {
fprintf(fp, "%s\n", e.detail);
}
matched = true;
}
}
return matched;
}
static int builtin_help(DSState &, Array_Object &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
printAllUsage(stdout);
return 0;
}
bool isShortHelp = false;
bool foundValidCommand = false;
for(unsigned int i = 1; i < size; i++) {
const char *arg = str(argvObj.getValues()[i]);
if(strcmp(arg, "-s") == 0 && size == 2) {
printAllUsage(stdout);
foundValidCommand = true;
} else if(strcmp(arg, "-s") == 0 && i == 1) {
isShortHelp = true;
} else {
if(printUsage(stdout, arg, isShortHelp)) {
foundValidCommand = true;
}
}
}
if(!foundValidCommand) {
ERROR(argvObj, "no help topics match `%s'. Try `help help'.", str(argvObj.getValues()[size - 1]));
return 1;
}
return 0;
}
static int showUsage(const Array_Object &obj) {
printUsage(stderr, str(obj.getValues()[0]));
return 2;
}
int invalidOptionError(const Array_Object &obj, const GetOptState &s) {
ERROR(obj, "-%c: invalid option", s.optOpt);
return showUsage(obj);
}
static int invalidOptionError(const Array_Object &obj, const char *opt) {
ERROR(obj, "%s: invalid option", opt);
return showUsage(obj);
}
static int builtin_cd(DSState &state, Array_Object &argvObj) {
GetOptState optState;
bool useLogical = true;
for(int opt; (opt = optState(argvObj, "PL")) != -1;) {
switch(opt) {
case 'P':
useLogical = false;
break;
case 'L':
useLogical = true;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
unsigned int index = optState.index;
const char *dest = nullptr;
bool useOldpwd = false;
if(index < argvObj.getValues().size()) {
dest = str(argvObj.getValues()[index]);
if(strcmp(dest, "-") == 0) {
dest = getenv(ENV_OLDPWD);
if(dest == nullptr) {
ERROR(argvObj, "OLDPWD not set");
return 1;
}
useOldpwd = true;
}
} else {
dest = getenv(ENV_HOME);
if(dest == nullptr) {
ERROR(argvObj, "HOME not set");
return 1;
}
}
if(useOldpwd && dest != nullptr) {
printf("%s\n", dest);
}
if(!changeWorkingDir(state, dest, useLogical)) {
PERROR(argvObj, "%s", dest);
return 1;
}
return 0;
}
static int builtin_check_env(DSState &, Array_Object &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
return showUsage(argvObj);
}
for(unsigned int i = 1; i < size; i++) {
const char *env = getenv(str(argvObj.getValues()[i]));
if(env == nullptr || strlen(env) == 0) {
return 1;
}
}
return 0;
}
static int builtin_echo(DSState &, Array_Object &argvObj) {
bool newline = true;
bool interpEscape = false;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "neE")) != -1;) {
switch(opt) {
case 'n':
newline = false;
break;
case 'e':
interpEscape = true;
break;
case 'E':
interpEscape = false;
break;
default:
goto END;
}
}
END:
// print argument
if(optState.index > 1 && strcmp(str(argvObj.getValues()[optState.index - 1]), "--") == 0) {
optState.index--;
}
unsigned int index = optState.index;
const unsigned int argc = argvObj.getValues().size();
bool firstArg = true;
for(; index < argc; index++) {
if(firstArg) {
firstArg = false;
} else {
fputc(' ', stdout);
}
if(!interpEscape) {
fputs(str(argvObj.getValues()[index]), stdout);
continue;
}
const char *arg = str(argvObj.getValues()[index]);
for(unsigned int i = 0; arg[i] != '\0'; i++) {
char ch = arg[i];
if(ch == '\\' && arg[i + 1] != '\0') {
switch(arg[++i]) {
case '\\':
ch = '\\';
break;
case 'a':
ch = '\a';
break;
case 'b':
ch = '\b';
break;
case 'c': // stop printing
return 0;
case 'e':
case 'E':
ch = '\033';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'v':
ch = '\v';
break;
case '0': {
int v = 0;
for(unsigned int c = 0; c < 3; c++) {
if(isOctal(arg[i + 1])) {
v *= 8;
v += arg[++i] - '0';
} else {
break;
}
}
ch = static_cast<char>(v);
break;
}
case 'x': {
if(isHex(arg[i + 1])) {
int v = toHex(arg[++i]);
if(isHex(arg[i + 1])) {
v *= 16;
v += toHex(arg[++i]);
}
ch = static_cast<char>(v);
break;
}
i--;
break;
}
default:
i--;
break;
}
}
fputc(ch, stdout);
}
}
if(newline) {
fputc('\n', stdout);
}
return 0;
}
static int builtin_true(DSState &, Array_Object &) {
return 0;
}
static int builtin_false(DSState &, Array_Object &) {
return 1;
}
/**
* for stdin redirection test
*/
static int builtin___gets(DSState &, Array_Object &) {
unsigned int bufSize = 256;
char buf[bufSize];
int readSize;
while((readSize = fread(buf, sizeof(char), bufSize, stdin)) > 0) {
fwrite(buf, sizeof(char), readSize, stdout);
}
clearerr(stdin); // clear eof flag
return 0;
}
/**
* for stdout/stderr redirection test
*/
static int builtin___puts(DSState &, Array_Object &argvObj) {
GetOptState optState;
for(int opt; (opt = optState(argvObj, "1:2:")) != -1;) {
switch(opt) {
case '1':
fputs(optState.optArg, stdout);
fputc('\n', stdout);
fflush(stdout);
break;
case '2':
fputs(optState.optArg, stderr);
fputc('\n', stderr);
fflush(stderr);
break;
default:
return 1;
}
}
return 0;
}
/**
* for prompt string debugging
*/
static int builtin_ps_intrp(DSState &state, Array_Object &argvObj) {
if(argvObj.getValues().size() != 2) {
return showUsage(argvObj);
}
std::string v = interpretPromptString(state, str(argvObj.getValues()[1]));
fputs(v.c_str(), stdout);
fputc('\n', stdout);
return 0;
}
static int builtin_pwd(DSState &state, Array_Object &argvObj) {
bool useLogical = true;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "LP")) != -1;) {
switch(opt) {
case 'L':
useLogical = true;
break;
case 'P':
useLogical = false;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
std::string buf;
const char *ptr = getWorkingDir(state, useLogical, buf);
if(ptr == nullptr) {
PERROR(argvObj, ".");
return 1;
}
printf("%s\n", ptr);
return 0;
}
enum class BinaryOp : unsigned int {
INVALID,
STR_EQ,
STR_NE,
STR_LT,
STR_GT,
EQ,
NE,
LT,
GT,
LE,
GE,
};
static int builtin_test(DSState &, Array_Object &argvObj) {
const struct {
const char *k;
BinaryOp op;
} binaryOpTable[] = {
{"=", BinaryOp::STR_EQ},
{"==", BinaryOp::STR_EQ},
{"!=", BinaryOp::STR_NE},
{"<", BinaryOp::STR_LT},
{">", BinaryOp::STR_GT},
{"-eq", BinaryOp::EQ},
{"-ne", BinaryOp::NE},
{"-lt", BinaryOp::LT},
{"-gt", BinaryOp::GT},
{"-le", BinaryOp::LE},
{"-ge", BinaryOp::GE},
};
bool result = false;
unsigned int argc = argvObj.getValues().size();
const unsigned int argSize = argc - 1;
switch(argSize) {
case 0: {
result = false;
break;
}
case 1: {
result = strlen(str(argvObj.getValues()[1])) != 0; // check if string is not empty
break;
}
case 2: { // unary op
const char *op = str(argvObj.getValues()[1]);
const char *value = str(argvObj.getValues()[2]);
if(strlen(op) != 2 || op[0] != '-') {
ERROR(argvObj, "%s: invalid unary operator", op);
return 2;
}
const char opKind = op[1]; // ignore -
switch(opKind) {
case 'z': { // check if string is empty
result = strlen(value) == 0;
break;
}
case 'n': { // check if string not empty
result = strlen(value) != 0;
break;
}
case 'a':
case 'e': {
result = access(value, F_OK) == 0; // check if file exists
break;
}
case 'b': {
result = S_ISBLK(getStMode(value)); // check if file is block device
break;
}
case 'c': {
result = S_ISCHR(getStMode(value)); // check if file is character device
break;
}
case 'd': {
result = S_ISDIR(getStMode(value)); // check if file is directory
break;
}
case 'f': {
result = S_ISREG(getStMode(value)); // check if file is regular file.
break;
}
case 'g': {
result = S_IS_PERM_(getStMode(value), S_ISUID); // check if file has set-uid-bit
break;
}
case 'h':
case 'L': {
mode_t mode = 0;
struct stat st{};
if(lstat(value, &st) == 0) {
mode = st.st_mode;
}
result = S_ISLNK(mode); // check if file is symbolic-link
break;
}
case 'k': {
result = S_IS_PERM_(getStMode(value), S_ISVTX); // check if file has sticky bit
break;
}
case 'p': {
result = S_ISFIFO(getStMode(value)); // check if file is a named pipe
break;
}
case 'r': {
result = access(value, R_OK) == 0; // check if file is readable
break;
}
case 's': {
struct stat st{};
result = stat(value, &st) == 0 && st.st_size != 0; // check if file is not empty
break;
}
case 'S': {
result = S_ISSOCK(getStMode(value)); // check file is a socket
break;
}
case 't': {
int s;
long n = convertToInt64(value, s);
result = s == 0 && n >= INT32_MIN && n <= INT32_MAX && isatty(n) != 0; // check if FD is a terminal
break;
}
case 'u': {
result = S_IS_PERM_(getStMode(value), S_ISUID); // check file has set-user-id bit
break;
}
case 'w': {
result = access(value, W_OK) == 0; // check if file is writable
break;
}
case 'x': {
result = access(value, X_OK) == 0; // check if file is executable
break;
}
case 'O': {
struct stat st{};
result = stat(value, &st) == 0 && st.st_uid == geteuid(); // check if file is effectively owned
break;
}
case 'G': {
struct stat st{};
result = stat(value, &st) == 0 && st.st_gid == getegid(); // check if file is effectively owned by group
break;
}
default: {
ERROR(argvObj, "%s: invalid unary operator", op);
return 2;
}
}
break;
}
case 3: { // binary op
const char *left = str(argvObj.getValues()[1]);
const char *op = str(argvObj.getValues()[2]);
const char *right = str(argvObj.getValues()[3]);
BinaryOp opKind = BinaryOp::INVALID;
for(auto &e : binaryOpTable) {
if(strcmp(op, e.k) == 0) {
opKind = e.op;
break;
}
}
switch(opKind) {
case BinaryOp::STR_EQ: {
result = strcmp(left, right) == 0;
break;
}
case BinaryOp::STR_NE: {
result = strcmp(left, right) != 0;
break;
}
case BinaryOp::STR_LT: {
result = strcmp(left, right) < 0;
break;
}
case BinaryOp::STR_GT: {
result = strcmp(left, right) > 0;
break;
}
case BinaryOp::EQ:
case BinaryOp::NE:
case BinaryOp::LT:
case BinaryOp::GT:
case BinaryOp::LE:
case BinaryOp::GE: {
int s = 0;
long n1 = convertToInt64(left, s);
if(s != 0) {
ERROR(argvObj, "%s: must be integer", left);
return 2;
}
long n2 = convertToInt64(right, s);
if(s != 0) {
ERROR(argvObj, "%s: must be integer", right);
return 2;
}
if(opKind == BinaryOp::EQ) {
result = n1 == n2;
} else if(opKind == BinaryOp::NE) {
result = n1 != n2;
} else if(opKind == BinaryOp::LT) {
result = n1 < n2;
} else if(opKind == BinaryOp::GT) {
result = n1 > n2;
} else if(opKind == BinaryOp::LE) {
result = n1 <= n2;
} else if(opKind == BinaryOp::GE) {
result = n1 >= n2;
}
break;
}
case BinaryOp::INVALID: {
ERROR(argvObj, "%s: invalid binary operator", op);
return 2;
}
}
break;
}
default: {
ERROR(argvObj, "too many arguments");
return 2;
}
}
return result ? 0 : 1;
}
static int xfgetc(int fd, int timeout) {
char ch;
do {
errno = 0;
if(timeout > -2) {
struct pollfd pollfd[1];
pollfd[0].fd = fd;
pollfd[0].events = POLLIN;
if(poll(pollfd, 1, timeout) != 1) {
return EOF;
}
}
if(read(fd, &ch, 1) <= 0) {
ch = EOF;
}
} while(ch == EOF && (errno == EAGAIN || errno == EINTR));
return ch;
}
static int builtin_read(DSState &state, Array_Object &argvObj) { //FIXME: timeout, UTF-8
const char *prompt = "";
const char *ifs = nullptr;
unsigned int ifsSize = 0;
bool backslash = true;
bool noecho = false;
int fd = STDIN_FILENO;
int timeout = -1;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "rp:f:su:t:")) != -1;) {
switch(opt) {
case 'p':
prompt = optState.optArg;
break;
case 'f':
ifs = optState.optArg;
ifsSize = typeAs<String_Object>(argvObj.getValues()[optState.index - 1])->size();
break;
case 'r':
backslash = false;
break;
case 's':
noecho = true;
break;
case 'u': {
const char *arg = optState.optArg;
if(arg == strstr(arg, "/dev/fd/")) {
arg += strlen("/dev/fd/");
}
int s;
long t = convertToInt64(arg, s);
if(s != 0 || t < 0 || t > INT32_MAX) {
ERROR(argvObj, "%s: invalid file descriptor", optState.optArg);
return 1;
}
fd = static_cast<int>(t);
break;
}
case 't': {
int s;
long t = convertToInt64(optState.optArg, s);
if(s == 0) {
if(t > -1 && t <= INT32_MAX) {
t *= 1000;
if(t > -1 && t <= INT32_MAX) {
timeout = static_cast<int>(t);
break;
}
}
}
ERROR(argvObj, "%s: invalid timeout specification", optState.optArg);
return 1;
}
case ':':
ERROR(argvObj, "-%c: option require argument", optState.optOpt);
return 2;
default:
return invalidOptionError(argvObj, optState);
}
}
const unsigned int argc = argvObj.getValues().size();
unsigned int index = optState.index;
const bool isTTY = isatty(fd) != 0;
// check ifs
if(ifs == nullptr) {
auto *strObj = typeAs<String_Object>(getGlobal(state, toIndex(BuiltinVarOffset::IFS)));
ifs = strObj->getValue();
ifsSize = strObj->size();
}
// clear old variable before read
setGlobal(state, toIndex(BuiltinVarOffset::REPLY), getEmptyStrObj(state)); // clear REPLY
typeAs<Map_Object>(getGlobal(state, toIndex(BuiltinVarOffset::REPLY_VAR)))->clear(); // clear reply
const int varSize = argc - index; // if zero, store line to REPLY
const unsigned int varIndex = toIndex(varSize == 0 ? BuiltinVarOffset::REPLY : BuiltinVarOffset::REPLY_VAR);
std::string strBuf;
// show prompt
if(isTTY) {
fputs(prompt, stderr);
fflush(stderr);
}
// change tty state
struct termios tty{};
struct termios oldtty{};
if(noecho && isTTY) {
tcgetattr(fd, &tty);
oldtty = tty;
tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
tcsetattr(fd, TCSANOW, &tty);
}
// read line
if(!isTTY) {
timeout = -2;
}
unsigned int skipCount = 1;
int ch;
for(bool prevIsBackslash = false; (ch = xfgetc(fd, timeout)) != EOF;
prevIsBackslash = backslash && ch == '\\' && !prevIsBackslash) {
if(ch == '\n') {
if(prevIsBackslash) {
continue;
}
break;
}
if(ch == '\\' && !prevIsBackslash && backslash) {
continue;
}
bool fieldSep = isFieldSep(ifsSize, ifs, ch) && !prevIsBackslash;
if(fieldSep && skipCount > 0) {
if(isSpace(ch)) {
continue;
}
if(--skipCount == 1) {
continue;
}
}
skipCount = 0;
if(fieldSep && index < argc - 1) {
auto obj = typeAs<Map_Object>(getGlobal(state, varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::create<String_Object>(getPool(state).get(TYPE::String), std::move(strBuf));
obj->set(std::move(varObj), std::move(valueObj));
strBuf = "";
index++;
skipCount = isSpace(ch) ? 2 : 1;
continue;
}
strBuf += static_cast<char>(ch);
}
// remove last spaces
if(!strBuf.empty()) {
// check if field separator has spaces
bool hasSpace = false;
for(unsigned int i = 0; ifs[i] != '\0'; i++) {
if((hasSpace = isSpace(ifs[i]))) {
break;
}
}
if(hasSpace) {
while(!strBuf.empty() && isSpace(strBuf.back())) {
strBuf.pop_back();
}
}
}
if(varSize == 0) {
setGlobal(state, varIndex,
DSValue::create<String_Object>(getPool(state).get(TYPE::String), std::move(strBuf)));
strBuf = "";
}
// set rest variable
for(; index < argc; index++) {
auto obj = typeAs<Map_Object>(getGlobal(state, varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::create<String_Object>(getPool(state).get(TYPE::String), std::move(strBuf));
obj->set(std::move(varObj), std::move(valueObj));
strBuf = "";
}
// restore tty setting
if(noecho && isTTY) {
tcsetattr(fd, TCSANOW, &oldtty);
}
// report error
int ret = ch == EOF ? 1 : 0;
if(ret != 0 && errno != 0) {
PERROR(argvObj, "%d", fd);
}
return ret;
}
static int builtin_hash(DSState &state, Array_Object &argvObj) {
bool remove = false;
// check option
const unsigned int argc = argvObj.getValues().size();
unsigned int index = 1;
for(; index < argc; index++) {
const char *arg = str(argvObj.getValues()[index]);
if(arg[0] != '-') {
break;
}
if(strcmp(arg, "-r") == 0) {
remove = true;
} else {
return invalidOptionError(argvObj, arg);
}
}
const bool hasNames = index < argc;
if(hasNames) {
for(; index < argc; index++) {
const char *name = str(argvObj.getValues()[index]);
if(remove) {
getPathCache(state).removePath(name);
} else {
if(getPathCache(state).searchPath(name) == nullptr) {
ERROR(argvObj, "%s: not found", name);
return 1;
}
}
}
} else {
if(remove) { // remove all cache
getPathCache(state).clear();
} else { // show all cache
const auto cend = getPathCache(state).end();
if(getPathCache(state).begin() == cend) {
fputs("hash: file path cache is empty\n", stdout);
return 0;
}
for(auto &entry : getPathCache(state)) {
printf("%s=%s\n", entry.first, entry.second.c_str());
}
}
}
return 0;
}
// for completor debugging
static int builtin_complete(DSState &state, Array_Object &argvObj) {
const unsigned int argc = argvObj.getValues().size();
if(argc != 2) {
return showUsage(argvObj);
}
std::string line = str(argvObj.getValues()[1]);
line += '\n';
auto c = completeLine(state, line);
for(const auto &e : c) {
fputs(e, stdout);
fputc('\n', stdout);
free(e);
}
return 0;
}
static int showHistory(DSState &state, const Array_Object &obj) {
auto *history = DSState_history(&state);
unsigned int printOffset = history->size;
const unsigned int histSize = history->size;
const unsigned int argc = obj.getValues().size();
if(argc > 1) {
if(argc > 2) {
ERROR(obj, "too many arguments");
return 1;
}
int s;
const char *arg = str(obj.getValues()[1]);
printOffset = convertToUint64(arg, s);
if(s != 0) {
ERROR(obj, "%s: numeric argument required", arg);
return 1;
}
if(printOffset > histSize) {
printOffset = histSize;
}
}
const unsigned int histCmd = typeAs<Int_Object>(getGlobal(state, toIndex(BuiltinVarOffset::HIST_CMD)))->getValue();
const unsigned int base = histCmd - histSize;
for(unsigned int i = histSize - printOffset; i < histSize; i++) {
fprintf(stdout, "%5d %s\n", i + base, history->data[i]);
}
return 0;
}
static int builtin_history(DSState &state, Array_Object &argvObj) {
DSState_syncHistorySize(&state);
const unsigned int argc = argvObj.getValues().size();
if(argc == 1 || str(argvObj.getValues()[1])[0] != '-') {
return showHistory(state, argvObj);
}
char op = '\0';
const char *fileName = nullptr;
const char *deleteTarget = nullptr;
for(unsigned int i = 1; i < argc; i++) {
const char *arg = str(argvObj.getValues()[i]);
if(arg[0] == '-' && strlen(arg) == 2) {
char ch = arg[1];
switch(ch) {
case 'c':
DSState_clearHistory(&state);
return 0;
case 'd': {
if(i + 1 < argc) {
deleteTarget = str(argvObj.getValues()[++i]);
continue;
}
ERROR(argvObj, "%s: option requires argument", arg);
return 2;
}
case 'r':
case 'w': {
if(op != '\0') {
ERROR(argvObj, "cannot use more than one of -rw");
return 1;
}
op = ch;
fileName = i + 1 < argc
&& str(argvObj.getValues()[i + 1])[0] != '-' ? str(argvObj.getValues()[++i]) : nullptr;
continue;
}
default:
break;
}
}
return invalidOptionError(argvObj, arg);
}
auto *history = DSState_history(&state);
if(deleteTarget != nullptr) {
int s;
int offset = convertToInt64(deleteTarget, s) - 1;
if(s != 0 || offset < 0 || static_cast<unsigned int>(offset) > history->size) {
ERROR(argvObj, "%s: history offset out of range", deleteTarget);
return 1;
}
DSState_deleteHistoryAt(&state, offset);
return 0;
}
switch(op) {
case 'r':
DSState_loadHistory(&state, fileName);
break;
case 'w':
DSState_saveHistory(&state, fileName);
break;
}
return 0;
}
static int builtin_setenv(DSState &, Array_Object &argvObj) {
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
const char *kv = str(*iter);
auto *ptr = strchr(kv, '=');
errno = EINVAL;
if(ptr != nullptr && ptr != kv) {
std::string name(kv, ptr - kv);
if(setenv(name.c_str(), ptr + 1, 1) == 0) {
continue;
}
}
PERROR(argvObj, "%s", kv);
return 1;
}
return 0;
}
static int builtin_unsetenv(DSState &, Array_Object &argvObj) {
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
const char *envName = str(*iter);
if(unsetenv(envName) != 0) {
PERROR(argvObj, "%s", envName);
return 1;
}
}
return 0;
}
static std::pair<int, bool> toInt32(const char *str) {
int s = 0;
long v = convertToInt64(str, s);
if(s != 0 || v < INT32_MIN || v > INT32_MAX) {
return {0, false};
}
return {static_cast<int>(v), true};
};
static int toSigNum(const char *str) {
if(isDecimal(*str)) {
auto pair = toInt32(str);
if(!pair.second) {
return -1;
}
auto sigList = getUniqueSignalList();
return std::binary_search(sigList.begin(), sigList.end(), pair.first) ? pair.first : -1;
}
return getSignalNum(str);
}
static bool printNumOrName(const char *str) {
if(isDecimal(*str)) {
auto pair = toInt32(str);
if(!pair.second) {
return false;
}
const char *name = getSignalName(pair.first);
if(name == nullptr) {
return false;
}
printf("%s\n", name);
} else {
int sigNum = getSignalNum(str);
if(sigNum < 0) {
return false;
}
printf("%d\n", sigNum);
}
fflush(stdout);
return true;
}
static bool killProcOrJob(DSState &state, Array_Object &argvObj, const char *arg, int sigNum) {
bool isJob = *arg == '%';
auto pair = toInt32(isJob ? arg + 1 : arg);
if(!pair.second) {
ERROR(argvObj, "%s: arguments must be process or job IDs", arg);
return false;
}
if(isJob) {
if(pair.first > 0) {
auto job = getJobTable(state).findEntry(static_cast<unsigned int>(pair.first));
if(job) {
job->send(sigNum);
return true;
}
}
ERROR(argvObj, "%s: no such job", arg);
return false;
}
if(kill(pair.first, sigNum) < 0) {
PERROR(argvObj, "%s", arg);
return false;
}
return true;
}
// -s sig (pid | jobspec ...)
// -l
static int builtin_kill(DSState &state, Array_Object &argvObj) {
int sigNum = SIGTERM;
bool listing = false;
if(argvObj.getValues().size() == 1) {
return showUsage(argvObj);
}
GetOptState optState;
const int opt = optState(argvObj, "ls:");
switch(opt) {
case 'l':
listing = true;
break;
case 's':
case '?': {
const char *sigStr = optState.optArg;
if(opt == '?') {
sigStr = str(argvObj.getValues()[optState.index++]) + 1;
}
sigNum = toSigNum(sigStr);
if(sigNum == -1) {
ERROR(argvObj, "%s: invalid signal specification", sigStr);
return 1;
}
break;
}
case ':':
ERROR(argvObj, "-%c: option requires argument", optState.optOpt);
return 1;
}
auto begin = argvObj.getValues().begin() + optState.index;
const auto end = argvObj.getValues().end();
if(begin == end) {
if(listing) {
auto sigList = getUniqueSignalList();
unsigned int size = sigList.size();
for(unsigned int i = 0; i < size; i++) {
printf("%2d) SIG%s", sigList[i], getSignalName(sigList[i]));
if(i % 5 == 4 || i == size - 1) {
fputc('\n', stdout);
} else {
fputc('\t', stdout);
}
}
return 0;
}
return showUsage(argvObj);
}
unsigned int count = 0;
for(; begin != end; ++begin) {
const char *arg = str(*begin);
if(listing) {
if(!printNumOrName(arg)) {
count++;
ERROR(argvObj, "%s: invalid signal specification", arg);
}
} else {
if(killProcOrJob(state, argvObj, arg, sigNum)) {
count++;
}
}
}
if(listing && count > 0) {
return 1;
}
if(!listing && count == 0) {
return 1;
}
return 0;
}
static Job tryToGetJob(const JobTable &table, const char *name) {
if(*name == '%') {
name++;
}
Job job;
auto pair = toInt32(name);
if(pair.second && pair.first > -1) {
job = table.findEntry(pair.first);
}
return job;
}
static int builtin_fg_bg(DSState &state, Array_Object &argvObj) {
if(!hasFlag(DSState_option(&state), DS_OPTION_JOB_CONTROL)) {
ERROR(argvObj, "no job control in this shell");
return 1;
}
bool fg = strcmp("fg", str(argvObj.getValues()[0])) == 0;
unsigned int size = argvObj.getValues().size();
assert(size > 0);
Job job;
const char *arg = "current";
if(size == 1) {
job = getJobTable(state).getLatestEntry();
} else {
arg = str(argvObj.getValues()[1]);
job = tryToGetJob(getJobTable(state), arg);
}
int ret = 0;
if(job) {
if(fg) {
tcsetpgrp(STDIN_FILENO, getpgid(job->getPid(0)));
}
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg);
ret = 1;
if(fg) {
return ret;
}
}
if(fg) {
int s = getJobTable(state).waitAndDetach(job, true); //FIXME: check root shell
tryToForeground(state);
getJobTable(state).updateStatus();
return s;
}
// process remain arguments
for(unsigned int i = 2; i < size; i++) {
arg = str(argvObj.getValues()[i]);
job = tryToGetJob(getJobTable(state), arg);
if(job) {
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg);
ret = 1;
}
}
return ret;
}
} // namespace ydsh
test command accepts /dev/fd/*
/*
* Copyright (C) 2015-2018 Nagisa Sekiguchi
*
* 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 <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <poll.h>
#include <cstdlib>
#include <cstdarg>
#include <unordered_map>
#include <ydsh/ydsh.h>
#include "logger.h"
#include "cmd.h"
#include "core.h"
#include "constant.h"
#include "symbol_table.h"
#include "object.h"
#include "signals.h"
#include "misc/num.h"
#include "misc/files.h"
namespace ydsh {
// builtin command definition
static int builtin___gets(DSState &state, Array_Object &argvObj);
static int builtin___puts(DSState &state, Array_Object &argvObj);
static int builtin_cd(DSState &state, Array_Object &argvObj);
static int builtin_check_env(DSState &state, Array_Object &argvObj);
static int builtin_complete(DSState &state, Array_Object &argvObj);
static int builtin_echo(DSState &state, Array_Object &argvObj);
static int builtin_false(DSState &state, Array_Object &argvObj);
static int builtin_fg_bg(DSState &state, Array_Object &argvObj);
static int builtin_hash(DSState &state, Array_Object &argvObj);
static int builtin_help(DSState &state, Array_Object &argvObj);
static int builtin_history(DSState &state, Array_Object &argvObj);
static int builtin_kill(DSState &state, Array_Object &argvObj);
static int builtin_ps_intrp(DSState &state, Array_Object &argvObj);
static int builtin_pwd(DSState &state, Array_Object &argvObj);
static int builtin_read(DSState &state, Array_Object &argvObj);
static int builtin_setenv(DSState &state, Array_Object &argvObj);
static int builtin_test(DSState &state, Array_Object &argvObj);
static int builtin_true(DSState &state, Array_Object &argvObj);
static int builtin_unsetenv(DSState &state, Array_Object &argvObj);
const struct {
const char *commandName;
builtin_command_t cmd_ptr;
const char *usage;
const char *detail;
} builtinCommands[] {
{":", builtin_true, "",
" Null command. Always success (exit status is 0)."},
{"__gets", builtin___gets, "",
" Read standard input and write to standard output."},
{"__puts", builtin___puts, "[-1 arg1] [-2 arg2]",
" Print specified argument to standard output/error and print new line.\n"
" Options:\n"
" -1 print to standard output\n"
" -2 print to standard error"},
{"bg", builtin_fg_bg, "[job_spec ...]",
" Move jobs to the background.\n"
" If JOB_SPEC is not present, latest job is used."},
{"cd", builtin_cd, "[-LP] [dir]",
" Changing the current directory to DIR. The Environment variable\n"
" HOME is the default DIR. A null directory name is the same as\n"
" the current directory. If -L is specified, use logical directory \n"
" (with symbolic link). If -P is specified, use physical directory \n"
" (without symbolic link). Default is -L."},
{"check_env", builtin_check_env, "variable ...",
" Check existence of specified environmental variables.\n"
" If all of variables are exist and not empty string, exit with 0."},
{"command", nullptr, "[-pVv] command [arg ...]",
" Execute COMMAND with ARGS excepting user defined command.\n"
" If -p option is specified, search command from default PATH.\n"
" If -V or -v option are specified, print description of COMMAND.\n"
" -V option shows more detailed information."},
{"complete", builtin_complete, "line",
" Show completion candidates."},
{"echo", builtin_echo, "[-neE] [arg ...]",
" Print argument to standard output and print new line.\n"
" Options:\n"
" -n not print new line\n"
" -e interpret some escape sequence\n"
" \\\\ backslash\n"
" \\a bell\n"
" \\b backspace\n"
" \\c ignore subsequent string\n"
" \\e escape sequence\n"
" \\E escape sequence\n"
" \\f form feed\n"
" \\n newline\n"
" \\r carriage return\n"
" \\t horizontal tab\n"
" \\v vertical tab\n"
" \\0nnn N is octal number. NNN can be 0 to 3 number\n"
" \\xnn N is hex number. NN can be 1 to 2 number\n"
" -E disable escape sequence interpretation"},
{"eval", nullptr, "[args ...]",
" evaluate ARGS as command."},
{"exec", nullptr, "[-c] [-a name] file [args ...]",
" Execute FILE and replace this shell with specified program.\n"
" If FILE is not specified, the redirections take effect in this shell.\n"
" IF FILE execution fail, terminate this shell immediately\n"
" Options:\n"
" -c cleaner environmental variable\n"
" -a specify set program name(default is FILE)"},
{"exit", nullptr, "[n]",
" Exit the shell with a status of N. If N is omitted, the exit\n"
" status is $?."},
{"false", builtin_false, "",
" Always failure (exit status is 1)."},
{"fg", builtin_fg_bg, "[job_spec]",
" Move job to the foreground.\n"
" If JOB_SPEC is not present, latest job is used."},
{"hash", builtin_hash, "[-r] [command ...]",
" Cache file path of specified commands. If -r option is supplied,\n"
" removes specified command path (if not specified, remove all cache).\n"
" If option is not supplied, display all cached path."},
{"help", builtin_help, "[-s] [pattern ...]",
" Display helpful information about builtin commands."},
{"history", builtin_history, "[-c] [-d offset] or history [-rw] [file]",
" Display or manipulate history list.\n"
" Options:\n"
" -c clear the history list\n"
" -d offset delete the history entry at OFFSET\n"
"\n"
" -r read the history list from history file\n"
" -w write the history list to history file"},
{"kill", builtin_kill, "[-s signal] pid | jobspec ... or kill -l [signal...]",
" Send a signal to a process or job.\n"
" If signal is not specified, then SIGTERM is assumed.\n"
" Options:\n"
" -s sig send a signal. SIG is a signal name or signal number\n"
" -l list the signal names"},
{"ps_intrp", builtin_ps_intrp, "prompt",
" Interpret prompt string.\n"
" Escape Sequence:\n"
" \\a bell\n"
" \\d date\n"
" \\e escape sequence\n"
" \\h host name\n"
" \\H fully qualified host name\n"
" \\n newline\n"
" \\r carriage return\n"
" \\s base name of $0\n"
" \\t 24 hour notation (HH:MM:SS)\n"
" \\T 12 hour notation (HH:MM:SS)\n"
" \\@ 12 hour notation with AM/PM\n"
" \\u user name\n"
" \\v version\n"
" \\V version with patch level\n"
" \\w current directory\n"
" \\W base name of current directory($HOME is replaced by tilde)\n"
" \\$ # if uid is 0, otherwise $\n"
" \\\\ backslash\n"
" \\[ begin of unprintable sequence\n"
" \\] end of unprintable sequence\n"
" \\0nnn N is octal number. NNN can be 0 to 3 number\n"
" \\xnn N is hex number. NN can be 1 to 2 number"},
{"pwd", builtin_pwd, "[-LP]",
" Print the current working directory(absolute path).\n"
" If -L specified, print logical working directory.\n"
" If -P specified, print physical working directory\n"
" (without symbolic link). Default is -L."},
{"read", builtin_read, "[-r] [-p prompt] [-f field separator] [-u fd] [-t timeout] [name ...]",
" Read from standard input.\n"
" Options:\n"
" -r disable backslash escape\n"
" -p specify prompt string\n"
" -f specify field separator (if not, use IFS)\n"
" -s disable echo back\n"
" -u specify file descriptor\n"
" -t timeout set timeout second (only available if input fd is a tty)"},
{"set_env", builtin_setenv, "[name=env ...]",
" set environmental variables."},
{"test", builtin_test, "[expr]",
" Unary or Binary expressions.\n"
" If expression is true, return 0\n"
" If expression is false, return 1\n"
" If operand or operator is invalid, return 2\n"
"\n"
" String operators:\n"
" -z STRING check if string is empty\n"
" -n STRING\n"
" STRING check if string is not empty\n"
" STRING1 = STRING2\n"
" STRING1 == STRING2\n"
" check if strings are equal\n"
" STRING1 != STRING2\n"
" check if strings are not equal\n"
" STRING1 < STRING2\n"
" check if STRING1 is less than STRING2 with dictionary order\n"
" STRING1 > STRING2\n"
" check if STRING2 is greater than STRING2 with dictionary order\n"
" Integer operators:\n"
" INT1 -eq INT2 check if integers are equal\n"
" INT1 -ne INT2 check if integers are not equal\n"
" INT1 -lt INT2 check if INT1 is less than INT2\n"
" INT1 -gt INT2 check if INT1 is greater than INT2\n"
" INT1 -le INT2 check if INT1 is less than or equal to INT2\n"
" INT1 -ge INT2 check if INT1 is greater than or equal to INT2\n"
"\n"
" Integer value is signed int 64.\n"
"\n"
" File operators:\n"
" -a FILE\n"
" -e FILE check if file exists\n"
" -b FILE check if file is block device\n"
" -c FILE check if file is character device\n"
" -d FILE check if file is a directory\n"
" -f FILE check if file is a regular file\n"
" -g FILE check if file has set-group-id bit\n"
" -h FILE\n"
" -L FILE check if file is a symbolic link\n"
" -k FILE check if file has sticky bit\n"
" -p FILE check if file is a named pipe\n"
" -r FILE check if file is readable\n"
" -s FILE check if file is not empty\n"
" -S FILE check if file is a socket\n"
" -t FD check if file descriptor is a terminal\n"
" -u FILE check if file has set-user-id bit\n"
" -w FILE check if file is writable\n"
" -x FILE check if file is executable\n"
" -O FILE check if file is effectively owned by user\n"
" -G FILE check if file is effectively owned by group"},
{"true", builtin_true, "",
" Always success (exit status is 0)."},
{"unset_env", builtin_unsetenv, "[name ...]",
" unset environmental variables."},
};
unsigned int getBuiltinCommandSize() {
return arraySize(builtinCommands);
}
const char *getBuiltinCommandName(unsigned int index) {
assert(index < getBuiltinCommandSize());
return builtinCommands[index].commandName;
}
/**
* return null, if not found builtin command.
*/
builtin_command_t lookupBuiltinCommand(const char *commandName) {
/**
* builtin command name and index.
*/
static CStringHashMap<unsigned int> builtinMap;
if(builtinMap.empty()) {
for(unsigned int i = 0; i < arraySize(builtinCommands); i++) {
builtinMap.insert(std::make_pair(builtinCommands[i].commandName, i));
}
}
auto iter = builtinMap.find(commandName);
if(iter == builtinMap.end()) {
return nullptr;
}
return builtinCommands[iter->second].cmd_ptr;
}
static void printAllUsage(FILE *fp) {
for(const auto &e : builtinCommands) {
fprintf(fp, "%s %s\n", e.commandName, e.usage);
}
}
static bool startsWith(const char *prefix, const char *target) {
const unsigned int prefixSize = strlen(prefix);
const unsigned int targetSize = strlen(target);
return prefixSize <= targetSize && strncmp(prefix, target, prefixSize) == 0;
}
/**
* if not found command, return false.
*/
static bool printUsage(FILE *fp, const char *prefix, bool isShortHelp = true) {
bool matched = false;
for(const auto &e : builtinCommands) {
const char *cmdName = e.commandName;
if(startsWith(prefix, cmdName)) {
fprintf(fp, "%s: %s %s\n", cmdName, cmdName, e.usage);
if(!isShortHelp) {
fprintf(fp, "%s\n", e.detail);
}
matched = true;
}
}
return matched;
}
static int builtin_help(DSState &, Array_Object &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
printAllUsage(stdout);
return 0;
}
bool isShortHelp = false;
bool foundValidCommand = false;
for(unsigned int i = 1; i < size; i++) {
const char *arg = str(argvObj.getValues()[i]);
if(strcmp(arg, "-s") == 0 && size == 2) {
printAllUsage(stdout);
foundValidCommand = true;
} else if(strcmp(arg, "-s") == 0 && i == 1) {
isShortHelp = true;
} else {
if(printUsage(stdout, arg, isShortHelp)) {
foundValidCommand = true;
}
}
}
if(!foundValidCommand) {
ERROR(argvObj, "no help topics match `%s'. Try `help help'.", str(argvObj.getValues()[size - 1]));
return 1;
}
return 0;
}
static int showUsage(const Array_Object &obj) {
printUsage(stderr, str(obj.getValues()[0]));
return 2;
}
int invalidOptionError(const Array_Object &obj, const GetOptState &s) {
ERROR(obj, "-%c: invalid option", s.optOpt);
return showUsage(obj);
}
static int invalidOptionError(const Array_Object &obj, const char *opt) {
ERROR(obj, "%s: invalid option", opt);
return showUsage(obj);
}
static int builtin_cd(DSState &state, Array_Object &argvObj) {
GetOptState optState;
bool useLogical = true;
for(int opt; (opt = optState(argvObj, "PL")) != -1;) {
switch(opt) {
case 'P':
useLogical = false;
break;
case 'L':
useLogical = true;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
unsigned int index = optState.index;
const char *dest = nullptr;
bool useOldpwd = false;
if(index < argvObj.getValues().size()) {
dest = str(argvObj.getValues()[index]);
if(strcmp(dest, "-") == 0) {
dest = getenv(ENV_OLDPWD);
if(dest == nullptr) {
ERROR(argvObj, "OLDPWD not set");
return 1;
}
useOldpwd = true;
}
} else {
dest = getenv(ENV_HOME);
if(dest == nullptr) {
ERROR(argvObj, "HOME not set");
return 1;
}
}
if(useOldpwd && dest != nullptr) {
printf("%s\n", dest);
}
if(!changeWorkingDir(state, dest, useLogical)) {
PERROR(argvObj, "%s", dest);
return 1;
}
return 0;
}
static int builtin_check_env(DSState &, Array_Object &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
return showUsage(argvObj);
}
for(unsigned int i = 1; i < size; i++) {
const char *env = getenv(str(argvObj.getValues()[i]));
if(env == nullptr || strlen(env) == 0) {
return 1;
}
}
return 0;
}
static int builtin_echo(DSState &, Array_Object &argvObj) {
bool newline = true;
bool interpEscape = false;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "neE")) != -1;) {
switch(opt) {
case 'n':
newline = false;
break;
case 'e':
interpEscape = true;
break;
case 'E':
interpEscape = false;
break;
default:
goto END;
}
}
END:
// print argument
if(optState.index > 1 && strcmp(str(argvObj.getValues()[optState.index - 1]), "--") == 0) {
optState.index--;
}
unsigned int index = optState.index;
const unsigned int argc = argvObj.getValues().size();
bool firstArg = true;
for(; index < argc; index++) {
if(firstArg) {
firstArg = false;
} else {
fputc(' ', stdout);
}
if(!interpEscape) {
fputs(str(argvObj.getValues()[index]), stdout);
continue;
}
const char *arg = str(argvObj.getValues()[index]);
for(unsigned int i = 0; arg[i] != '\0'; i++) {
char ch = arg[i];
if(ch == '\\' && arg[i + 1] != '\0') {
switch(arg[++i]) {
case '\\':
ch = '\\';
break;
case 'a':
ch = '\a';
break;
case 'b':
ch = '\b';
break;
case 'c': // stop printing
return 0;
case 'e':
case 'E':
ch = '\033';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'v':
ch = '\v';
break;
case '0': {
int v = 0;
for(unsigned int c = 0; c < 3; c++) {
if(isOctal(arg[i + 1])) {
v *= 8;
v += arg[++i] - '0';
} else {
break;
}
}
ch = static_cast<char>(v);
break;
}
case 'x': {
if(isHex(arg[i + 1])) {
int v = toHex(arg[++i]);
if(isHex(arg[i + 1])) {
v *= 16;
v += toHex(arg[++i]);
}
ch = static_cast<char>(v);
break;
}
i--;
break;
}
default:
i--;
break;
}
}
fputc(ch, stdout);
}
}
if(newline) {
fputc('\n', stdout);
}
return 0;
}
static int builtin_true(DSState &, Array_Object &) {
return 0;
}
static int builtin_false(DSState &, Array_Object &) {
return 1;
}
/**
* for stdin redirection test
*/
static int builtin___gets(DSState &, Array_Object &) {
unsigned int bufSize = 256;
char buf[bufSize];
int readSize;
while((readSize = fread(buf, sizeof(char), bufSize, stdin)) > 0) {
fwrite(buf, sizeof(char), readSize, stdout);
}
clearerr(stdin); // clear eof flag
return 0;
}
/**
* for stdout/stderr redirection test
*/
static int builtin___puts(DSState &, Array_Object &argvObj) {
GetOptState optState;
for(int opt; (opt = optState(argvObj, "1:2:")) != -1;) {
switch(opt) {
case '1':
fputs(optState.optArg, stdout);
fputc('\n', stdout);
fflush(stdout);
break;
case '2':
fputs(optState.optArg, stderr);
fputc('\n', stderr);
fflush(stderr);
break;
default:
return 1;
}
}
return 0;
}
/**
* for prompt string debugging
*/
static int builtin_ps_intrp(DSState &state, Array_Object &argvObj) {
if(argvObj.getValues().size() != 2) {
return showUsage(argvObj);
}
std::string v = interpretPromptString(state, str(argvObj.getValues()[1]));
fputs(v.c_str(), stdout);
fputc('\n', stdout);
return 0;
}
static int builtin_pwd(DSState &state, Array_Object &argvObj) {
bool useLogical = true;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "LP")) != -1;) {
switch(opt) {
case 'L':
useLogical = true;
break;
case 'P':
useLogical = false;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
std::string buf;
const char *ptr = getWorkingDir(state, useLogical, buf);
if(ptr == nullptr) {
PERROR(argvObj, ".");
return 1;
}
printf("%s\n", ptr);
return 0;
}
enum class BinaryOp : unsigned int {
INVALID,
STR_EQ,
STR_NE,
STR_LT,
STR_GT,
EQ,
NE,
LT,
GT,
LE,
GE,
};
static int builtin_test(DSState &, Array_Object &argvObj) {
const struct {
const char *k;
BinaryOp op;
} binaryOpTable[] = {
{"=", BinaryOp::STR_EQ},
{"==", BinaryOp::STR_EQ},
{"!=", BinaryOp::STR_NE},
{"<", BinaryOp::STR_LT},
{">", BinaryOp::STR_GT},
{"-eq", BinaryOp::EQ},
{"-ne", BinaryOp::NE},
{"-lt", BinaryOp::LT},
{"-gt", BinaryOp::GT},
{"-le", BinaryOp::LE},
{"-ge", BinaryOp::GE},
};
bool result = false;
unsigned int argc = argvObj.getValues().size();
const unsigned int argSize = argc - 1;
switch(argSize) {
case 0: {
result = false;
break;
}
case 1: {
result = strlen(str(argvObj.getValues()[1])) != 0; // check if string is not empty
break;
}
case 2: { // unary op
const char *op = str(argvObj.getValues()[1]);
const char *value = str(argvObj.getValues()[2]);
if(strlen(op) != 2 || op[0] != '-') {
ERROR(argvObj, "%s: invalid unary operator", op);
return 2;
}
const char opKind = op[1]; // ignore -
switch(opKind) {
case 'z': { // check if string is empty
result = strlen(value) == 0;
break;
}
case 'n': { // check if string not empty
result = strlen(value) != 0;
break;
}
case 'a':
case 'e': {
result = access(value, F_OK) == 0; // check if file exists
break;
}
case 'b': {
result = S_ISBLK(getStMode(value)); // check if file is block device
break;
}
case 'c': {
result = S_ISCHR(getStMode(value)); // check if file is character device
break;
}
case 'd': {
result = S_ISDIR(getStMode(value)); // check if file is directory
break;
}
case 'f': {
result = S_ISREG(getStMode(value)); // check if file is regular file.
break;
}
case 'g': {
result = S_IS_PERM_(getStMode(value), S_ISUID); // check if file has set-uid-bit
break;
}
case 'h':
case 'L': {
mode_t mode = 0;
struct stat st{};
if(lstat(value, &st) == 0) {
mode = st.st_mode;
}
result = S_ISLNK(mode); // check if file is symbolic-link
break;
}
case 'k': {
result = S_IS_PERM_(getStMode(value), S_ISVTX); // check if file has sticky bit
break;
}
case 'p': {
result = S_ISFIFO(getStMode(value)); // check if file is a named pipe
break;
}
case 'r': {
result = access(value, R_OK) == 0; // check if file is readable
break;
}
case 's': {
struct stat st{};
result = stat(value, &st) == 0 && st.st_size != 0; // check if file is not empty
break;
}
case 'S': {
result = S_ISSOCK(getStMode(value)); // check file is a socket
break;
}
case 't': {
if(value == strstr(value, "/dev/fd/")) {
value += strlen("/dev/fd/");
}
int s;
long n = convertToInt64(value, s);
result = s == 0 && n > -1 && n <= INT32_MAX && isatty(n) != 0; // check if FD is a terminal
break;
}
case 'u': {
result = S_IS_PERM_(getStMode(value), S_ISUID); // check file has set-user-id bit
break;
}
case 'w': {
result = access(value, W_OK) == 0; // check if file is writable
break;
}
case 'x': {
result = access(value, X_OK) == 0; // check if file is executable
break;
}
case 'O': {
struct stat st{};
result = stat(value, &st) == 0 && st.st_uid == geteuid(); // check if file is effectively owned
break;
}
case 'G': {
struct stat st{};
result = stat(value, &st) == 0 && st.st_gid == getegid(); // check if file is effectively owned by group
break;
}
default: {
ERROR(argvObj, "%s: invalid unary operator", op);
return 2;
}
}
break;
}
case 3: { // binary op
const char *left = str(argvObj.getValues()[1]);
const char *op = str(argvObj.getValues()[2]);
const char *right = str(argvObj.getValues()[3]);
BinaryOp opKind = BinaryOp::INVALID;
for(auto &e : binaryOpTable) {
if(strcmp(op, e.k) == 0) {
opKind = e.op;
break;
}
}
switch(opKind) {
case BinaryOp::STR_EQ: {
result = strcmp(left, right) == 0;
break;
}
case BinaryOp::STR_NE: {
result = strcmp(left, right) != 0;
break;
}
case BinaryOp::STR_LT: {
result = strcmp(left, right) < 0;
break;
}
case BinaryOp::STR_GT: {
result = strcmp(left, right) > 0;
break;
}
case BinaryOp::EQ:
case BinaryOp::NE:
case BinaryOp::LT:
case BinaryOp::GT:
case BinaryOp::LE:
case BinaryOp::GE: {
int s = 0;
long n1 = convertToInt64(left, s);
if(s != 0) {
ERROR(argvObj, "%s: must be integer", left);
return 2;
}
long n2 = convertToInt64(right, s);
if(s != 0) {
ERROR(argvObj, "%s: must be integer", right);
return 2;
}
if(opKind == BinaryOp::EQ) {
result = n1 == n2;
} else if(opKind == BinaryOp::NE) {
result = n1 != n2;
} else if(opKind == BinaryOp::LT) {
result = n1 < n2;
} else if(opKind == BinaryOp::GT) {
result = n1 > n2;
} else if(opKind == BinaryOp::LE) {
result = n1 <= n2;
} else if(opKind == BinaryOp::GE) {
result = n1 >= n2;
}
break;
}
case BinaryOp::INVALID: {
ERROR(argvObj, "%s: invalid binary operator", op);
return 2;
}
}
break;
}
default: {
ERROR(argvObj, "too many arguments");
return 2;
}
}
return result ? 0 : 1;
}
static int xfgetc(int fd, int timeout) {
char ch;
do {
errno = 0;
if(timeout > -2) {
struct pollfd pollfd[1];
pollfd[0].fd = fd;
pollfd[0].events = POLLIN;
if(poll(pollfd, 1, timeout) != 1) {
return EOF;
}
}
if(read(fd, &ch, 1) <= 0) {
ch = EOF;
}
} while(ch == EOF && (errno == EAGAIN || errno == EINTR));
return ch;
}
static int builtin_read(DSState &state, Array_Object &argvObj) { //FIXME: timeout, UTF-8
const char *prompt = "";
const char *ifs = nullptr;
unsigned int ifsSize = 0;
bool backslash = true;
bool noecho = false;
int fd = STDIN_FILENO;
int timeout = -1;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "rp:f:su:t:")) != -1;) {
switch(opt) {
case 'p':
prompt = optState.optArg;
break;
case 'f':
ifs = optState.optArg;
ifsSize = typeAs<String_Object>(argvObj.getValues()[optState.index - 1])->size();
break;
case 'r':
backslash = false;
break;
case 's':
noecho = true;
break;
case 'u': {
const char *arg = optState.optArg;
if(arg == strstr(arg, "/dev/fd/")) {
arg += strlen("/dev/fd/");
}
int s;
long t = convertToInt64(arg, s);
if(s != 0 || t < 0 || t > INT32_MAX) {
ERROR(argvObj, "%s: invalid file descriptor", optState.optArg);
return 1;
}
fd = static_cast<int>(t);
break;
}
case 't': {
int s;
long t = convertToInt64(optState.optArg, s);
if(s == 0) {
if(t > -1 && t <= INT32_MAX) {
t *= 1000;
if(t > -1 && t <= INT32_MAX) {
timeout = static_cast<int>(t);
break;
}
}
}
ERROR(argvObj, "%s: invalid timeout specification", optState.optArg);
return 1;
}
case ':':
ERROR(argvObj, "-%c: option require argument", optState.optOpt);
return 2;
default:
return invalidOptionError(argvObj, optState);
}
}
const unsigned int argc = argvObj.getValues().size();
unsigned int index = optState.index;
const bool isTTY = isatty(fd) != 0;
// check ifs
if(ifs == nullptr) {
auto *strObj = typeAs<String_Object>(getGlobal(state, toIndex(BuiltinVarOffset::IFS)));
ifs = strObj->getValue();
ifsSize = strObj->size();
}
// clear old variable before read
setGlobal(state, toIndex(BuiltinVarOffset::REPLY), getEmptyStrObj(state)); // clear REPLY
typeAs<Map_Object>(getGlobal(state, toIndex(BuiltinVarOffset::REPLY_VAR)))->clear(); // clear reply
const int varSize = argc - index; // if zero, store line to REPLY
const unsigned int varIndex = toIndex(varSize == 0 ? BuiltinVarOffset::REPLY : BuiltinVarOffset::REPLY_VAR);
std::string strBuf;
// show prompt
if(isTTY) {
fputs(prompt, stderr);
fflush(stderr);
}
// change tty state
struct termios tty{};
struct termios oldtty{};
if(noecho && isTTY) {
tcgetattr(fd, &tty);
oldtty = tty;
tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
tcsetattr(fd, TCSANOW, &tty);
}
// read line
if(!isTTY) {
timeout = -2;
}
unsigned int skipCount = 1;
int ch;
for(bool prevIsBackslash = false; (ch = xfgetc(fd, timeout)) != EOF;
prevIsBackslash = backslash && ch == '\\' && !prevIsBackslash) {
if(ch == '\n') {
if(prevIsBackslash) {
continue;
}
break;
}
if(ch == '\\' && !prevIsBackslash && backslash) {
continue;
}
bool fieldSep = isFieldSep(ifsSize, ifs, ch) && !prevIsBackslash;
if(fieldSep && skipCount > 0) {
if(isSpace(ch)) {
continue;
}
if(--skipCount == 1) {
continue;
}
}
skipCount = 0;
if(fieldSep && index < argc - 1) {
auto obj = typeAs<Map_Object>(getGlobal(state, varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::create<String_Object>(getPool(state).get(TYPE::String), std::move(strBuf));
obj->set(std::move(varObj), std::move(valueObj));
strBuf = "";
index++;
skipCount = isSpace(ch) ? 2 : 1;
continue;
}
strBuf += static_cast<char>(ch);
}
// remove last spaces
if(!strBuf.empty()) {
// check if field separator has spaces
bool hasSpace = false;
for(unsigned int i = 0; ifs[i] != '\0'; i++) {
if((hasSpace = isSpace(ifs[i]))) {
break;
}
}
if(hasSpace) {
while(!strBuf.empty() && isSpace(strBuf.back())) {
strBuf.pop_back();
}
}
}
if(varSize == 0) {
setGlobal(state, varIndex,
DSValue::create<String_Object>(getPool(state).get(TYPE::String), std::move(strBuf)));
strBuf = "";
}
// set rest variable
for(; index < argc; index++) {
auto obj = typeAs<Map_Object>(getGlobal(state, varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::create<String_Object>(getPool(state).get(TYPE::String), std::move(strBuf));
obj->set(std::move(varObj), std::move(valueObj));
strBuf = "";
}
// restore tty setting
if(noecho && isTTY) {
tcsetattr(fd, TCSANOW, &oldtty);
}
// report error
int ret = ch == EOF ? 1 : 0;
if(ret != 0 && errno != 0) {
PERROR(argvObj, "%d", fd);
}
return ret;
}
static int builtin_hash(DSState &state, Array_Object &argvObj) {
bool remove = false;
// check option
const unsigned int argc = argvObj.getValues().size();
unsigned int index = 1;
for(; index < argc; index++) {
const char *arg = str(argvObj.getValues()[index]);
if(arg[0] != '-') {
break;
}
if(strcmp(arg, "-r") == 0) {
remove = true;
} else {
return invalidOptionError(argvObj, arg);
}
}
const bool hasNames = index < argc;
if(hasNames) {
for(; index < argc; index++) {
const char *name = str(argvObj.getValues()[index]);
if(remove) {
getPathCache(state).removePath(name);
} else {
if(getPathCache(state).searchPath(name) == nullptr) {
ERROR(argvObj, "%s: not found", name);
return 1;
}
}
}
} else {
if(remove) { // remove all cache
getPathCache(state).clear();
} else { // show all cache
const auto cend = getPathCache(state).end();
if(getPathCache(state).begin() == cend) {
fputs("hash: file path cache is empty\n", stdout);
return 0;
}
for(auto &entry : getPathCache(state)) {
printf("%s=%s\n", entry.first, entry.second.c_str());
}
}
}
return 0;
}
// for completor debugging
static int builtin_complete(DSState &state, Array_Object &argvObj) {
const unsigned int argc = argvObj.getValues().size();
if(argc != 2) {
return showUsage(argvObj);
}
std::string line = str(argvObj.getValues()[1]);
line += '\n';
auto c = completeLine(state, line);
for(const auto &e : c) {
fputs(e, stdout);
fputc('\n', stdout);
free(e);
}
return 0;
}
static int showHistory(DSState &state, const Array_Object &obj) {
auto *history = DSState_history(&state);
unsigned int printOffset = history->size;
const unsigned int histSize = history->size;
const unsigned int argc = obj.getValues().size();
if(argc > 1) {
if(argc > 2) {
ERROR(obj, "too many arguments");
return 1;
}
int s;
const char *arg = str(obj.getValues()[1]);
printOffset = convertToUint64(arg, s);
if(s != 0) {
ERROR(obj, "%s: numeric argument required", arg);
return 1;
}
if(printOffset > histSize) {
printOffset = histSize;
}
}
const unsigned int histCmd = typeAs<Int_Object>(getGlobal(state, toIndex(BuiltinVarOffset::HIST_CMD)))->getValue();
const unsigned int base = histCmd - histSize;
for(unsigned int i = histSize - printOffset; i < histSize; i++) {
fprintf(stdout, "%5d %s\n", i + base, history->data[i]);
}
return 0;
}
static int builtin_history(DSState &state, Array_Object &argvObj) {
DSState_syncHistorySize(&state);
const unsigned int argc = argvObj.getValues().size();
if(argc == 1 || str(argvObj.getValues()[1])[0] != '-') {
return showHistory(state, argvObj);
}
char op = '\0';
const char *fileName = nullptr;
const char *deleteTarget = nullptr;
for(unsigned int i = 1; i < argc; i++) {
const char *arg = str(argvObj.getValues()[i]);
if(arg[0] == '-' && strlen(arg) == 2) {
char ch = arg[1];
switch(ch) {
case 'c':
DSState_clearHistory(&state);
return 0;
case 'd': {
if(i + 1 < argc) {
deleteTarget = str(argvObj.getValues()[++i]);
continue;
}
ERROR(argvObj, "%s: option requires argument", arg);
return 2;
}
case 'r':
case 'w': {
if(op != '\0') {
ERROR(argvObj, "cannot use more than one of -rw");
return 1;
}
op = ch;
fileName = i + 1 < argc
&& str(argvObj.getValues()[i + 1])[0] != '-' ? str(argvObj.getValues()[++i]) : nullptr;
continue;
}
default:
break;
}
}
return invalidOptionError(argvObj, arg);
}
auto *history = DSState_history(&state);
if(deleteTarget != nullptr) {
int s;
int offset = convertToInt64(deleteTarget, s) - 1;
if(s != 0 || offset < 0 || static_cast<unsigned int>(offset) > history->size) {
ERROR(argvObj, "%s: history offset out of range", deleteTarget);
return 1;
}
DSState_deleteHistoryAt(&state, offset);
return 0;
}
switch(op) {
case 'r':
DSState_loadHistory(&state, fileName);
break;
case 'w':
DSState_saveHistory(&state, fileName);
break;
}
return 0;
}
static int builtin_setenv(DSState &, Array_Object &argvObj) {
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
const char *kv = str(*iter);
auto *ptr = strchr(kv, '=');
errno = EINVAL;
if(ptr != nullptr && ptr != kv) {
std::string name(kv, ptr - kv);
if(setenv(name.c_str(), ptr + 1, 1) == 0) {
continue;
}
}
PERROR(argvObj, "%s", kv);
return 1;
}
return 0;
}
static int builtin_unsetenv(DSState &, Array_Object &argvObj) {
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
const char *envName = str(*iter);
if(unsetenv(envName) != 0) {
PERROR(argvObj, "%s", envName);
return 1;
}
}
return 0;
}
static std::pair<int, bool> toInt32(const char *str) {
int s = 0;
long v = convertToInt64(str, s);
if(s != 0 || v < INT32_MIN || v > INT32_MAX) {
return {0, false};
}
return {static_cast<int>(v), true};
};
static int toSigNum(const char *str) {
if(isDecimal(*str)) {
auto pair = toInt32(str);
if(!pair.second) {
return -1;
}
auto sigList = getUniqueSignalList();
return std::binary_search(sigList.begin(), sigList.end(), pair.first) ? pair.first : -1;
}
return getSignalNum(str);
}
static bool printNumOrName(const char *str) {
if(isDecimal(*str)) {
auto pair = toInt32(str);
if(!pair.second) {
return false;
}
const char *name = getSignalName(pair.first);
if(name == nullptr) {
return false;
}
printf("%s\n", name);
} else {
int sigNum = getSignalNum(str);
if(sigNum < 0) {
return false;
}
printf("%d\n", sigNum);
}
fflush(stdout);
return true;
}
static bool killProcOrJob(DSState &state, Array_Object &argvObj, const char *arg, int sigNum) {
bool isJob = *arg == '%';
auto pair = toInt32(isJob ? arg + 1 : arg);
if(!pair.second) {
ERROR(argvObj, "%s: arguments must be process or job IDs", arg);
return false;
}
if(isJob) {
if(pair.first > 0) {
auto job = getJobTable(state).findEntry(static_cast<unsigned int>(pair.first));
if(job) {
job->send(sigNum);
return true;
}
}
ERROR(argvObj, "%s: no such job", arg);
return false;
}
if(kill(pair.first, sigNum) < 0) {
PERROR(argvObj, "%s", arg);
return false;
}
return true;
}
// -s sig (pid | jobspec ...)
// -l
static int builtin_kill(DSState &state, Array_Object &argvObj) {
int sigNum = SIGTERM;
bool listing = false;
if(argvObj.getValues().size() == 1) {
return showUsage(argvObj);
}
GetOptState optState;
const int opt = optState(argvObj, "ls:");
switch(opt) {
case 'l':
listing = true;
break;
case 's':
case '?': {
const char *sigStr = optState.optArg;
if(opt == '?') {
sigStr = str(argvObj.getValues()[optState.index++]) + 1;
}
sigNum = toSigNum(sigStr);
if(sigNum == -1) {
ERROR(argvObj, "%s: invalid signal specification", sigStr);
return 1;
}
break;
}
case ':':
ERROR(argvObj, "-%c: option requires argument", optState.optOpt);
return 1;
}
auto begin = argvObj.getValues().begin() + optState.index;
const auto end = argvObj.getValues().end();
if(begin == end) {
if(listing) {
auto sigList = getUniqueSignalList();
unsigned int size = sigList.size();
for(unsigned int i = 0; i < size; i++) {
printf("%2d) SIG%s", sigList[i], getSignalName(sigList[i]));
if(i % 5 == 4 || i == size - 1) {
fputc('\n', stdout);
} else {
fputc('\t', stdout);
}
}
return 0;
}
return showUsage(argvObj);
}
unsigned int count = 0;
for(; begin != end; ++begin) {
const char *arg = str(*begin);
if(listing) {
if(!printNumOrName(arg)) {
count++;
ERROR(argvObj, "%s: invalid signal specification", arg);
}
} else {
if(killProcOrJob(state, argvObj, arg, sigNum)) {
count++;
}
}
}
if(listing && count > 0) {
return 1;
}
if(!listing && count == 0) {
return 1;
}
return 0;
}
static Job tryToGetJob(const JobTable &table, const char *name) {
if(*name == '%') {
name++;
}
Job job;
auto pair = toInt32(name);
if(pair.second && pair.first > -1) {
job = table.findEntry(pair.first);
}
return job;
}
static int builtin_fg_bg(DSState &state, Array_Object &argvObj) {
if(!hasFlag(DSState_option(&state), DS_OPTION_JOB_CONTROL)) {
ERROR(argvObj, "no job control in this shell");
return 1;
}
bool fg = strcmp("fg", str(argvObj.getValues()[0])) == 0;
unsigned int size = argvObj.getValues().size();
assert(size > 0);
Job job;
const char *arg = "current";
if(size == 1) {
job = getJobTable(state).getLatestEntry();
} else {
arg = str(argvObj.getValues()[1]);
job = tryToGetJob(getJobTable(state), arg);
}
int ret = 0;
if(job) {
if(fg) {
tcsetpgrp(STDIN_FILENO, getpgid(job->getPid(0)));
}
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg);
ret = 1;
if(fg) {
return ret;
}
}
if(fg) {
int s = getJobTable(state).waitAndDetach(job, true); //FIXME: check root shell
tryToForeground(state);
getJobTable(state).updateStatus();
return s;
}
// process remain arguments
for(unsigned int i = 2; i < size; i++) {
arg = str(argvObj.getValues()[i]);
job = tryToGetJob(getJobTable(state), arg);
if(job) {
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg);
ret = 1;
}
}
return ret;
}
} // namespace ydsh
|
/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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.
=========================================================================*/
#include "mvdImageViewManipulator.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
namespace mvd
{
/*
TRANSLATOR mvd::ImageViewManipulator
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
AbstractViewManipulator( parent ),
m_PreviousIsotropicZoom(1.)
{
}
/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}
/*****************************************************************************/
bool
ImageViewManipulator
::HasZoomChanged() const
{
bool res = false;
if (vcl_abs(m_IsotropicZoom - m_PreviousIsotropicZoom) > 0.00000001 )
{
res = true;
}
return res;
}
/******************************************************************************/
void
ImageViewManipulator
::mousePressEvent(QMouseEvent * event)
{
// Update the context with the pressed position
m_MouseContext.x = event->x();
m_MouseContext.y = event->y();
// Update the context with the pressed position for the mouseMoveEvent
m_MouseContext.xMove = event->x();
m_MouseContext.yMove = event->y();
}
/******************************************************************************/
void
ImageViewManipulator
::mouseMoveEvent( QMouseEvent * event)
{
m_PreviousIsotropicZoom = m_IsotropicZoom;
// Update the mouse context
m_MouseContext.dx = -event->x() + m_MouseContext.xMove;
m_MouseContext.dy = -event->y() + m_MouseContext.yMove;
// moveRegion
this->moveRegion( m_MouseContext.dx, m_MouseContext.dy);
// Update the position of the first press to take into account the
// last drag
m_MouseContext.xMove -= m_MouseContext.dx;
m_MouseContext.yMove -= m_MouseContext.dy;
}
/******************************************************************************/
void
ImageViewManipulator
::moveRegion(double dx, double dy)
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Apply the offset to the (start) index of the stored region
ImageRegionType::OffsetType offset;
offset[0] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dx/m_IsotropicZoom + 0.5);
offset[1] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dy/m_IsotropicZoom + 0.5);
// Apply the offset to the (start) index of the stored region
IndexType index = currentRegion.GetIndex() + offset;
currentRegion.SetIndex(index);
// Constraint the region to the largestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
/******************************************************************************/
void
ImageViewManipulator
::mouseReleaseEvent( QMouseEvent * event)
{
//TODO: Implement mouseReleaseEvent.
//std::cout <<" Not Implemented yet ..." << std::endl;
}
/******************************************************************************/
void ImageViewManipulator
::resizeEvent( QResizeEvent * event )
{
this->ResizeRegion( event->size().width(),
event->size().height());
}
/******************************************************************************/
void ImageViewManipulator
::ResizeRegion(unsigned int w, unsigned int h)
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Get the new widget size
ImageRegionType::SizeType size;
size[0] = w;
size[1] = h;
// Update the stored region with the new size
currentRegion.SetSize(size);
// Recompute the size before
m_NavigationContext.m_SizeXBeforeConstrain = (double)size[0] / this->GetIsotropicZoom();
m_NavigationContext.m_SizeYBeforeConstrain = (double)size[1] / this->GetIsotropicZoom();
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// call the rescale method with the same zoom as before (scale = 1)
this->Zoom(1.);
}
/******************************************************************************/
void
ImageViewManipulator
::wheelEvent( QWheelEvent * event)
{
// compute the new scale
double scaleRatio = 1.25;
double numDegrees = event->delta() / 8.;
int nbSteps = static_cast<int>(numDegrees / 15.);
double scale = vcl_pow(scaleRatio, nbSteps);
// center the region on the center of the previous region
this->CenterRegion(scale);
// rescale the viewport region
this->Zoom(scale);
}
/******************************************************************************/
void
ImageViewManipulator
::Zoom(const double scale)
{
m_PreviousIsotropicZoom = m_IsotropicZoom;
// compute the new size
double sizeX = m_NavigationContext.m_SizeXBeforeConstrain / scale;
double sizeY = m_NavigationContext.m_SizeYBeforeConstrain / scale;
// check that the new size is greater than 30x30
// check that the new isoZoom is not too low and not too large
// TODO : compute automatically the minSize and the isoZoom range ???
if (sizeX > 30 && sizeY > 30 &&
m_IsotropicZoom * scale > 0.01 &&
m_IsotropicZoom * scale < 10.)
{
// Update the the sizeBeforeConstrain
m_NavigationContext.m_SizeXBeforeConstrain = sizeX;
m_NavigationContext.m_SizeYBeforeConstrain = sizeY;
// Update the viewort region with the new size
ImageRegionType::SizeType size;
size[0] = static_cast<unsigned int>(sizeX);
size[1] = static_cast<unsigned int>(sizeY);
// The viewPort Region must be adapted to this zoom ratio
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Update the stored region with the new size
currentRegion.SetSize(size);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// Update the isotropicZoom
m_IsotropicZoom *= scale;
}
}
/******************************************************************************/
void
ImageViewManipulator
::CenterRegion(double scale)
{
if( m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.)
{
// The viewPort Region must be adapted to this zoom ratio
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// center the region on the position under the cursor
IndexType origin = currentRegion.GetIndex();
double centerX = (double)(origin[0]) + (double)(currentRegion.GetSize()[0])/2.;
double centerY = (double)(origin[1]) + (double)(currentRegion.GetSize()[1])/2.;
// new origin
IndexType newIndex;
newIndex[0] = centerX - currentRegion.GetSize()[0]/scale/2.;
if (newIndex[0] < 0) newIndex[0] = 0;
newIndex[1] = centerY - currentRegion.GetSize()[1]/scale/2.;
if (newIndex[1] < 0) newIndex[1] = 0;
// set the new origin
currentRegion.SetIndex(newIndex);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
}
/******************************************************************************/
void
ImageViewManipulator
::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest)
{
ImageRegionType::SizeType zeroSize;
zeroSize.Fill(0);
if (largest.GetSize() != zeroSize)
{
// Else we can constrain it
IndexType index = region.GetIndex();
ImageRegionType::SizeType size = region.GetSize();
// If region is larger than big, then crop
if (region.GetSize()[0] > largest.GetSize()[0])
{
size[0] = largest.GetSize()[0];
}
if (region.GetSize()[1] > largest.GetSize()[1])
{
size[1] = largest.GetSize()[1];
}
// Else we can constrain it
// For each dimension
for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim)
{
// push left if necessary
if (region.GetIndex()[dim] < largest.GetIndex()[dim])
{
index[dim] = largest.GetIndex()[dim];
}
// push right if necessary
if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim])
{
index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim];
}
}
region.SetSize(size);
region.SetIndex(index);
}
}
/******************************************************************************/
void
ImageViewManipulator
::keyPressEvent( QKeyEvent * event )
{
switch(event->key())
{
case Qt::Key_Minus:
CenterRegion(0.8);
Zoom(0.8);
break;
case Qt::Key_Plus:
CenterRegion(1.25);
Zoom(1.25);
break;
case Qt::Key_Left:
moveRegion(-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
break;
case Qt::Key_Right:
moveRegion(static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
break;
case Qt::Key_Up:
moveRegion(0,-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
break;
case Qt::Key_Down:
moveRegion(0,static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
break;
default:
break;
}
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
/*****************************************************************************/
void ImageViewManipulator
::OnModelImageRegionChanged(const ImageRegionType & largestRegion, const SpacingType& spacing)
{
// update the spacing
SetSpacing(spacing);
// set back the zoom to 1
m_IsotropicZoom = 1.;
m_PreviousIsotropicZoom = 1.;
// store the image largest region
m_NavigationContext.m_ModelImageRegion = largestRegion;
// set back the origin to O
IndexType nullIndex;
nullIndex.Fill(0);
m_NavigationContext.m_ViewportImageRegion.SetIndex(nullIndex);
// get the widget size and use it to resize the Viewport region
QWidget* parent_widget = qobject_cast< QWidget* >( parent() );
if (parent_widget)
{
this->ResizeRegion(parent_widget->width(), parent_widget->height());
}
// compute the intial scale factor to fit to screen
double factorX = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[0]
/(double)(largestRegion.GetSize()[0]);
double factorY = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[1]
/(double)(largestRegion.GetSize()[1]);
double scale = std::min(factorX, factorY);
this->Zoom(scale);
}
/*****************************************************************************/
void ImageViewManipulator
::OnViewportRegionChanged(double Xpc, double Ypc)
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// center the region on the position under the cursor
IndexType origin;
origin[0] = ( Xpc / vcl_abs(GetSpacing()[0]) - currentRegion.GetSize()[0] / 2 );
origin[1] = ( Ypc / vcl_abs(GetSpacing()[1]) - currentRegion.GetSize()[1] / 2 );
currentRegion.SetIndex(origin);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// force repaintGL
qobject_cast< QWidget* >( parent() )->update();
}
} // end namespace 'mvd'
BUG: Fixing chaotic handling of mouse move event (several calls to event->x() and event->y() which change between calls
/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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.
=========================================================================*/
#include "mvdImageViewManipulator.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
namespace mvd
{
/*
TRANSLATOR mvd::ImageViewManipulator
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
AbstractViewManipulator( parent ),
m_PreviousIsotropicZoom(1.)
{
}
/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}
/*****************************************************************************/
bool
ImageViewManipulator
::HasZoomChanged() const
{
bool res = false;
if (vcl_abs(m_IsotropicZoom - m_PreviousIsotropicZoom) > 0.00000001 )
{
res = true;
}
return res;
}
/******************************************************************************/
void
ImageViewManipulator
::mousePressEvent(QMouseEvent * event)
{
// Update the context with the pressed position
m_MouseContext.x = event->x();
m_MouseContext.y = event->y();
// Update the context with the pressed position for the mouseMoveEvent
m_MouseContext.xMove = event->x();
m_MouseContext.yMove = event->y();
}
/******************************************************************************/
void
ImageViewManipulator
::mouseMoveEvent( QMouseEvent * event)
{
m_PreviousIsotropicZoom = m_IsotropicZoom;
// Update the context with the pressed position
m_MouseContext.x = event->x();
m_MouseContext.y = event->y();
// Update the mouse context
m_MouseContext.dx = m_MouseContext.xMove - m_MouseContext.x;
m_MouseContext.dy = m_MouseContext.yMove - m_MouseContext.y;
// moveRegion
this->moveRegion( m_MouseContext.dx, m_MouseContext.dy);
// Update the position of the first press to take into account the
// last drag
m_MouseContext.xMove = m_MouseContext.x;
m_MouseContext.yMove = m_MouseContext.y;
}
/******************************************************************************/
void
ImageViewManipulator
::moveRegion(double dx, double dy)
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Apply the offset to the (start) index of the stored region
ImageRegionType::OffsetType offset;
offset[0] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dx/m_IsotropicZoom + 0.5);
offset[1] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dy/m_IsotropicZoom + 0.5);
// Apply the offset to the (start) index of the stored region
IndexType index = currentRegion.GetIndex() + offset;
currentRegion.SetIndex(index);
// Constraint the region to the largestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
/******************************************************************************/
void
ImageViewManipulator
::mouseReleaseEvent( QMouseEvent * event)
{
//TODO: Implement mouseReleaseEvent.
//std::cout <<" Not Implemented yet ..." << std::endl;
}
/******************************************************************************/
void ImageViewManipulator
::resizeEvent( QResizeEvent * event )
{
this->ResizeRegion( event->size().width(),
event->size().height());
}
/******************************************************************************/
void ImageViewManipulator
::ResizeRegion(unsigned int w, unsigned int h)
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Get the new widget size
ImageRegionType::SizeType size;
size[0] = w;
size[1] = h;
// Update the stored region with the new size
currentRegion.SetSize(size);
// Recompute the size before
m_NavigationContext.m_SizeXBeforeConstrain = (double)size[0] / this->GetIsotropicZoom();
m_NavigationContext.m_SizeYBeforeConstrain = (double)size[1] / this->GetIsotropicZoom();
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// call the rescale method with the same zoom as before (scale = 1)
this->Zoom(1.);
}
/******************************************************************************/
void
ImageViewManipulator
::wheelEvent( QWheelEvent * event)
{
// compute the new scale
double scaleRatio = 1.25;
double numDegrees = event->delta() / 8.;
int nbSteps = static_cast<int>(numDegrees / 15.);
double scale = vcl_pow(scaleRatio, nbSteps);
// center the region on the center of the previous region
this->CenterRegion(scale);
// rescale the viewport region
this->Zoom(scale);
}
/******************************************************************************/
void
ImageViewManipulator
::Zoom(const double scale)
{
m_PreviousIsotropicZoom = m_IsotropicZoom;
// compute the new size
double sizeX = m_NavigationContext.m_SizeXBeforeConstrain / scale;
double sizeY = m_NavigationContext.m_SizeYBeforeConstrain / scale;
// check that the new size is greater than 30x30
// check that the new isoZoom is not too low and not too large
// TODO : compute automatically the minSize and the isoZoom range ???
if (sizeX > 30 && sizeY > 30 &&
m_IsotropicZoom * scale > 0.01 &&
m_IsotropicZoom * scale < 10.)
{
// Update the the sizeBeforeConstrain
m_NavigationContext.m_SizeXBeforeConstrain = sizeX;
m_NavigationContext.m_SizeYBeforeConstrain = sizeY;
// Update the viewort region with the new size
ImageRegionType::SizeType size;
size[0] = static_cast<unsigned int>(sizeX);
size[1] = static_cast<unsigned int>(sizeY);
// The viewPort Region must be adapted to this zoom ratio
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Update the stored region with the new size
currentRegion.SetSize(size);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// Update the isotropicZoom
m_IsotropicZoom *= scale;
}
}
/******************************************************************************/
void
ImageViewManipulator
::CenterRegion(double scale)
{
if( m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.)
{
// The viewPort Region must be adapted to this zoom ratio
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// center the region on the position under the cursor
IndexType origin = currentRegion.GetIndex();
double centerX = (double)(origin[0]) + (double)(currentRegion.GetSize()[0])/2.;
double centerY = (double)(origin[1]) + (double)(currentRegion.GetSize()[1])/2.;
// new origin
IndexType newIndex;
newIndex[0] = centerX - currentRegion.GetSize()[0]/scale/2.;
if (newIndex[0] < 0) newIndex[0] = 0;
newIndex[1] = centerY - currentRegion.GetSize()[1]/scale/2.;
if (newIndex[1] < 0) newIndex[1] = 0;
// set the new origin
currentRegion.SetIndex(newIndex);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
}
/******************************************************************************/
void
ImageViewManipulator
::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest)
{
ImageRegionType::SizeType zeroSize;
zeroSize.Fill(0);
if (largest.GetSize() != zeroSize)
{
// Else we can constrain it
IndexType index = region.GetIndex();
ImageRegionType::SizeType size = region.GetSize();
// If region is larger than big, then crop
if (region.GetSize()[0] > largest.GetSize()[0])
{
size[0] = largest.GetSize()[0];
}
if (region.GetSize()[1] > largest.GetSize()[1])
{
size[1] = largest.GetSize()[1];
}
// Else we can constrain it
// For each dimension
for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim)
{
// push left if necessary
if (region.GetIndex()[dim] < largest.GetIndex()[dim])
{
index[dim] = largest.GetIndex()[dim];
}
// push right if necessary
if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim])
{
index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim];
}
}
region.SetSize(size);
region.SetIndex(index);
}
}
/******************************************************************************/
void
ImageViewManipulator
::keyPressEvent( QKeyEvent * event )
{
switch(event->key())
{
case Qt::Key_Minus:
CenterRegion(0.8);
Zoom(0.8);
break;
case Qt::Key_Plus:
CenterRegion(1.25);
Zoom(1.25);
break;
case Qt::Key_Left:
moveRegion(-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
break;
case Qt::Key_Right:
moveRegion(static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
break;
case Qt::Key_Up:
moveRegion(0,-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
break;
case Qt::Key_Down:
moveRegion(0,static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
break;
default:
break;
}
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
/*****************************************************************************/
void ImageViewManipulator
::OnModelImageRegionChanged(const ImageRegionType & largestRegion, const SpacingType& spacing)
{
// update the spacing
SetSpacing(spacing);
// set back the zoom to 1
m_IsotropicZoom = 1.;
m_PreviousIsotropicZoom = 1.;
// store the image largest region
m_NavigationContext.m_ModelImageRegion = largestRegion;
// set back the origin to O
IndexType nullIndex;
nullIndex.Fill(0);
m_NavigationContext.m_ViewportImageRegion.SetIndex(nullIndex);
// get the widget size and use it to resize the Viewport region
QWidget* parent_widget = qobject_cast< QWidget* >( parent() );
if (parent_widget)
{
this->ResizeRegion(parent_widget->width(), parent_widget->height());
}
// compute the intial scale factor to fit to screen
double factorX = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[0]
/(double)(largestRegion.GetSize()[0]);
double factorY = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[1]
/(double)(largestRegion.GetSize()[1]);
double scale = std::min(factorX, factorY);
this->Zoom(scale);
}
/*****************************************************************************/
void ImageViewManipulator
::OnViewportRegionChanged(double Xpc, double Ypc)
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// center the region on the position under the cursor
IndexType origin;
origin[0] = ( Xpc / vcl_abs(GetSpacing()[0]) - currentRegion.GetSize()[0] / 2 );
origin[1] = ( Ypc / vcl_abs(GetSpacing()[1]) - currentRegion.GetSize()[1] / 2 );
currentRegion.SetIndex(origin);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// force repaintGL
qobject_cast< QWidget* >( parent() )->update();
}
} // end namespace 'mvd'
|
/*
* Copyright (C) 2015-2018 Nagisa Sekiguchi
*
* 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 <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <poll.h>
#include <sys/resource.h>
#include <cstdlib>
#include <unordered_map>
#include <ydsh/ydsh.h>
#include "vm.h"
#include "complete.h"
#include "misc/num_util.hpp"
#include "misc/files.h"
extern char **environ; //NOLINT
namespace ydsh {
// builtin command definition
static int builtin___gets(DSState &state, ArrayObject &argvObj);
static int builtin___puts(DSState &state, ArrayObject &argvObj);
static int builtin_cd(DSState &state, ArrayObject &argvObj);
static int builtin_check_env(DSState &state, ArrayObject &argvObj);
static int builtin_complete(DSState &state, ArrayObject &argvObj);
static int builtin_echo(DSState &state, ArrayObject &argvObj);
static int builtin_exit(DSState &state, ArrayObject &argvObj);
static int builtin__exit(DSState &state, ArrayObject &argvObj);
static int builtin_false(DSState &state, ArrayObject &argvObj);
static int builtin_fg_bg(DSState &state, ArrayObject &argvObj);
static int builtin_hash(DSState &state, ArrayObject &argvObj);
static int builtin_help(DSState &state, ArrayObject &argvObj);
static int builtin_kill(DSState &state, ArrayObject &argvObj);
static int builtin_pwd(DSState &state, ArrayObject &argvObj);
static int builtin_read(DSState &state, ArrayObject &argvObj);
static int builtin_setenv(DSState &state, ArrayObject &argvObj);
static int builtin_shctl(DSState &state, ArrayObject &argvObj);
static int builtin_test(DSState &state, ArrayObject &argvObj);
static int builtin_true(DSState &state, ArrayObject &argvObj);
static int builtin_ulimit(DSState &state, ArrayObject &argvObj);
static int builtin_umask(DSState &state, ArrayObject &argvObj);
static int builtin_unsetenv(DSState &state, ArrayObject &argvObj);
static constexpr struct {
const char *commandName;
builtin_command_t cmd_ptr;
const char *usage;
const char *detail;
} builtinCommands[] {
{":", builtin_true, "",
" Null command. Always success (exit status is 0)."},
{"__gets", builtin___gets, "",
" Read standard input and write to standard output."},
{"__puts", builtin___puts, "[-1 arg1] [-2 arg2]",
" Print specified argument to standard output/error and print new line.\n"
" Options:\n"
" -1 print to standard output\n"
" -2 print to standard error"},
{"_exit", builtin__exit, "[n]",
" Exit the shell with a status of N. If N is omitted, the exit\n"
" status is $?. Unlike exit, it causes normal program termination\n"
" without cleaning the resources."},
{"bg", builtin_fg_bg, "[job_spec ...]",
" Move jobs to the background.\n"
" If JOB_SPEC is not present, latest job is used."},
{"cd", builtin_cd, "[-LP] [dir]",
" Changing the current directory to DIR. The Environment variable\n"
" HOME is the default DIR. A null directory name is the same as\n"
" the current directory. If -L is specified, use logical directory \n"
" (with symbolic link). If -P is specified, use physical directory \n"
" (without symbolic link). Default is -L."},
{"checkenv", builtin_check_env, "variable ...",
" Check existence of specified environmental variables.\n"
" If all of variables are exist and not empty string, exit with 0."},
{"command", nullptr, "[-pVv] command [arg ...]",
" Execute COMMAND with ARGs excepting user defined command.\n"
" If -p option is specified, search command from default PATH.\n"
" If -V or -v option are specified, print description of COMMAND.\n"
" -V option shows more detailed information."},
{"complete", builtin_complete, "[-A action] line",
" Show completion candidates.\n"
" If -A option is specified, show completion candidates via ACTION.\n"
" Actions:\n"
" file complete file names\n"
" dir complete directory names\n"
" module complete module names\n"
" exec complete executable file names\n"
" tilde expand tilde before completion. only available in \n"
" combination of file, module exec actions\n"
" command complete command names including external, user-defined, builtin ones\n"
" cmd equivalent to 'command'\n"
" external complete external commans\n"
" builtin complete builtin commands\n"
" udc complete user-defined commands\n"
" variable complete variable names\n"
" var equivalent to var\n"
" type complete type names\n"
" env complete environmental variables names\n"
" signal complete signal names\n"
" user complete user names\n"
" group complete group names\n"
" stmt_kw complete statement keywords\n"
" expr_kw complete expression keywords"},
{"echo", builtin_echo, "[-neE] [arg ...]",
" Print argument to standard output and print new line.\n"
" Options:\n"
" -n not print new line\n"
" -e interpret some escape sequence\n"
" \\\\ backslash\n"
" \\a bell\n"
" \\b backspace\n"
" \\c ignore subsequent string\n"
" \\e escape sequence\n"
" \\E escape sequence\n"
" \\f form feed\n"
" \\n newline\n"
" \\r carriage return\n"
" \\t horizontal tab\n"
" \\v vertical tab\n"
" \\0nnn N is octal number. NNN can be 0 to 3 number\n"
" \\xnn N is hex number. NN can be 1 to 2 number\n"
" -E disable escape sequence interpretation"},
{"eval", nullptr, "[arg ...]",
" Evaluate ARGs as command."},
{"exec", nullptr, "[-c] [-a name] file [args ...]",
" Execute FILE and replace this shell with specified program.\n"
" If FILE is not specified, the redirections take effect in this shell.\n"
" IF FILE execution fail, terminate this shell immediately\n"
" Options:\n"
" -c cleaner environmental variable\n"
" -a specify set program name(default is FILE)"},
{"exit", builtin_exit, "[n]",
" Exit the shell with a status of N. If N is omitted, the exit\n"
" status is $?."},
{"false", builtin_false, "",
" Always failure (exit status is 1)."},
{"fg", builtin_fg_bg, "[job_spec]",
" Move job to the foreground.\n"
" If JOB_SPEC is not present, latest job is used."},
{"hash", builtin_hash, "[-r] [command ...]",
" Cache file path of specified commands. If -r option is supplied,\n"
" removes specified command path (if not specified, remove all cache).\n"
" If option is not supplied, display all cached path."},
{"help", builtin_help, "[-s] [pattern ...]",
" Display helpful information about builtin commands."},
{"kill", builtin_kill, "[-s signal] pid | jobspec ... or kill -l [signal...]",
" Send a signal to a process or job.\n"
" If signal is not specified, then SIGTERM is assumed.\n"
" Options:\n"
" -s sig send a signal. SIG is a signal name or signal number\n"
" -l list the signal names"},
{"pwd", builtin_pwd, "[-LP]",
" Print the current working directory(absolute path).\n"
" If -L specified, print logical working directory.\n"
" If -P specified, print physical working directory\n"
" (without symbolic link). Default is -L."},
{"read", builtin_read, "[-r] [-p prompt] [-f field separator] [-u fd] [-t timeout] [name ...]",
" Read from standard input.\n"
" Options:\n"
" -r disable backslash escape\n"
" -p specify prompt string\n"
" -f specify field separator (if not, use IFS)\n"
" -s disable echo back\n"
" -u specify file descriptor\n"
" -t timeout set timeout second (only available if input fd is a tty)"},
{"setenv", builtin_setenv, "[name=env ...]",
" Set environmental variables."},
{"shctl", builtin_shctl, "[subcommand]",
" Query and set runtime information\n"
" Subcommands:\n"
" is-interactive return 0 if shell is interactive mode.\n"
" is-sourced return 0 if current script is sourced.\n"
" backtrace print stack trace.\n"
" function print current function/command name.\n"
" module print full path of loaded modules or scripts\n"
" show [OPTION ...] print runtime option setting.\n"
" set OPTION ... set/enable/on runtime option.\n"
" unset OPTION ... unset/disable/off runtime option"},
{"test", builtin_test, "[expr]",
" Unary or Binary expressions.\n"
" If expression is true, return 0\n"
" If expression is false, return 1\n"
" If operand or operator is invalid, return 2\n"
"\n"
" String operators:\n"
" -z STRING check if string is empty\n"
" -n STRING\n"
" STRING check if string is not empty\n"
" STRING1 = STRING2\n"
" STRING1 == STRING2\n"
" check if strings are equal\n"
" STRING1 != STRING2\n"
" check if strings are not equal\n"
" STRING1 < STRING2\n"
" check if STRING1 is less than STRING2 with dictionary order\n"
" STRING1 > STRING2\n"
" check if STRING2 is greater than STRING2 with dictionary order\n"
" Integer operators:\n"
" INT1 -eq INT2 check if integers are equal\n"
" INT1 -ne INT2 check if integers are not equal\n"
" INT1 -lt INT2 check if INT1 is less than INT2\n"
" INT1 -gt INT2 check if INT1 is greater than INT2\n"
" INT1 -le INT2 check if INT1 is less than or equal to INT2\n"
" INT1 -ge INT2 check if INT1 is greater than or equal to INT2\n"
"\n"
" Integer value is signed int 64.\n"
"\n"
" File operators:\n"
" -a FILE\n"
" -e FILE check if file exists\n"
" -b FILE check if file is block device\n"
" -c FILE check if file is character device\n"
" -d FILE check if file is a directory\n"
" -f FILE check if file is a regular file\n"
" -g FILE check if file has set-group-id bit\n"
" -h FILE\n"
" -L FILE check if file is a symbolic link\n"
" -k FILE check if file has sticky bit\n"
" -p FILE check if file is a named pipe\n"
" -r FILE check if file is readable\n"
" -s FILE check if file is not empty\n"
" -S FILE check if file is a socket\n"
" -t FD check if file descriptor is a terminal\n"
" -u FILE check if file has set-user-id bit\n"
" -w FILE check if file is writable\n"
" -x FILE check if file is executable\n"
" -O FILE check if file is effectively owned by user\n"
" -G FILE check if file is effectively owned by group\n"
"\n"
" FILE1 -nt FILE2 check if file1 is newer than file2\n"
" FILE1 -ot FILE2 check if file1 is older than file2\n"
" FILE1 -ef FILE2 check if file1 and file2 refer to the same file"},
{"true", builtin_true, "",
" Always success (exit status is 0)."},
{"ulimit", builtin_ulimit, "[-H | -S] [-a | -"
#define DEF(O, R, S, N, D) O
#include "ulimit-def.in"
#undef DEF
" [value]]",
" Set or show resource limits of the shell and processes started by the shell.\n"
" If VALUE is `soft', `hard' and `unlimited', represent current soft limit\n"
" and hard limit and no limit. If no option specified, assume `-f'.\n"
" Options.\n"
" -H use `hard' resource limit\n"
" -S use `soft' resource limit (default)\n"
" -a show all resource limits"
#define DEF(O, R, S, N, D) "\n -" O " " D
#include "ulimit-def.in"
#undef DEF
},
{"umask", builtin_umask, "[-p] [-S] [mode]",
" Display or set file mode creation mask.\n"
" Set the calling process's file mode creation mask to MODE.\n"
" If MODE is omitted, prints current value of mask.\n"
" Options.\n"
" -p if mode is omitted, print current mask in a form that may be reused as input\n"
" -S print current mask in a symbolic form"},
{"unsetenv", builtin_unsetenv, "[name ...]",
" Unset environmental variables."},
};
unsigned int getBuiltinCommandSize() {
return arraySize(builtinCommands);
}
const char *getBuiltinCommandName(unsigned int index) {
assert(index < getBuiltinCommandSize());
return builtinCommands[index].commandName;
}
static auto initBuiltinMap() {
std::unordered_map<StringRef, unsigned int> map;
for(unsigned int i = 0; i < arraySize(builtinCommands); i++) {
map.emplace(builtinCommands[i].commandName, i);
}
return map;
}
/**
* return null, if not found builtin command.
*/
builtin_command_t lookupBuiltinCommand(const char *commandName) {
/**
* builtin command name and index.
*/
static auto builtinMap = initBuiltinMap();
auto iter = builtinMap.find(commandName);
if(iter == builtinMap.end()) {
return nullptr;
}
return builtinCommands[iter->second].cmd_ptr;
}
static void printAllUsage(FILE *fp) {
for(const auto &e : builtinCommands) {
fprintf(fp, "%s %s\n", e.commandName, e.usage);
}
}
/**
* if not found command, return false.
*/
static bool printUsage(FILE *fp, StringRef prefix, bool isShortHelp = true) {
bool matched = false;
for(const auto &e : builtinCommands) {
const char *cmdName = e.commandName;
if(StringRef(cmdName).startsWith(prefix)) {
fprintf(fp, "%s: %s %s\n", cmdName, cmdName, e.usage);
if(!isShortHelp) {
fprintf(fp, "%s\n", e.detail);
}
matched = true;
}
}
return matched;
}
static int builtin_help(DSState &, ArrayObject &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
printAllUsage(stdout);
return 0;
}
bool isShortHelp = false;
bool foundValidCommand = false;
for(unsigned int i = 1; i < size; i++) {
auto arg = argvObj.getValues()[i].asStrRef();
if(arg == "-s" && size == 2) {
printAllUsage(stdout);
foundValidCommand = true;
} else if(arg == "-s" && i == 1) {
isShortHelp = true;
} else {
if(printUsage(stdout, arg, isShortHelp)) {
foundValidCommand = true;
}
}
}
if(!foundValidCommand) {
ERROR(argvObj, "no help topics match `%s'. Try `help help'.", argvObj.getValues()[size - 1].asCStr());
return 1;
}
return 0;
}
static int showUsage(const ArrayObject &obj) {
printUsage(stderr, obj.getValues()[0].asStrRef());
return 2;
}
int invalidOptionError(const ArrayObject &obj, const GetOptState &s) {
ERROR(obj, "-%c: invalid option", s.optOpt);
return showUsage(obj);
}
static int invalidOptionError(const ArrayObject &obj, const char *opt) {
ERROR(obj, "%s: invalid option", opt);
return showUsage(obj);
}
static int builtin_cd(DSState &state, ArrayObject &argvObj) {
GetOptState optState;
bool useLogical = true;
for(int opt; (opt = optState(argvObj, "PL")) != -1;) {
switch(opt) {
case 'P':
useLogical = false;
break;
case 'L':
useLogical = true;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
unsigned int index = optState.index;
StringRef dest;
bool useOldpwd = false;
if(index < argvObj.getValues().size()) {
dest = argvObj.getValues()[index].asStrRef();
if(dest == "-") {
const char *v = getenv(ENV_OLDPWD);
if(v == nullptr) {
ERROR(argvObj, "OLDPWD not set");
return 1;
}
dest = v;
useOldpwd = true;
}
} else {
const char *v = getenv(ENV_HOME);
if(v == nullptr) {
ERROR(argvObj, "HOME not set");
return 1;
}
dest = v;
}
if(useOldpwd) {
printf("%s\n", dest.data());
}
if(!changeWorkingDir(state, dest, useLogical)) {
PERROR(argvObj, "%s", dest.data());
return 1;
}
return 0;
}
static int builtin_check_env(DSState &, ArrayObject &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
return showUsage(argvObj);
}
for(unsigned int i = 1; i < size; i++) {
auto ref = argvObj.getValues()[i].asStrRef();
if(ref.hasNullChar()) {
return 1;
}
const char *env = getenv(ref.data());
if(env == nullptr || strlen(env) == 0) {
return 1;
}
}
return 0;
}
static int builtin_echo(DSState &, ArrayObject &argvObj) {
bool newline = true;
bool interpEscape = false;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "neE")) != -1;) {
switch(opt) {
case 'n':
newline = false;
break;
case 'e':
interpEscape = true;
break;
case 'E':
interpEscape = false;
break;
default:
goto END;
}
}
END:
// print argument
if(optState.index > 1 && argvObj.getValues()[optState.index - 1].asStrRef() == "--") {
optState.index--;
}
unsigned int index = optState.index;
const unsigned int argc = argvObj.getValues().size();
bool firstArg = true;
for(; index < argc; index++) {
if(firstArg) {
firstArg = false;
} else {
fputc(' ', stdout);
}
if(!interpEscape) {
auto ref = argvObj.getValues()[index].asStrRef();
fwrite(ref.data(), sizeof(char), ref.size(), stdout);
continue;
}
auto arg = argvObj.getValues()[index].asStrRef();
for(unsigned int i = 0; i < arg.size(); i++) {
int ch = arg[i];
if(ch == '\\' && i + 1 < arg.size()) {
switch(arg[++i]) {
case '\\':
ch = '\\';
break;
case 'a':
ch = '\a';
break;
case 'b':
ch = '\b';
break;
case 'c': // stop printing
return 0;
case 'e':
case 'E':
ch = '\033';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'v':
ch = '\v';
break;
case '0': {
int v = 0;
for(unsigned int c = 0; c < 3; c++) {
if(i + 1 < arg.size() && isOctal(arg[i + 1])) {
v *= 8;
v += arg[++i] - '0';
} else {
break;
}
}
ch = static_cast<char>(v);
break;
}
case 'x': {
if(i + 1 < arg.size() && isHex(arg[i + 1])) {
unsigned int v = hexToNum(arg[++i]);
if(i + 1 < arg.size() && isHex(arg[i + 1])) {
v *= 16;
v += hexToNum(arg[++i]);
}
ch = static_cast<char>(v);
break;
}
i--;
break;
}
default:
i--;
break;
}
}
fputc(ch, stdout);
}
}
if(newline) {
fputc('\n', stdout);
}
return 0;
}
static int parseExitStatus(const DSState &state, const ArrayObject &argvObj) {
int64_t ret = state.getGlobal(BuiltinVarOffset::EXIT_STATUS).asInt();
if(argvObj.getValues().size() > 1) {
auto value = argvObj.getValues()[1].asStrRef();
auto pair = convertToNum<int64_t>(value.begin(), value.end());
if(pair.second) {
ret = pair.first;
}
}
return maskExitStatus(ret);
}
static int builtin_exit(DSState &state, ArrayObject &argvObj) {
int ret = parseExitStatus(state, argvObj);
if(hasFlag(state.compileOption, CompileOption::INTERACTIVE)) {
state.jobTable.send(SIGHUP);
}
std::string str("terminated by exit ");
str += std::to_string(ret);
raiseError(state, TYPE::_ShellExit, std::move(str), ret);
return ret;
}
static int builtin__exit(DSState &state, ArrayObject &argvObj) {
int ret = parseExitStatus(state, argvObj);
terminate(ret);
}
static int builtin_true(DSState &, ArrayObject &) {
return 0;
}
static int builtin_false(DSState &, ArrayObject &) {
return 1;
}
/**
* for stdin redirection test
*/
static int builtin___gets(DSState &, ArrayObject &) {
char buf[256];
int readSize = 0;
while((readSize = read(STDIN_FILENO, buf, arraySize(buf))) > 0) {
int r = write(STDOUT_FILENO, buf, readSize);
(void) r;
}
return 0;
}
/**
* for stdout/stderr redirection test
*/
static int builtin___puts(DSState &, ArrayObject &argvObj) {
GetOptState optState;
for(int opt; (opt = optState(argvObj, "1:2:")) != -1;) {
switch(opt) {
case '1':
fwrite(optState.optArg.data(), sizeof(char), optState.optArg.size(), stdout);
fputc('\n', stdout);
fflush(stdout);
break;
case '2':
fwrite(optState.optArg.data(), sizeof(char), optState.optArg.size(), stderr);
fputc('\n', stderr);
fflush(stderr);
break;
default:
return 1;
}
}
return 0;
}
static int builtin_pwd(DSState &state, ArrayObject &argvObj) {
bool useLogical = true;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "LP")) != -1;) {
switch(opt) {
case 'L':
useLogical = true;
break;
case 'P':
useLogical = false;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
auto workdir = getWorkingDir(state, useLogical);
if(!workdir) {
PERROR(argvObj, ".");
return 1;
}
printf("%s\n", workdir.get());
return 0;
}
#define EACH_STR_COMP_OP(OP) \
OP(STR_EQ, "==", ==) \
OP(STR_EQ2, "=", ==) \
OP(STR_NE, "!=", !=) \
OP(STR_LT, "<", <) \
OP(STR_GT, ">", >)
#define EACH_INT_COMP_OP(OP) \
OP(EQ, "-eq", ==) \
OP(NE, "-ne", !=) \
OP(LT, "-lt", <) \
OP(GT, "-gt", >) \
OP(LE, "-le", <=) \
OP(GE, "-ge", >=)
#define EACH_FILE_COMP_OP(OP) \
OP(NT, "-nt", %) \
OP(OT, "-ot", %) \
OP(EF, "-ef", %)
enum class BinaryOp : unsigned int {
INVALID,
#define GEN_ENUM(E, S, O) E,
EACH_STR_COMP_OP(GEN_ENUM)
EACH_INT_COMP_OP(GEN_ENUM)
EACH_FILE_COMP_OP(GEN_ENUM)
#undef GEN_ENUM
};
static BinaryOp resolveBinaryOp(StringRef opStr) {
const struct {
const char *k;
BinaryOp op;
} table[] = {
#define GEN_ENTRY(E, S, O) {S, BinaryOp::E},
EACH_INT_COMP_OP(GEN_ENTRY)
EACH_STR_COMP_OP(GEN_ENTRY)
EACH_FILE_COMP_OP(GEN_ENTRY)
#undef GEN_ENTRY
};
for(auto &e : table) {
if(opStr == e.k) {
return e.op;
}
}
return BinaryOp::INVALID;
}
static bool compareStr(StringRef left, BinaryOp op, StringRef right) {
switch(op) {
#define GEN_CASE(E, S, O) case BinaryOp::E: return left O right;
EACH_STR_COMP_OP(GEN_CASE)
#undef GEN_CASE
default:
break;
}
return false;
}
static bool compareInt(int64_t x, BinaryOp op, int64_t y) {
switch(op) {
#define GEN_CASE(E, S, O) case BinaryOp::E: return x O y;
EACH_INT_COMP_OP(GEN_CASE)
#undef GEN_CASE
default:
break;
}
return false;
}
static bool operator<(const timespec &left, const timespec &right) {
if(left.tv_sec == right.tv_sec) {
return left.tv_nsec < right.tv_nsec;
}
return left.tv_sec < right.tv_sec;
}
static bool compareFile(StringRef x, BinaryOp op, StringRef y) {
if(x.hasNullChar() || y.hasNullChar()) {
return false;
}
struct stat st1; //NOLINT
struct stat st2; //NOLINT
if(stat(x.data(), &st1) != 0) {
return false;
}
if(stat(y.data(), &st2) != 0) {
return false;
}
switch(op) {
case BinaryOp::NT:
#ifdef __APPLE__
return st2.st_mtimespec < st1.st_mtimespec;
#else
return st2.st_mtim < st1.st_mtim;
#endif
case BinaryOp::OT:
#ifdef __APPLE__
return st1.st_mtimespec < st2.st_mtimespec;
#else
return st1.st_mtim < st2.st_mtim;
#endif
case BinaryOp::EF:
return st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino;
default:
return false;
}
}
static int parseFD(StringRef value) {
if(value.startsWith("/dev/fd/")) {
value.removePrefix(strlen("/dev/fd/"));
}
auto ret = convertToNum<int32_t>(value.begin(), value.end());
if(!ret.second || ret.first < 0) {
return -1;
}
return ret.first;
}
static int testFile(char op, const char *value) {
bool result = false;
switch(op) {
case 'a':
case 'e':
result = access(value, F_OK) == 0; // check if file exists
break;
case 'b':
result = S_ISBLK(getStMode(value)); // check if file is block device
break;
case 'c':
result = S_ISCHR(getStMode(value)); // check if file is character device
break;
case 'd':
result = S_ISDIR(getStMode(value)); // check if file is directory
break;
case 'f':
result = S_ISREG(getStMode(value)); // check if file is regular file.
break;
case 'g':
result = S_IS_PERM_(getStMode(value), S_ISUID); // check if file has set-uid-bit
break;
case 'h':
case 'L': {
mode_t mode = 0;
struct stat st; //NOLINT
if(lstat(value, &st) == 0) {
mode = st.st_mode;
}
result = S_ISLNK(mode); // check if file is symbolic-link
break;
}
case 'k':
result = S_IS_PERM_(getStMode(value), S_ISVTX); // check if file has sticky bit
break;
case 'p':
result = S_ISFIFO(getStMode(value)); // check if file is a named pipe
break;
case 'r':
result = access(value, R_OK) == 0; // check if file is readable
break;
case 's': {
struct stat st; //NOLINT
result = stat(value, &st) == 0 && st.st_size != 0; // check if file is not empty
break;
}
case 'S':
result = S_ISSOCK(getStMode(value)); // check file is a socket
break;
case 't': {
int fd = parseFD(value);
result = fd > -1 && isatty(fd) != 0; // check if FD is a terminal
break;
}
case 'u':
result = S_IS_PERM_(getStMode(value), S_ISUID); // check file has set-user-id bit
break;
case 'w':
result = access(value, W_OK) == 0; // check if file is writable
break;
case 'x':
result = access(value, X_OK) == 0; // check if file is executable
break;
case 'O': {
struct stat st; //NOLINT
result = stat(value, &st) == 0 && st.st_uid == geteuid(); // check if file is effectively owned
break;
}
case 'G': {
struct stat st; //NOLINT
result = stat(value, &st) == 0 && st.st_gid == getegid(); // check if file is effectively owned by group
break;
}
default:
return 2;
}
return result ? 0 : 1;
}
static int builtin_test(DSState &, ArrayObject &argvObj) {
bool result = false;
unsigned int argc = argvObj.getValues().size();
const unsigned int argSize = argc - 1;
switch(argSize) {
case 0: {
result = false;
break;
}
case 1: {
result = !argvObj.getValues()[1].asStrRef().empty(); // check if string is not empty
break;
}
case 2: { // unary op
auto op = argvObj.getValues()[1].asStrRef();
auto ref = argvObj.getValues()[2].asStrRef();
if(op.size() != 2 || op[0] != '-') {
ERROR(argvObj, "%s: invalid unary operator", op.data());
return 2;
}
const char opKind = op[1]; // ignore -
if(opKind == 'z') { // check if string is empty
result = ref.empty();
} else if(opKind == 'n') { // check if string not empty
result = !ref.empty();
} else {
if(ref.hasNullChar()) {
ERROR(argvObj, "file path contains null characters");
return 2;
}
int r = testFile(opKind, ref.data());
if(r == 2) {
ERROR(argvObj, "%s: invalid unary operator", op.data());
}
return r;
}
break;
}
case 3: { // binary op
auto left = argvObj.getValues()[1].asStrRef();
auto op = argvObj.getValues()[2].asStrRef();
auto opKind = resolveBinaryOp(op);
auto right = argvObj.getValues()[3].asStrRef();
switch(opKind) {
#define GEN_CASE(E, S, O) case BinaryOp::E:
EACH_STR_COMP_OP(GEN_CASE) {
result = compareStr(left, opKind, right);
break;
}
EACH_INT_COMP_OP(GEN_CASE) {
auto pair = convertToNum<int64_t>(left.begin(), left.end());
int64_t n1 = pair.first;
if(!pair.second) {
ERROR(argvObj, "%s: must be integer", left.data());
return 2;
}
pair = convertToNum<int64_t>(right.begin(), right.end());
int64_t n2 = pair.first;
if(!pair.second) {
ERROR(argvObj, "%s: must be integer", right.data());
return 2;
}
result = compareInt(n1, opKind, n2);
break;
}
EACH_FILE_COMP_OP(GEN_CASE) {
result = compareFile(left, opKind, right);
break;
}
#undef GEN_CASE
case BinaryOp::INVALID:
ERROR(argvObj, "%s: invalid binary operator", op.data()); //FIXME:
return 2;
}
break;
}
default: {
ERROR(argvObj, "too many arguments");
return 2;
}
}
return result ? 0 : 1;
}
static int xfgetc(int fd, int timeout) {
signed char ch;
do {
errno = 0;
if(timeout > -2) {
struct pollfd pollfd[1];
pollfd[0].fd = fd;
pollfd[0].events = POLLIN;
if(poll(pollfd, 1, timeout) != 1) {
return EOF;
}
}
if(read(fd, &ch, 1) <= 0) {
ch = EOF;
}
} while(static_cast<int>(ch) == EOF && errno == EAGAIN);
return ch;
}
static int builtin_read(DSState &state, ArrayObject &argvObj) { //FIXME: timeout, UTF-8
StringRef prompt;
StringRef ifs;
bool backslash = true;
bool noecho = false;
int fd = STDIN_FILENO;
int timeout = -1;
GetOptState optState;
for(int opt; (opt = optState(argvObj, ":rp:f:su:t:")) != -1;) {
switch(opt) {
case 'p':
prompt = optState.optArg;
break;
case 'f':
ifs = optState.optArg;
break;
case 'r':
backslash = false;
break;
case 's':
noecho = true;
break;
case 'u': {
StringRef value = optState.optArg;
fd = parseFD(value);
if(fd < 0) {
ERROR(argvObj, "%s: invalid file descriptor", value.data());
return 1;
}
break;
}
case 't': {
auto ret = convertToNum<int64_t>(optState.optArg.begin(), optState.optArg.end());
int64_t t = ret.first;
if(ret.second) {
if(t > -1 && t <= INT32_MAX) {
t *= 1000;
if(t > -1 && t <= INT32_MAX) {
timeout = static_cast<int>(t);
break;
}
}
}
ERROR(argvObj, "%s: invalid timeout specification", optState.optArg.data());
return 1;
}
case ':':
ERROR(argvObj, "-%c: option require argument", optState.optOpt);
return 2;
default:
return invalidOptionError(argvObj, optState);
}
}
const unsigned int argc = argvObj.getValues().size();
unsigned int index = optState.index;
const bool isTTY = isatty(fd) != 0;
// check ifs
if(ifs.data() == nullptr) {
ifs = state.getGlobal(BuiltinVarOffset::IFS).asStrRef();
}
// clear old variable before read
state.setGlobal(toIndex(BuiltinVarOffset::REPLY), DSValue::createStr()); // clear REPLY
typeAs<MapObject>(state.getGlobal(BuiltinVarOffset::REPLY_VAR)).clear(); // clear reply
const unsigned int varSize = argc - index; // if zero, store line to REPLY
const unsigned int varIndex = toIndex(varSize == 0 ? BuiltinVarOffset::REPLY : BuiltinVarOffset::REPLY_VAR);
std::string strBuf;
// show prompt
if(isTTY) {
fwrite(prompt.data(), sizeof(char), prompt.size(), stderr);
fflush(stderr);
}
// change tty state
struct termios tty{};
struct termios oldtty{};
if(noecho && isTTY) {
tcgetattr(fd, &tty);
oldtty = tty;
tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
tcsetattr(fd, TCSANOW, &tty);
}
// read line
if(!isTTY) {
timeout = -2;
}
unsigned int skipCount = 1;
int ch;
for(bool prevIsBackslash = false; (ch = xfgetc(fd, timeout)) != EOF;
prevIsBackslash = backslash && ch == '\\' && !prevIsBackslash) {
if(ch == '\n') {
if(prevIsBackslash) {
continue;
}
break;
}
if(ch == '\\' && !prevIsBackslash && backslash) {
continue;
}
bool fieldSep = matchFieldSep(ifs, ch) && !prevIsBackslash;
if(fieldSep && skipCount > 0) {
if(isSpace(ch)) {
continue;
}
if(--skipCount == 1) {
continue;
}
}
skipCount = 0;
if(fieldSep && index < argc - 1) {
auto &obj = typeAs<MapObject>(state.getGlobal(varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::createStr(std::move(strBuf));
obj.set(std::move(varObj), std::move(valueObj));
strBuf = "";
index++;
skipCount = isSpace(ch) ? 2 : 1;
continue;
}
strBuf += static_cast<char>(ch);
}
// remove last spaces
if(!strBuf.empty()) {
if(hasSpace(ifs)) { // check if field separator has spaces
while(!strBuf.empty() && isSpace(strBuf.back())) {
strBuf.pop_back();
}
}
}
if(varSize == 0) {
state.setGlobal(varIndex, DSValue::createStr(std::move(strBuf)));
strBuf = "";
}
// set rest variable
for(; index < argc; index++) {
auto &obj = typeAs<MapObject>(state.getGlobal(varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::createStr(std::move(strBuf));
obj.set(std::move(varObj), std::move(valueObj));
strBuf = "";
}
// restore tty setting
if(noecho && isTTY) {
tcsetattr(fd, TCSANOW, &oldtty);
}
// report error
int ret = ch == EOF ? 1 : 0;
if(ret != 0 && errno != 0) {
PERROR(argvObj, "%d", fd);
}
return ret;
}
static int builtin_hash(DSState &state, ArrayObject &argvObj) {
bool remove = false;
// check option
const unsigned int argc = argvObj.getValues().size();
unsigned int index = 1;
for(; index < argc; index++) {
auto arg = argvObj.getValues()[index].asStrRef();
if(arg[0] != '-') {
break;
}
if(arg == "-r") {
remove = true;
} else {
return invalidOptionError(argvObj, arg.data());
}
}
const bool hasNames = index < argc;
if(hasNames) {
for(; index < argc; index++) {
auto ref = argvObj.getValues()[index].asStrRef();
const char *name = ref.data();
bool hasNul = ref.hasNullChar();
if(remove) {
state.pathCache.removePath(hasNul ? nullptr : name);
} else {
if(hasNul || state.pathCache.searchPath(name) == nullptr) {
ERROR(argvObj, "%s: not found", name);
return 1;
}
}
}
} else {
if(remove) { // remove all cache
state.pathCache.clear();
} else { // show all cache
const auto cend = state.pathCache.end();
if(state.pathCache.begin() == cend) {
fputs("hash: file path cache is empty\n", stdout);
return 0;
}
for(auto &entry : state.pathCache) {
printf("%s=%s\n", entry.first, entry.second.c_str());
}
}
}
return 0;
}
static std::unordered_map<StringRef, CodeCompOp> initCompActions() {
return {
{"file", CodeCompOp::FILE},
{"dir", CodeCompOp::DIR},
{"module", CodeCompOp::MODULE},
{"exec", CodeCompOp::EXEC},
{"tilde", CodeCompOp::TILDE},
{"command", CodeCompOp::COMMAND},
{"cmd", CodeCompOp::COMMAND},
{"external", CodeCompOp::EXTERNAL},
{"builtin", CodeCompOp::BUILTIN},
{"udc", CodeCompOp::UDC},
{"variable", CodeCompOp::VAR},
{"var", CodeCompOp::VAR},
{"env", CodeCompOp::ENV},
{"signal", CodeCompOp::SIGNAL},
{"user", CodeCompOp::USER},
{"group", CodeCompOp::GROUP},
{"stmt_kw", CodeCompOp::STMT_KW},
{"expr_kw", CodeCompOp::EXPR_KW},
{"type", CodeCompOp::TYPE},
};
}
static int builtin_complete(DSState &state, ArrayObject &argvObj) {
static auto actionMap = initCompActions();
CodeCompOp compOp{};
GetOptState optState;
for(int opt; (opt = optState(argvObj, ":A:")) != -1;) {
switch(opt) {
case 'A': {
auto iter = actionMap.find(optState.optArg);
if(iter == actionMap.end()) {
ERROR(argvObj, "%s: invalid action", optState.optArg.data());
return showUsage(argvObj);
}
setFlag(compOp, iter->second);
break;
}
case ':':
ERROR(argvObj, "-%c: option requires argument", optState.optOpt);
return 1;
default:
return invalidOptionError(argvObj, optState);
}
}
StringRef line;
if(optState.index < argvObj.size()) {
line = argvObj.getValues()[optState.index].asStrRef();
}
doCodeCompletion(state, line, compOp);
auto &ret = typeAs<ArrayObject>(state.getGlobal(BuiltinVarOffset::COMPREPLY));
for(const auto &e : ret.getValues()) {
fputs(e.asCStr(), stdout);
fputc('\n', stdout);
}
return 0;
}
static int builtin_setenv(DSState &, ArrayObject &argvObj) {
if(argvObj.size() == 1) {
for(unsigned int i = 0; environ[i] != nullptr; i++) {
const char *e = environ[i];
fprintf(stdout, "%s\n", e);
}
return 0;
}
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
auto kv = iter->asStrRef();
auto pos = kv.hasNullChar() ? StringRef::npos : kv.find("=");
errno = EINVAL;
if(pos != StringRef::npos && pos != 0) {
auto name = kv.substr(0, pos).toString();
auto value = kv.substr(pos + 1);
if(setenv(name.c_str(), value.data(), 1) == 0) {
continue;
}
}
PERROR(argvObj, "%s", kv.data());
return 1;
}
return 0;
}
static int builtin_unsetenv(DSState &, ArrayObject &argvObj) {
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
auto envName = iter->asStrRef();
if(unsetenv(envName.hasNullChar() ? "" : envName.data()) != 0) {
PERROR(argvObj, "%s", envName.data());
return 1;
}
}
return 0;
}
static std::pair<int, bool> toInt32(StringRef str) {
return convertToNum<int32_t>(str.begin(), str.end());
}
static int toSigNum(StringRef str) {
if(!str.empty() && isDecimal(*str.data())) {
auto pair = toInt32(str);
if(!pair.second) {
return -1;
}
auto sigList = getUniqueSignalList();
return std::binary_search(sigList.begin(), sigList.end(), pair.first) ? pair.first : -1;
}
return getSignalNum(str);
}
static bool printNumOrName(StringRef str) {
if(!str.empty() && isDecimal(*str.data())) {
auto pair = toInt32(str);
if(!pair.second) {
return false;
}
const char *name = getSignalName(pair.first);
if(name == nullptr) {
return false;
}
printf("%s\n", name);
} else {
int sigNum = getSignalNum(str);
if(sigNum < 0) {
return false;
}
printf("%d\n", sigNum);
}
fflush(stdout);
return true;
}
static bool killProcOrJob(DSState &state, ArrayObject &argvObj, StringRef arg, int sigNum) {
bool isJob = arg.startsWith("%");
auto pair = toInt32(isJob ? arg.substr(1) : arg);
if(!pair.second) {
ERROR(argvObj, "%s: arguments must be process or job IDs", arg.data());
return false;
}
if(isJob) {
if(pair.first > 0) {
auto job = state.jobTable.findEntry(static_cast<unsigned int>(pair.first));
if(job) {
job->send(sigNum);
return true;
}
}
ERROR(argvObj, "%s: no such job", arg.data());
return false;
}
if(kill(pair.first, sigNum) < 0) {
PERROR(argvObj, "%s", arg.data());
return false;
}
return true;
}
// -s sig (pid | jobspec ...)
// -l
static int builtin_kill(DSState &state, ArrayObject &argvObj) {
int sigNum = SIGTERM;
bool listing = false;
if(argvObj.getValues().size() == 1) {
return showUsage(argvObj);
}
GetOptState optState;
const int opt = optState(argvObj, ":ls:");
switch(opt) {
case 'l':
listing = true;
break;
case 's':
case '?': {
StringRef sigStr = optState.optArg;
if(opt == '?') { // skip prefix '-', ex. -9
sigStr = argvObj.getValues()[optState.index++].asStrRef().substr(1);
}
sigNum = toSigNum(sigStr);
if(sigNum == -1) {
ERROR(argvObj, "%s: invalid signal specification", sigStr.data());
return 1;
}
break;
}
case ':':
ERROR(argvObj, "-%c: option requires argument", optState.optOpt);
return 1;
default:
break;
}
auto begin = argvObj.getValues().begin() + optState.index;
const auto end = argvObj.getValues().end();
if(begin == end) {
if(listing) {
auto sigList = getUniqueSignalList();
unsigned int size = sigList.size();
for(unsigned int i = 0; i < size; i++) {
printf("%2d) SIG%s", sigList[i], getSignalName(sigList[i]));
if(i % 5 == 4 || i == size - 1) {
fputc('\n', stdout);
} else {
fputc('\t', stdout);
}
}
return 0;
}
return showUsage(argvObj);
}
unsigned int count = 0;
for(; begin != end; ++begin) {
auto arg = begin->asStrRef();
if(listing) {
if(!printNumOrName(arg)) {
count++;
ERROR(argvObj, "%s: invalid signal specification", arg.data());
}
} else {
if(killProcOrJob(state, argvObj, arg, sigNum)) {
count++;
}
}
}
if(listing && count > 0) {
return 1;
}
if(!listing && count == 0) {
return 1;
}
return 0;
}
static Job tryToGetJob(const JobTable &table, StringRef name) {
if(name.startsWith("%")) {
name.removePrefix(1);
}
Job job;
auto pair = toInt32(name);
if(pair.second && pair.first > -1) {
job = table.findEntry(pair.first);
}
return job;
}
static int builtin_fg_bg(DSState &state, ArrayObject &argvObj) {
if(!state.isJobControl()) {
ERROR(argvObj, "no job control in this shell");
return 1;
}
bool fg = argvObj.getValues()[0].asStrRef() == "fg";
unsigned int size = argvObj.getValues().size();
assert(size > 0);
Job job;
StringRef arg = "current";
if(size == 1) {
job = state.jobTable.getLatestEntry();
} else {
arg = argvObj.getValues()[1].asStrRef();
job = tryToGetJob(state.jobTable, arg);
}
int ret = 0;
if(job) {
if(fg) {
beForeground(job->getPid(0));
}
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg.data());
ret = 1;
if(fg) {
return ret;
}
}
if(fg) {
int s = state.jobTable.waitAndDetach(job, true); //FIXME: check root shell
int errNum = errno;
state.tryToBeForeground();
if(errNum != 0) {
PERROR(argvObj, "wait failed");
}
state.jobTable.updateStatus();
return s;
}
// process remain arguments
for(unsigned int i = 2; i < size; i++) {
arg = argvObj.getValues()[i].asStrRef();
job = tryToGetJob(state.jobTable, arg);
if(job) {
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg.data());
ret = 1;
}
}
return ret;
}
// for ulimit command
static constexpr flag8_t RLIM_HARD = 1u << 0;
static constexpr flag8_t RLIM_SOFT = 1u << 1;
struct ulimitOp {
char op;
char resource;
char shift;
const char *name;
void print(flag8_set_t limOpt, unsigned int maxNameLen) const {
rlimit limit{};
getrlimit(this->resource, &limit);
if(maxNameLen) {
printf("-%c: %s ", this->op, this->name);
for(unsigned int len = strlen(this->name); len < maxNameLen; len++) {
printf(" ");
}
}
auto value = hasFlag(limOpt, RLIM_HARD) ? limit.rlim_max : limit.rlim_cur;
if(value == RLIM_INFINITY) {
printf("unlimited\n");
} else {
value >>= this->shift;
printf("%llu\n", static_cast<unsigned long long>(value));
}
fflush(stdout);
}
};
struct UlimitOptEntry {
enum Kind : unsigned char {
UNUSED,
NUM,
SOFT,
HARD,
UNLIMITED,
};
Kind kind{UNUSED};
rlim_t value{0};
explicit operator bool() const {
return this->kind != UNUSED;
}
rlim_t getValue(const rlimit &limit) const {
switch(this->kind) {
case SOFT:
return limit.rlim_cur;
case HARD:
return limit.rlim_max;
case UNLIMITED:
return RLIM_INFINITY;
default:
return this->value;
}
}
};
static constexpr ulimitOp ulimitOps[] = {
#define DEF(O, R, S, N, D) {O[0], R, S, N},
#include "ulimit-def.in"
#undef DEF
};
static unsigned int computeMaxNameLen() {
unsigned int max = 0;
for(auto &e : ulimitOps) {
unsigned int len = strlen(e.name);
if(len > max) {
max = len;
}
}
return max;
}
static bool parseUlimitOpt(StringRef ref, unsigned int index, UlimitOptEntry &entry) {
using underlying_t = std::conditional<sizeof(rlim_t) == sizeof(uint64_t),
uint64_t, std::conditional<sizeof(rlim_t) == sizeof(uint32_t), uint32_t, void>::type>::type;
if(ref.hasNullChar()) {
return false;
}
const char *str = ref.data();
if(strcasecmp(str, "soft") == 0) {
entry.kind = UlimitOptEntry::SOFT;
return true;
} else if(strcasecmp(str, "hard") == 0) {
entry.kind = UlimitOptEntry::HARD;
return true;
} else if(strcasecmp(str, "unlimited") == 0) {
entry.kind = UlimitOptEntry::UNLIMITED;
return true;
}
auto pair = convertToNum<underlying_t>(str);
if(!pair.second) {
return false;
}
entry.value = pair.first;
entry.value <<= ulimitOps[index].shift;
entry.kind = UlimitOptEntry::NUM;
return true;
}
struct UlimitOptEntryTable {
uint64_t printSet{0};
std::array<UlimitOptEntry, arraySize(ulimitOps)> entries;
unsigned int count{0};
int tryToUpdate(GetOptState &optState, ArrayObject &argvObj, int opt) {
DSValue arg;
if(optState.index < argvObj.getValues().size() && *argvObj.getValues()[optState.index].asCStr() != '-') {
arg = argvObj.getValues()[optState.index++];
}
if(!this->update(opt, arg)) {
ERROR(argvObj, "%s: invalid number", arg.asCStr());
return 1;
}
return 0;
}
private:
bool update(int ch, const DSValue &value) {
this->count++;
// search entry
for(unsigned int index = 0; index < arraySize(ulimitOps); index++) {
if(ulimitOps[index].op == ch) {
auto &entry = this->entries[index];
if(value) {
if(!parseUlimitOpt(value.asStrRef(), index, entry)) {
return false;
}
} else {
setFlag(this->printSet, static_cast<uint64_t>(1) << index);
}
}
}
return true;
}
};
static int builtin_ulimit(DSState &, ArrayObject &argvObj) {
flag8_set_t limOpt = 0;
bool showAll = false;
GetOptState optState;
const char *optStr = "HSa"
#define DEF(O, R, S, N, D) O
#include "ulimit-def.in"
#undef DEF
;
UlimitOptEntryTable table;
// parse option
for(int opt; (opt = optState(argvObj, optStr)) != -1;) {
switch(opt) {
case 'H':
setFlag(limOpt, RLIM_HARD);
break;
case 'S':
setFlag(limOpt, RLIM_SOFT);
break;
case 'a':
showAll = true;
break;
case '?':
return invalidOptionError(argvObj, optState);
default:
int ret = table.tryToUpdate(optState, argvObj, opt);
if(ret) {
return ret;
}
break;
}
}
// parse remain
if(table.count == 0) {
int ret = table.tryToUpdate(optState, argvObj, 'f');
if(ret) {
return ret;
}
}
if(limOpt == 0) {
setFlag(limOpt, RLIM_SOFT);
}
if(showAll) {
unsigned int maxDescLen = computeMaxNameLen();
for(auto &e : ulimitOps) {
e.print(limOpt, maxDescLen);
}
return 0;
}
// print or set limit
unsigned int maxNameLen = 0;
if(table.printSet > 0 && (table.printSet & (table.printSet - 1)) != 0) {
maxNameLen = computeMaxNameLen();
}
for(unsigned int index = 0; index < static_cast<unsigned int>(table.entries.size()); index++) {
if(table.entries[index]) {
const auto &op = ulimitOps[index];
rlimit limit{};
getrlimit(op.resource, &limit);
rlim_t value = table.entries[index].getValue(limit);
if(hasFlag(limOpt, RLIM_SOFT)) {
limit.rlim_cur = value;
}
if(hasFlag(limOpt, RLIM_HARD)) {
limit.rlim_max = value;
}
if(setrlimit(op.resource, &limit) < 0) {
PERROR(argvObj, "%s: cannot change limit", op.name);
return 1;
}
}
if(hasFlag(table.printSet, static_cast<uint64_t>(1) << index)) {
ulimitOps[index].print(limOpt, maxNameLen);
}
}
return 0;
}
enum class PrintMaskOp : unsigned int {
ONLY_PRINT = 1 << 0,
REUSE = 1 << 1,
SYMBOLIC = 1 << 2,
};
template <> struct allow_enum_bitop<PrintMaskOp> : std::true_type {};
static void printMask(mode_t mask, PrintMaskOp op) {
if(hasFlag(op, PrintMaskOp::SYMBOLIC)) {
char buf[arraySize("u=rwx,g=rwx,o=rwx")];
char *ptr = buf;
/**
* u g o
* rwx|rwx|rwx
* 111 111 111
*
*/
for(auto &user : {'u', 'g', 'o'}) {
if(ptr != buf) {
*(ptr++) = ',';
}
*(ptr++) = user;
*(ptr++) = '=';
for(auto &perm : {'r', 'w', 'x'}) {
if(!(mask & 0400)) {
*(ptr++) = perm;
}
mask <<= 1;
}
}
*ptr = '\0';
fprintf(stdout, "%s%s\n", hasFlag(op, PrintMaskOp::REUSE) ? "umask -S " : "", buf);
} else if(hasFlag(op, PrintMaskOp::ONLY_PRINT)) {
fprintf(stdout, "%s%04o\n", hasFlag(op, PrintMaskOp::REUSE) ? "umask " : "", mask);
}
}
/**
* MODE = [ugoa]* [+-=] [rwx]*
*
* @param value
* @param mode
* @return
* if failed, return false
*/
static bool parseMode(const char *&value, mode_t &mode) {
// [ugoa]*
mode_t user = 0;
for(bool next = true; next; ) {
int ch = *(value++);
switch(ch) {
case 'u':
user |= 0700;
break;
case 'g':
user |= 0070;
break;
case 'o':
user |= 0007;
break;
case 'a':
user |= 0777;
break;
default: // may be [-+=]
next = false;
--value;
break;
}
}
if(user == 0) {
user = 0777;
}
// [-+=]
char op = *(value++);
if(op != '-' && op != '+' && op != '=') {
return false;
}
// [rwx]*
mode_t newMode = 0;
while(*value && *value != ',') {
int ch = *(value++);
switch(ch) {
case 'r':
newMode |= 0444 & user;
break;
case 'w':
newMode |= 0222 & user;
break;
case 'x':
newMode |= 0111 & user;
break;
default:
return false;
}
}
// apply op
if(op == '+') {
unsetFlag(mode, newMode);
} else if(op == '-') {
setFlag(mode, newMode);
} else {
setFlag(mode, user);
unsetFlag(mode, newMode);
}
return true;
}
struct SymbolicParseResult {
bool success;
char invalid;
mode_t mode;
};
/**
* MODES = MODE (, MODE)*
*
* @param ref
* @param mode
* @return
*/
static SymbolicParseResult parseSymbolicMode(StringRef ref, mode_t mode) {
SymbolicParseResult ret {
.success = true,
.invalid = 0,
.mode = mode,
};
if(ref.hasNullChar()) {
ret.success = false;
ret.invalid = '\0';
return ret;
}
const char *value = ref.data();
if(!parseMode(value, ret.mode)) {
ret.success = false;
ret.invalid = *(--value);
return ret;
}
while(*value) {
if(*(value++) == ',' && parseMode(value, ret.mode)) {
continue;
}
ret.success = false;
ret.invalid = *(--value);
break;
}
return ret;
}
static int builtin_umask(DSState &, ArrayObject &argvObj) {
auto op = PrintMaskOp::ONLY_PRINT;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "pS")) != -1; ) {
switch(opt) {
case 'p':
setFlag(op, PrintMaskOp::REUSE);
break;
case 'S':
setFlag(op, PrintMaskOp::SYMBOLIC);
break;
default:
return invalidOptionError(argvObj, optState);
}
}
auto mask = umask(0);
umask(mask);
if(optState.index < argvObj.getValues().size()) {
unsetFlag(op, PrintMaskOp::ONLY_PRINT | PrintMaskOp::REUSE);
auto value = argvObj.getValues()[optState.index].asStrRef();
if(!value.empty() && isDecimal(*value.data())) {
auto pair = convertToNum<int32_t>(value.begin(), value.end(), 8);
int num = pair.first;
if(!pair.second || num < 0 || num > 0777) {
ERROR(argvObj, "%s: octal number out of range (0000~0777)", value.data());
return 1;
}
mask = num;
} else {
auto ret = parseSymbolicMode(value, mask);
mask = ret.mode;
if(!ret.success) {
int ch = ret.invalid;
if(isascii(ch) && ch != 0) {
ERROR(argvObj, "%c: invalid symbolic operator", ch);
} else {
ERROR(argvObj, "0x%02x: invalid symbolic operator", ch);
}
return 1;
}
}
umask(mask);
}
printMask(mask, op);
return 0;
}
static int printBacktrace(const VMState &state) {
auto traces = state.createStackTrace();
for(auto &s : traces) {
fprintf(stdout, "from %s:%d '%s()'\n",
s.getSourceName().c_str(), s.getLineNum(), s.getCallerName().c_str());
}
return 0;
}
static int printFuncName(const VMState &state) {
auto *code = state.getFrame().code;
const char *name = nullptr;
if(!code->is(CodeKind::NATIVE) && !code->is(CodeKind::TOPLEVEL)) {
name = static_cast<const CompiledCode *>(code)->getName();
}
fprintf(stdout, "%s\n", name != nullptr ? name : "<toplevel>");
return name != nullptr ? 0 : 1;
}
static constexpr struct {
RuntimeOption option;
const char *name;
} runtimeOptions[] = {
#define GEN_OPT(E, V, N) {RuntimeOption::E, N},
EACH_RUNTIME_OPTION(GEN_OPT)
#undef GEN_OPT
};
static RuntimeOption lookupRuntimeOption(StringRef name) {
for(auto &e : runtimeOptions) {
if(name == e.name) {
return e.option;
}
}
return RuntimeOption{};
}
static unsigned int computeMaxOptionNameSize() {
unsigned int maxSize = 0;
for(auto &e : runtimeOptions) {
unsigned int size = strlen(e.name) + 2;
if(size > maxSize) {
maxSize = size;
}
}
return maxSize;
}
static void printRuntimeOpt(const char *name, unsigned int size, bool set) {
std::string value = name;
value.append(size - strlen(name), ' ');
value += (set ? "on" : "off");
value += "\n";
fputs(value.c_str(), stdout);
}
static int showOption(const DSState &state, const ArrayObject &argvObj) {
const unsigned int size = argvObj.size();
RuntimeOption foundSet{};
if(size == 2) {
foundSet = static_cast<RuntimeOption>(static_cast<unsigned int>(-1));
} else {
for(unsigned int i = 2; i < size; i++) {
auto name = argvObj.getValues()[i].asStrRef();
auto option = lookupRuntimeOption(name);
if(empty(option)) {
ERROR(argvObj, "undefined runtime option: %s", name.data());
return 1;
}
setFlag(foundSet, option);
}
}
// print
const unsigned int maxNameSize = computeMaxOptionNameSize();
for(auto &e : runtimeOptions) {
if(hasFlag(foundSet, e.option)) {
printRuntimeOpt(e.name, maxNameSize, hasFlag(state.runtimeOption, e.option));
}
}
return 0;
}
static int setOption(DSState &state, const ArrayObject &argvObj, const bool set) {
const unsigned int size = argvObj.size();
if(size == 2) {
ERROR(argvObj, "`%s' subcommand requires argument", set ? "set" : "unset");
return 2;
}
bool foundMonitor = false;
for(unsigned int i = 2; i < size; i++) {
auto name = argvObj.getValues()[i].asStrRef();
auto option = lookupRuntimeOption(name);
if(empty(option)) {
ERROR(argvObj, "undefined runtime option: %s", name.data());
return 1;
}
if(option == RuntimeOption::MONITOR && !foundMonitor) {
foundMonitor = true;
setJobControlSignalSetting(state, set);
}
if(set) {
setFlag(state.runtimeOption, option);
} else {
unsetFlag(state.runtimeOption, option);
}
}
return 0;
}
static int showModule(const DSState &state) {
auto &loader = state.modLoader;
unsigned int size = loader.modSize();
auto *buf = new const char *[size];
for(auto &e : loader) {
buf[e.second.getIndex()] = e.first.data();
}
for(unsigned int i = 0; i < size; i++) {
fprintf(stdout, "%s\n", buf[i]);
}
delete[] buf;
return 0;
}
static int isSourced(const DSState &state) {
const CompiledCode *code = nullptr;
state.getCallStack().walkFrames([&](const ControlFrame &frame) {
auto *c = frame.code;
if(c->is(CodeKind::NATIVE)) {
return true; // continue
}
code = static_cast<const CompiledCode *>(c);
return false;
});
if(code) {
auto *entry = state.modLoader.find(code->getSourceName());
if(entry) {
return entry->isSealed() ? 0 : 1;
}
}
return 1;
}
static int builtin_shctl(DSState &state, ArrayObject &argvObj) {
if(argvObj.size() > 1) {
auto ref = argvObj.getValues()[1].asStrRef();
if(ref == "backtrace") {
return printBacktrace(state.getCallStack());
} else if(ref == "is-sourced") {
return isSourced(state);
} else if(ref == "is-interactive") {
return hasFlag(state.compileOption, CompileOption::INTERACTIVE) ? 0 : 1;
} else if(ref == "function") {
return printFuncName(state.getCallStack());
} else if(ref == "show") {
return showOption(state, argvObj);
} else if(ref == "set") {
return setOption(state, argvObj, true);
} else if(ref == "unset") {
return setOption(state, argvObj, false);
} else if(ref == "module") {
return showModule(state);
} else {
ERROR(argvObj, "undefined subcommand: %s", ref.data());
return 2;
}
}
return 0;
}
} // namespace ydsh
fix internal is-source checking
/*
* Copyright (C) 2015-2018 Nagisa Sekiguchi
*
* 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 <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <poll.h>
#include <sys/resource.h>
#include <cstdlib>
#include <unordered_map>
#include <ydsh/ydsh.h>
#include "vm.h"
#include "complete.h"
#include "misc/num_util.hpp"
#include "misc/files.h"
extern char **environ; //NOLINT
namespace ydsh {
// builtin command definition
static int builtin___gets(DSState &state, ArrayObject &argvObj);
static int builtin___puts(DSState &state, ArrayObject &argvObj);
static int builtin_cd(DSState &state, ArrayObject &argvObj);
static int builtin_check_env(DSState &state, ArrayObject &argvObj);
static int builtin_complete(DSState &state, ArrayObject &argvObj);
static int builtin_echo(DSState &state, ArrayObject &argvObj);
static int builtin_exit(DSState &state, ArrayObject &argvObj);
static int builtin__exit(DSState &state, ArrayObject &argvObj);
static int builtin_false(DSState &state, ArrayObject &argvObj);
static int builtin_fg_bg(DSState &state, ArrayObject &argvObj);
static int builtin_hash(DSState &state, ArrayObject &argvObj);
static int builtin_help(DSState &state, ArrayObject &argvObj);
static int builtin_kill(DSState &state, ArrayObject &argvObj);
static int builtin_pwd(DSState &state, ArrayObject &argvObj);
static int builtin_read(DSState &state, ArrayObject &argvObj);
static int builtin_setenv(DSState &state, ArrayObject &argvObj);
static int builtin_shctl(DSState &state, ArrayObject &argvObj);
static int builtin_test(DSState &state, ArrayObject &argvObj);
static int builtin_true(DSState &state, ArrayObject &argvObj);
static int builtin_ulimit(DSState &state, ArrayObject &argvObj);
static int builtin_umask(DSState &state, ArrayObject &argvObj);
static int builtin_unsetenv(DSState &state, ArrayObject &argvObj);
static constexpr struct {
const char *commandName;
builtin_command_t cmd_ptr;
const char *usage;
const char *detail;
} builtinCommands[] {
{":", builtin_true, "",
" Null command. Always success (exit status is 0)."},
{"__gets", builtin___gets, "",
" Read standard input and write to standard output."},
{"__puts", builtin___puts, "[-1 arg1] [-2 arg2]",
" Print specified argument to standard output/error and print new line.\n"
" Options:\n"
" -1 print to standard output\n"
" -2 print to standard error"},
{"_exit", builtin__exit, "[n]",
" Exit the shell with a status of N. If N is omitted, the exit\n"
" status is $?. Unlike exit, it causes normal program termination\n"
" without cleaning the resources."},
{"bg", builtin_fg_bg, "[job_spec ...]",
" Move jobs to the background.\n"
" If JOB_SPEC is not present, latest job is used."},
{"cd", builtin_cd, "[-LP] [dir]",
" Changing the current directory to DIR. The Environment variable\n"
" HOME is the default DIR. A null directory name is the same as\n"
" the current directory. If -L is specified, use logical directory \n"
" (with symbolic link). If -P is specified, use physical directory \n"
" (without symbolic link). Default is -L."},
{"checkenv", builtin_check_env, "variable ...",
" Check existence of specified environmental variables.\n"
" If all of variables are exist and not empty string, exit with 0."},
{"command", nullptr, "[-pVv] command [arg ...]",
" Execute COMMAND with ARGs excepting user defined command.\n"
" If -p option is specified, search command from default PATH.\n"
" If -V or -v option are specified, print description of COMMAND.\n"
" -V option shows more detailed information."},
{"complete", builtin_complete, "[-A action] line",
" Show completion candidates.\n"
" If -A option is specified, show completion candidates via ACTION.\n"
" Actions:\n"
" file complete file names\n"
" dir complete directory names\n"
" module complete module names\n"
" exec complete executable file names\n"
" tilde expand tilde before completion. only available in \n"
" combination of file, module exec actions\n"
" command complete command names including external, user-defined, builtin ones\n"
" cmd equivalent to 'command'\n"
" external complete external commans\n"
" builtin complete builtin commands\n"
" udc complete user-defined commands\n"
" variable complete variable names\n"
" var equivalent to var\n"
" type complete type names\n"
" env complete environmental variables names\n"
" signal complete signal names\n"
" user complete user names\n"
" group complete group names\n"
" stmt_kw complete statement keywords\n"
" expr_kw complete expression keywords"},
{"echo", builtin_echo, "[-neE] [arg ...]",
" Print argument to standard output and print new line.\n"
" Options:\n"
" -n not print new line\n"
" -e interpret some escape sequence\n"
" \\\\ backslash\n"
" \\a bell\n"
" \\b backspace\n"
" \\c ignore subsequent string\n"
" \\e escape sequence\n"
" \\E escape sequence\n"
" \\f form feed\n"
" \\n newline\n"
" \\r carriage return\n"
" \\t horizontal tab\n"
" \\v vertical tab\n"
" \\0nnn N is octal number. NNN can be 0 to 3 number\n"
" \\xnn N is hex number. NN can be 1 to 2 number\n"
" -E disable escape sequence interpretation"},
{"eval", nullptr, "[arg ...]",
" Evaluate ARGs as command."},
{"exec", nullptr, "[-c] [-a name] file [args ...]",
" Execute FILE and replace this shell with specified program.\n"
" If FILE is not specified, the redirections take effect in this shell.\n"
" IF FILE execution fail, terminate this shell immediately\n"
" Options:\n"
" -c cleaner environmental variable\n"
" -a specify set program name(default is FILE)"},
{"exit", builtin_exit, "[n]",
" Exit the shell with a status of N. If N is omitted, the exit\n"
" status is $?."},
{"false", builtin_false, "",
" Always failure (exit status is 1)."},
{"fg", builtin_fg_bg, "[job_spec]",
" Move job to the foreground.\n"
" If JOB_SPEC is not present, latest job is used."},
{"hash", builtin_hash, "[-r] [command ...]",
" Cache file path of specified commands. If -r option is supplied,\n"
" removes specified command path (if not specified, remove all cache).\n"
" If option is not supplied, display all cached path."},
{"help", builtin_help, "[-s] [pattern ...]",
" Display helpful information about builtin commands."},
{"kill", builtin_kill, "[-s signal] pid | jobspec ... or kill -l [signal...]",
" Send a signal to a process or job.\n"
" If signal is not specified, then SIGTERM is assumed.\n"
" Options:\n"
" -s sig send a signal. SIG is a signal name or signal number\n"
" -l list the signal names"},
{"pwd", builtin_pwd, "[-LP]",
" Print the current working directory(absolute path).\n"
" If -L specified, print logical working directory.\n"
" If -P specified, print physical working directory\n"
" (without symbolic link). Default is -L."},
{"read", builtin_read, "[-r] [-p prompt] [-f field separator] [-u fd] [-t timeout] [name ...]",
" Read from standard input.\n"
" Options:\n"
" -r disable backslash escape\n"
" -p specify prompt string\n"
" -f specify field separator (if not, use IFS)\n"
" -s disable echo back\n"
" -u specify file descriptor\n"
" -t timeout set timeout second (only available if input fd is a tty)"},
{"setenv", builtin_setenv, "[name=env ...]",
" Set environmental variables."},
{"shctl", builtin_shctl, "[subcommand]",
" Query and set runtime information\n"
" Subcommands:\n"
" is-interactive return 0 if shell is interactive mode.\n"
" is-sourced return 0 if current script is sourced.\n"
" backtrace print stack trace.\n"
" function print current function/command name.\n"
" module print full path of loaded modules or scripts\n"
" show [OPTION ...] print runtime option setting.\n"
" set OPTION ... set/enable/on runtime option.\n"
" unset OPTION ... unset/disable/off runtime option"},
{"test", builtin_test, "[expr]",
" Unary or Binary expressions.\n"
" If expression is true, return 0\n"
" If expression is false, return 1\n"
" If operand or operator is invalid, return 2\n"
"\n"
" String operators:\n"
" -z STRING check if string is empty\n"
" -n STRING\n"
" STRING check if string is not empty\n"
" STRING1 = STRING2\n"
" STRING1 == STRING2\n"
" check if strings are equal\n"
" STRING1 != STRING2\n"
" check if strings are not equal\n"
" STRING1 < STRING2\n"
" check if STRING1 is less than STRING2 with dictionary order\n"
" STRING1 > STRING2\n"
" check if STRING2 is greater than STRING2 with dictionary order\n"
" Integer operators:\n"
" INT1 -eq INT2 check if integers are equal\n"
" INT1 -ne INT2 check if integers are not equal\n"
" INT1 -lt INT2 check if INT1 is less than INT2\n"
" INT1 -gt INT2 check if INT1 is greater than INT2\n"
" INT1 -le INT2 check if INT1 is less than or equal to INT2\n"
" INT1 -ge INT2 check if INT1 is greater than or equal to INT2\n"
"\n"
" Integer value is signed int 64.\n"
"\n"
" File operators:\n"
" -a FILE\n"
" -e FILE check if file exists\n"
" -b FILE check if file is block device\n"
" -c FILE check if file is character device\n"
" -d FILE check if file is a directory\n"
" -f FILE check if file is a regular file\n"
" -g FILE check if file has set-group-id bit\n"
" -h FILE\n"
" -L FILE check if file is a symbolic link\n"
" -k FILE check if file has sticky bit\n"
" -p FILE check if file is a named pipe\n"
" -r FILE check if file is readable\n"
" -s FILE check if file is not empty\n"
" -S FILE check if file is a socket\n"
" -t FD check if file descriptor is a terminal\n"
" -u FILE check if file has set-user-id bit\n"
" -w FILE check if file is writable\n"
" -x FILE check if file is executable\n"
" -O FILE check if file is effectively owned by user\n"
" -G FILE check if file is effectively owned by group\n"
"\n"
" FILE1 -nt FILE2 check if file1 is newer than file2\n"
" FILE1 -ot FILE2 check if file1 is older than file2\n"
" FILE1 -ef FILE2 check if file1 and file2 refer to the same file"},
{"true", builtin_true, "",
" Always success (exit status is 0)."},
{"ulimit", builtin_ulimit, "[-H | -S] [-a | -"
#define DEF(O, R, S, N, D) O
#include "ulimit-def.in"
#undef DEF
" [value]]",
" Set or show resource limits of the shell and processes started by the shell.\n"
" If VALUE is `soft', `hard' and `unlimited', represent current soft limit\n"
" and hard limit and no limit. If no option specified, assume `-f'.\n"
" Options.\n"
" -H use `hard' resource limit\n"
" -S use `soft' resource limit (default)\n"
" -a show all resource limits"
#define DEF(O, R, S, N, D) "\n -" O " " D
#include "ulimit-def.in"
#undef DEF
},
{"umask", builtin_umask, "[-p] [-S] [mode]",
" Display or set file mode creation mask.\n"
" Set the calling process's file mode creation mask to MODE.\n"
" If MODE is omitted, prints current value of mask.\n"
" Options.\n"
" -p if mode is omitted, print current mask in a form that may be reused as input\n"
" -S print current mask in a symbolic form"},
{"unsetenv", builtin_unsetenv, "[name ...]",
" Unset environmental variables."},
};
unsigned int getBuiltinCommandSize() {
return arraySize(builtinCommands);
}
const char *getBuiltinCommandName(unsigned int index) {
assert(index < getBuiltinCommandSize());
return builtinCommands[index].commandName;
}
static auto initBuiltinMap() {
std::unordered_map<StringRef, unsigned int> map;
for(unsigned int i = 0; i < arraySize(builtinCommands); i++) {
map.emplace(builtinCommands[i].commandName, i);
}
return map;
}
/**
* return null, if not found builtin command.
*/
builtin_command_t lookupBuiltinCommand(const char *commandName) {
/**
* builtin command name and index.
*/
static auto builtinMap = initBuiltinMap();
auto iter = builtinMap.find(commandName);
if(iter == builtinMap.end()) {
return nullptr;
}
return builtinCommands[iter->second].cmd_ptr;
}
static void printAllUsage(FILE *fp) {
for(const auto &e : builtinCommands) {
fprintf(fp, "%s %s\n", e.commandName, e.usage);
}
}
/**
* if not found command, return false.
*/
static bool printUsage(FILE *fp, StringRef prefix, bool isShortHelp = true) {
bool matched = false;
for(const auto &e : builtinCommands) {
const char *cmdName = e.commandName;
if(StringRef(cmdName).startsWith(prefix)) {
fprintf(fp, "%s: %s %s\n", cmdName, cmdName, e.usage);
if(!isShortHelp) {
fprintf(fp, "%s\n", e.detail);
}
matched = true;
}
}
return matched;
}
static int builtin_help(DSState &, ArrayObject &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
printAllUsage(stdout);
return 0;
}
bool isShortHelp = false;
bool foundValidCommand = false;
for(unsigned int i = 1; i < size; i++) {
auto arg = argvObj.getValues()[i].asStrRef();
if(arg == "-s" && size == 2) {
printAllUsage(stdout);
foundValidCommand = true;
} else if(arg == "-s" && i == 1) {
isShortHelp = true;
} else {
if(printUsage(stdout, arg, isShortHelp)) {
foundValidCommand = true;
}
}
}
if(!foundValidCommand) {
ERROR(argvObj, "no help topics match `%s'. Try `help help'.", argvObj.getValues()[size - 1].asCStr());
return 1;
}
return 0;
}
static int showUsage(const ArrayObject &obj) {
printUsage(stderr, obj.getValues()[0].asStrRef());
return 2;
}
int invalidOptionError(const ArrayObject &obj, const GetOptState &s) {
ERROR(obj, "-%c: invalid option", s.optOpt);
return showUsage(obj);
}
static int invalidOptionError(const ArrayObject &obj, const char *opt) {
ERROR(obj, "%s: invalid option", opt);
return showUsage(obj);
}
static int builtin_cd(DSState &state, ArrayObject &argvObj) {
GetOptState optState;
bool useLogical = true;
for(int opt; (opt = optState(argvObj, "PL")) != -1;) {
switch(opt) {
case 'P':
useLogical = false;
break;
case 'L':
useLogical = true;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
unsigned int index = optState.index;
StringRef dest;
bool useOldpwd = false;
if(index < argvObj.getValues().size()) {
dest = argvObj.getValues()[index].asStrRef();
if(dest == "-") {
const char *v = getenv(ENV_OLDPWD);
if(v == nullptr) {
ERROR(argvObj, "OLDPWD not set");
return 1;
}
dest = v;
useOldpwd = true;
}
} else {
const char *v = getenv(ENV_HOME);
if(v == nullptr) {
ERROR(argvObj, "HOME not set");
return 1;
}
dest = v;
}
if(useOldpwd) {
printf("%s\n", dest.data());
}
if(!changeWorkingDir(state, dest, useLogical)) {
PERROR(argvObj, "%s", dest.data());
return 1;
}
return 0;
}
static int builtin_check_env(DSState &, ArrayObject &argvObj) {
const unsigned int size = argvObj.getValues().size();
if(size == 1) {
return showUsage(argvObj);
}
for(unsigned int i = 1; i < size; i++) {
auto ref = argvObj.getValues()[i].asStrRef();
if(ref.hasNullChar()) {
return 1;
}
const char *env = getenv(ref.data());
if(env == nullptr || strlen(env) == 0) {
return 1;
}
}
return 0;
}
static int builtin_echo(DSState &, ArrayObject &argvObj) {
bool newline = true;
bool interpEscape = false;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "neE")) != -1;) {
switch(opt) {
case 'n':
newline = false;
break;
case 'e':
interpEscape = true;
break;
case 'E':
interpEscape = false;
break;
default:
goto END;
}
}
END:
// print argument
if(optState.index > 1 && argvObj.getValues()[optState.index - 1].asStrRef() == "--") {
optState.index--;
}
unsigned int index = optState.index;
const unsigned int argc = argvObj.getValues().size();
bool firstArg = true;
for(; index < argc; index++) {
if(firstArg) {
firstArg = false;
} else {
fputc(' ', stdout);
}
if(!interpEscape) {
auto ref = argvObj.getValues()[index].asStrRef();
fwrite(ref.data(), sizeof(char), ref.size(), stdout);
continue;
}
auto arg = argvObj.getValues()[index].asStrRef();
for(unsigned int i = 0; i < arg.size(); i++) {
int ch = arg[i];
if(ch == '\\' && i + 1 < arg.size()) {
switch(arg[++i]) {
case '\\':
ch = '\\';
break;
case 'a':
ch = '\a';
break;
case 'b':
ch = '\b';
break;
case 'c': // stop printing
return 0;
case 'e':
case 'E':
ch = '\033';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'v':
ch = '\v';
break;
case '0': {
int v = 0;
for(unsigned int c = 0; c < 3; c++) {
if(i + 1 < arg.size() && isOctal(arg[i + 1])) {
v *= 8;
v += arg[++i] - '0';
} else {
break;
}
}
ch = static_cast<char>(v);
break;
}
case 'x': {
if(i + 1 < arg.size() && isHex(arg[i + 1])) {
unsigned int v = hexToNum(arg[++i]);
if(i + 1 < arg.size() && isHex(arg[i + 1])) {
v *= 16;
v += hexToNum(arg[++i]);
}
ch = static_cast<char>(v);
break;
}
i--;
break;
}
default:
i--;
break;
}
}
fputc(ch, stdout);
}
}
if(newline) {
fputc('\n', stdout);
}
return 0;
}
static int parseExitStatus(const DSState &state, const ArrayObject &argvObj) {
int64_t ret = state.getGlobal(BuiltinVarOffset::EXIT_STATUS).asInt();
if(argvObj.getValues().size() > 1) {
auto value = argvObj.getValues()[1].asStrRef();
auto pair = convertToNum<int64_t>(value.begin(), value.end());
if(pair.second) {
ret = pair.first;
}
}
return maskExitStatus(ret);
}
static int builtin_exit(DSState &state, ArrayObject &argvObj) {
int ret = parseExitStatus(state, argvObj);
if(hasFlag(state.compileOption, CompileOption::INTERACTIVE)) {
state.jobTable.send(SIGHUP);
}
std::string str("terminated by exit ");
str += std::to_string(ret);
raiseError(state, TYPE::_ShellExit, std::move(str), ret);
return ret;
}
static int builtin__exit(DSState &state, ArrayObject &argvObj) {
int ret = parseExitStatus(state, argvObj);
terminate(ret);
}
static int builtin_true(DSState &, ArrayObject &) {
return 0;
}
static int builtin_false(DSState &, ArrayObject &) {
return 1;
}
/**
* for stdin redirection test
*/
static int builtin___gets(DSState &, ArrayObject &) {
char buf[256];
int readSize = 0;
while((readSize = read(STDIN_FILENO, buf, arraySize(buf))) > 0) {
int r = write(STDOUT_FILENO, buf, readSize);
(void) r;
}
return 0;
}
/**
* for stdout/stderr redirection test
*/
static int builtin___puts(DSState &, ArrayObject &argvObj) {
GetOptState optState;
for(int opt; (opt = optState(argvObj, "1:2:")) != -1;) {
switch(opt) {
case '1':
fwrite(optState.optArg.data(), sizeof(char), optState.optArg.size(), stdout);
fputc('\n', stdout);
fflush(stdout);
break;
case '2':
fwrite(optState.optArg.data(), sizeof(char), optState.optArg.size(), stderr);
fputc('\n', stderr);
fflush(stderr);
break;
default:
return 1;
}
}
return 0;
}
static int builtin_pwd(DSState &state, ArrayObject &argvObj) {
bool useLogical = true;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "LP")) != -1;) {
switch(opt) {
case 'L':
useLogical = true;
break;
case 'P':
useLogical = false;
break;
default:
return invalidOptionError(argvObj, optState);
}
}
auto workdir = getWorkingDir(state, useLogical);
if(!workdir) {
PERROR(argvObj, ".");
return 1;
}
printf("%s\n", workdir.get());
return 0;
}
#define EACH_STR_COMP_OP(OP) \
OP(STR_EQ, "==", ==) \
OP(STR_EQ2, "=", ==) \
OP(STR_NE, "!=", !=) \
OP(STR_LT, "<", <) \
OP(STR_GT, ">", >)
#define EACH_INT_COMP_OP(OP) \
OP(EQ, "-eq", ==) \
OP(NE, "-ne", !=) \
OP(LT, "-lt", <) \
OP(GT, "-gt", >) \
OP(LE, "-le", <=) \
OP(GE, "-ge", >=)
#define EACH_FILE_COMP_OP(OP) \
OP(NT, "-nt", %) \
OP(OT, "-ot", %) \
OP(EF, "-ef", %)
enum class BinaryOp : unsigned int {
INVALID,
#define GEN_ENUM(E, S, O) E,
EACH_STR_COMP_OP(GEN_ENUM)
EACH_INT_COMP_OP(GEN_ENUM)
EACH_FILE_COMP_OP(GEN_ENUM)
#undef GEN_ENUM
};
static BinaryOp resolveBinaryOp(StringRef opStr) {
const struct {
const char *k;
BinaryOp op;
} table[] = {
#define GEN_ENTRY(E, S, O) {S, BinaryOp::E},
EACH_INT_COMP_OP(GEN_ENTRY)
EACH_STR_COMP_OP(GEN_ENTRY)
EACH_FILE_COMP_OP(GEN_ENTRY)
#undef GEN_ENTRY
};
for(auto &e : table) {
if(opStr == e.k) {
return e.op;
}
}
return BinaryOp::INVALID;
}
static bool compareStr(StringRef left, BinaryOp op, StringRef right) {
switch(op) {
#define GEN_CASE(E, S, O) case BinaryOp::E: return left O right;
EACH_STR_COMP_OP(GEN_CASE)
#undef GEN_CASE
default:
break;
}
return false;
}
static bool compareInt(int64_t x, BinaryOp op, int64_t y) {
switch(op) {
#define GEN_CASE(E, S, O) case BinaryOp::E: return x O y;
EACH_INT_COMP_OP(GEN_CASE)
#undef GEN_CASE
default:
break;
}
return false;
}
static bool operator<(const timespec &left, const timespec &right) {
if(left.tv_sec == right.tv_sec) {
return left.tv_nsec < right.tv_nsec;
}
return left.tv_sec < right.tv_sec;
}
static bool compareFile(StringRef x, BinaryOp op, StringRef y) {
if(x.hasNullChar() || y.hasNullChar()) {
return false;
}
struct stat st1; //NOLINT
struct stat st2; //NOLINT
if(stat(x.data(), &st1) != 0) {
return false;
}
if(stat(y.data(), &st2) != 0) {
return false;
}
switch(op) {
case BinaryOp::NT:
#ifdef __APPLE__
return st2.st_mtimespec < st1.st_mtimespec;
#else
return st2.st_mtim < st1.st_mtim;
#endif
case BinaryOp::OT:
#ifdef __APPLE__
return st1.st_mtimespec < st2.st_mtimespec;
#else
return st1.st_mtim < st2.st_mtim;
#endif
case BinaryOp::EF:
return st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino;
default:
return false;
}
}
static int parseFD(StringRef value) {
if(value.startsWith("/dev/fd/")) {
value.removePrefix(strlen("/dev/fd/"));
}
auto ret = convertToNum<int32_t>(value.begin(), value.end());
if(!ret.second || ret.first < 0) {
return -1;
}
return ret.first;
}
static int testFile(char op, const char *value) {
bool result = false;
switch(op) {
case 'a':
case 'e':
result = access(value, F_OK) == 0; // check if file exists
break;
case 'b':
result = S_ISBLK(getStMode(value)); // check if file is block device
break;
case 'c':
result = S_ISCHR(getStMode(value)); // check if file is character device
break;
case 'd':
result = S_ISDIR(getStMode(value)); // check if file is directory
break;
case 'f':
result = S_ISREG(getStMode(value)); // check if file is regular file.
break;
case 'g':
result = S_IS_PERM_(getStMode(value), S_ISUID); // check if file has set-uid-bit
break;
case 'h':
case 'L': {
mode_t mode = 0;
struct stat st; //NOLINT
if(lstat(value, &st) == 0) {
mode = st.st_mode;
}
result = S_ISLNK(mode); // check if file is symbolic-link
break;
}
case 'k':
result = S_IS_PERM_(getStMode(value), S_ISVTX); // check if file has sticky bit
break;
case 'p':
result = S_ISFIFO(getStMode(value)); // check if file is a named pipe
break;
case 'r':
result = access(value, R_OK) == 0; // check if file is readable
break;
case 's': {
struct stat st; //NOLINT
result = stat(value, &st) == 0 && st.st_size != 0; // check if file is not empty
break;
}
case 'S':
result = S_ISSOCK(getStMode(value)); // check file is a socket
break;
case 't': {
int fd = parseFD(value);
result = fd > -1 && isatty(fd) != 0; // check if FD is a terminal
break;
}
case 'u':
result = S_IS_PERM_(getStMode(value), S_ISUID); // check file has set-user-id bit
break;
case 'w':
result = access(value, W_OK) == 0; // check if file is writable
break;
case 'x':
result = access(value, X_OK) == 0; // check if file is executable
break;
case 'O': {
struct stat st; //NOLINT
result = stat(value, &st) == 0 && st.st_uid == geteuid(); // check if file is effectively owned
break;
}
case 'G': {
struct stat st; //NOLINT
result = stat(value, &st) == 0 && st.st_gid == getegid(); // check if file is effectively owned by group
break;
}
default:
return 2;
}
return result ? 0 : 1;
}
static int builtin_test(DSState &, ArrayObject &argvObj) {
bool result = false;
unsigned int argc = argvObj.getValues().size();
const unsigned int argSize = argc - 1;
switch(argSize) {
case 0: {
result = false;
break;
}
case 1: {
result = !argvObj.getValues()[1].asStrRef().empty(); // check if string is not empty
break;
}
case 2: { // unary op
auto op = argvObj.getValues()[1].asStrRef();
auto ref = argvObj.getValues()[2].asStrRef();
if(op.size() != 2 || op[0] != '-') {
ERROR(argvObj, "%s: invalid unary operator", op.data());
return 2;
}
const char opKind = op[1]; // ignore -
if(opKind == 'z') { // check if string is empty
result = ref.empty();
} else if(opKind == 'n') { // check if string not empty
result = !ref.empty();
} else {
if(ref.hasNullChar()) {
ERROR(argvObj, "file path contains null characters");
return 2;
}
int r = testFile(opKind, ref.data());
if(r == 2) {
ERROR(argvObj, "%s: invalid unary operator", op.data());
}
return r;
}
break;
}
case 3: { // binary op
auto left = argvObj.getValues()[1].asStrRef();
auto op = argvObj.getValues()[2].asStrRef();
auto opKind = resolveBinaryOp(op);
auto right = argvObj.getValues()[3].asStrRef();
switch(opKind) {
#define GEN_CASE(E, S, O) case BinaryOp::E:
EACH_STR_COMP_OP(GEN_CASE) {
result = compareStr(left, opKind, right);
break;
}
EACH_INT_COMP_OP(GEN_CASE) {
auto pair = convertToNum<int64_t>(left.begin(), left.end());
int64_t n1 = pair.first;
if(!pair.second) {
ERROR(argvObj, "%s: must be integer", left.data());
return 2;
}
pair = convertToNum<int64_t>(right.begin(), right.end());
int64_t n2 = pair.first;
if(!pair.second) {
ERROR(argvObj, "%s: must be integer", right.data());
return 2;
}
result = compareInt(n1, opKind, n2);
break;
}
EACH_FILE_COMP_OP(GEN_CASE) {
result = compareFile(left, opKind, right);
break;
}
#undef GEN_CASE
case BinaryOp::INVALID:
ERROR(argvObj, "%s: invalid binary operator", op.data()); //FIXME:
return 2;
}
break;
}
default: {
ERROR(argvObj, "too many arguments");
return 2;
}
}
return result ? 0 : 1;
}
static int xfgetc(int fd, int timeout) {
signed char ch;
do {
errno = 0;
if(timeout > -2) {
struct pollfd pollfd[1];
pollfd[0].fd = fd;
pollfd[0].events = POLLIN;
if(poll(pollfd, 1, timeout) != 1) {
return EOF;
}
}
if(read(fd, &ch, 1) <= 0) {
ch = EOF;
}
} while(static_cast<int>(ch) == EOF && errno == EAGAIN);
return ch;
}
static int builtin_read(DSState &state, ArrayObject &argvObj) { //FIXME: timeout, UTF-8
StringRef prompt;
StringRef ifs;
bool backslash = true;
bool noecho = false;
int fd = STDIN_FILENO;
int timeout = -1;
GetOptState optState;
for(int opt; (opt = optState(argvObj, ":rp:f:su:t:")) != -1;) {
switch(opt) {
case 'p':
prompt = optState.optArg;
break;
case 'f':
ifs = optState.optArg;
break;
case 'r':
backslash = false;
break;
case 's':
noecho = true;
break;
case 'u': {
StringRef value = optState.optArg;
fd = parseFD(value);
if(fd < 0) {
ERROR(argvObj, "%s: invalid file descriptor", value.data());
return 1;
}
break;
}
case 't': {
auto ret = convertToNum<int64_t>(optState.optArg.begin(), optState.optArg.end());
int64_t t = ret.first;
if(ret.second) {
if(t > -1 && t <= INT32_MAX) {
t *= 1000;
if(t > -1 && t <= INT32_MAX) {
timeout = static_cast<int>(t);
break;
}
}
}
ERROR(argvObj, "%s: invalid timeout specification", optState.optArg.data());
return 1;
}
case ':':
ERROR(argvObj, "-%c: option require argument", optState.optOpt);
return 2;
default:
return invalidOptionError(argvObj, optState);
}
}
const unsigned int argc = argvObj.getValues().size();
unsigned int index = optState.index;
const bool isTTY = isatty(fd) != 0;
// check ifs
if(ifs.data() == nullptr) {
ifs = state.getGlobal(BuiltinVarOffset::IFS).asStrRef();
}
// clear old variable before read
state.setGlobal(toIndex(BuiltinVarOffset::REPLY), DSValue::createStr()); // clear REPLY
typeAs<MapObject>(state.getGlobal(BuiltinVarOffset::REPLY_VAR)).clear(); // clear reply
const unsigned int varSize = argc - index; // if zero, store line to REPLY
const unsigned int varIndex = toIndex(varSize == 0 ? BuiltinVarOffset::REPLY : BuiltinVarOffset::REPLY_VAR);
std::string strBuf;
// show prompt
if(isTTY) {
fwrite(prompt.data(), sizeof(char), prompt.size(), stderr);
fflush(stderr);
}
// change tty state
struct termios tty{};
struct termios oldtty{};
if(noecho && isTTY) {
tcgetattr(fd, &tty);
oldtty = tty;
tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
tcsetattr(fd, TCSANOW, &tty);
}
// read line
if(!isTTY) {
timeout = -2;
}
unsigned int skipCount = 1;
int ch;
for(bool prevIsBackslash = false; (ch = xfgetc(fd, timeout)) != EOF;
prevIsBackslash = backslash && ch == '\\' && !prevIsBackslash) {
if(ch == '\n') {
if(prevIsBackslash) {
continue;
}
break;
}
if(ch == '\\' && !prevIsBackslash && backslash) {
continue;
}
bool fieldSep = matchFieldSep(ifs, ch) && !prevIsBackslash;
if(fieldSep && skipCount > 0) {
if(isSpace(ch)) {
continue;
}
if(--skipCount == 1) {
continue;
}
}
skipCount = 0;
if(fieldSep && index < argc - 1) {
auto &obj = typeAs<MapObject>(state.getGlobal(varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::createStr(std::move(strBuf));
obj.set(std::move(varObj), std::move(valueObj));
strBuf = "";
index++;
skipCount = isSpace(ch) ? 2 : 1;
continue;
}
strBuf += static_cast<char>(ch);
}
// remove last spaces
if(!strBuf.empty()) {
if(hasSpace(ifs)) { // check if field separator has spaces
while(!strBuf.empty() && isSpace(strBuf.back())) {
strBuf.pop_back();
}
}
}
if(varSize == 0) {
state.setGlobal(varIndex, DSValue::createStr(std::move(strBuf)));
strBuf = "";
}
// set rest variable
for(; index < argc; index++) {
auto &obj = typeAs<MapObject>(state.getGlobal(varIndex));
auto varObj = argvObj.getValues()[index];
auto valueObj = DSValue::createStr(std::move(strBuf));
obj.set(std::move(varObj), std::move(valueObj));
strBuf = "";
}
// restore tty setting
if(noecho && isTTY) {
tcsetattr(fd, TCSANOW, &oldtty);
}
// report error
int ret = ch == EOF ? 1 : 0;
if(ret != 0 && errno != 0) {
PERROR(argvObj, "%d", fd);
}
return ret;
}
static int builtin_hash(DSState &state, ArrayObject &argvObj) {
bool remove = false;
// check option
const unsigned int argc = argvObj.getValues().size();
unsigned int index = 1;
for(; index < argc; index++) {
auto arg = argvObj.getValues()[index].asStrRef();
if(arg[0] != '-') {
break;
}
if(arg == "-r") {
remove = true;
} else {
return invalidOptionError(argvObj, arg.data());
}
}
const bool hasNames = index < argc;
if(hasNames) {
for(; index < argc; index++) {
auto ref = argvObj.getValues()[index].asStrRef();
const char *name = ref.data();
bool hasNul = ref.hasNullChar();
if(remove) {
state.pathCache.removePath(hasNul ? nullptr : name);
} else {
if(hasNul || state.pathCache.searchPath(name) == nullptr) {
ERROR(argvObj, "%s: not found", name);
return 1;
}
}
}
} else {
if(remove) { // remove all cache
state.pathCache.clear();
} else { // show all cache
const auto cend = state.pathCache.end();
if(state.pathCache.begin() == cend) {
fputs("hash: file path cache is empty\n", stdout);
return 0;
}
for(auto &entry : state.pathCache) {
printf("%s=%s\n", entry.first, entry.second.c_str());
}
}
}
return 0;
}
static std::unordered_map<StringRef, CodeCompOp> initCompActions() {
return {
{"file", CodeCompOp::FILE},
{"dir", CodeCompOp::DIR},
{"module", CodeCompOp::MODULE},
{"exec", CodeCompOp::EXEC},
{"tilde", CodeCompOp::TILDE},
{"command", CodeCompOp::COMMAND},
{"cmd", CodeCompOp::COMMAND},
{"external", CodeCompOp::EXTERNAL},
{"builtin", CodeCompOp::BUILTIN},
{"udc", CodeCompOp::UDC},
{"variable", CodeCompOp::VAR},
{"var", CodeCompOp::VAR},
{"env", CodeCompOp::ENV},
{"signal", CodeCompOp::SIGNAL},
{"user", CodeCompOp::USER},
{"group", CodeCompOp::GROUP},
{"stmt_kw", CodeCompOp::STMT_KW},
{"expr_kw", CodeCompOp::EXPR_KW},
{"type", CodeCompOp::TYPE},
};
}
static int builtin_complete(DSState &state, ArrayObject &argvObj) {
static auto actionMap = initCompActions();
CodeCompOp compOp{};
GetOptState optState;
for(int opt; (opt = optState(argvObj, ":A:")) != -1;) {
switch(opt) {
case 'A': {
auto iter = actionMap.find(optState.optArg);
if(iter == actionMap.end()) {
ERROR(argvObj, "%s: invalid action", optState.optArg.data());
return showUsage(argvObj);
}
setFlag(compOp, iter->second);
break;
}
case ':':
ERROR(argvObj, "-%c: option requires argument", optState.optOpt);
return 1;
default:
return invalidOptionError(argvObj, optState);
}
}
StringRef line;
if(optState.index < argvObj.size()) {
line = argvObj.getValues()[optState.index].asStrRef();
}
doCodeCompletion(state, line, compOp);
auto &ret = typeAs<ArrayObject>(state.getGlobal(BuiltinVarOffset::COMPREPLY));
for(const auto &e : ret.getValues()) {
fputs(e.asCStr(), stdout);
fputc('\n', stdout);
}
return 0;
}
static int builtin_setenv(DSState &, ArrayObject &argvObj) {
if(argvObj.size() == 1) {
for(unsigned int i = 0; environ[i] != nullptr; i++) {
const char *e = environ[i];
fprintf(stdout, "%s\n", e);
}
return 0;
}
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
auto kv = iter->asStrRef();
auto pos = kv.hasNullChar() ? StringRef::npos : kv.find("=");
errno = EINVAL;
if(pos != StringRef::npos && pos != 0) {
auto name = kv.substr(0, pos).toString();
auto value = kv.substr(pos + 1);
if(setenv(name.c_str(), value.data(), 1) == 0) {
continue;
}
}
PERROR(argvObj, "%s", kv.data());
return 1;
}
return 0;
}
static int builtin_unsetenv(DSState &, ArrayObject &argvObj) {
auto end = argvObj.getValues().end();
for(auto iter = argvObj.getValues().begin() + 1; iter != end; ++iter) {
auto envName = iter->asStrRef();
if(unsetenv(envName.hasNullChar() ? "" : envName.data()) != 0) {
PERROR(argvObj, "%s", envName.data());
return 1;
}
}
return 0;
}
static std::pair<int, bool> toInt32(StringRef str) {
return convertToNum<int32_t>(str.begin(), str.end());
}
static int toSigNum(StringRef str) {
if(!str.empty() && isDecimal(*str.data())) {
auto pair = toInt32(str);
if(!pair.second) {
return -1;
}
auto sigList = getUniqueSignalList();
return std::binary_search(sigList.begin(), sigList.end(), pair.first) ? pair.first : -1;
}
return getSignalNum(str);
}
static bool printNumOrName(StringRef str) {
if(!str.empty() && isDecimal(*str.data())) {
auto pair = toInt32(str);
if(!pair.second) {
return false;
}
const char *name = getSignalName(pair.first);
if(name == nullptr) {
return false;
}
printf("%s\n", name);
} else {
int sigNum = getSignalNum(str);
if(sigNum < 0) {
return false;
}
printf("%d\n", sigNum);
}
fflush(stdout);
return true;
}
static bool killProcOrJob(DSState &state, ArrayObject &argvObj, StringRef arg, int sigNum) {
bool isJob = arg.startsWith("%");
auto pair = toInt32(isJob ? arg.substr(1) : arg);
if(!pair.second) {
ERROR(argvObj, "%s: arguments must be process or job IDs", arg.data());
return false;
}
if(isJob) {
if(pair.first > 0) {
auto job = state.jobTable.findEntry(static_cast<unsigned int>(pair.first));
if(job) {
job->send(sigNum);
return true;
}
}
ERROR(argvObj, "%s: no such job", arg.data());
return false;
}
if(kill(pair.first, sigNum) < 0) {
PERROR(argvObj, "%s", arg.data());
return false;
}
return true;
}
// -s sig (pid | jobspec ...)
// -l
static int builtin_kill(DSState &state, ArrayObject &argvObj) {
int sigNum = SIGTERM;
bool listing = false;
if(argvObj.getValues().size() == 1) {
return showUsage(argvObj);
}
GetOptState optState;
const int opt = optState(argvObj, ":ls:");
switch(opt) {
case 'l':
listing = true;
break;
case 's':
case '?': {
StringRef sigStr = optState.optArg;
if(opt == '?') { // skip prefix '-', ex. -9
sigStr = argvObj.getValues()[optState.index++].asStrRef().substr(1);
}
sigNum = toSigNum(sigStr);
if(sigNum == -1) {
ERROR(argvObj, "%s: invalid signal specification", sigStr.data());
return 1;
}
break;
}
case ':':
ERROR(argvObj, "-%c: option requires argument", optState.optOpt);
return 1;
default:
break;
}
auto begin = argvObj.getValues().begin() + optState.index;
const auto end = argvObj.getValues().end();
if(begin == end) {
if(listing) {
auto sigList = getUniqueSignalList();
unsigned int size = sigList.size();
for(unsigned int i = 0; i < size; i++) {
printf("%2d) SIG%s", sigList[i], getSignalName(sigList[i]));
if(i % 5 == 4 || i == size - 1) {
fputc('\n', stdout);
} else {
fputc('\t', stdout);
}
}
return 0;
}
return showUsage(argvObj);
}
unsigned int count = 0;
for(; begin != end; ++begin) {
auto arg = begin->asStrRef();
if(listing) {
if(!printNumOrName(arg)) {
count++;
ERROR(argvObj, "%s: invalid signal specification", arg.data());
}
} else {
if(killProcOrJob(state, argvObj, arg, sigNum)) {
count++;
}
}
}
if(listing && count > 0) {
return 1;
}
if(!listing && count == 0) {
return 1;
}
return 0;
}
static Job tryToGetJob(const JobTable &table, StringRef name) {
if(name.startsWith("%")) {
name.removePrefix(1);
}
Job job;
auto pair = toInt32(name);
if(pair.second && pair.first > -1) {
job = table.findEntry(pair.first);
}
return job;
}
static int builtin_fg_bg(DSState &state, ArrayObject &argvObj) {
if(!state.isJobControl()) {
ERROR(argvObj, "no job control in this shell");
return 1;
}
bool fg = argvObj.getValues()[0].asStrRef() == "fg";
unsigned int size = argvObj.getValues().size();
assert(size > 0);
Job job;
StringRef arg = "current";
if(size == 1) {
job = state.jobTable.getLatestEntry();
} else {
arg = argvObj.getValues()[1].asStrRef();
job = tryToGetJob(state.jobTable, arg);
}
int ret = 0;
if(job) {
if(fg) {
beForeground(job->getPid(0));
}
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg.data());
ret = 1;
if(fg) {
return ret;
}
}
if(fg) {
int s = state.jobTable.waitAndDetach(job, true); //FIXME: check root shell
int errNum = errno;
state.tryToBeForeground();
if(errNum != 0) {
PERROR(argvObj, "wait failed");
}
state.jobTable.updateStatus();
return s;
}
// process remain arguments
for(unsigned int i = 2; i < size; i++) {
arg = argvObj.getValues()[i].asStrRef();
job = tryToGetJob(state.jobTable, arg);
if(job) {
job->send(SIGCONT);
} else {
ERROR(argvObj, "%s: no such job", arg.data());
ret = 1;
}
}
return ret;
}
// for ulimit command
static constexpr flag8_t RLIM_HARD = 1u << 0;
static constexpr flag8_t RLIM_SOFT = 1u << 1;
struct ulimitOp {
char op;
char resource;
char shift;
const char *name;
void print(flag8_set_t limOpt, unsigned int maxNameLen) const {
rlimit limit{};
getrlimit(this->resource, &limit);
if(maxNameLen) {
printf("-%c: %s ", this->op, this->name);
for(unsigned int len = strlen(this->name); len < maxNameLen; len++) {
printf(" ");
}
}
auto value = hasFlag(limOpt, RLIM_HARD) ? limit.rlim_max : limit.rlim_cur;
if(value == RLIM_INFINITY) {
printf("unlimited\n");
} else {
value >>= this->shift;
printf("%llu\n", static_cast<unsigned long long>(value));
}
fflush(stdout);
}
};
struct UlimitOptEntry {
enum Kind : unsigned char {
UNUSED,
NUM,
SOFT,
HARD,
UNLIMITED,
};
Kind kind{UNUSED};
rlim_t value{0};
explicit operator bool() const {
return this->kind != UNUSED;
}
rlim_t getValue(const rlimit &limit) const {
switch(this->kind) {
case SOFT:
return limit.rlim_cur;
case HARD:
return limit.rlim_max;
case UNLIMITED:
return RLIM_INFINITY;
default:
return this->value;
}
}
};
static constexpr ulimitOp ulimitOps[] = {
#define DEF(O, R, S, N, D) {O[0], R, S, N},
#include "ulimit-def.in"
#undef DEF
};
static unsigned int computeMaxNameLen() {
unsigned int max = 0;
for(auto &e : ulimitOps) {
unsigned int len = strlen(e.name);
if(len > max) {
max = len;
}
}
return max;
}
static bool parseUlimitOpt(StringRef ref, unsigned int index, UlimitOptEntry &entry) {
using underlying_t = std::conditional<sizeof(rlim_t) == sizeof(uint64_t),
uint64_t, std::conditional<sizeof(rlim_t) == sizeof(uint32_t), uint32_t, void>::type>::type;
if(ref.hasNullChar()) {
return false;
}
const char *str = ref.data();
if(strcasecmp(str, "soft") == 0) {
entry.kind = UlimitOptEntry::SOFT;
return true;
} else if(strcasecmp(str, "hard") == 0) {
entry.kind = UlimitOptEntry::HARD;
return true;
} else if(strcasecmp(str, "unlimited") == 0) {
entry.kind = UlimitOptEntry::UNLIMITED;
return true;
}
auto pair = convertToNum<underlying_t>(str);
if(!pair.second) {
return false;
}
entry.value = pair.first;
entry.value <<= ulimitOps[index].shift;
entry.kind = UlimitOptEntry::NUM;
return true;
}
struct UlimitOptEntryTable {
uint64_t printSet{0};
std::array<UlimitOptEntry, arraySize(ulimitOps)> entries;
unsigned int count{0};
int tryToUpdate(GetOptState &optState, ArrayObject &argvObj, int opt) {
DSValue arg;
if(optState.index < argvObj.getValues().size() && *argvObj.getValues()[optState.index].asCStr() != '-') {
arg = argvObj.getValues()[optState.index++];
}
if(!this->update(opt, arg)) {
ERROR(argvObj, "%s: invalid number", arg.asCStr());
return 1;
}
return 0;
}
private:
bool update(int ch, const DSValue &value) {
this->count++;
// search entry
for(unsigned int index = 0; index < arraySize(ulimitOps); index++) {
if(ulimitOps[index].op == ch) {
auto &entry = this->entries[index];
if(value) {
if(!parseUlimitOpt(value.asStrRef(), index, entry)) {
return false;
}
} else {
setFlag(this->printSet, static_cast<uint64_t>(1) << index);
}
}
}
return true;
}
};
static int builtin_ulimit(DSState &, ArrayObject &argvObj) {
flag8_set_t limOpt = 0;
bool showAll = false;
GetOptState optState;
const char *optStr = "HSa"
#define DEF(O, R, S, N, D) O
#include "ulimit-def.in"
#undef DEF
;
UlimitOptEntryTable table;
// parse option
for(int opt; (opt = optState(argvObj, optStr)) != -1;) {
switch(opt) {
case 'H':
setFlag(limOpt, RLIM_HARD);
break;
case 'S':
setFlag(limOpt, RLIM_SOFT);
break;
case 'a':
showAll = true;
break;
case '?':
return invalidOptionError(argvObj, optState);
default:
int ret = table.tryToUpdate(optState, argvObj, opt);
if(ret) {
return ret;
}
break;
}
}
// parse remain
if(table.count == 0) {
int ret = table.tryToUpdate(optState, argvObj, 'f');
if(ret) {
return ret;
}
}
if(limOpt == 0) {
setFlag(limOpt, RLIM_SOFT);
}
if(showAll) {
unsigned int maxDescLen = computeMaxNameLen();
for(auto &e : ulimitOps) {
e.print(limOpt, maxDescLen);
}
return 0;
}
// print or set limit
unsigned int maxNameLen = 0;
if(table.printSet > 0 && (table.printSet & (table.printSet - 1)) != 0) {
maxNameLen = computeMaxNameLen();
}
for(unsigned int index = 0; index < static_cast<unsigned int>(table.entries.size()); index++) {
if(table.entries[index]) {
const auto &op = ulimitOps[index];
rlimit limit{};
getrlimit(op.resource, &limit);
rlim_t value = table.entries[index].getValue(limit);
if(hasFlag(limOpt, RLIM_SOFT)) {
limit.rlim_cur = value;
}
if(hasFlag(limOpt, RLIM_HARD)) {
limit.rlim_max = value;
}
if(setrlimit(op.resource, &limit) < 0) {
PERROR(argvObj, "%s: cannot change limit", op.name);
return 1;
}
}
if(hasFlag(table.printSet, static_cast<uint64_t>(1) << index)) {
ulimitOps[index].print(limOpt, maxNameLen);
}
}
return 0;
}
enum class PrintMaskOp : unsigned int {
ONLY_PRINT = 1 << 0,
REUSE = 1 << 1,
SYMBOLIC = 1 << 2,
};
template <> struct allow_enum_bitop<PrintMaskOp> : std::true_type {};
static void printMask(mode_t mask, PrintMaskOp op) {
if(hasFlag(op, PrintMaskOp::SYMBOLIC)) {
char buf[arraySize("u=rwx,g=rwx,o=rwx")];
char *ptr = buf;
/**
* u g o
* rwx|rwx|rwx
* 111 111 111
*
*/
for(auto &user : {'u', 'g', 'o'}) {
if(ptr != buf) {
*(ptr++) = ',';
}
*(ptr++) = user;
*(ptr++) = '=';
for(auto &perm : {'r', 'w', 'x'}) {
if(!(mask & 0400)) {
*(ptr++) = perm;
}
mask <<= 1;
}
}
*ptr = '\0';
fprintf(stdout, "%s%s\n", hasFlag(op, PrintMaskOp::REUSE) ? "umask -S " : "", buf);
} else if(hasFlag(op, PrintMaskOp::ONLY_PRINT)) {
fprintf(stdout, "%s%04o\n", hasFlag(op, PrintMaskOp::REUSE) ? "umask " : "", mask);
}
}
/**
* MODE = [ugoa]* [+-=] [rwx]*
*
* @param value
* @param mode
* @return
* if failed, return false
*/
static bool parseMode(const char *&value, mode_t &mode) {
// [ugoa]*
mode_t user = 0;
for(bool next = true; next; ) {
int ch = *(value++);
switch(ch) {
case 'u':
user |= 0700;
break;
case 'g':
user |= 0070;
break;
case 'o':
user |= 0007;
break;
case 'a':
user |= 0777;
break;
default: // may be [-+=]
next = false;
--value;
break;
}
}
if(user == 0) {
user = 0777;
}
// [-+=]
char op = *(value++);
if(op != '-' && op != '+' && op != '=') {
return false;
}
// [rwx]*
mode_t newMode = 0;
while(*value && *value != ',') {
int ch = *(value++);
switch(ch) {
case 'r':
newMode |= 0444 & user;
break;
case 'w':
newMode |= 0222 & user;
break;
case 'x':
newMode |= 0111 & user;
break;
default:
return false;
}
}
// apply op
if(op == '+') {
unsetFlag(mode, newMode);
} else if(op == '-') {
setFlag(mode, newMode);
} else {
setFlag(mode, user);
unsetFlag(mode, newMode);
}
return true;
}
struct SymbolicParseResult {
bool success;
char invalid;
mode_t mode;
};
/**
* MODES = MODE (, MODE)*
*
* @param ref
* @param mode
* @return
*/
static SymbolicParseResult parseSymbolicMode(StringRef ref, mode_t mode) {
SymbolicParseResult ret {
.success = true,
.invalid = 0,
.mode = mode,
};
if(ref.hasNullChar()) {
ret.success = false;
ret.invalid = '\0';
return ret;
}
const char *value = ref.data();
if(!parseMode(value, ret.mode)) {
ret.success = false;
ret.invalid = *(--value);
return ret;
}
while(*value) {
if(*(value++) == ',' && parseMode(value, ret.mode)) {
continue;
}
ret.success = false;
ret.invalid = *(--value);
break;
}
return ret;
}
static int builtin_umask(DSState &, ArrayObject &argvObj) {
auto op = PrintMaskOp::ONLY_PRINT;
GetOptState optState;
for(int opt; (opt = optState(argvObj, "pS")) != -1; ) {
switch(opt) {
case 'p':
setFlag(op, PrintMaskOp::REUSE);
break;
case 'S':
setFlag(op, PrintMaskOp::SYMBOLIC);
break;
default:
return invalidOptionError(argvObj, optState);
}
}
auto mask = umask(0);
umask(mask);
if(optState.index < argvObj.getValues().size()) {
unsetFlag(op, PrintMaskOp::ONLY_PRINT | PrintMaskOp::REUSE);
auto value = argvObj.getValues()[optState.index].asStrRef();
if(!value.empty() && isDecimal(*value.data())) {
auto pair = convertToNum<int32_t>(value.begin(), value.end(), 8);
int num = pair.first;
if(!pair.second || num < 0 || num > 0777) {
ERROR(argvObj, "%s: octal number out of range (0000~0777)", value.data());
return 1;
}
mask = num;
} else {
auto ret = parseSymbolicMode(value, mask);
mask = ret.mode;
if(!ret.success) {
int ch = ret.invalid;
if(isascii(ch) && ch != 0) {
ERROR(argvObj, "%c: invalid symbolic operator", ch);
} else {
ERROR(argvObj, "0x%02x: invalid symbolic operator", ch);
}
return 1;
}
}
umask(mask);
}
printMask(mask, op);
return 0;
}
static int printBacktrace(const VMState &state) {
auto traces = state.createStackTrace();
for(auto &s : traces) {
fprintf(stdout, "from %s:%d '%s()'\n",
s.getSourceName().c_str(), s.getLineNum(), s.getCallerName().c_str());
}
return 0;
}
static int printFuncName(const VMState &state) {
auto *code = state.getFrame().code;
const char *name = nullptr;
if(!code->is(CodeKind::NATIVE) && !code->is(CodeKind::TOPLEVEL)) {
name = static_cast<const CompiledCode *>(code)->getName();
}
fprintf(stdout, "%s\n", name != nullptr ? name : "<toplevel>");
return name != nullptr ? 0 : 1;
}
static constexpr struct {
RuntimeOption option;
const char *name;
} runtimeOptions[] = {
#define GEN_OPT(E, V, N) {RuntimeOption::E, N},
EACH_RUNTIME_OPTION(GEN_OPT)
#undef GEN_OPT
};
static RuntimeOption lookupRuntimeOption(StringRef name) {
for(auto &e : runtimeOptions) {
if(name == e.name) {
return e.option;
}
}
return RuntimeOption{};
}
static unsigned int computeMaxOptionNameSize() {
unsigned int maxSize = 0;
for(auto &e : runtimeOptions) {
unsigned int size = strlen(e.name) + 2;
if(size > maxSize) {
maxSize = size;
}
}
return maxSize;
}
static void printRuntimeOpt(const char *name, unsigned int size, bool set) {
std::string value = name;
value.append(size - strlen(name), ' ');
value += (set ? "on" : "off");
value += "\n";
fputs(value.c_str(), stdout);
}
static int showOption(const DSState &state, const ArrayObject &argvObj) {
const unsigned int size = argvObj.size();
RuntimeOption foundSet{};
if(size == 2) {
foundSet = static_cast<RuntimeOption>(static_cast<unsigned int>(-1));
} else {
for(unsigned int i = 2; i < size; i++) {
auto name = argvObj.getValues()[i].asStrRef();
auto option = lookupRuntimeOption(name);
if(empty(option)) {
ERROR(argvObj, "undefined runtime option: %s", name.data());
return 1;
}
setFlag(foundSet, option);
}
}
// print
const unsigned int maxNameSize = computeMaxOptionNameSize();
for(auto &e : runtimeOptions) {
if(hasFlag(foundSet, e.option)) {
printRuntimeOpt(e.name, maxNameSize, hasFlag(state.runtimeOption, e.option));
}
}
return 0;
}
static int setOption(DSState &state, const ArrayObject &argvObj, const bool set) {
const unsigned int size = argvObj.size();
if(size == 2) {
ERROR(argvObj, "`%s' subcommand requires argument", set ? "set" : "unset");
return 2;
}
bool foundMonitor = false;
for(unsigned int i = 2; i < size; i++) {
auto name = argvObj.getValues()[i].asStrRef();
auto option = lookupRuntimeOption(name);
if(empty(option)) {
ERROR(argvObj, "undefined runtime option: %s", name.data());
return 1;
}
if(option == RuntimeOption::MONITOR && !foundMonitor) {
foundMonitor = true;
setJobControlSignalSetting(state, set);
}
if(set) {
setFlag(state.runtimeOption, option);
} else {
unsetFlag(state.runtimeOption, option);
}
}
return 0;
}
static int showModule(const DSState &state) {
auto &loader = state.modLoader;
unsigned int size = loader.modSize();
auto *buf = new const char *[size];
for(auto &e : loader) {
buf[e.second.getIndex()] = e.first.data();
}
for(unsigned int i = 0; i < size; i++) {
fprintf(stdout, "%s\n", buf[i]);
}
delete[] buf;
return 0;
}
static int isSourced(const VMState &st) {
if(st.getFrame().code->is(CodeKind::NATIVE)) {
return 1;
}
auto *top = static_cast<const CompiledCode*>(st.getFrame().code);
auto *bottom = top;
st.walkFrames([&](const ControlFrame &frame) {
auto *c = frame.code;
if(!c->is(CodeKind::NATIVE)) {
bottom = static_cast<const CompiledCode *>(c);
}
return true;
});
return top->getSourceName() == bottom->getSourceName() ? 1 : 0;
}
static int builtin_shctl(DSState &state, ArrayObject &argvObj) {
if(argvObj.size() > 1) {
auto ref = argvObj.getValues()[1].asStrRef();
if(ref == "backtrace") {
return printBacktrace(state.getCallStack());
} else if(ref == "is-sourced") {
return isSourced(state.getCallStack());
} else if(ref == "is-interactive") {
return hasFlag(state.compileOption, CompileOption::INTERACTIVE) ? 0 : 1;
} else if(ref == "function") {
return printFuncName(state.getCallStack());
} else if(ref == "show") {
return showOption(state, argvObj);
} else if(ref == "set") {
return setOption(state, argvObj, true);
} else if(ref == "unset") {
return setOption(state, argvObj, false);
} else if(ref == "module") {
return showModule(state);
} else {
ERROR(argvObj, "undefined subcommand: %s", ref.data());
return 2;
}
}
return 0;
}
} // namespace ydsh
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Portions of this code based on Mozilla:
// (netwerk/cookie/src/nsCookieService.cpp)
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Daniel Witte (dwitte@stanford.edu)
* Michiel van Leeuwen (mvl@exedo.nl)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "net/base/cookie_monster.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "net/base/registry_controlled_domain.h"
// #define COOKIE_LOGGING_ENABLED
#ifdef COOKIE_LOGGING_ENABLED
#define COOKIE_DLOG(severity) DLOG_IF(INFO, 1)
#else
#define COOKIE_DLOG(severity) DLOG_IF(INFO, 0)
#endif
using base::Time;
using base::TimeDelta;
namespace net {
// Cookie garbage collection thresholds. Based off of the Mozilla defaults.
// It might seem scary to have a high purge value, but really it's not. You
// just make sure that you increase the max to cover the increase in purge,
// and we would have been purging the same amount of cookies. We're just
// going through the garbage collection process less often.
static const size_t kNumCookiesPerHost = 70; // ~50 cookies
static const size_t kNumCookiesPerHostPurge = 20;
static const size_t kNumCookiesTotal = 3300; // ~3000 cookies
static const size_t kNumCookiesTotalPurge = 300;
// Default minimum delay after updating a cookie's LastAccessDate before we
// will update it again.
static const int kDefaultAccessUpdateThresholdSeconds = 60;
// static
bool CookieMonster::enable_file_scheme_ = false;
// static
void CookieMonster::EnableFileScheme() {
enable_file_scheme_ = true;
}
CookieMonster::CookieMonster()
: initialized_(false),
store_(NULL),
last_access_threshold_(
TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)) {
SetDefaultCookieableSchemes();
}
CookieMonster::CookieMonster(PersistentCookieStore* store)
: initialized_(false),
store_(store),
last_access_threshold_(
TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)) {
SetDefaultCookieableSchemes();
}
CookieMonster::~CookieMonster() {
DeleteAll(false);
}
void CookieMonster::InitStore() {
DCHECK(store_) << "Store must exist to initialize";
// Initialize the store and sync in any saved persistent cookies. We don't
// care if it's expired, insert it so it can be garbage collected, removed,
// and sync'd.
std::vector<KeyedCanonicalCookie> cookies;
// Reserve space for the maximum amount of cookies a database should have.
// This prevents multiple vector growth / copies as we append cookies.
cookies.reserve(kNumCookiesTotal);
store_->Load(&cookies);
for (std::vector<KeyedCanonicalCookie>::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
InternalInsertCookie(it->first, it->second, false);
}
}
void CookieMonster::SetDefaultCookieableSchemes() {
// Note: file must be the last scheme.
static const char* kDefaultCookieableSchemes[] = { "http", "https", "file" };
int num_schemes = enable_file_scheme_ ? 3 : 2;
SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
}
// The system resolution is not high enough, so we can have multiple
// set cookies that result in the same system time. When this happens, we
// increment by one Time unit. Let's hope computers don't get too fast.
Time CookieMonster::CurrentTime() {
return std::max(Time::Now(),
Time::FromInternalValue(last_time_seen_.ToInternalValue() + 1));
}
// Parse a cookie expiration time. We try to be lenient, but we need to
// assume some order to distinguish the fields. The basic rules:
// - The month name must be present and prefix the first 3 letters of the
// full month name (jan for January, jun for June).
// - If the year is <= 2 digits, it must occur after the day of month.
// - The time must be of the format hh:mm:ss.
// An average cookie expiration will look something like this:
// Sat, 15-Apr-17 21:01:22 GMT
Time CookieMonster::ParseCookieTime(const std::string& time_string) {
static const char* kMonths[] = { "jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec" };
static const int kMonthsLen = arraysize(kMonths);
// We want to be pretty liberal, and support most non-ascii and non-digit
// characters as a delimiter. We can't treat : as a delimiter, because it
// is the delimiter for hh:mm:ss, and we want to keep this field together.
// We make sure to include - and +, since they could prefix numbers.
// If the cookie attribute came in in quotes (ex expires="XXX"), the quotes
// will be preserved, and we will get them here. So we make sure to include
// quote characters, and also \ for anything that was internally escaped.
static const char* kDelimiters = "\t !\"#$%&'()*+,-./;<=>?@[\\]^_`{|}~";
Time::Exploded exploded = {0};
StringTokenizer tokenizer(time_string, kDelimiters);
bool found_day_of_month = false;
bool found_month = false;
bool found_time = false;
bool found_year = false;
while (tokenizer.GetNext()) {
const std::string token = tokenizer.token();
DCHECK(!token.empty());
bool numerical = IsAsciiDigit(token[0]);
// String field
if (!numerical) {
if (!found_month) {
for (int i = 0; i < kMonthsLen; ++i) {
// Match prefix, so we could match January, etc
if (base::strncasecmp(token.c_str(), kMonths[i], 3) == 0) {
exploded.month = i + 1;
found_month = true;
break;
}
}
} else {
// If we've gotten here, it means we've already found and parsed our
// month, and we have another string, which we would expect to be the
// the time zone name. According to the RFC and my experiments with
// how sites format their expirations, we don't have much of a reason
// to support timezones. We don't want to ever barf on user input,
// but this DCHECK should pass for well-formed data.
// DCHECK(token == "GMT");
}
// Numeric field w/ a colon
} else if (token.find(':') != std::string::npos) {
if (!found_time &&
#ifdef COMPILER_MSVC
sscanf_s(
#else
sscanf(
#endif
token.c_str(), "%2u:%2u:%2u", &exploded.hour,
&exploded.minute, &exploded.second) == 3) {
found_time = true;
} else {
// We should only ever encounter one time-like thing. If we're here,
// it means we've found a second, which shouldn't happen. We keep
// the first. This check should be ok for well-formed input:
// NOTREACHED();
}
// Numeric field
} else {
// Overflow with atoi() is unspecified, so we enforce a max length.
if (!found_day_of_month && token.length() <= 2) {
exploded.day_of_month = atoi(token.c_str());
found_day_of_month = true;
} else if (!found_year && token.length() <= 5) {
exploded.year = atoi(token.c_str());
found_year = true;
} else {
// If we're here, it means we've either found an extra numeric field,
// or a numeric field which was too long. For well-formed input, the
// following check would be reasonable:
// NOTREACHED();
}
}
}
if (!found_day_of_month || !found_month || !found_time || !found_year) {
// We didn't find all of the fields we need. For well-formed input, the
// following check would be reasonable:
// NOTREACHED() << "Cookie parse expiration failed: " << time_string;
return Time();
}
// Normalize the year to expand abbreviated years to the full year.
if (exploded.year >= 69 && exploded.year <= 99)
exploded.year += 1900;
if (exploded.year >= 0 && exploded.year <= 68)
exploded.year += 2000;
// If our values are within their correct ranges, we got our time.
if (exploded.day_of_month >= 1 && exploded.day_of_month <= 31 &&
exploded.month >= 1 && exploded.month <= 12 &&
exploded.year >= 1601 && exploded.year <= 30827 &&
exploded.hour <= 23 && exploded.minute <= 59 && exploded.second <= 59) {
return Time::FromUTCExploded(exploded);
}
// One of our values was out of expected range. For well-formed input,
// the following check would be reasonable:
// NOTREACHED() << "Cookie exploded expiration failed: " << time_string;
return Time();
}
// Determine the cookie domain key to use for setting the specified cookie.
// On success returns true, and sets cookie_domain_key to either a
// -host cookie key (ex: "google.com")
// -domain cookie key (ex: ".google.com")
static bool GetCookieDomainKey(const GURL& url,
const CookieMonster::ParsedCookie& pc,
std::string* cookie_domain_key) {
const std::string url_host(url.host());
// If no domain was specified in the cookie, default to a host cookie.
// We match IE/Firefox in allowing a domain=IPADDR if it matches the url
// ip address hostname exactly. It should be treated as a host cookie.
if (!pc.HasDomain() || pc.Domain().empty() ||
(url.HostIsIPAddress() && url_host == pc.Domain())) {
*cookie_domain_key = url_host;
DCHECK((*cookie_domain_key)[0] != '.');
return true;
}
// Get the normalized domain specified in cookie line.
// Note: The RFC says we can reject a cookie if the domain
// attribute does not start with a dot. IE/FF/Safari however, allow a cookie
// of the form domain=my.domain.com, treating it the same as
// domain=.my.domain.com -- for compatibility we do the same here. Firefox
// also treats domain=.....my.domain.com like domain=.my.domain.com, but
// neither IE nor Safari do this, and we don't either.
url_canon::CanonHostInfo ignored;
std::string cookie_domain(net::CanonicalizeHost(pc.Domain(), &ignored));
if (cookie_domain.empty())
return false;
if (cookie_domain[0] != '.')
cookie_domain = "." + cookie_domain;
// Ensure |url| and |cookie_domain| have the same domain+registry.
const std::string url_domain_and_registry(
RegistryControlledDomainService::GetDomainAndRegistry(url));
if (url_domain_and_registry.empty())
return false; // IP addresses/intranet hosts can't set domain cookies.
const std::string cookie_domain_and_registry(
RegistryControlledDomainService::GetDomainAndRegistry(cookie_domain));
if (url_domain_and_registry != cookie_domain_and_registry)
return false; // Can't set a cookie on a different domain + registry.
// Ensure |url_host| is |cookie_domain| or one of its subdomains. Given that
// we know the domain+registry are the same from the above checks, this is
// basically a simple string suffix check.
if ((url_host.length() < cookie_domain.length()) ?
(cookie_domain != ("." + url_host)) :
url_host.compare(url_host.length() - cookie_domain.length(),
cookie_domain.length(), cookie_domain))
return false;
*cookie_domain_key = cookie_domain;
return true;
}
static std::string CanonPath(const GURL& url,
const CookieMonster::ParsedCookie& pc) {
// The RFC says the path should be a prefix of the current URL path.
// However, Mozilla allows you to set any path for compatibility with
// broken websites. We unfortunately will mimic this behavior. We try
// to be generous and accept cookies with an invalid path attribute, and
// default the path to something reasonable.
// The path was supplied in the cookie, we'll take it.
if (pc.HasPath() && !pc.Path().empty() && pc.Path()[0] == '/')
return pc.Path();
// The path was not supplied in the cookie or invalid, we will default
// to the current URL path.
// """Defaults to the path of the request URL that generated the
// Set-Cookie response, up to, but not including, the
// right-most /."""
// How would this work for a cookie on /? We will include it then.
const std::string& url_path = url.path();
size_t idx = url_path.find_last_of('/');
// The cookie path was invalid or a single '/'.
if (idx == 0 || idx == std::string::npos)
return std::string("/");
// Return up to the rightmost '/'.
return url_path.substr(0, idx);
}
static Time CanonExpiration(const CookieMonster::ParsedCookie& pc,
const Time& current) {
// First, try the Max-Age attribute.
uint64 max_age = 0;
if (pc.HasMaxAge() &&
#ifdef COMPILER_MSVC
sscanf_s(
#else
sscanf(
#endif
pc.MaxAge().c_str(), " %" PRIu64, &max_age) == 1) {
return current + TimeDelta::FromSeconds(max_age);
}
// Try the Expires attribute.
if (pc.HasExpires())
return CookieMonster::ParseCookieTime(pc.Expires());
// Invalid or no expiration, persistent cookie.
return Time();
}
bool CookieMonster::HasCookieableScheme(const GURL& url) {
// Make sure the request is on a cookie-able url scheme.
for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
// We matched a scheme.
if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
// We've matched a supported scheme.
return true;
}
}
// The scheme didn't match any in our whitelist.
COOKIE_DLOG(WARNING) << "Unsupported cookie scheme: " << url.scheme();
return false;
}
void CookieMonster::SetCookieableSchemes(
const char* schemes[], size_t num_schemes) {
cookieable_schemes_.clear();
cookieable_schemes_.insert(cookieable_schemes_.end(),
schemes, schemes + num_schemes);
}
bool CookieMonster::SetCookie(const GURL& url,
const std::string& cookie_line) {
CookieOptions options;
return SetCookieWithOptions(url, cookie_line, options);
}
bool CookieMonster::SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const CookieOptions& options) {
Time creation_date;
{
AutoLock autolock(lock_);
creation_date = CurrentTime();
last_time_seen_ = creation_date;
}
return SetCookieWithCreationTimeWithOptions(url,
cookie_line,
creation_date,
options);
}
bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
const std::string& cookie_line,
const Time& creation_time) {
CookieOptions options;
return SetCookieWithCreationTimeWithOptions(url,
cookie_line,
creation_time,
options);
}
bool CookieMonster::SetCookieWithCreationTimeWithOptions(
const GURL& url,
const std::string& cookie_line,
const Time& creation_time,
const CookieOptions& options) {
DCHECK(!creation_time.is_null());
if (!HasCookieableScheme(url)) {
return false;
}
AutoLock autolock(lock_);
InitIfNecessary();
COOKIE_DLOG(INFO) << "SetCookie() line: " << cookie_line;
// Parse the cookie.
ParsedCookie pc(cookie_line);
if (!pc.IsValid()) {
COOKIE_DLOG(WARNING) << "Couldn't parse cookie";
return false;
}
if (options.exclude_httponly() && pc.IsHttpOnly()) {
COOKIE_DLOG(INFO) << "SetCookie() not setting httponly cookie";
return false;
}
std::string cookie_domain;
if (!GetCookieDomainKey(url, pc, &cookie_domain)) {
return false;
}
std::string cookie_path = CanonPath(url, pc);
scoped_ptr<CanonicalCookie> cc;
Time cookie_expires = CanonExpiration(pc, creation_time);
cc.reset(new CanonicalCookie(pc.Name(), pc.Value(), cookie_path,
pc.IsSecure(), pc.IsHttpOnly(),
creation_time, creation_time,
!cookie_expires.is_null(), cookie_expires));
if (!cc.get()) {
COOKIE_DLOG(WARNING) << "Failed to allocate CanonicalCookie";
return false;
}
if (DeleteAnyEquivalentCookie(cookie_domain,
*cc,
options.exclude_httponly())) {
COOKIE_DLOG(INFO) << "SetCookie() not clobbering httponly cookie";
return false;
}
COOKIE_DLOG(INFO) << "SetCookie() cc: " << cc->DebugString();
// Realize that we might be setting an expired cookie, and the only point
// was to delete the cookie which we've already done.
if (!cc->IsExpired(creation_time))
InternalInsertCookie(cookie_domain, cc.release(), true);
// We assume that hopefully setting a cookie will be less common than
// querying a cookie. Since setting a cookie can put us over our limits,
// make sure that we garbage collect... We can also make the assumption that
// if a cookie was set, in the common case it will be used soon after,
// and we will purge the expired cookies in GetCookies().
GarbageCollect(creation_time, cookie_domain);
return true;
}
void CookieMonster::SetCookies(const GURL& url,
const std::vector<std::string>& cookies) {
CookieOptions options;
SetCookiesWithOptions(url, cookies, options);
}
void CookieMonster::SetCookiesWithOptions(
const GURL& url,
const std::vector<std::string>& cookies,
const CookieOptions& options) {
for (std::vector<std::string>::const_iterator iter = cookies.begin();
iter != cookies.end(); ++iter)
SetCookieWithOptions(url, *iter, options);
}
void CookieMonster::InternalInsertCookie(const std::string& key,
CanonicalCookie* cc,
bool sync_to_store) {
if (cc->IsPersistent() && store_ && sync_to_store)
store_->AddCookie(key, *cc);
cookies_.insert(CookieMap::value_type(key, cc));
}
void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc) {
// Based off the Mozilla code. When a cookie has been accessed recently,
// don't bother updating its access time again. This reduces the number of
// updates we do during pageload, which in turn reduces the chance our storage
// backend will hit its batch thresholds and be forced to update.
const Time current = Time::Now();
if ((current - cc->LastAccessDate()) < last_access_threshold_)
return;
cc->SetLastAccessDate(current);
if (cc->IsPersistent() && store_)
store_->UpdateCookieAccessTime(*cc);
}
void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
bool sync_to_store) {
CanonicalCookie* cc = it->second;
COOKIE_DLOG(INFO) << "InternalDeleteCookie() cc: " << cc->DebugString();
if (cc->IsPersistent() && store_ && sync_to_store)
store_->DeleteCookie(*cc);
cookies_.erase(it);
delete cc;
}
bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
const CanonicalCookie& ecc,
bool skip_httponly) {
bool found_equivalent_cookie = false;
bool skipped_httponly = false;
for (CookieMapItPair its = cookies_.equal_range(key);
its.first != its.second; ) {
CookieMap::iterator curit = its.first;
CanonicalCookie* cc = curit->second;
++its.first;
if (ecc.IsEquivalent(*cc)) {
// We should never have more than one equivalent cookie, since they should
// overwrite each other.
DCHECK(!found_equivalent_cookie) <<
"Duplicate equivalent cookies found, cookie store is corrupted.";
if (skip_httponly && cc->IsHttpOnly()) {
skipped_httponly = true;
} else {
InternalDeleteCookie(curit, true);
}
found_equivalent_cookie = true;
#ifdef NDEBUG
// Speed optimization: No point looping through the rest of the cookies
// since we're only doing it as a consistency check.
break;
#endif
}
}
return skipped_httponly;
}
int CookieMonster::GarbageCollect(const Time& current,
const std::string& key) {
int num_deleted = 0;
// Collect garbage for this key.
if (cookies_.count(key) > kNumCookiesPerHost) {
COOKIE_DLOG(INFO) << "GarbageCollect() key: " << key;
num_deleted += GarbageCollectRange(current, cookies_.equal_range(key),
kNumCookiesPerHost, kNumCookiesPerHostPurge);
}
// Collect garbage for everything.
if (cookies_.size() > kNumCookiesTotal) {
COOKIE_DLOG(INFO) << "GarbageCollect() everything";
num_deleted += GarbageCollectRange(current,
CookieMapItPair(cookies_.begin(), cookies_.end()), kNumCookiesTotal,
kNumCookiesTotalPurge);
}
return num_deleted;
}
static bool LRUCookieSorter(const CookieMonster::CookieMap::iterator& it1,
const CookieMonster::CookieMap::iterator& it2) {
// Cookies accessed less recently should be deleted first.
if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
return it1->second->LastAccessDate() < it2->second->LastAccessDate();
// In rare cases we might have two cookies with identical last access times.
// To preserve the stability of the sort, in these cases prefer to delete
// older cookies over newer ones. CreationDate() is guaranteed to be unique.
return it1->second->CreationDate() < it2->second->CreationDate();
}
int CookieMonster::GarbageCollectRange(const Time& current,
const CookieMapItPair& itpair,
size_t num_max,
size_t num_purge) {
// First, delete anything that's expired.
std::vector<CookieMap::iterator> cookie_its;
int num_deleted = GarbageCollectExpired(current, itpair, &cookie_its);
// If the range still has too many cookies, delete the least recently used.
if (cookie_its.size() > num_max) {
COOKIE_DLOG(INFO) << "GarbageCollectRange() Deep Garbage Collect.";
// Purge down to (|num_max| - |num_purge|) total cookies.
DCHECK(num_purge <= num_max);
num_purge += cookie_its.size() - num_max;
std::partial_sort(cookie_its.begin(), cookie_its.begin() + num_purge,
cookie_its.end(), LRUCookieSorter);
for (size_t i = 0; i < num_purge; ++i)
InternalDeleteCookie(cookie_its[i], true);
num_deleted += num_purge;
}
return num_deleted;
}
int CookieMonster::GarbageCollectExpired(
const Time& current,
const CookieMapItPair& itpair,
std::vector<CookieMap::iterator>* cookie_its) {
int num_deleted = 0;
for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
CookieMap::iterator curit = it;
++it;
if (curit->second->IsExpired(current)) {
InternalDeleteCookie(curit, true);
++num_deleted;
} else if (cookie_its) {
cookie_its->push_back(curit);
}
}
return num_deleted;
}
int CookieMonster::DeleteAll(bool sync_to_store) {
AutoLock autolock(lock_);
InitIfNecessary();
int num_deleted = 0;
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
CookieMap::iterator curit = it;
++it;
InternalDeleteCookie(curit, sync_to_store);
++num_deleted;
}
return num_deleted;
}
int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
const Time& delete_end,
bool sync_to_store) {
AutoLock autolock(lock_);
InitIfNecessary();
int num_deleted = 0;
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
CookieMap::iterator curit = it;
CanonicalCookie* cc = curit->second;
++it;
if (cc->CreationDate() >= delete_begin &&
(delete_end.is_null() || cc->CreationDate() < delete_end)) {
InternalDeleteCookie(curit, sync_to_store);
++num_deleted;
}
}
return num_deleted;
}
int CookieMonster::DeleteAllCreatedAfter(const Time& delete_begin,
bool sync_to_store) {
return DeleteAllCreatedBetween(delete_begin, Time(), sync_to_store);
}
bool CookieMonster::DeleteCookie(const std::string& domain,
const CanonicalCookie& cookie,
bool sync_to_store) {
AutoLock autolock(lock_);
InitIfNecessary();
for (CookieMapItPair its = cookies_.equal_range(domain);
its.first != its.second; ++its.first) {
// The creation date acts as our unique index...
if (its.first->second->CreationDate() == cookie.CreationDate()) {
InternalDeleteCookie(its.first, sync_to_store);
return true;
}
}
return false;
}
// Mozilla sorts on the path length (longest first), and then it
// sorts by creation time (oldest first).
// The RFC says the sort order for the domain attribute is undefined.
static bool CookieSorter(CookieMonster::CanonicalCookie* cc1,
CookieMonster::CanonicalCookie* cc2) {
if (cc1->Path().length() == cc2->Path().length())
return cc1->CreationDate() < cc2->CreationDate();
return cc1->Path().length() > cc2->Path().length();
}
// Currently our cookie datastructure is based on Mozilla's approach. We have a
// hash keyed on the cookie's domain, and for any query we walk down the domain
// components and probe for cookies until we reach the TLD, where we stop.
// For example, a.b.blah.com, we would probe
// - a.b.blah.com
// - .a.b.blah.com (TODO should we check this first or second?)
// - .b.blah.com
// - .blah.com
// There are some alternative datastructures we could try, like a
// search/prefix trie, where we reverse the hostname and query for all
// keys that are a prefix of our hostname. I think the hash probing
// should be fast and simple enough for now.
std::string CookieMonster::GetCookies(const GURL& url) {
CookieOptions options;
return GetCookiesWithOptions(url, options);
}
std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
const CookieOptions& options) {
if (!HasCookieableScheme(url)) {
return std::string();
}
// Get the cookies for this host and its domain(s).
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, &cookies);
std::sort(cookies.begin(), cookies.end(), CookieSorter);
std::string cookie_line;
for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
if (it != cookies.begin())
cookie_line += "; ";
// In Mozilla if you set a cookie like AAAA, it will have an empty token
// and a value of AAAA. When it sends the cookie back, it will send AAAA,
// so we need to avoid sending =AAAA for a blank token value.
if (!(*it)->Name().empty())
cookie_line += (*it)->Name() + "=";
cookie_line += (*it)->Value();
}
COOKIE_DLOG(INFO) << "GetCookies() result: " << cookie_line;
return cookie_line;
}
void CookieMonster::GetRawCookies(const GURL& url,
std::vector<CanonicalCookie>* raw_cookies) {
raw_cookies->clear();
if (!HasCookieableScheme(url))
return;
CookieOptions options;
options.set_include_httponly();
// Get the cookies for this host and its domain(s).
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, &cookies);
std::sort(cookies.begin(), cookies.end(), CookieSorter);
for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
it != cookies.end(); ++it)
raw_cookies->push_back(*(*it));
}
void CookieMonster::DeleteCookie(const GURL& url,
const std::string& cookie_name) {
if (!HasCookieableScheme(url))
return;
CookieOptions options;
options.set_include_httponly();
// Get the cookies for this host and its domain(s).
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, &cookies);
std::set<CanonicalCookie*> matching_cookies;
for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
if ((*it)->Name() != cookie_name)
continue;
if (url.path().find((*it)->Path()))
continue;
matching_cookies.insert(*it);
}
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
CookieMap::iterator curit = it;
++it;
if (matching_cookies.find(curit->second) != matching_cookies.end())
InternalDeleteCookie(curit, true);
}
}
CookieMonster::CookieList CookieMonster::GetAllCookies() {
AutoLock autolock(lock_);
InitIfNecessary();
// This function is being called to scrape the cookie list for management UI
// or similar. We shouldn't show expired cookies in this list since it will
// just be confusing to users, and this function is called rarely enough (and
// is already slow enough) that it's OK to take the time to garbage collect
// the expired cookies now.
//
// Note that this does not prune cookies to be below our limits (if we've
// exceeded them) the way that calling GarbageCollect() would.
GarbageCollectExpired(Time::Now(),
CookieMapItPair(cookies_.begin(), cookies_.end()),
NULL);
CookieList cookie_list;
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
cookie_list.push_back(CookieListPair(it->first, *it->second));
return cookie_list;
}
void CookieMonster::FindCookiesForHostAndDomain(
const GURL& url,
const CookieOptions& options,
std::vector<CanonicalCookie*>* cookies) {
AutoLock autolock(lock_);
InitIfNecessary();
const Time current_time(CurrentTime());
// Query for the full host, For example: 'a.c.blah.com'.
std::string key(url.host());
FindCookiesForKey(key, url, options, current_time, cookies);
// See if we can search for domain cookies, i.e. if the host has a TLD + 1.
const std::string domain(
RegistryControlledDomainService::GetDomainAndRegistry(key));
if (domain.empty())
return;
DCHECK_LE(domain.length(), key.length());
DCHECK_EQ(0, key.compare(key.length() - domain.length(), domain.length(),
domain));
// Walk through the string and query at the dot points (GURL should have
// canonicalized the dots, so this should be safe). Stop once we reach the
// domain + registry; we can't write cookies past this point, and with some
// registrars other domains can, in which case we don't want to read their
// cookies.
for (key = "." + key; key.length() > domain.length(); ) {
FindCookiesForKey(key, url, options, current_time, cookies);
const size_t next_dot = key.find('.', 1); // Skip over leading dot.
key.erase(0, next_dot);
}
}
void CookieMonster::FindCookiesForKey(
const std::string& key,
const GURL& url,
const CookieOptions& options,
const Time& current,
std::vector<CanonicalCookie*>* cookies) {
bool secure = url.SchemeIsSecure();
for (CookieMapItPair its = cookies_.equal_range(key);
its.first != its.second; ) {
CookieMap::iterator curit = its.first;
CanonicalCookie* cc = curit->second;
++its.first;
// If the cookie is expired, delete it.
if (cc->IsExpired(current)) {
InternalDeleteCookie(curit, true);
continue;
}
// Filter out HttpOnly cookies, per options.
if (options.exclude_httponly() && cc->IsHttpOnly())
continue;
// Filter out secure cookies unless we're https.
if (!secure && cc->IsSecure())
continue;
if (!cc->IsOnPath(url.path()))
continue;
// Add this cookie to the set of matching cookies. Since we're reading the
// cookie, update its last access time.
InternalUpdateCookieAccessTime(cc);
cookies->push_back(cc);
}
}
CookieMonster::ParsedCookie::ParsedCookie(const std::string& cookie_line)
: is_valid_(false),
path_index_(0),
domain_index_(0),
expires_index_(0),
maxage_index_(0),
secure_index_(0),
httponly_index_(0) {
if (cookie_line.size() > kMaxCookieSize) {
LOG(INFO) << "Not parsing cookie, too large: " << cookie_line.size();
return;
}
ParseTokenValuePairs(cookie_line);
if (pairs_.size() > 0) {
is_valid_ = true;
SetupAttributes();
}
}
// Returns true if |c| occurs in |chars|
// TODO maybe make this take an iterator, could check for end also?
static inline bool CharIsA(const char c, const char* chars) {
return strchr(chars, c) != NULL;
}
// Seek the iterator to the first occurrence of a character in |chars|.
// Returns true if it hit the end, false otherwise.
static inline bool SeekTo(std::string::const_iterator* it,
const std::string::const_iterator& end,
const char* chars) {
for (; *it != end && !CharIsA(**it, chars); ++(*it));
return *it == end;
}
// Seek the iterator to the first occurrence of a character not in |chars|.
// Returns true if it hit the end, false otherwise.
static inline bool SeekPast(std::string::const_iterator* it,
const std::string::const_iterator& end,
const char* chars) {
for (; *it != end && CharIsA(**it, chars); ++(*it));
return *it == end;
}
static inline bool SeekBackPast(std::string::const_iterator* it,
const std::string::const_iterator& end,
const char* chars) {
for (; *it != end && CharIsA(**it, chars); --(*it));
return *it == end;
}
// Parse all token/value pairs and populate pairs_.
void CookieMonster::ParsedCookie::ParseTokenValuePairs(
const std::string& cookie_line) {
static const char kTerminator[] = "\n\r\0";
static const int kTerminatorLen = sizeof(kTerminator) - 1;
static const char kWhitespace[] = " \t";
static const char kValueSeparator[] = ";";
static const char kTokenSeparator[] = ";=";
pairs_.clear();
// Ok, here we go. We should be expecting to be starting somewhere
// before the cookie line, not including any header name...
std::string::const_iterator start = cookie_line.begin();
std::string::const_iterator end = cookie_line.end();
std::string::const_iterator it = start;
// TODO Make sure we're stripping \r\n in the network code. Then we
// can log any unexpected terminators.
size_t term_pos =
cookie_line.find_first_of(std::string(kTerminator, kTerminatorLen));
if (term_pos != std::string::npos) {
// We found a character we should treat as an end of string.
end = start + term_pos;
}
for (int pair_num = 0; pair_num < kMaxPairs && it != end; ++pair_num) {
TokenValuePair pair;
std::string::const_iterator token_start, token_real_end, token_end;
// Seek past any whitespace before the "token" (the name).
// token_start should point at the first character in the token
if (SeekPast(&it, end, kWhitespace))
break; // No token, whitespace or empty.
token_start = it;
// Seek over the token, to the token separator.
// token_real_end should point at the token separator, i.e. '='.
// If it == end after the seek, we probably have a token-value.
SeekTo(&it, end, kTokenSeparator);
token_real_end = it;
// Ignore any whitespace between the token and the token separator.
// token_end should point after the last interesting token character,
// pointing at either whitespace, or at '=' (and equal to token_real_end).
if (it != token_start) { // We could have an empty token name.
--it; // Go back before the token separator.
// Skip over any whitespace to the first non-whitespace character.
SeekBackPast(&it, token_start, kWhitespace);
// Point after it.
++it;
}
token_end = it;
// Seek us back to the end of the token.
it = token_real_end;
if (it == end || *it != '=') {
// We have a token-value, we didn't have any token name.
if (pair_num == 0) {
// For the first time around, we want to treat single values
// as a value with an empty name. (Mozilla bug 169091).
// IE seems to also have this behavior, ex "AAA", and "AAA=10" will
// set 2 different cookies, and setting "BBB" will then replace "AAA".
pair.first = "";
// Rewind to the beginning of what we thought was the token name,
// and let it get parsed as a value.
it = token_start;
} else {
// Any not-first attribute we want to treat a value as a
// name with an empty value... This is so something like
// "secure;" will get parsed as a Token name, and not a value.
pair.first = std::string(token_start, token_end);
}
} else {
// We have a TOKEN=VALUE.
pair.first = std::string(token_start, token_end);
++it; // Skip past the '='.
}
// OK, now try to parse a value.
std::string::const_iterator value_start, value_end;
// Seek past any whitespace that might in-between the token and value.
SeekPast(&it, end, kWhitespace);
// value_start should point at the first character of the value.
value_start = it;
// It is unclear exactly how quoted string values should be handled.
// Major browsers do different things, for example, Firefox supports
// semicolons embedded in a quoted value, while IE does not. Looking at
// the specs, RFC 2109 and 2965 allow for a quoted-string as the value.
// However, these specs were apparently written after browsers had
// implemented cookies, and they seem very distant from the reality of
// what is actually implemented and used on the web. The original spec
// from Netscape is possibly what is closest to the cookies used today.
// This spec didn't have explicit support for double quoted strings, and
// states that ; is not allowed as part of a value. We had originally
// implement the Firefox behavior (A="B;C"; -> A="B;C";). However, since
// there is no standard that makes sense, we decided to follow the behavior
// of IE and Safari, which is closer to the original Netscape proposal.
// This means that A="B;C" -> A="B;. This also makes the code much simpler
// and reduces the possibility for invalid cookies, where other browsers
// like Opera currently reject those invalid cookies (ex A="B" "C";).
// Just look for ';' to terminate ('=' allowed).
// We can hit the end, maybe they didn't terminate.
SeekTo(&it, end, kValueSeparator);
// Will be pointed at the ; seperator or the end.
value_end = it;
// Ignore any unwanted whitespace after the value.
if (value_end != value_start) { // Could have an empty value
--value_end;
SeekBackPast(&value_end, value_start, kWhitespace);
++value_end;
}
// OK, we're finished with a Token/Value.
pair.second = std::string(value_start, value_end);
// From RFC2109: "Attributes (names) (attr) are case-insensitive."
if (pair_num != 0)
StringToLowerASCII(&pair.first);
pairs_.push_back(pair);
// We've processed a token/value pair, we're either at the end of
// the string or a ValueSeparator like ';', which we want to skip.
if (it != end)
++it;
}
}
void CookieMonster::ParsedCookie::SetupAttributes() {
static const char kPathTokenName[] = "path";
static const char kDomainTokenName[] = "domain";
static const char kExpiresTokenName[] = "expires";
static const char kMaxAgeTokenName[] = "max-age";
static const char kSecureTokenName[] = "secure";
static const char kHttpOnlyTokenName[] = "httponly";
// We skip over the first token/value, the user supplied one.
for (size_t i = 1; i < pairs_.size(); ++i) {
if (pairs_[i].first == kPathTokenName)
path_index_ = i;
else if (pairs_[i].first == kDomainTokenName)
domain_index_ = i;
else if (pairs_[i].first == kExpiresTokenName)
expires_index_ = i;
else if (pairs_[i].first == kMaxAgeTokenName)
maxage_index_ = i;
else if (pairs_[i].first == kSecureTokenName)
secure_index_ = i;
else if (pairs_[i].first == kHttpOnlyTokenName)
httponly_index_ = i;
else { /* some attribute we don't know or don't care about. */ }
}
}
// Create a cookie-line for the cookie. For debugging only!
// If we want to use this for something more than debugging, we
// should rewrite it better...
std::string CookieMonster::ParsedCookie::DebugString() const {
std::string out;
for (PairList::const_iterator it = pairs_.begin();
it != pairs_.end(); ++it) {
out.append(it->first);
out.append("=");
out.append(it->second);
out.append("; ");
}
return out;
}
bool CookieMonster::CanonicalCookie::IsOnPath(
const std::string& url_path) const {
// A zero length would be unsafe for our trailing '/' checks, and
// would also make no sense for our prefix match. The code that
// creates a CanonicalCookie should make sure the path is never zero length,
// but we double check anyway.
if (path_.empty())
return false;
// The Mozilla code broke it into 3 cases, if it's strings lengths
// are less than, equal, or greater. I think this is simpler:
// Make sure the cookie path is a prefix of the url path. If the
// url path is shorter than the cookie path, then the cookie path
// can't be a prefix.
if (url_path.find(path_) != 0)
return false;
// Now we know that url_path is >= cookie_path, and that cookie_path
// is a prefix of url_path. If they are the are the same length then
// they are identical, otherwise we need an additional check:
// In order to avoid in correctly matching a cookie path of /blah
// with a request path of '/blahblah/', we need to make sure that either
// the cookie path ends in a trailing '/', or that we prefix up to a '/'
// in the url path. Since we know that the url path length is greater
// than the cookie path length, it's safe to index one byte past.
if (path_.length() != url_path.length() &&
path_[path_.length() - 1] != '/' &&
url_path[path_.length()] != '/')
return false;
return true;
}
std::string CookieMonster::CanonicalCookie::DebugString() const {
return StringPrintf("name: %s value: %s path: %s creation: %" PRId64,
name_.c_str(), value_.c_str(), path_.c_str(),
static_cast<int64>(creation_date_.ToTimeT()));
}
} // namespace
In the CookieMonster code, use the RegistryControlledDomainService only for
http and https URLs. For other schemes (like chrome-extension), use the host
itself as the effective TLD.
BUG=31867
Review URL: http://codereview.chromium.org/536017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@36035 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Portions of this code based on Mozilla:
// (netwerk/cookie/src/nsCookieService.cpp)
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Daniel Witte (dwitte@stanford.edu)
* Michiel van Leeuwen (mvl@exedo.nl)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "net/base/cookie_monster.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "net/base/registry_controlled_domain.h"
// #define COOKIE_LOGGING_ENABLED
#ifdef COOKIE_LOGGING_ENABLED
#define COOKIE_DLOG(severity) DLOG_IF(INFO, 1)
#else
#define COOKIE_DLOG(severity) DLOG_IF(INFO, 0)
#endif
using base::Time;
using base::TimeDelta;
namespace net {
// Cookie garbage collection thresholds. Based off of the Mozilla defaults.
// It might seem scary to have a high purge value, but really it's not. You
// just make sure that you increase the max to cover the increase in purge,
// and we would have been purging the same amount of cookies. We're just
// going through the garbage collection process less often.
static const size_t kNumCookiesPerHost = 70; // ~50 cookies
static const size_t kNumCookiesPerHostPurge = 20;
static const size_t kNumCookiesTotal = 3300; // ~3000 cookies
static const size_t kNumCookiesTotalPurge = 300;
// Default minimum delay after updating a cookie's LastAccessDate before we
// will update it again.
static const int kDefaultAccessUpdateThresholdSeconds = 60;
// static
bool CookieMonster::enable_file_scheme_ = false;
// static
void CookieMonster::EnableFileScheme() {
enable_file_scheme_ = true;
}
CookieMonster::CookieMonster()
: initialized_(false),
store_(NULL),
last_access_threshold_(
TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)) {
SetDefaultCookieableSchemes();
}
CookieMonster::CookieMonster(PersistentCookieStore* store)
: initialized_(false),
store_(store),
last_access_threshold_(
TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)) {
SetDefaultCookieableSchemes();
}
CookieMonster::~CookieMonster() {
DeleteAll(false);
}
void CookieMonster::InitStore() {
DCHECK(store_) << "Store must exist to initialize";
// Initialize the store and sync in any saved persistent cookies. We don't
// care if it's expired, insert it so it can be garbage collected, removed,
// and sync'd.
std::vector<KeyedCanonicalCookie> cookies;
// Reserve space for the maximum amount of cookies a database should have.
// This prevents multiple vector growth / copies as we append cookies.
cookies.reserve(kNumCookiesTotal);
store_->Load(&cookies);
for (std::vector<KeyedCanonicalCookie>::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
InternalInsertCookie(it->first, it->second, false);
}
}
void CookieMonster::SetDefaultCookieableSchemes() {
// Note: file must be the last scheme.
static const char* kDefaultCookieableSchemes[] = { "http", "https", "file" };
int num_schemes = enable_file_scheme_ ? 3 : 2;
SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
}
// The system resolution is not high enough, so we can have multiple
// set cookies that result in the same system time. When this happens, we
// increment by one Time unit. Let's hope computers don't get too fast.
Time CookieMonster::CurrentTime() {
return std::max(Time::Now(),
Time::FromInternalValue(last_time_seen_.ToInternalValue() + 1));
}
// Parse a cookie expiration time. We try to be lenient, but we need to
// assume some order to distinguish the fields. The basic rules:
// - The month name must be present and prefix the first 3 letters of the
// full month name (jan for January, jun for June).
// - If the year is <= 2 digits, it must occur after the day of month.
// - The time must be of the format hh:mm:ss.
// An average cookie expiration will look something like this:
// Sat, 15-Apr-17 21:01:22 GMT
Time CookieMonster::ParseCookieTime(const std::string& time_string) {
static const char* kMonths[] = { "jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec" };
static const int kMonthsLen = arraysize(kMonths);
// We want to be pretty liberal, and support most non-ascii and non-digit
// characters as a delimiter. We can't treat : as a delimiter, because it
// is the delimiter for hh:mm:ss, and we want to keep this field together.
// We make sure to include - and +, since they could prefix numbers.
// If the cookie attribute came in in quotes (ex expires="XXX"), the quotes
// will be preserved, and we will get them here. So we make sure to include
// quote characters, and also \ for anything that was internally escaped.
static const char* kDelimiters = "\t !\"#$%&'()*+,-./;<=>?@[\\]^_`{|}~";
Time::Exploded exploded = {0};
StringTokenizer tokenizer(time_string, kDelimiters);
bool found_day_of_month = false;
bool found_month = false;
bool found_time = false;
bool found_year = false;
while (tokenizer.GetNext()) {
const std::string token = tokenizer.token();
DCHECK(!token.empty());
bool numerical = IsAsciiDigit(token[0]);
// String field
if (!numerical) {
if (!found_month) {
for (int i = 0; i < kMonthsLen; ++i) {
// Match prefix, so we could match January, etc
if (base::strncasecmp(token.c_str(), kMonths[i], 3) == 0) {
exploded.month = i + 1;
found_month = true;
break;
}
}
} else {
// If we've gotten here, it means we've already found and parsed our
// month, and we have another string, which we would expect to be the
// the time zone name. According to the RFC and my experiments with
// how sites format their expirations, we don't have much of a reason
// to support timezones. We don't want to ever barf on user input,
// but this DCHECK should pass for well-formed data.
// DCHECK(token == "GMT");
}
// Numeric field w/ a colon
} else if (token.find(':') != std::string::npos) {
if (!found_time &&
#ifdef COMPILER_MSVC
sscanf_s(
#else
sscanf(
#endif
token.c_str(), "%2u:%2u:%2u", &exploded.hour,
&exploded.minute, &exploded.second) == 3) {
found_time = true;
} else {
// We should only ever encounter one time-like thing. If we're here,
// it means we've found a second, which shouldn't happen. We keep
// the first. This check should be ok for well-formed input:
// NOTREACHED();
}
// Numeric field
} else {
// Overflow with atoi() is unspecified, so we enforce a max length.
if (!found_day_of_month && token.length() <= 2) {
exploded.day_of_month = atoi(token.c_str());
found_day_of_month = true;
} else if (!found_year && token.length() <= 5) {
exploded.year = atoi(token.c_str());
found_year = true;
} else {
// If we're here, it means we've either found an extra numeric field,
// or a numeric field which was too long. For well-formed input, the
// following check would be reasonable:
// NOTREACHED();
}
}
}
if (!found_day_of_month || !found_month || !found_time || !found_year) {
// We didn't find all of the fields we need. For well-formed input, the
// following check would be reasonable:
// NOTREACHED() << "Cookie parse expiration failed: " << time_string;
return Time();
}
// Normalize the year to expand abbreviated years to the full year.
if (exploded.year >= 69 && exploded.year <= 99)
exploded.year += 1900;
if (exploded.year >= 0 && exploded.year <= 68)
exploded.year += 2000;
// If our values are within their correct ranges, we got our time.
if (exploded.day_of_month >= 1 && exploded.day_of_month <= 31 &&
exploded.month >= 1 && exploded.month <= 12 &&
exploded.year >= 1601 && exploded.year <= 30827 &&
exploded.hour <= 23 && exploded.minute <= 59 && exploded.second <= 59) {
return Time::FromUTCExploded(exploded);
}
// One of our values was out of expected range. For well-formed input,
// the following check would be reasonable:
// NOTREACHED() << "Cookie exploded expiration failed: " << time_string;
return Time();
}
// Returns the effective TLD+1 for a given host. This only makes sense for http
// and https schemes. For other schemes, the host will be returned unchanged
// (minus any leading .).
static std::string GetEffectiveDomain(const std::string& scheme,
const std::string& host) {
if (scheme == "http" || scheme == "https")
return RegistryControlledDomainService::GetDomainAndRegistry(host);
if (!host.empty() && host[0] == '.')
return host.substr(1);
return host;
}
// Determine the cookie domain key to use for setting the specified cookie.
// On success returns true, and sets cookie_domain_key to either a
// -host cookie key (ex: "google.com")
// -domain cookie key (ex: ".google.com")
static bool GetCookieDomainKey(const GURL& url,
const CookieMonster::ParsedCookie& pc,
std::string* cookie_domain_key) {
const std::string url_host(url.host());
// If no domain was specified in the cookie, default to a host cookie.
// We match IE/Firefox in allowing a domain=IPADDR if it matches the url
// ip address hostname exactly. It should be treated as a host cookie.
if (!pc.HasDomain() || pc.Domain().empty() ||
(url.HostIsIPAddress() && url_host == pc.Domain())) {
*cookie_domain_key = url_host;
DCHECK((*cookie_domain_key)[0] != '.');
return true;
}
// Get the normalized domain specified in cookie line.
// Note: The RFC says we can reject a cookie if the domain
// attribute does not start with a dot. IE/FF/Safari however, allow a cookie
// of the form domain=my.domain.com, treating it the same as
// domain=.my.domain.com -- for compatibility we do the same here. Firefox
// also treats domain=.....my.domain.com like domain=.my.domain.com, but
// neither IE nor Safari do this, and we don't either.
url_canon::CanonHostInfo ignored;
std::string cookie_domain(net::CanonicalizeHost(pc.Domain(), &ignored));
if (cookie_domain.empty())
return false;
if (cookie_domain[0] != '.')
cookie_domain = "." + cookie_domain;
// Ensure |url| and |cookie_domain| have the same domain+registry.
const std::string url_scheme(url.scheme());
const std::string url_domain_and_registry(
GetEffectiveDomain(url_scheme, url_host));
if (url_domain_and_registry.empty())
return false; // IP addresses/intranet hosts can't set domain cookies.
const std::string cookie_domain_and_registry(
GetEffectiveDomain(url_scheme, cookie_domain));
if (url_domain_and_registry != cookie_domain_and_registry)
return false; // Can't set a cookie on a different domain + registry.
// Ensure |url_host| is |cookie_domain| or one of its subdomains. Given that
// we know the domain+registry are the same from the above checks, this is
// basically a simple string suffix check.
if ((url_host.length() < cookie_domain.length()) ?
(cookie_domain != ("." + url_host)) :
url_host.compare(url_host.length() - cookie_domain.length(),
cookie_domain.length(), cookie_domain))
return false;
*cookie_domain_key = cookie_domain;
return true;
}
static std::string CanonPath(const GURL& url,
const CookieMonster::ParsedCookie& pc) {
// The RFC says the path should be a prefix of the current URL path.
// However, Mozilla allows you to set any path for compatibility with
// broken websites. We unfortunately will mimic this behavior. We try
// to be generous and accept cookies with an invalid path attribute, and
// default the path to something reasonable.
// The path was supplied in the cookie, we'll take it.
if (pc.HasPath() && !pc.Path().empty() && pc.Path()[0] == '/')
return pc.Path();
// The path was not supplied in the cookie or invalid, we will default
// to the current URL path.
// """Defaults to the path of the request URL that generated the
// Set-Cookie response, up to, but not including, the
// right-most /."""
// How would this work for a cookie on /? We will include it then.
const std::string& url_path = url.path();
size_t idx = url_path.find_last_of('/');
// The cookie path was invalid or a single '/'.
if (idx == 0 || idx == std::string::npos)
return std::string("/");
// Return up to the rightmost '/'.
return url_path.substr(0, idx);
}
static Time CanonExpiration(const CookieMonster::ParsedCookie& pc,
const Time& current) {
// First, try the Max-Age attribute.
uint64 max_age = 0;
if (pc.HasMaxAge() &&
#ifdef COMPILER_MSVC
sscanf_s(
#else
sscanf(
#endif
pc.MaxAge().c_str(), " %" PRIu64, &max_age) == 1) {
return current + TimeDelta::FromSeconds(max_age);
}
// Try the Expires attribute.
if (pc.HasExpires())
return CookieMonster::ParseCookieTime(pc.Expires());
// Invalid or no expiration, persistent cookie.
return Time();
}
bool CookieMonster::HasCookieableScheme(const GURL& url) {
// Make sure the request is on a cookie-able url scheme.
for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
// We matched a scheme.
if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
// We've matched a supported scheme.
return true;
}
}
// The scheme didn't match any in our whitelist.
COOKIE_DLOG(WARNING) << "Unsupported cookie scheme: " << url.scheme();
return false;
}
void CookieMonster::SetCookieableSchemes(
const char* schemes[], size_t num_schemes) {
cookieable_schemes_.clear();
cookieable_schemes_.insert(cookieable_schemes_.end(),
schemes, schemes + num_schemes);
}
bool CookieMonster::SetCookie(const GURL& url,
const std::string& cookie_line) {
CookieOptions options;
return SetCookieWithOptions(url, cookie_line, options);
}
bool CookieMonster::SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const CookieOptions& options) {
Time creation_date;
{
AutoLock autolock(lock_);
creation_date = CurrentTime();
last_time_seen_ = creation_date;
}
return SetCookieWithCreationTimeWithOptions(url,
cookie_line,
creation_date,
options);
}
bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
const std::string& cookie_line,
const Time& creation_time) {
CookieOptions options;
return SetCookieWithCreationTimeWithOptions(url,
cookie_line,
creation_time,
options);
}
bool CookieMonster::SetCookieWithCreationTimeWithOptions(
const GURL& url,
const std::string& cookie_line,
const Time& creation_time,
const CookieOptions& options) {
DCHECK(!creation_time.is_null());
if (!HasCookieableScheme(url)) {
return false;
}
AutoLock autolock(lock_);
InitIfNecessary();
COOKIE_DLOG(INFO) << "SetCookie() line: " << cookie_line;
// Parse the cookie.
ParsedCookie pc(cookie_line);
if (!pc.IsValid()) {
COOKIE_DLOG(WARNING) << "Couldn't parse cookie";
return false;
}
if (options.exclude_httponly() && pc.IsHttpOnly()) {
COOKIE_DLOG(INFO) << "SetCookie() not setting httponly cookie";
return false;
}
std::string cookie_domain;
if (!GetCookieDomainKey(url, pc, &cookie_domain)) {
return false;
}
std::string cookie_path = CanonPath(url, pc);
scoped_ptr<CanonicalCookie> cc;
Time cookie_expires = CanonExpiration(pc, creation_time);
cc.reset(new CanonicalCookie(pc.Name(), pc.Value(), cookie_path,
pc.IsSecure(), pc.IsHttpOnly(),
creation_time, creation_time,
!cookie_expires.is_null(), cookie_expires));
if (!cc.get()) {
COOKIE_DLOG(WARNING) << "Failed to allocate CanonicalCookie";
return false;
}
if (DeleteAnyEquivalentCookie(cookie_domain,
*cc,
options.exclude_httponly())) {
COOKIE_DLOG(INFO) << "SetCookie() not clobbering httponly cookie";
return false;
}
COOKIE_DLOG(INFO) << "SetCookie() cc: " << cc->DebugString();
// Realize that we might be setting an expired cookie, and the only point
// was to delete the cookie which we've already done.
if (!cc->IsExpired(creation_time))
InternalInsertCookie(cookie_domain, cc.release(), true);
// We assume that hopefully setting a cookie will be less common than
// querying a cookie. Since setting a cookie can put us over our limits,
// make sure that we garbage collect... We can also make the assumption that
// if a cookie was set, in the common case it will be used soon after,
// and we will purge the expired cookies in GetCookies().
GarbageCollect(creation_time, cookie_domain);
return true;
}
void CookieMonster::SetCookies(const GURL& url,
const std::vector<std::string>& cookies) {
CookieOptions options;
SetCookiesWithOptions(url, cookies, options);
}
void CookieMonster::SetCookiesWithOptions(
const GURL& url,
const std::vector<std::string>& cookies,
const CookieOptions& options) {
for (std::vector<std::string>::const_iterator iter = cookies.begin();
iter != cookies.end(); ++iter)
SetCookieWithOptions(url, *iter, options);
}
void CookieMonster::InternalInsertCookie(const std::string& key,
CanonicalCookie* cc,
bool sync_to_store) {
if (cc->IsPersistent() && store_ && sync_to_store)
store_->AddCookie(key, *cc);
cookies_.insert(CookieMap::value_type(key, cc));
}
void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc) {
// Based off the Mozilla code. When a cookie has been accessed recently,
// don't bother updating its access time again. This reduces the number of
// updates we do during pageload, which in turn reduces the chance our storage
// backend will hit its batch thresholds and be forced to update.
const Time current = Time::Now();
if ((current - cc->LastAccessDate()) < last_access_threshold_)
return;
cc->SetLastAccessDate(current);
if (cc->IsPersistent() && store_)
store_->UpdateCookieAccessTime(*cc);
}
void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
bool sync_to_store) {
CanonicalCookie* cc = it->second;
COOKIE_DLOG(INFO) << "InternalDeleteCookie() cc: " << cc->DebugString();
if (cc->IsPersistent() && store_ && sync_to_store)
store_->DeleteCookie(*cc);
cookies_.erase(it);
delete cc;
}
bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
const CanonicalCookie& ecc,
bool skip_httponly) {
bool found_equivalent_cookie = false;
bool skipped_httponly = false;
for (CookieMapItPair its = cookies_.equal_range(key);
its.first != its.second; ) {
CookieMap::iterator curit = its.first;
CanonicalCookie* cc = curit->second;
++its.first;
if (ecc.IsEquivalent(*cc)) {
// We should never have more than one equivalent cookie, since they should
// overwrite each other.
DCHECK(!found_equivalent_cookie) <<
"Duplicate equivalent cookies found, cookie store is corrupted.";
if (skip_httponly && cc->IsHttpOnly()) {
skipped_httponly = true;
} else {
InternalDeleteCookie(curit, true);
}
found_equivalent_cookie = true;
#ifdef NDEBUG
// Speed optimization: No point looping through the rest of the cookies
// since we're only doing it as a consistency check.
break;
#endif
}
}
return skipped_httponly;
}
int CookieMonster::GarbageCollect(const Time& current,
const std::string& key) {
int num_deleted = 0;
// Collect garbage for this key.
if (cookies_.count(key) > kNumCookiesPerHost) {
COOKIE_DLOG(INFO) << "GarbageCollect() key: " << key;
num_deleted += GarbageCollectRange(current, cookies_.equal_range(key),
kNumCookiesPerHost, kNumCookiesPerHostPurge);
}
// Collect garbage for everything.
if (cookies_.size() > kNumCookiesTotal) {
COOKIE_DLOG(INFO) << "GarbageCollect() everything";
num_deleted += GarbageCollectRange(current,
CookieMapItPair(cookies_.begin(), cookies_.end()), kNumCookiesTotal,
kNumCookiesTotalPurge);
}
return num_deleted;
}
static bool LRUCookieSorter(const CookieMonster::CookieMap::iterator& it1,
const CookieMonster::CookieMap::iterator& it2) {
// Cookies accessed less recently should be deleted first.
if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
return it1->second->LastAccessDate() < it2->second->LastAccessDate();
// In rare cases we might have two cookies with identical last access times.
// To preserve the stability of the sort, in these cases prefer to delete
// older cookies over newer ones. CreationDate() is guaranteed to be unique.
return it1->second->CreationDate() < it2->second->CreationDate();
}
int CookieMonster::GarbageCollectRange(const Time& current,
const CookieMapItPair& itpair,
size_t num_max,
size_t num_purge) {
// First, delete anything that's expired.
std::vector<CookieMap::iterator> cookie_its;
int num_deleted = GarbageCollectExpired(current, itpair, &cookie_its);
// If the range still has too many cookies, delete the least recently used.
if (cookie_its.size() > num_max) {
COOKIE_DLOG(INFO) << "GarbageCollectRange() Deep Garbage Collect.";
// Purge down to (|num_max| - |num_purge|) total cookies.
DCHECK(num_purge <= num_max);
num_purge += cookie_its.size() - num_max;
std::partial_sort(cookie_its.begin(), cookie_its.begin() + num_purge,
cookie_its.end(), LRUCookieSorter);
for (size_t i = 0; i < num_purge; ++i)
InternalDeleteCookie(cookie_its[i], true);
num_deleted += num_purge;
}
return num_deleted;
}
int CookieMonster::GarbageCollectExpired(
const Time& current,
const CookieMapItPair& itpair,
std::vector<CookieMap::iterator>* cookie_its) {
int num_deleted = 0;
for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
CookieMap::iterator curit = it;
++it;
if (curit->second->IsExpired(current)) {
InternalDeleteCookie(curit, true);
++num_deleted;
} else if (cookie_its) {
cookie_its->push_back(curit);
}
}
return num_deleted;
}
int CookieMonster::DeleteAll(bool sync_to_store) {
AutoLock autolock(lock_);
InitIfNecessary();
int num_deleted = 0;
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
CookieMap::iterator curit = it;
++it;
InternalDeleteCookie(curit, sync_to_store);
++num_deleted;
}
return num_deleted;
}
int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
const Time& delete_end,
bool sync_to_store) {
AutoLock autolock(lock_);
InitIfNecessary();
int num_deleted = 0;
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
CookieMap::iterator curit = it;
CanonicalCookie* cc = curit->second;
++it;
if (cc->CreationDate() >= delete_begin &&
(delete_end.is_null() || cc->CreationDate() < delete_end)) {
InternalDeleteCookie(curit, sync_to_store);
++num_deleted;
}
}
return num_deleted;
}
int CookieMonster::DeleteAllCreatedAfter(const Time& delete_begin,
bool sync_to_store) {
return DeleteAllCreatedBetween(delete_begin, Time(), sync_to_store);
}
bool CookieMonster::DeleteCookie(const std::string& domain,
const CanonicalCookie& cookie,
bool sync_to_store) {
AutoLock autolock(lock_);
InitIfNecessary();
for (CookieMapItPair its = cookies_.equal_range(domain);
its.first != its.second; ++its.first) {
// The creation date acts as our unique index...
if (its.first->second->CreationDate() == cookie.CreationDate()) {
InternalDeleteCookie(its.first, sync_to_store);
return true;
}
}
return false;
}
// Mozilla sorts on the path length (longest first), and then it
// sorts by creation time (oldest first).
// The RFC says the sort order for the domain attribute is undefined.
static bool CookieSorter(CookieMonster::CanonicalCookie* cc1,
CookieMonster::CanonicalCookie* cc2) {
if (cc1->Path().length() == cc2->Path().length())
return cc1->CreationDate() < cc2->CreationDate();
return cc1->Path().length() > cc2->Path().length();
}
// Currently our cookie datastructure is based on Mozilla's approach. We have a
// hash keyed on the cookie's domain, and for any query we walk down the domain
// components and probe for cookies until we reach the TLD, where we stop.
// For example, a.b.blah.com, we would probe
// - a.b.blah.com
// - .a.b.blah.com (TODO should we check this first or second?)
// - .b.blah.com
// - .blah.com
// There are some alternative datastructures we could try, like a
// search/prefix trie, where we reverse the hostname and query for all
// keys that are a prefix of our hostname. I think the hash probing
// should be fast and simple enough for now.
std::string CookieMonster::GetCookies(const GURL& url) {
CookieOptions options;
return GetCookiesWithOptions(url, options);
}
std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
const CookieOptions& options) {
if (!HasCookieableScheme(url)) {
return std::string();
}
// Get the cookies for this host and its domain(s).
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, &cookies);
std::sort(cookies.begin(), cookies.end(), CookieSorter);
std::string cookie_line;
for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
if (it != cookies.begin())
cookie_line += "; ";
// In Mozilla if you set a cookie like AAAA, it will have an empty token
// and a value of AAAA. When it sends the cookie back, it will send AAAA,
// so we need to avoid sending =AAAA for a blank token value.
if (!(*it)->Name().empty())
cookie_line += (*it)->Name() + "=";
cookie_line += (*it)->Value();
}
COOKIE_DLOG(INFO) << "GetCookies() result: " << cookie_line;
return cookie_line;
}
void CookieMonster::GetRawCookies(const GURL& url,
std::vector<CanonicalCookie>* raw_cookies) {
raw_cookies->clear();
if (!HasCookieableScheme(url))
return;
CookieOptions options;
options.set_include_httponly();
// Get the cookies for this host and its domain(s).
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, &cookies);
std::sort(cookies.begin(), cookies.end(), CookieSorter);
for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
it != cookies.end(); ++it)
raw_cookies->push_back(*(*it));
}
void CookieMonster::DeleteCookie(const GURL& url,
const std::string& cookie_name) {
if (!HasCookieableScheme(url))
return;
CookieOptions options;
options.set_include_httponly();
// Get the cookies for this host and its domain(s).
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, &cookies);
std::set<CanonicalCookie*> matching_cookies;
for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
if ((*it)->Name() != cookie_name)
continue;
if (url.path().find((*it)->Path()))
continue;
matching_cookies.insert(*it);
}
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
CookieMap::iterator curit = it;
++it;
if (matching_cookies.find(curit->second) != matching_cookies.end())
InternalDeleteCookie(curit, true);
}
}
CookieMonster::CookieList CookieMonster::GetAllCookies() {
AutoLock autolock(lock_);
InitIfNecessary();
// This function is being called to scrape the cookie list for management UI
// or similar. We shouldn't show expired cookies in this list since it will
// just be confusing to users, and this function is called rarely enough (and
// is already slow enough) that it's OK to take the time to garbage collect
// the expired cookies now.
//
// Note that this does not prune cookies to be below our limits (if we've
// exceeded them) the way that calling GarbageCollect() would.
GarbageCollectExpired(Time::Now(),
CookieMapItPair(cookies_.begin(), cookies_.end()),
NULL);
CookieList cookie_list;
for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
cookie_list.push_back(CookieListPair(it->first, *it->second));
return cookie_list;
}
void CookieMonster::FindCookiesForHostAndDomain(
const GURL& url,
const CookieOptions& options,
std::vector<CanonicalCookie*>* cookies) {
AutoLock autolock(lock_);
InitIfNecessary();
const Time current_time(CurrentTime());
// Query for the full host, For example: 'a.c.blah.com'.
std::string key(url.host());
FindCookiesForKey(key, url, options, current_time, cookies);
// See if we can search for domain cookies, i.e. if the host has a TLD + 1.
const std::string domain(GetEffectiveDomain(url.scheme(), key));
if (domain.empty())
return;
DCHECK_LE(domain.length(), key.length());
DCHECK_EQ(0, key.compare(key.length() - domain.length(), domain.length(),
domain));
// Walk through the string and query at the dot points (GURL should have
// canonicalized the dots, so this should be safe). Stop once we reach the
// domain + registry; we can't write cookies past this point, and with some
// registrars other domains can, in which case we don't want to read their
// cookies.
for (key = "." + key; key.length() > domain.length(); ) {
FindCookiesForKey(key, url, options, current_time, cookies);
const size_t next_dot = key.find('.', 1); // Skip over leading dot.
key.erase(0, next_dot);
}
}
void CookieMonster::FindCookiesForKey(
const std::string& key,
const GURL& url,
const CookieOptions& options,
const Time& current,
std::vector<CanonicalCookie*>* cookies) {
bool secure = url.SchemeIsSecure();
for (CookieMapItPair its = cookies_.equal_range(key);
its.first != its.second; ) {
CookieMap::iterator curit = its.first;
CanonicalCookie* cc = curit->second;
++its.first;
// If the cookie is expired, delete it.
if (cc->IsExpired(current)) {
InternalDeleteCookie(curit, true);
continue;
}
// Filter out HttpOnly cookies, per options.
if (options.exclude_httponly() && cc->IsHttpOnly())
continue;
// Filter out secure cookies unless we're https.
if (!secure && cc->IsSecure())
continue;
if (!cc->IsOnPath(url.path()))
continue;
// Add this cookie to the set of matching cookies. Since we're reading the
// cookie, update its last access time.
InternalUpdateCookieAccessTime(cc);
cookies->push_back(cc);
}
}
CookieMonster::ParsedCookie::ParsedCookie(const std::string& cookie_line)
: is_valid_(false),
path_index_(0),
domain_index_(0),
expires_index_(0),
maxage_index_(0),
secure_index_(0),
httponly_index_(0) {
if (cookie_line.size() > kMaxCookieSize) {
LOG(INFO) << "Not parsing cookie, too large: " << cookie_line.size();
return;
}
ParseTokenValuePairs(cookie_line);
if (pairs_.size() > 0) {
is_valid_ = true;
SetupAttributes();
}
}
// Returns true if |c| occurs in |chars|
// TODO maybe make this take an iterator, could check for end also?
static inline bool CharIsA(const char c, const char* chars) {
return strchr(chars, c) != NULL;
}
// Seek the iterator to the first occurrence of a character in |chars|.
// Returns true if it hit the end, false otherwise.
static inline bool SeekTo(std::string::const_iterator* it,
const std::string::const_iterator& end,
const char* chars) {
for (; *it != end && !CharIsA(**it, chars); ++(*it));
return *it == end;
}
// Seek the iterator to the first occurrence of a character not in |chars|.
// Returns true if it hit the end, false otherwise.
static inline bool SeekPast(std::string::const_iterator* it,
const std::string::const_iterator& end,
const char* chars) {
for (; *it != end && CharIsA(**it, chars); ++(*it));
return *it == end;
}
static inline bool SeekBackPast(std::string::const_iterator* it,
const std::string::const_iterator& end,
const char* chars) {
for (; *it != end && CharIsA(**it, chars); --(*it));
return *it == end;
}
// Parse all token/value pairs and populate pairs_.
void CookieMonster::ParsedCookie::ParseTokenValuePairs(
const std::string& cookie_line) {
static const char kTerminator[] = "\n\r\0";
static const int kTerminatorLen = sizeof(kTerminator) - 1;
static const char kWhitespace[] = " \t";
static const char kValueSeparator[] = ";";
static const char kTokenSeparator[] = ";=";
pairs_.clear();
// Ok, here we go. We should be expecting to be starting somewhere
// before the cookie line, not including any header name...
std::string::const_iterator start = cookie_line.begin();
std::string::const_iterator end = cookie_line.end();
std::string::const_iterator it = start;
// TODO Make sure we're stripping \r\n in the network code. Then we
// can log any unexpected terminators.
size_t term_pos =
cookie_line.find_first_of(std::string(kTerminator, kTerminatorLen));
if (term_pos != std::string::npos) {
// We found a character we should treat as an end of string.
end = start + term_pos;
}
for (int pair_num = 0; pair_num < kMaxPairs && it != end; ++pair_num) {
TokenValuePair pair;
std::string::const_iterator token_start, token_real_end, token_end;
// Seek past any whitespace before the "token" (the name).
// token_start should point at the first character in the token
if (SeekPast(&it, end, kWhitespace))
break; // No token, whitespace or empty.
token_start = it;
// Seek over the token, to the token separator.
// token_real_end should point at the token separator, i.e. '='.
// If it == end after the seek, we probably have a token-value.
SeekTo(&it, end, kTokenSeparator);
token_real_end = it;
// Ignore any whitespace between the token and the token separator.
// token_end should point after the last interesting token character,
// pointing at either whitespace, or at '=' (and equal to token_real_end).
if (it != token_start) { // We could have an empty token name.
--it; // Go back before the token separator.
// Skip over any whitespace to the first non-whitespace character.
SeekBackPast(&it, token_start, kWhitespace);
// Point after it.
++it;
}
token_end = it;
// Seek us back to the end of the token.
it = token_real_end;
if (it == end || *it != '=') {
// We have a token-value, we didn't have any token name.
if (pair_num == 0) {
// For the first time around, we want to treat single values
// as a value with an empty name. (Mozilla bug 169091).
// IE seems to also have this behavior, ex "AAA", and "AAA=10" will
// set 2 different cookies, and setting "BBB" will then replace "AAA".
pair.first = "";
// Rewind to the beginning of what we thought was the token name,
// and let it get parsed as a value.
it = token_start;
} else {
// Any not-first attribute we want to treat a value as a
// name with an empty value... This is so something like
// "secure;" will get parsed as a Token name, and not a value.
pair.first = std::string(token_start, token_end);
}
} else {
// We have a TOKEN=VALUE.
pair.first = std::string(token_start, token_end);
++it; // Skip past the '='.
}
// OK, now try to parse a value.
std::string::const_iterator value_start, value_end;
// Seek past any whitespace that might in-between the token and value.
SeekPast(&it, end, kWhitespace);
// value_start should point at the first character of the value.
value_start = it;
// It is unclear exactly how quoted string values should be handled.
// Major browsers do different things, for example, Firefox supports
// semicolons embedded in a quoted value, while IE does not. Looking at
// the specs, RFC 2109 and 2965 allow for a quoted-string as the value.
// However, these specs were apparently written after browsers had
// implemented cookies, and they seem very distant from the reality of
// what is actually implemented and used on the web. The original spec
// from Netscape is possibly what is closest to the cookies used today.
// This spec didn't have explicit support for double quoted strings, and
// states that ; is not allowed as part of a value. We had originally
// implement the Firefox behavior (A="B;C"; -> A="B;C";). However, since
// there is no standard that makes sense, we decided to follow the behavior
// of IE and Safari, which is closer to the original Netscape proposal.
// This means that A="B;C" -> A="B;. This also makes the code much simpler
// and reduces the possibility for invalid cookies, where other browsers
// like Opera currently reject those invalid cookies (ex A="B" "C";).
// Just look for ';' to terminate ('=' allowed).
// We can hit the end, maybe they didn't terminate.
SeekTo(&it, end, kValueSeparator);
// Will be pointed at the ; seperator or the end.
value_end = it;
// Ignore any unwanted whitespace after the value.
if (value_end != value_start) { // Could have an empty value
--value_end;
SeekBackPast(&value_end, value_start, kWhitespace);
++value_end;
}
// OK, we're finished with a Token/Value.
pair.second = std::string(value_start, value_end);
// From RFC2109: "Attributes (names) (attr) are case-insensitive."
if (pair_num != 0)
StringToLowerASCII(&pair.first);
pairs_.push_back(pair);
// We've processed a token/value pair, we're either at the end of
// the string or a ValueSeparator like ';', which we want to skip.
if (it != end)
++it;
}
}
void CookieMonster::ParsedCookie::SetupAttributes() {
static const char kPathTokenName[] = "path";
static const char kDomainTokenName[] = "domain";
static const char kExpiresTokenName[] = "expires";
static const char kMaxAgeTokenName[] = "max-age";
static const char kSecureTokenName[] = "secure";
static const char kHttpOnlyTokenName[] = "httponly";
// We skip over the first token/value, the user supplied one.
for (size_t i = 1; i < pairs_.size(); ++i) {
if (pairs_[i].first == kPathTokenName)
path_index_ = i;
else if (pairs_[i].first == kDomainTokenName)
domain_index_ = i;
else if (pairs_[i].first == kExpiresTokenName)
expires_index_ = i;
else if (pairs_[i].first == kMaxAgeTokenName)
maxage_index_ = i;
else if (pairs_[i].first == kSecureTokenName)
secure_index_ = i;
else if (pairs_[i].first == kHttpOnlyTokenName)
httponly_index_ = i;
else { /* some attribute we don't know or don't care about. */ }
}
}
// Create a cookie-line for the cookie. For debugging only!
// If we want to use this for something more than debugging, we
// should rewrite it better...
std::string CookieMonster::ParsedCookie::DebugString() const {
std::string out;
for (PairList::const_iterator it = pairs_.begin();
it != pairs_.end(); ++it) {
out.append(it->first);
out.append("=");
out.append(it->second);
out.append("; ");
}
return out;
}
bool CookieMonster::CanonicalCookie::IsOnPath(
const std::string& url_path) const {
// A zero length would be unsafe for our trailing '/' checks, and
// would also make no sense for our prefix match. The code that
// creates a CanonicalCookie should make sure the path is never zero length,
// but we double check anyway.
if (path_.empty())
return false;
// The Mozilla code broke it into 3 cases, if it's strings lengths
// are less than, equal, or greater. I think this is simpler:
// Make sure the cookie path is a prefix of the url path. If the
// url path is shorter than the cookie path, then the cookie path
// can't be a prefix.
if (url_path.find(path_) != 0)
return false;
// Now we know that url_path is >= cookie_path, and that cookie_path
// is a prefix of url_path. If they are the are the same length then
// they are identical, otherwise we need an additional check:
// In order to avoid in correctly matching a cookie path of /blah
// with a request path of '/blahblah/', we need to make sure that either
// the cookie path ends in a trailing '/', or that we prefix up to a '/'
// in the url path. Since we know that the url path length is greater
// than the cookie path length, it's safe to index one byte past.
if (path_.length() != url_path.length() &&
path_[path_.length() - 1] != '/' &&
url_path[path_.length()] != '/')
return false;
return true;
}
std::string CookieMonster::CanonicalCookie::DebugString() const {
return StringPrintf("name: %s value: %s path: %s creation: %" PRId64,
name_.c_str(), value_.c_str(), path_.c_str(),
static_cast<int64>(creation_date_.ToTimeT()));
}
} // namespace
|
// Copyright (c) 2017-2018 Intel Corporation
//
// 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 "umc_defs.h"
#ifdef MFX_ENABLE_H265_VIDEO_DECODE
#include "umc_h265_mfx_supplier.h"
#include "umc_h265_frame_list.h"
#include "umc_h265_nal_spl.h"
#include "umc_h265_bitstream_headers.h"
#include "umc_h265_dec_defs.h"
#include "vm_sys_info.h"
#include "umc_h265_debug.h"
#include "umc_h265_mfx_utils.h"
namespace UMC_HEVC_DECODER
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
RawHeader_H265::RawHeader_H265()
{
Reset();
}
void RawHeader_H265::Reset()
{
m_id = -1;
m_buffer.clear();
}
int32_t RawHeader_H265::GetID() const
{
return m_id;
}
size_t RawHeader_H265::GetSize() const
{
return m_buffer.size();
}
uint8_t * RawHeader_H265::GetPointer()
{
return
m_buffer.empty() ? nullptr : &m_buffer[0];
}
void RawHeader_H265::Resize(int32_t id, size_t newSize)
{
m_id = id;
m_buffer.resize(newSize);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RawHeaders_H265::Reset()
{
m_sps.Reset();
m_pps.Reset();
}
RawHeader_H265 * RawHeaders_H265::GetSPS()
{
return &m_sps;
}
RawHeader_H265 * RawHeaders_H265::GetPPS()
{
return &m_pps;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
MFXTaskSupplier_H265::MFXTaskSupplier_H265()
: TaskSupplier_H265()
{
memset(&m_firstVideoParams, 0, sizeof(mfxVideoParam));
}
MFXTaskSupplier_H265::~MFXTaskSupplier_H265()
{
Close();
}
// Initialize task supplier
UMC::Status MFXTaskSupplier_H265::Init(UMC::VideoDecoderParams *init)
{
UMC::Status umcRes;
if (NULL == init)
return UMC::UMC_ERR_NULL_PTR;
Close();
m_initializationParams = *init;
m_pMemoryAllocator = init->lpMemoryAllocator;
m_DPBSizeEx = 0;
m_sei_messages = new SEI_Storer_H265();
m_sei_messages->Init();
int32_t nAllowedThreadNumber = init->numThreads;
if(nAllowedThreadNumber < 0) nAllowedThreadNumber = 0;
// calculate number of slice decoders.
// It should be equal to CPU number
m_iThreadNum = (0 == nAllowedThreadNumber) ? (vm_sys_info_get_cpu_num()) : (nAllowedThreadNumber);
umcRes = MVC_Extension::Init();
if (UMC::UMC_OK != umcRes)
{
return umcRes;
}
AU_Splitter_H265::Init(init);
m_pSegmentDecoder = new H265SegmentDecoderBase *[m_iThreadNum];
memset(m_pSegmentDecoder, 0, sizeof(H265SegmentDecoderBase *) * m_iThreadNum);
CreateTaskBroker();
m_pTaskBroker->Init(m_iThreadNum);
for (uint32_t i = 0; i < m_iThreadNum; i += 1)
{
if (UMC::UMC_OK != m_pSegmentDecoder[i]->Init(i))
return UMC::UMC_ERR_INIT;
}
m_local_delta_frame_time = 1.0/30;
m_frameOrder = 0;
m_use_external_framerate = 0 < init->info.framerate;
if (m_use_external_framerate)
{
m_local_delta_frame_time = 1 / init->info.framerate;
}
GetView()->dpbSize = 16;
m_DPBSizeEx = m_iThreadNum + init->info.bitrate;
return UMC::UMC_OK;
}
// Check whether specified frame has been decoded, and if it was,
// whether it is necessary to display some frame
bool MFXTaskSupplier_H265::CheckDecoding(bool should_additional_check, H265DecoderFrame * outputFrame)
{
ViewItem_H265 &view = *GetView();
if (!outputFrame->IsDecodingStarted())
return false;
if (outputFrame->IsDecodingCompleted())
{
if (!should_additional_check)
return true;
int32_t maxReadyUID = outputFrame->m_UID;
uint32_t inDisplayStage = 0;
UMC::AutomaticUMCMutex guard(m_mGuard);
for (H265DecoderFrame * pTmp = view.pDPB->head(); pTmp; pTmp = pTmp->future())
{
if (pTmp->m_wasOutputted != 0 && pTmp->m_wasDisplayed == 0 && pTmp->m_maxUIDWhenWasDisplayed)
{
inDisplayStage++; // number of outputted frames at this moment
}
if ((pTmp->IsDecoded() || pTmp->IsDecodingCompleted()) && maxReadyUID < pTmp->m_UID)
maxReadyUID = pTmp->m_UID;
}
DEBUG_PRINT1((VM_STRING("output frame - %d, notDecoded - %u, count - %u\n"), outputFrame->m_PicOrderCnt, notDecoded, count));
if (inDisplayStage > 1 || m_maxUIDWhenWasDisplayed <= maxReadyUID)
{
return true;
}
}
return false;
}
// Perform decoding task for thread number threadNumber
mfxStatus MFXTaskSupplier_H265::RunThread(mfxU32 threadNumber)
{
UMC::Status sts = m_pSegmentDecoder[threadNumber]->ProcessSegment();
if (sts == UMC::UMC_ERR_NOT_ENOUGH_DATA)
return MFX_TASK_BUSY;
else if(sts == UMC::UMC_ERR_DEVICE_FAILED)
return MFX_ERR_DEVICE_FAILED;
else if (sts == UMC::UMC_ERR_GPU_HANG)
return MFX_ERR_GPU_HANG;
if (sts != UMC::UMC_OK)
return MFX_ERR_UNDEFINED_BEHAVIOR;
return MFX_TASK_WORKING;
}
// Check whether all slices for the frame were found
void MFXTaskSupplier_H265::CompleteFrame(H265DecoderFrame * pFrame)
{
if (!pFrame)
return;
H265DecoderFrameInfo * slicesInfo = pFrame->GetAU();
if (slicesInfo->GetStatus() > H265DecoderFrameInfo::STATUS_NOT_FILLED)
return;
TaskSupplier_H265::CompleteFrame(pFrame);
}
// Set initial video params from application
void MFXTaskSupplier_H265::SetVideoParams(mfxVideoParam * par)
{
m_firstVideoParams = *par;
m_decodedOrder = m_firstVideoParams.mfx.DecodedOrder != 0;
}
UMC::Status MFXTaskSupplier_H265::FillVideoParam(mfxVideoParam *par, bool full)
{
const H265SeqParamSet * seq = GetHeaders()->m_SeqParams.GetCurrentHeader();
if (!seq)
return UMC::UMC_ERR_FAILED;
if (MFX_Utility::FillVideoParam(seq, par, full) != UMC::UMC_OK)
return UMC::UMC_ERR_FAILED;
return UMC::UMC_OK;
}
// Decode headers nal unit
UMC::Status MFXTaskSupplier_H265::DecodeHeaders(UMC::MediaDataEx *nalUnit)
{
UMC::Status sts = TaskSupplier_H265::DecodeHeaders(nalUnit);
if (sts != UMC::UMC_OK)
return sts;
{
// save sps/pps
uint32_t nal_unit_type = nalUnit->GetExData()->values[0];
switch(nal_unit_type)
{
case NAL_UT_SPS:
case NAL_UT_PPS:
{
static const uint8_t start_code_prefix[] = {0, 0, 0, 1};
size_t const prefix_size = sizeof(start_code_prefix);
size_t size = nalUnit->GetDataSize();
bool isSPS = (nal_unit_type == NAL_UT_SPS);
RawHeader_H265 * hdr = isSPS ? GetSPS() : GetPPS();
H265SeqParamSet * currSPS = isSPS ? m_Headers.m_SeqParams.GetCurrentHeader() : nullptr;
H265PicParamSet * currPPS = isSPS ? nullptr : m_Headers.m_PicParams.GetCurrentHeader();
int32_t id = isSPS ? m_Headers.m_SeqParams.GetCurrentID() : m_Headers.m_PicParams.GetCurrentID();
if (hdr->GetPointer() != nullptr)
{
if (hdr->GetID() == id)
{
bool changed =
size + prefix_size != hdr->GetSize() ||
!!memcmp(hdr->GetPointer() + prefix_size, nalUnit->GetDataPointer(), size);
if (isSPS && currSPS != nullptr)
currSPS->m_changed = changed;
else if (currPPS != nullptr)
currPPS->m_changed = changed;
}
hdr->Resize(id, size + prefix_size);
std::copy(start_code_prefix, start_code_prefix + prefix_size, hdr->GetPointer());
std::copy((uint8_t*)nalUnit->GetDataPointer(), (uint8_t*)nalUnit->GetDataPointer() + size, hdr->GetPointer() + prefix_size);
}
}
break;
}
}
UMC::MediaDataEx::_MediaDataEx* pMediaDataEx = nalUnit->GetExData();
if ((NalUnitType)pMediaDataEx->values[0] == NAL_UT_SPS && m_firstVideoParams.mfx.FrameInfo.Width)
{
H265SeqParamSet * currSPS = m_Headers.m_SeqParams.GetCurrentHeader();
if (currSPS)
{
if (m_firstVideoParams.mfx.FrameInfo.Width < (currSPS->pic_width_in_luma_samples) ||
m_firstVideoParams.mfx.FrameInfo.Height < (currSPS->pic_height_in_luma_samples) ||
(currSPS->m_pcPTL.GetGeneralPTL()->level_idc && m_firstVideoParams.mfx.CodecLevel && m_firstVideoParams.mfx.CodecLevel < currSPS->m_pcPTL.GetGeneralPTL()->level_idc))
{
return UMC::UMC_NTF_NEW_RESOLUTION;
}
}
return UMC::UMC_WRN_REPOSITION_INPROGRESS;
}
return UMC::UMC_OK;
}
// Decode SEI nal unit
UMC::Status MFXTaskSupplier_H265::DecodeSEI(UMC::MediaDataEx *nalUnit)
{
if (m_Headers.m_SeqParams.GetCurrentID() == -1)
return UMC::UMC_OK;
H265HeadersBitstream bitStream;
try
{
MemoryPiece mem;
mem.SetData(nalUnit);
MemoryPiece swappedMem;
swappedMem.Allocate(nalUnit->GetDataSize() + DEFAULT_NU_TAIL_SIZE);
SwapperBase * swapper = m_pNALSplitter->GetSwapper();
swapper->SwapMemory(&swappedMem, &mem, 0);
bitStream.Reset((uint8_t*)swappedMem.GetPointer(), (uint32_t)swappedMem.GetDataSize());
NalUnitType nal_unit_type;
uint32_t temporal_id;
bitStream.GetNALUnitType(nal_unit_type, temporal_id);
nalUnit->MoveDataPointer(2); // skip[ [NAL unit header = 16 bits]
do
{
H265SEIPayLoad m_SEIPayLoads;
size_t decoded1 = bitStream.BytesDecoded();
bitStream.ParseSEI(m_Headers.m_SeqParams, m_Headers.m_SeqParams.GetCurrentID(), &m_SEIPayLoads);
if (m_SEIPayLoads.payLoadType == SEI_USER_DATA_REGISTERED_TYPE)
{
m_UserData = m_SEIPayLoads;
}
else
{
if (m_SEIPayLoads.payLoadType == SEI_RESERVED)
continue;
m_Headers.m_SEIParams.AddHeader(&m_SEIPayLoads);
}
size_t decoded2 = bitStream.BytesDecoded();
// calculate payload size
size_t size = decoded2 - decoded1;
VM_ASSERT(size == m_SEIPayLoads.payLoadSize + 2 + (m_SEIPayLoads.payLoadSize / 255) + (m_SEIPayLoads.payLoadType / 255));
if (m_sei_messages)
{
UMC::MediaDataEx nalUnit1;
size_t nal_u_size = size;
for(uint8_t *ptr = (uint8_t*)nalUnit->GetDataPointer(); ptr < (uint8_t*)nalUnit->GetDataPointer() + nal_u_size; ptr++)
if (ptr[0]==0 && ptr[1]==0 && ptr[2]==3)
nal_u_size += 1;
nalUnit1.SetBufferPointer((uint8_t*)nalUnit->GetDataPointer(), nal_u_size);
nalUnit1.SetDataSize(nal_u_size);
nalUnit1.SetExData(nalUnit->GetExData());
double start, stop;
nalUnit->GetTime(start, stop);
nalUnit1.SetTime(start, stop);
nalUnit->MoveDataPointer((int32_t)nal_u_size);
SEI_Storer_H265::SEI_Message* msg =
m_sei_messages->AddMessage(&nalUnit1, m_SEIPayLoads.payLoadType);
//frame is bound to SEI prefix payloads w/ the first slice
//here we bind SEI suffix payloads
if (msg && msg->nal_type == NAL_UT_SEI_SUFFIX)
msg->frame = GetView()->pCurFrame;
}
} while (bitStream.More_RBSP_Data());
} catch(...)
{
// nothing to do just catch it
}
return UMC::UMC_OK;
}
// Do something in case reference frame is missing
void MFXTaskSupplier_H265::AddFakeReferenceFrame(H265Slice * )
{
}
} // namespace UMC_HEVC_DECODER
#endif // MFX_ENABLE_H265_VIDEO_DECODE
[h265d/UMC]Fix saving SPS/PPS
-This change is partial revert of commit
"[h265/UMC]Avoid possible dereferencing nullptr from GetCurrentHeader()"
(4987704)
-If RawHeader_H265::m_buffer is empty - call Resize() and copy current header
to m_buffer
// Copyright (c) 2017-2018 Intel Corporation
//
// 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 "umc_defs.h"
#ifdef MFX_ENABLE_H265_VIDEO_DECODE
#include "umc_h265_mfx_supplier.h"
#include "umc_h265_frame_list.h"
#include "umc_h265_nal_spl.h"
#include "umc_h265_bitstream_headers.h"
#include "umc_h265_dec_defs.h"
#include "vm_sys_info.h"
#include "umc_h265_debug.h"
#include "umc_h265_mfx_utils.h"
namespace UMC_HEVC_DECODER
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
RawHeader_H265::RawHeader_H265()
{
Reset();
}
void RawHeader_H265::Reset()
{
m_id = -1;
m_buffer.clear();
}
int32_t RawHeader_H265::GetID() const
{
return m_id;
}
size_t RawHeader_H265::GetSize() const
{
return m_buffer.size();
}
uint8_t * RawHeader_H265::GetPointer()
{
return
m_buffer.empty() ? nullptr : &m_buffer[0];
}
void RawHeader_H265::Resize(int32_t id, size_t newSize)
{
m_id = id;
m_buffer.resize(newSize);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RawHeaders_H265::Reset()
{
m_sps.Reset();
m_pps.Reset();
}
RawHeader_H265 * RawHeaders_H265::GetSPS()
{
return &m_sps;
}
RawHeader_H265 * RawHeaders_H265::GetPPS()
{
return &m_pps;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
MFXTaskSupplier_H265::MFXTaskSupplier_H265()
: TaskSupplier_H265()
{
memset(&m_firstVideoParams, 0, sizeof(mfxVideoParam));
}
MFXTaskSupplier_H265::~MFXTaskSupplier_H265()
{
Close();
}
// Initialize task supplier
UMC::Status MFXTaskSupplier_H265::Init(UMC::VideoDecoderParams *init)
{
UMC::Status umcRes;
if (NULL == init)
return UMC::UMC_ERR_NULL_PTR;
Close();
m_initializationParams = *init;
m_pMemoryAllocator = init->lpMemoryAllocator;
m_DPBSizeEx = 0;
m_sei_messages = new SEI_Storer_H265();
m_sei_messages->Init();
int32_t nAllowedThreadNumber = init->numThreads;
if(nAllowedThreadNumber < 0) nAllowedThreadNumber = 0;
// calculate number of slice decoders.
// It should be equal to CPU number
m_iThreadNum = (0 == nAllowedThreadNumber) ? (vm_sys_info_get_cpu_num()) : (nAllowedThreadNumber);
umcRes = MVC_Extension::Init();
if (UMC::UMC_OK != umcRes)
{
return umcRes;
}
AU_Splitter_H265::Init(init);
m_pSegmentDecoder = new H265SegmentDecoderBase *[m_iThreadNum];
memset(m_pSegmentDecoder, 0, sizeof(H265SegmentDecoderBase *) * m_iThreadNum);
CreateTaskBroker();
m_pTaskBroker->Init(m_iThreadNum);
for (uint32_t i = 0; i < m_iThreadNum; i += 1)
{
if (UMC::UMC_OK != m_pSegmentDecoder[i]->Init(i))
return UMC::UMC_ERR_INIT;
}
m_local_delta_frame_time = 1.0/30;
m_frameOrder = 0;
m_use_external_framerate = 0 < init->info.framerate;
if (m_use_external_framerate)
{
m_local_delta_frame_time = 1 / init->info.framerate;
}
GetView()->dpbSize = 16;
m_DPBSizeEx = m_iThreadNum + init->info.bitrate;
return UMC::UMC_OK;
}
// Check whether specified frame has been decoded, and if it was,
// whether it is necessary to display some frame
bool MFXTaskSupplier_H265::CheckDecoding(bool should_additional_check, H265DecoderFrame * outputFrame)
{
ViewItem_H265 &view = *GetView();
if (!outputFrame->IsDecodingStarted())
return false;
if (outputFrame->IsDecodingCompleted())
{
if (!should_additional_check)
return true;
int32_t maxReadyUID = outputFrame->m_UID;
uint32_t inDisplayStage = 0;
UMC::AutomaticUMCMutex guard(m_mGuard);
for (H265DecoderFrame * pTmp = view.pDPB->head(); pTmp; pTmp = pTmp->future())
{
if (pTmp->m_wasOutputted != 0 && pTmp->m_wasDisplayed == 0 && pTmp->m_maxUIDWhenWasDisplayed)
{
inDisplayStage++; // number of outputted frames at this moment
}
if ((pTmp->IsDecoded() || pTmp->IsDecodingCompleted()) && maxReadyUID < pTmp->m_UID)
maxReadyUID = pTmp->m_UID;
}
DEBUG_PRINT1((VM_STRING("output frame - %d, notDecoded - %u, count - %u\n"), outputFrame->m_PicOrderCnt, notDecoded, count));
if (inDisplayStage > 1 || m_maxUIDWhenWasDisplayed <= maxReadyUID)
{
return true;
}
}
return false;
}
// Perform decoding task for thread number threadNumber
mfxStatus MFXTaskSupplier_H265::RunThread(mfxU32 threadNumber)
{
UMC::Status sts = m_pSegmentDecoder[threadNumber]->ProcessSegment();
if (sts == UMC::UMC_ERR_NOT_ENOUGH_DATA)
return MFX_TASK_BUSY;
else if(sts == UMC::UMC_ERR_DEVICE_FAILED)
return MFX_ERR_DEVICE_FAILED;
else if (sts == UMC::UMC_ERR_GPU_HANG)
return MFX_ERR_GPU_HANG;
if (sts != UMC::UMC_OK)
return MFX_ERR_UNDEFINED_BEHAVIOR;
return MFX_TASK_WORKING;
}
// Check whether all slices for the frame were found
void MFXTaskSupplier_H265::CompleteFrame(H265DecoderFrame * pFrame)
{
if (!pFrame)
return;
H265DecoderFrameInfo * slicesInfo = pFrame->GetAU();
if (slicesInfo->GetStatus() > H265DecoderFrameInfo::STATUS_NOT_FILLED)
return;
TaskSupplier_H265::CompleteFrame(pFrame);
}
// Set initial video params from application
void MFXTaskSupplier_H265::SetVideoParams(mfxVideoParam * par)
{
m_firstVideoParams = *par;
m_decodedOrder = m_firstVideoParams.mfx.DecodedOrder != 0;
}
UMC::Status MFXTaskSupplier_H265::FillVideoParam(mfxVideoParam *par, bool full)
{
const H265SeqParamSet * seq = GetHeaders()->m_SeqParams.GetCurrentHeader();
if (!seq)
return UMC::UMC_ERR_FAILED;
if (MFX_Utility::FillVideoParam(seq, par, full) != UMC::UMC_OK)
return UMC::UMC_ERR_FAILED;
return UMC::UMC_OK;
}
// Decode headers nal unit
UMC::Status MFXTaskSupplier_H265::DecodeHeaders(UMC::MediaDataEx *nalUnit)
{
UMC::Status sts = TaskSupplier_H265::DecodeHeaders(nalUnit);
if (sts != UMC::UMC_OK)
return sts;
{
// save sps/pps
uint32_t nal_unit_type = nalUnit->GetExData()->values[0];
switch(nal_unit_type)
{
case NAL_UT_SPS:
case NAL_UT_PPS:
{
static const uint8_t start_code_prefix[] = {0, 0, 0, 1};
size_t const prefix_size = sizeof(start_code_prefix);
size_t size = nalUnit->GetDataSize();
bool isSPS = (nal_unit_type == NAL_UT_SPS);
RawHeader_H265 * hdr = isSPS ? GetSPS() : GetPPS();
H265SeqParamSet * currSPS = isSPS ? m_Headers.m_SeqParams.GetCurrentHeader() : nullptr;
H265PicParamSet * currPPS = isSPS ? nullptr : m_Headers.m_PicParams.GetCurrentHeader();
int32_t id = isSPS ? m_Headers.m_SeqParams.GetCurrentID() : m_Headers.m_PicParams.GetCurrentID();
if (hdr->GetPointer() != nullptr && hdr->GetID() == id)
{
bool changed =
size + prefix_size != hdr->GetSize() ||
!!memcmp(hdr->GetPointer() + prefix_size, nalUnit->GetDataPointer(), size);
if (isSPS && currSPS != nullptr)
currSPS->m_changed = changed;
else if (currPPS != nullptr)
currPPS->m_changed = changed;
}
hdr->Resize(id, size + prefix_size);
std::copy(start_code_prefix, start_code_prefix + prefix_size, hdr->GetPointer());
std::copy((uint8_t*)nalUnit->GetDataPointer(), (uint8_t*)nalUnit->GetDataPointer() + size, hdr->GetPointer() + prefix_size);
}
break;
}
}
UMC::MediaDataEx::_MediaDataEx* pMediaDataEx = nalUnit->GetExData();
if ((NalUnitType)pMediaDataEx->values[0] == NAL_UT_SPS && m_firstVideoParams.mfx.FrameInfo.Width)
{
H265SeqParamSet * currSPS = m_Headers.m_SeqParams.GetCurrentHeader();
if (currSPS)
{
if (m_firstVideoParams.mfx.FrameInfo.Width < (currSPS->pic_width_in_luma_samples) ||
m_firstVideoParams.mfx.FrameInfo.Height < (currSPS->pic_height_in_luma_samples) ||
(currSPS->m_pcPTL.GetGeneralPTL()->level_idc && m_firstVideoParams.mfx.CodecLevel && m_firstVideoParams.mfx.CodecLevel < currSPS->m_pcPTL.GetGeneralPTL()->level_idc))
{
return UMC::UMC_NTF_NEW_RESOLUTION;
}
}
return UMC::UMC_WRN_REPOSITION_INPROGRESS;
}
return UMC::UMC_OK;
}
// Decode SEI nal unit
UMC::Status MFXTaskSupplier_H265::DecodeSEI(UMC::MediaDataEx *nalUnit)
{
if (m_Headers.m_SeqParams.GetCurrentID() == -1)
return UMC::UMC_OK;
H265HeadersBitstream bitStream;
try
{
MemoryPiece mem;
mem.SetData(nalUnit);
MemoryPiece swappedMem;
swappedMem.Allocate(nalUnit->GetDataSize() + DEFAULT_NU_TAIL_SIZE);
SwapperBase * swapper = m_pNALSplitter->GetSwapper();
swapper->SwapMemory(&swappedMem, &mem, 0);
bitStream.Reset((uint8_t*)swappedMem.GetPointer(), (uint32_t)swappedMem.GetDataSize());
NalUnitType nal_unit_type;
uint32_t temporal_id;
bitStream.GetNALUnitType(nal_unit_type, temporal_id);
nalUnit->MoveDataPointer(2); // skip[ [NAL unit header = 16 bits]
do
{
H265SEIPayLoad m_SEIPayLoads;
size_t decoded1 = bitStream.BytesDecoded();
bitStream.ParseSEI(m_Headers.m_SeqParams, m_Headers.m_SeqParams.GetCurrentID(), &m_SEIPayLoads);
if (m_SEIPayLoads.payLoadType == SEI_USER_DATA_REGISTERED_TYPE)
{
m_UserData = m_SEIPayLoads;
}
else
{
if (m_SEIPayLoads.payLoadType == SEI_RESERVED)
continue;
m_Headers.m_SEIParams.AddHeader(&m_SEIPayLoads);
}
size_t decoded2 = bitStream.BytesDecoded();
// calculate payload size
size_t size = decoded2 - decoded1;
VM_ASSERT(size == m_SEIPayLoads.payLoadSize + 2 + (m_SEIPayLoads.payLoadSize / 255) + (m_SEIPayLoads.payLoadType / 255));
if (m_sei_messages)
{
UMC::MediaDataEx nalUnit1;
size_t nal_u_size = size;
for(uint8_t *ptr = (uint8_t*)nalUnit->GetDataPointer(); ptr < (uint8_t*)nalUnit->GetDataPointer() + nal_u_size; ptr++)
if (ptr[0]==0 && ptr[1]==0 && ptr[2]==3)
nal_u_size += 1;
nalUnit1.SetBufferPointer((uint8_t*)nalUnit->GetDataPointer(), nal_u_size);
nalUnit1.SetDataSize(nal_u_size);
nalUnit1.SetExData(nalUnit->GetExData());
double start, stop;
nalUnit->GetTime(start, stop);
nalUnit1.SetTime(start, stop);
nalUnit->MoveDataPointer((int32_t)nal_u_size);
SEI_Storer_H265::SEI_Message* msg =
m_sei_messages->AddMessage(&nalUnit1, m_SEIPayLoads.payLoadType);
//frame is bound to SEI prefix payloads w/ the first slice
//here we bind SEI suffix payloads
if (msg && msg->nal_type == NAL_UT_SEI_SUFFIX)
msg->frame = GetView()->pCurFrame;
}
} while (bitStream.More_RBSP_Data());
} catch(...)
{
// nothing to do just catch it
}
return UMC::UMC_OK;
}
// Do something in case reference frame is missing
void MFXTaskSupplier_H265::AddFakeReferenceFrame(H265Slice * )
{
}
} // namespace UMC_HEVC_DECODER
#endif // MFX_ENABLE_H265_VIDEO_DECODE
|
#include <algorithm>
#include <random>
#include <stack>
#include <vector>
#include "aim.hpp"
#include "maze.hpp"
struct Delta
{
int x, y;
Delta(int x, int y) : x(x), y(y) {}
};
struct UnvisitOnDelete
{
char** maze_;
Dimension dim_;
UnvisitOnDelete(char** maze, Dimension const& dim) : maze_(maze), dim_(dim) {}
~UnvisitOnDelete()
{
const char visited { to_char(MazeElement::Undefined) };
const char wall { to_char(MazeElement::Wall) };
for (std::size_t j {} ; j < dim_.height ; j += 2)
{
for (std::size_t i {} ; i < dim_.width ; i += 2)
{
if (maze_[j][i] == visited) { maze_[j][i] = wall; }
}
}
}
};
// Check properties
static bool is_inside(char** /*maze*/, Dimension const& dim, Point const& pt)
{
return pt.x < dim.width && pt.y < dim.height;
}
static bool is_wall(char** maze, Dimension const& /*dim*/, Point const& pt)
{
return maze[pt.y][pt.x] == to_char(MazeElement::Wall);
}
static bool is_inside_wall(char** maze, Dimension const& dim, Point const& pt)
{
return is_inside(maze, dim, pt) && is_wall(maze, dim, pt);
}
static bool can_reach_end(char** maze, Dimension const& dim, Point const& origin, Point const& end)
{
UnvisitOnDelete undoMe { maze, dim };
std::stack<Point> can_be_visited;
auto push_and_visit = [&can_be_visited,&maze,visited=to_char(MazeElement::Undefined)](auto&& pt) {
can_be_visited.push(pt);
maze[pt.y][pt.x] = visited;
};
push_and_visit(origin);
while (! can_be_visited.empty())
{
Point pt { can_be_visited.top() };
can_be_visited.pop();
if (pt == end) { return true; }
if (is_inside_wall(maze, dim, Point{pt.x-2, pt.y})) { push_and_visit(Point{pt.x-2, pt.y}); }
if (is_inside_wall(maze, dim, Point{pt.x+2, pt.y})) { push_and_visit(Point{pt.x+2, pt.y}); }
if (is_inside_wall(maze, dim, Point{pt.x, pt.y-2})) { push_and_visit(Point{pt.x, pt.y-2}); }
if (is_inside_wall(maze, dim, Point{pt.x, pt.y+2})) { push_and_visit(Point{pt.x, pt.y+2}); }
}
return false;
}
// Helpers
template <class Container, class Predicate>
static void push_if(Container& container, char** maze, Dimension const& dim, Point const& pt, Delta const& delta, Predicate&& predicate)
{
if (predicate(maze, dim, Point{pt.x + 2*delta.x, pt.y + 2*delta.y}))
{
container.push_back(delta);
}
}
template <class Predicate, class Gen>
static auto build_choices(char** maze, Dimension const& dim, Point const& pt, Predicate&& predicate, Gen& g)
{
std::vector<Delta> choices;
push_if(choices, maze, dim, pt, Delta{-1, 0}, predicate);
push_if(choices, maze, dim, pt, Delta{ 1, 0}, predicate);
push_if(choices, maze, dim, pt, Delta{ 0,-1}, predicate);
push_if(choices, maze, dim, pt, Delta{ 0, 1}, predicate);
std::shuffle(choices.begin(), choices.end(), g);
return choices;
}
template <class Gen>
static void adapt_for_traps(std::vector<std::pair<Point, std::vector<Delta>>>& main_roads, char** maze, Dimension const& dim, Gen& g)
{
main_roads.erase(
std::remove_if(main_roads.begin(), main_roads.end(), [](auto&& details) { return details.first.x % 2 != 0 || details.first.y % 2 != 0; })
, main_roads.end());
std::transform(main_roads.begin(), main_roads.end()
, main_roads.begin()
, [&](auto&& details) { return std::make_pair(details.first, build_choices(maze, dim, details.first, is_inside_wall, g)); });
main_roads.erase(
std::remove_if(main_roads.begin(), main_roads.end(), [](auto&& details) { return details.second.empty(); })
, main_roads.end());
std::shuffle(main_roads.begin(), main_roads.end(), g);
}
// Maze generation steps
static void reset(char** maze, Dimension const& dim)
{
std::for_each(maze, maze+dim.height
, [width = dim.width, wall = to_char(MazeElement::Wall)](char* line) { std::fill(line, line + width, wall); });
}
template <class Gen>
static auto generate_main_path(char** maze, Dimension const& dim, Point const& start_pt, Point const& end_pt, Gen& g)
{
// Generate a random path starting at start_pt and going to end_pt
// Only one path will be generated
const char road = to_char(MazeElement::Road);
const char wall = to_char(MazeElement::Wall);
auto path_to_end = std::vector<std::pair<Point, std::vector<Delta>>>{};
auto current = Point{ start_pt };
auto choices = build_choices(maze, dim, current, is_inside_wall, g);
while (current != end_pt)
{
if (choices.empty())
{// no more choices: backtrack
current = path_to_end.back().first;
maze[current.y][current.x] = wall;
path_to_end.pop_back();
current = path_to_end.back().first;
choices = std::move(path_to_end.back().second);
maze[current.y][current.x] = wall;
path_to_end.pop_back();
continue;
}
auto d = Delta{ choices.back() };
choices.pop_back();
// check if such path can lead to the end of the maze
maze[current.y][current.x] = road;
if (! can_reach_end(maze, dim, Point{ current.x + 2 * d.x, current.y + 2 * d.y }, end_pt))
{
maze[current.y][current.x] = to_char(MazeElement::Wall);
continue;
}
// current decision
path_to_end.emplace_back(current, std::move(choices));
// junction road
current = Point{ current.x + d.x, current.y + d.y };
path_to_end.emplace_back(current, decltype(choices){});
maze[current.y][current.x] = road;
// next position
current = Point{ current.x + d.x, current.y + d.y };
choices = build_choices(maze, dim, current, is_inside_wall, g);
}
maze[start_pt.y][start_pt.x] = to_char(MazeElement::Start);
maze[end_pt.y][end_pt.x] = to_char(MazeElement::End);
return path_to_end;
}
static void clean_not_accessible(char** maze, Dimension const& dim, std::pair<Point, std::vector<Delta>>& crossroad)
{
auto const& pt = crossroad.first;
auto& choices = crossroad.second;
choices.erase(
std::remove_if(choices.begin(), choices.end(), [&](auto const& d) { return ! is_inside_wall(maze, dim, Point{ pt.x + 2 * d.x, pt.y + 2 * d.y }); })
, choices.end());
}
template <class Gen>
static void generate_trap_paths(char** maze, Dimension const& dim, std::vector<std::pair<Point, std::vector<Delta>>> nonfull_crossroads, Gen& g)
{
const char road = to_char(MazeElement::Road);
while (! nonfull_crossroads.empty())
{
auto const& pt { nonfull_crossroads.back().first };
auto& choices { nonfull_crossroads.back().second };
auto valid_delta = std::find_if(choices.begin(), choices.end()
, [&](Delta d) { return is_inside_wall(maze, dim, Point{ pt.x + 2 * d.x, pt.y + 2 * d.y }); });
if (valid_delta == choices.end())
{// no path is accessible from this road
// update possible choices of each road
std::for_each(nonfull_crossroads.begin(), nonfull_crossroads.end(), [&](auto&& details) { clean_not_accessible(maze, dim, details); });
// remove roads not having choices
nonfull_crossroads.erase(
std::remove_if(nonfull_crossroads.begin(), nonfull_crossroads.end(), [](auto&& details) { return details.second.empty(); })
, nonfull_crossroads.end());
// shuffle remaining roads
std::shuffle(nonfull_crossroads.begin(), nonfull_crossroads.end(), g);
continue;
}
auto d = *valid_delta;
auto junction = Point{ pt.x + d.x, pt.y + d.y };
auto target = Point{ pt.x + 2 * d.x, pt.y + 2 * d.y };
maze[junction.y][junction.x] = road;
maze[target.y][target.x] = road;
auto next_choices = build_choices(maze, dim, target, is_inside_wall, g);
if (! next_choices.empty())
{
nonfull_crossroads.emplace_back(target, std::move(next_choices));
}
}
}
// Algorithm to be tested
void generate_maze(char** maze, Dimension const& dim, Point const& start_pt, Point const& end_pt, unsigned seed)
{
std::mt19937 g(seed);
reset(maze, dim);
auto main_roads = generate_main_path(maze, dim, start_pt, end_pt, g);
adapt_for_traps(main_roads, maze, dim, g);
generate_trap_paths(maze, dim, std::move(main_roads), g);
}
[maze-generator-no-odd] Try to fix compile issues on older compilers
#include <algorithm>
#include <random>
#include <stack>
#include <vector>
#include "aim.hpp"
#include "maze.hpp"
struct Delta
{
int x, y;
Delta(int x, int y) : x(x), y(y) {}
};
struct UnvisitOnDelete
{
char** maze_;
Dimension dim_;
UnvisitOnDelete(char** maze, Dimension const& dim) : maze_(maze), dim_(dim) {}
~UnvisitOnDelete()
{
const char visited { to_char(MazeElement::Undefined) };
const char wall { to_char(MazeElement::Wall) };
for (std::size_t j {} ; j < dim_.height ; j += 2)
{
for (std::size_t i {} ; i < dim_.width ; i += 2)
{
if (maze_[j][i] == visited) { maze_[j][i] = wall; }
}
}
}
};
// Check properties
static bool is_inside(char** /*maze*/, Dimension const& dim, Point const& pt)
{
return pt.x < dim.width && pt.y < dim.height;
}
static bool is_wall(char** maze, Dimension const& /*dim*/, Point const& pt)
{
return maze[pt.y][pt.x] == to_char(MazeElement::Wall);
}
static bool is_inside_wall(char** maze, Dimension const& dim, Point const& pt)
{
return is_inside(maze, dim, pt) && is_wall(maze, dim, pt);
}
static bool can_reach_end(char** maze, Dimension const& dim, Point const& origin, Point const& end)
{
UnvisitOnDelete undoMe { maze, dim };
std::stack<Point> can_be_visited;
auto push_and_visit = [&can_be_visited,&maze,visited=to_char(MazeElement::Undefined)](auto&& pt) {
can_be_visited.push(pt);
maze[pt.y][pt.x] = visited;
};
push_and_visit(origin);
while (! can_be_visited.empty())
{
Point pt { can_be_visited.top() };
can_be_visited.pop();
if (pt == end) { return true; }
if (is_inside_wall(maze, dim, Point{pt.x-2, pt.y})) { push_and_visit(Point{pt.x-2, pt.y}); }
if (is_inside_wall(maze, dim, Point{pt.x+2, pt.y})) { push_and_visit(Point{pt.x+2, pt.y}); }
if (is_inside_wall(maze, dim, Point{pt.x, pt.y-2})) { push_and_visit(Point{pt.x, pt.y-2}); }
if (is_inside_wall(maze, dim, Point{pt.x, pt.y+2})) { push_and_visit(Point{pt.x, pt.y+2}); }
}
return false;
}
// Helpers
template <class Container, class Predicate>
static void push_if(Container& container, char** maze, Dimension const& dim, Point const& pt, Delta const& delta, Predicate&& predicate)
{
if (predicate(maze, dim, Point{pt.x + 2*delta.x, pt.y + 2*delta.y}))
{
container.push_back(delta);
}
}
template <class Predicate, class Gen>
static auto build_choices(char** maze, Dimension const& dim, Point const& pt, Predicate&& predicate, Gen& g)
{
std::vector<Delta> choices;
push_if(choices, maze, dim, pt, Delta{-1, 0}, predicate);
push_if(choices, maze, dim, pt, Delta{ 1, 0}, predicate);
push_if(choices, maze, dim, pt, Delta{ 0,-1}, predicate);
push_if(choices, maze, dim, pt, Delta{ 0, 1}, predicate);
std::shuffle(choices.begin(), choices.end(), g);
return choices;
}
template <class Gen>
static void adapt_for_traps(std::vector<std::pair<Point, std::vector<Delta>>>& main_roads, char** maze, Dimension const& dim, Gen& g)
{
main_roads.erase(
std::remove_if(main_roads.begin(), main_roads.end(), [](auto&& details) { return details.first.x % 2 != 0 || details.first.y % 2 != 0; })
, main_roads.end());
std::transform(main_roads.begin(), main_roads.end()
, main_roads.begin()
, [&](auto&& details) { return std::make_pair(details.first, build_choices(maze, dim, details.first, is_inside_wall, g)); });
main_roads.erase(
std::remove_if(main_roads.begin(), main_roads.end(), [](auto&& details) { return details.second.empty(); })
, main_roads.end());
std::shuffle(main_roads.begin(), main_roads.end(), g);
}
// Maze generation steps
static void reset(char** maze, Dimension const& dim)
{
std::for_each(maze, maze+dim.height
, [width = dim.width, wall = to_char(MazeElement::Wall)](char* line) { std::fill(line, line + width, wall); });
}
template <class Gen>
static auto generate_main_path(char** maze, Dimension const& dim, Point const& start_pt, Point const& end_pt, Gen& g)
{
// Generate a random path starting at start_pt and going to end_pt
// Only one path will be generated
const char road = to_char(MazeElement::Road);
const char wall = to_char(MazeElement::Wall);
auto path_to_end = std::vector<std::pair<Point, std::vector<Delta>>>{};
auto current = Point{ start_pt };
auto choices = build_choices(maze, dim, current, is_inside_wall, g);
while (current != end_pt)
{
if (choices.empty())
{// no more choices: backtrack
current = path_to_end.back().first;
maze[current.y][current.x] = wall;
path_to_end.pop_back();
current = path_to_end.back().first;
choices = std::move(path_to_end.back().second);
maze[current.y][current.x] = wall;
path_to_end.pop_back();
continue;
}
auto d = Delta{ choices.back() };
choices.pop_back();
// check if such path can lead to the end of the maze
maze[current.y][current.x] = road;
if (! can_reach_end(maze, dim, Point{ current.x + 2 * d.x, current.y + 2 * d.y }, end_pt))
{
maze[current.y][current.x] = to_char(MazeElement::Wall);
continue;
}
// current decision
path_to_end.emplace_back(current, std::move(choices));
// junction road
current = Point{ current.x + d.x, current.y + d.y };
path_to_end.emplace_back(current, decltype(choices){});
maze[current.y][current.x] = road;
// next position
current = Point{ current.x + d.x, current.y + d.y };
choices = build_choices(maze, dim, current, is_inside_wall, g);
}
maze[start_pt.y][start_pt.x] = to_char(MazeElement::Start);
maze[end_pt.y][end_pt.x] = to_char(MazeElement::End);
return path_to_end;
}
static void clean_not_accessible(char** maze, Dimension const& dim, std::pair<Point, std::vector<Delta>>& crossroad)
{
auto const& pt = crossroad.first;
auto& choices = crossroad.second;
choices.erase(
std::remove_if(choices.begin(), choices.end(), [&](auto const& d) { return ! is_inside_wall(maze, dim, Point{ pt.x + 2 * d.x, pt.y + 2 * d.y }); })
, choices.end());
}
template <class Gen>
static void generate_trap_paths(char** maze, Dimension const& dim, std::vector<std::pair<Point, std::vector<Delta>>> nonfull_crossroads, Gen& g)
{
const char road = to_char(MazeElement::Road);
while (! nonfull_crossroads.empty())
{
auto const& pt = nonfull_crossroads.back().first;
auto& choices = nonfull_crossroads.back().second;
auto valid_delta = std::find_if(choices.begin(), choices.end()
, [&](Delta d) { return is_inside_wall(maze, dim, Point{ pt.x + 2 * d.x, pt.y + 2 * d.y }); });
if (valid_delta == choices.end())
{// no path is accessible from this road
// update possible choices of each road
std::for_each(nonfull_crossroads.begin(), nonfull_crossroads.end(), [&](auto&& details) { clean_not_accessible(maze, dim, details); });
// remove roads not having choices
nonfull_crossroads.erase(
std::remove_if(nonfull_crossroads.begin(), nonfull_crossroads.end(), [](auto&& details) { return details.second.empty(); })
, nonfull_crossroads.end());
// shuffle remaining roads
std::shuffle(nonfull_crossroads.begin(), nonfull_crossroads.end(), g);
continue;
}
auto d = *valid_delta;
auto junction = Point{ pt.x + d.x, pt.y + d.y };
auto target = Point{ pt.x + 2 * d.x, pt.y + 2 * d.y };
maze[junction.y][junction.x] = road;
maze[target.y][target.x] = road;
auto next_choices = build_choices(maze, dim, target, is_inside_wall, g);
if (! next_choices.empty())
{
nonfull_crossroads.emplace_back(target, std::move(next_choices));
}
}
}
// Algorithm to be tested
void generate_maze(char** maze, Dimension const& dim, Point const& start_pt, Point const& end_pt, unsigned seed)
{
std::mt19937 g(seed);
reset(maze, dim);
auto main_roads = generate_main_path(maze, dim, start_pt, end_pt, g);
adapt_for_traps(main_roads, maze, dim, g);
generate_trap_paths(maze, dim, std::move(main_roads), g);
}
|
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "TunManager.h"
extern "C" {
#include <netlink/route/link.h>
#include <netlink/route/addr.h>
#include <netlink/route/route.h>
#include <netlink/route/rule.h>
#include <linux/if.h>
#include <sys/ioctl.h>
}
#include "fboss/agent/NlError.h"
#include "fboss/agent/RxPacket.h"
#include "fboss/agent/SysError.h"
#include "fboss/agent/TunIntf.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/InterfaceMap.h"
#include "fboss/agent/state/Port.h"
#include "fboss/agent/state/SwitchState.h"
#include <folly/Demangle.h>
#include <folly/io/async/EventBase.h>
#include <boost/container/flat_set.hpp>
namespace {
const int kDefaultMtu = 1500;
}
namespace facebook { namespace fboss {
using folly::IPAddress;
using folly::EventBase;
TunManager::TunManager(SwSwitch *sw, EventBase *evb) : sw_(sw), evb_(evb) {
DCHECK(sw) << "NULL pointer to SwSwitch.";
DCHECK(evb) << "NULL pointer to EventBase";
sock_ = nl_socket_alloc();
if (!sock_) {
throw FbossError("failed to allocate libnl socket");
}
auto error = nl_connect(sock_, NETLINK_ROUTE);
nlCheckError(error, "failed to connect netlink socket to NETLINK_ROUTE");
}
TunManager::~TunManager() {
if (observingState_) {
sw_->unregisterStateObserver(this);
}
stop();
nl_close(sock_);
nl_socket_free(sock_);
}
void TunManager::startProbe() {
evb_->runInEventBaseThread([this]() {
this->probe();
});
}
void TunManager::startObservingUpdates() {
sw_->registerStateObserver(this, "TunManager");
observingState_ = true;
}
void TunManager::stateUpdated(const StateDelta& delta) {
// TODO(aeckert): We currently compare the entire interface map instead
// of using the iterator in this delta because some of the interfaces may get
// get probed from hardware, before they are in the SwitchState. It would be
// nicer if we did a little more work at startup to sync the state, perhaps
// updating the SwitchState with the probed interfaces. This would allow us
// to reuse the iterator in the delta for more readable code and also not
// have to worry about waiting to listen to updates until the SwSwitch is in
// the configured state. t4155406 should also help with that.
auto state = delta.newState();
evb_->runInEventBaseThread([this, state]() {
this->sync(state);
});
}
bool TunManager::sendPacketToHost(std::unique_ptr<RxPacket> pkt) {
auto ifID = InterfaceID(pkt->getSrcVlan());
std::lock_guard<std::mutex> lock(mutex_);
auto iter = intfs_.find(ifID);
if (iter == intfs_.end()) {
// the Interface ID has been deleted, make a log, and skip the pkt
VLOG(4) << "Dropping a packet for unknown unknwon " << ifID;
return false;
}
return iter->second->sendPacketToHost(std::move(pkt));
}
void TunManager::addExistingIntf(
const std::string& ifName,
int ifIndex) {
InterfaceID ifID = TunIntf::getIDFromTunIntfName(ifName);
auto ret = intfs_.emplace(ifID, nullptr);
if (!ret.second) {
throw FbossError("Duplicate interface ", ifName);
}
SCOPE_FAIL {
intfs_.erase(ret.first);
};
setIntfStatus(ifName, ifIndex, false);
ret.first->second.reset(
new TunIntf(sw_, evb_, ifID, ifIndex, getInterfaceMtu(ifID)));
}
void TunManager::addNewIntf(
InterfaceID ifID,
bool isUp,
const Interface::Addresses& addrs) {
auto ret = intfs_.emplace(ifID, nullptr);
if (!ret.second) {
throw FbossError("Duplicate interface for interface ", ifID);
}
SCOPE_FAIL {
intfs_.erase(ret.first);
};
auto intf = std::make_unique<TunIntf>(
sw_, evb_, ifID, isUp, addrs, getInterfaceMtu(ifID));
SCOPE_FAIL {
intf->setDelete();
};
const auto ifName = intf->getName();
auto ifIndex = intf->getIfIndex();
// bring up the interface so that we can add the default route in next step
setIntfStatus(ifName, ifIndex, isUp);
// create a new route table for this InterfaceID
addRouteTable(ifID, ifIndex);
// add all addresses
for (const auto& addr : addrs) {
addTunAddress(ifID, ifName, ifIndex, addr.first, addr.second);
}
// Store it in local map on success
ret.first->second = std::move(intf);
}
void TunManager::removeIntf(InterfaceID ifID) {
auto iter = intfs_.find(ifID);
if (iter == intfs_.end()) {
throw FbossError("Cannot find interface ", ifID, " for deleting.");
}
// Remove all addresses attached on this interface
auto& intf = iter->second;
for (auto const& addr : intf->getAddresses()) {
removeTunAddress(
ifID,
intf->getName(),
intf->getIfIndex(),
addr.first /* ip */,
addr.second /* mask */);
}
// Remove the route table and associated rule
removeRouteTable(ifID, intf->getIfIndex());
intf->setDelete();
intfs_.erase(iter);
}
void TunManager::addProbedAddr(
int ifIndex, const IPAddress& addr, uint8_t mask) {
for (auto& intf : intfs_) {
if (intf.second->getIfIndex() == ifIndex) {
intf.second->addAddress(addr, mask);
return;
}
}
// This function is called for all interface addresses discovered from
// the host. Since we only create TunIntf object for TUN interfaces,
// it is normal we cannot find the interface matching the ifIndex provided.
VLOG(3) << "Cannot find interface @ index " << ifIndex
<< " for probed address " << addr.str() << "/"
<< static_cast<int>(mask);
}
void TunManager::setIntfStatus(
const std::string& ifName,
int ifIndex,
bool status) {
/**
* NOTE: Why use `ioctl` instead of `netlink` ?
*
* netlink's `rtnl_link_change` API was in-effective. Internally netlink
* tries to pass a message with RTM_NEWLINK which some old kernel couldn't
* process. After messing my head around with netlink for few hours I decided
* to use `ioctl` which was much easy and straight-forward operation.
*/
// Prepare socket
auto sockFd = socket(PF_INET, SOCK_DGRAM, 0);
sysCheckError(sockFd, "Failed to open socket");
// Prepare request
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
folly::strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
// Get existing flags
int error = ioctl(sockFd, SIOCGIFFLAGS, static_cast<void*>(&ifr));
sysCheckError(error, "Failed to get existing interface flags of ", ifName);
// Mutate flags
if (status) {
ifr.ifr_flags |= IFF_UP;
} else {
ifr.ifr_flags &= ~IFF_UP;
}
// Set flags
error = ioctl(sockFd, SIOCSIFFLAGS, static_cast<void*>(&ifr));
sysCheckError(error, "Failed to set interface flags on ", ifName);
LOG(INFO) << "Brought " << (status ? "up" : "down") << " interface "
<< ifName << " @ index " << ifIndex;
}
int TunManager::getTableId(InterfaceID ifID) const {
// Kernel only supports up to 256 tables. The last few are used by kernel
// as main, default, and local. IDs 0, 254 and 255 are not available. So we
// use range 1-253 for our usecase.
// Special case to handle old front0 interfaces.
// XXX: Delete this case after 6 months (atleast one full rollout). 08-22-2016
if (ifID == InterfaceID(0)) {
return 100; // This was the old-ID used for creating front0
}
// Hacky. Need better solution but works for now. Our InterfaceID are
// Type-1: 2000, 2001, 2002, 2003 ...
// Type-2: 4000, 4001, 4002, 4003, 4004, ...
int tableId = static_cast<int>(ifID);
if (ifID >= InterfaceID(4000)) { // 4000, 4001, 4002, 4003 ...
tableId = ifID - 4000 + 201; // 201, 202, 203, ... [201-253]
} else { // 2000, 2001, ...
tableId = ifID - 2000 + 1; // 1, 2, 3, .... [1-200]
}
// Sanity checks. Generated ID must be in range [1-253]
CHECK_GE(tableId, 1);
CHECK_LE(tableId, 253);
return tableId;
}
int TunManager::getInterfaceMtu(InterfaceID ifID) const {
auto interface = sw_->getState()->getInterfaces()->getInterfaceIf(ifID);
return interface ? interface->getMtu() : kDefaultMtu;
}
void TunManager::addRemoveRouteTable(InterfaceID ifID, int ifIndex, bool add) {
// We just store default routes (one for IPv4 and one for IPv6) in each route
// table.
const folly::IPAddress addrs[] = {
IPAddress{"0.0.0.0"}, // v4 default
IPAddress{"::0"}, // v6 default
};
for (const auto& addr : addrs) {
auto route = rtnl_route_alloc();
SCOPE_EXIT { rtnl_route_put(route); };
auto error = rtnl_route_set_family(route, addr.family());
nlCheckError(error, "Failed to set family to", addr.family());
rtnl_route_set_table(route, getTableId(ifID));
rtnl_route_set_scope(route, RT_SCOPE_UNIVERSE);
rtnl_route_set_protocol(route, RTPROT_FBOSS);
error = rtnl_route_set_type(route, RTN_UNICAST);
nlCheckError(error, "Failed to set type to ", RTN_UNICAST);
auto destaddr = nl_addr_build(addr.family(),
const_cast<unsigned char *>(addr.bytes()), addr.byteCount());
if (!destaddr) {
throw FbossError("Failed to build destination address for ", addr);
}
SCOPE_EXIT { nl_addr_put(destaddr); };
nl_addr_set_prefixlen(destaddr, 0);
error = rtnl_route_set_dst(route, destaddr);
nlCheckError(error, "Failed to set destination route to ", addr);
auto nexthop = rtnl_route_nh_alloc();
if (!nexthop) {
throw FbossError("Failed to allocate nexthop");
}
rtnl_route_nh_set_ifindex(nexthop, ifIndex);
rtnl_route_add_nexthop(route, nexthop);
if (add) {
error = rtnl_route_add(sock_, route, NLM_F_REPLACE);
} else {
error = rtnl_route_delete(sock_, route, 0);
}
/**
* Disable: Because of some weird reason this CHECK fails while deleting
* v4 default route. However route actually gets wiped off from Linux
* routing table.
nlCheckError(error, "Failed to ", add ? "add" : "remove",
" default route ", addr, " @ index ", ifIndex,
" in table ", getTableId(ifID), " for interface ", ifID,
". ErrorCode: ", error);
*/
if (error < 0) {
LOG(WARNING) << "Failed to " << (add ? "add" : "remove")
<< " default route " << addr << " @index " << ifIndex
<< ". ErrorCode: " << error;
}
LOG(INFO) << (add ? "Added" : "Removed") << " default route " << addr
<< " @ index " << ifIndex << " in table " << getTableId(ifID)
<< " for interface " << ifID;
}
}
void TunManager::addRemoveSourceRouteRule(
InterfaceID ifID, const folly::IPAddress& addr, bool add) {
// We should not add source routing rule for link-local addresses because
// they can be re-used across interfaces.
if (addr.isLinkLocal()) {
VLOG(2) << "Ignoring source routing rule for V6 link-local address "
<< addr;
return;
}
auto rule = rtnl_rule_alloc();
SCOPE_EXIT { rtnl_rule_put(rule); };
rtnl_rule_set_family(rule, addr.family());
rtnl_rule_set_table(rule, getTableId(ifID));
rtnl_rule_set_action(rule, FR_ACT_TO_TBL);
auto sourceaddr = nl_addr_build(addr.family(),
const_cast<unsigned char *>(addr.bytes()), addr.byteCount());
if (!sourceaddr) {
throw FbossError("Failed to build destination address for ", addr);
}
SCOPE_EXIT { nl_addr_put(sourceaddr); };
nl_addr_set_prefixlen(sourceaddr, addr.bitCount());
auto error = rtnl_rule_set_src(rule, sourceaddr);
nlCheckError(error, "Failed to set destination route to ", addr);
if (add) {
error = rtnl_rule_add(sock_, rule, NLM_F_REPLACE);
} else {
error = rtnl_rule_delete(sock_, rule, 0);
}
nlCheckError(error, "Failed to ", add ? "add" : "remove",
" rule for address ", addr,
" to lookup table ", getTableId(ifID),
" for interface ", ifID);
LOG(INFO) << (add ? "Added" : "Removed") << " rule for address " << addr
<< " to lookup table " << getTableId(ifID)
<< " for interface " << ifID;
}
void TunManager::addRemoveTunAddress(
const std::string& ifName,
uint32_t ifIndex,
const folly::IPAddress& addr,
uint8_t mask,
bool add) {
auto tunaddr = rtnl_addr_alloc();
if (!tunaddr) {
throw FbossError("Failed to allocate address");
}
SCOPE_EXIT { rtnl_addr_put(tunaddr); };
rtnl_addr_set_family(tunaddr, addr.family());
auto localaddr = nl_addr_build(addr.family(),
const_cast<unsigned char *>(addr.bytes()), addr.byteCount());
if (!localaddr) {
throw FbossError("Failed to build destination address for ", addr);
}
SCOPE_EXIT { nl_addr_put(localaddr); };
auto error = rtnl_addr_set_local(tunaddr, localaddr);
nlCheckError(error, "Failed to set local address to ", addr);
rtnl_addr_set_prefixlen(tunaddr, mask);
rtnl_addr_set_ifindex(tunaddr, ifIndex);
if (add) {
/**
* When you bring down interface some routes are purged but some still stay
* there (I tested from command line and v6 routes were gone but v4 were
* there). To be on safe side, when we bring up interface we always add
* addresses and routes for that interface with REPLACE flag overriding
* existing ones if any.
*/
error = rtnl_addr_add(sock_, tunaddr, NLM_F_REPLACE);
} else {
error = rtnl_addr_delete(sock_, tunaddr, 0);
}
nlCheckError(error, "Failed to ", add ? "add" : "remove",
" address ", addr, "/", static_cast<int>(mask),
" to interface ", ifName, " @ index ", ifIndex);
LOG(INFO) << (add ? "Added" : "Removed") << " address " << addr.str() << "/"
<< static_cast<int>(mask) << " on interface " << ifName
<< " @ index " << ifIndex;
}
void TunManager::addTunAddress(
InterfaceID ifID,
const std::string& ifName,
uint32_t ifIndex,
folly::IPAddress addr,
uint8_t mask) {
addRemoveSourceRouteRule(ifID, addr, true);
SCOPE_FAIL {
try {
addRemoveSourceRouteRule(ifID, addr, false);
} catch (const std::exception& ex) {
LOG(ERROR) << "Failed to removed partially added source rule on "
<< "interface " << ifName;
}
};
addRemoveTunAddress(ifName, ifIndex, addr, mask, true);
}
void TunManager::removeTunAddress(
InterfaceID ifID,
const std::string& ifName,
uint32_t ifIndex,
folly::IPAddress addr,
uint8_t mask) {
addRemoveSourceRouteRule(ifID, addr, false);
SCOPE_FAIL {
try {
addRemoveSourceRouteRule(ifID, addr, true);
} catch (const std::exception& ex) {
LOG(ERROR) << "Failed to add partially added source rule on "
<< "interface " << ifName;
}
};
addRemoveTunAddress(ifName, ifIndex, addr, mask, false);
}
void TunManager::start() const {
for (const auto& intf : intfs_) {
intf.second->start();
}
}
void TunManager::stop() const {
for (const auto& intf : intfs_) {
intf.second->stop();
}
}
void TunManager::linkProcessor(struct nl_object *obj, void *data) {
struct rtnl_link * link = reinterpret_cast<struct rtnl_link *>(obj);
// Get name of an interface
const auto name = rtnl_link_get_name(link);
if (!name) {
throw FbossError("Device @ index ",
rtnl_link_get_ifindex(link), " does not have a name");
}
// Only add interface if it is a Tun interface
if (!TunIntf::isTunIntfName(name)) {
VLOG(3) << "Ignore interface " << name
<< " because it is not a tun interface";
return;
}
static_cast<TunManager*>(data)->addExistingIntf(
std::string(name),
rtnl_link_get_ifindex(link));
}
void TunManager::addressProcessor(struct nl_object *obj, void *data) {
struct rtnl_addr *addr = reinterpret_cast<struct rtnl_addr *>(obj);
// Validate family
auto family = rtnl_addr_get_family(addr);
if (family != AF_INET && family != AF_INET6) {
VLOG(3) << "Skip address from device @ index "
<< rtnl_addr_get_ifindex(addr)
<< " because of its address family " << family;
return;
}
// Validate address
auto localaddr = rtnl_addr_get_local(addr);
if (!localaddr) {
VLOG(3) << "Skip address from device @ index "
<< rtnl_addr_get_ifindex(addr)
<< " because of it does not have a local address ";
return;
}
// Convert rtnl_addr to string representation
char buf[INET6_ADDRSTRLEN];
nl_addr2str(localaddr, buf, sizeof(buf));
if (!*buf) {
VLOG(3) << "Device @ index " << rtnl_addr_get_ifindex(addr)
<< " does not have an address at family " << family;
}
auto ipaddr = IPAddress::createNetwork(buf, -1, false).first;
static_cast<TunManager *>(data)->addProbedAddr(
rtnl_addr_get_ifindex(addr),
ipaddr,
nl_addr_get_prefixlen(localaddr)
);
}
void TunManager::probe() {
std::lock_guard<std::mutex> lock(mutex_);
if (!probeDone_) {
doProbe(lock);
}
}
void TunManager::doProbe(std::lock_guard<std::mutex>& /* lock */) {
CHECK(!probeDone_); // Callers must check for probeDone before calling
stop(); // stop all interfaces
intfs_.clear(); // clear all interface info
// get links
struct nl_cache *cache;
auto error = rtnl_link_alloc_cache(sock_, AF_UNSPEC, &cache);
nlCheckError(error, "Cannot get links from Kernel");
SCOPE_EXIT { nl_cache_free(cache); };
nl_cache_foreach(cache, &TunManager::linkProcessor, this);
// get addresses
struct nl_cache *addressCache;
error = rtnl_addr_alloc_cache(sock_, &addressCache);
nlCheckError(error, "Cannot get addresses from Kernel");
SCOPE_EXIT { nl_cache_free(addressCache); };
nl_cache_foreach(addressCache, &TunManager::addressProcessor, this);
start();
probeDone_ = true;
}
boost::container::flat_map<InterfaceID, bool>
TunManager::getInterfaceStatus(std::shared_ptr<SwitchState> state) {
boost::container::flat_map<InterfaceID, bool> statusMap;
// Derive all ports
auto portMap = state->getPorts();
auto vlanMap = state->getVlans();
for (const auto& portIDToObj : portMap->getAllNodes()) {
const auto& port = portIDToObj.second;
bool isPortUp = port->isPortUp();
for (const auto& vlanIDToInfo : port->getVlans()) {
auto vlan = vlanMap->getVlanIf(vlanIDToInfo.first);
if (!vlan) {
LOG(ERROR) << "Vlan " << vlanIDToInfo.first << " not found in state.";
continue;
}
auto intfID = vlan->getInterfaceID();
statusMap[intfID] |= isPortUp; // NOTE: We are applying `OR` operator
} // for vlanIDToInfo
} // for portIDToObj
return statusMap;
}
void TunManager::sync(std::shared_ptr<SwitchState> state) {
using Addresses = Interface::Addresses;
using ConstAddressesIter = Addresses::const_iterator;
using IntfInfo = std::pair<bool /* status */, Addresses>;
using IntfToAddrsMap = boost::container::flat_map<InterfaceID, IntfInfo>;
using ConstIntfToAddrsMapIter = IntfToAddrsMap::const_iterator;
// Get interface status.
auto intfStatusMap = getInterfaceStatus(state);
// prepare new addresses
IntfToAddrsMap newIntfToInfo;
auto intfMap = state->getInterfaces();
for (const auto& intf : intfMap->getAllNodes()) {
const auto& addrs = intf.second->getAddresses();
newIntfToInfo[intf.first] = {intfStatusMap[intf.first], addrs};
}
// Hold mutex while changing interfaces
std::lock_guard<std::mutex> lock(mutex_);
if (!probeDone_) {
doProbe(lock);
}
// prepare old addresses
IntfToAddrsMap oldIntfToInfo;
for (const auto& intf : intfs_) {
const auto& addrs = intf.second->getAddresses();
bool status = intf.second->getStatus();
oldIntfToInfo[intf.first] = {status, addrs};
// Change MTU if it has altered
auto interface = intfMap->getInterfaceIf(intf.first);
if (interface && interface->getMtu() != intf.second->getMtu()) {
intf.second->setMtu(interface->getMtu());
}
}
// Callback function for updating addresses for a particular interface
auto applyInterfaceAddrChanges =
[this](InterfaceID ifID, const std::string& ifName, int ifIndex,
const Addresses& oldAddrs, const Addresses& newAddrs) {
applyChanges(
oldAddrs, newAddrs,
[&](ConstAddressesIter& oldIter, ConstAddressesIter& newIter) {
if (oldIter->second == newIter->second) {
// addresses and masks are both same
return;
}
removeTunAddress(
ifID, ifName, ifIndex, oldIter->first, oldIter->second);
addTunAddress(ifID, ifName, ifIndex, newIter->first, newIter->second);
},
[&](ConstAddressesIter& newIter) {
addTunAddress(ifID, ifName, ifIndex, newIter->first, newIter->second);
},
[&](ConstAddressesIter& oldIter) {
removeTunAddress(
ifID, ifName, ifIndex, oldIter->first, oldIter->second);
});
};
// Apply changes for all interfaces
applyChanges(
oldIntfToInfo, newIntfToInfo,
[&](ConstIntfToAddrsMapIter& oldIter, ConstIntfToAddrsMapIter& newIter) {
auto oldStatus = oldIter->second.first;
auto newStatus = newIter->second.first;
const auto& oldAddrs = oldIter->second.second;
const auto& newAddrs = newIter->second.second;
// Interface must exists
const auto& intf = intfs_.at(oldIter->first);
auto ifID = intf->getInterfaceID();
int ifIndex = intf->getIfIndex();
const auto& ifName = intf->getName();
// mutate intf status and addresses
intf->setStatus(newStatus);
intf->setAddresses(newAddrs);
// Update interface status
if (oldStatus ^ newStatus) { // old and new status is different
setIntfStatus(ifName, ifIndex, newStatus);
}
// We need to add route-table and tun-addresses if interface is brought
// up recently.
if (!oldStatus and newStatus) {
addRouteTable(ifID, ifIndex);
for (const auto& addr : newAddrs) {
addTunAddress(ifID, ifName, ifIndex, addr.first, addr.second);
}
}
// Update interface addresses only if interface was up before as well
// as now
if (oldStatus && newStatus) {
applyInterfaceAddrChanges(ifID, ifName, ifIndex, oldAddrs, newAddrs);
}
},
[&](ConstIntfToAddrsMapIter& newIter) {
auto& statusAddr = newIter->second;
addNewIntf(newIter->first, statusAddr.first, statusAddr.second);
},
[&](ConstIntfToAddrsMapIter& oldIter) {
removeIntf(oldIter->first);
});
start();
}
// TODO(aeckert): Find a way to reuse the iterator from NodeMapDelta here as
// this basically duplicates that code.
template<typename MAPNAME, typename CHANGEFN, typename ADDFN, typename REMOVEFN>
void TunManager::applyChanges(const MAPNAME& oldMap,
const MAPNAME& newMap,
CHANGEFN changeFn,
ADDFN addFn,
REMOVEFN removeFn) {
auto oldIter = oldMap.begin();
auto newIter = newMap.begin();
while (oldIter != oldMap.end() && newIter != newMap.end()) {
if (oldIter->first < newIter->first) {
removeFn(oldIter);
oldIter++;
} else if (oldIter->first > newIter->first) {
addFn(newIter);
newIter++;
} else {
changeFn(oldIter, newIter);
oldIter++;
newIter++;
}
}
for (; oldIter != oldMap.end(); oldIter++) {
removeFn(oldIter);
}
for (; newIter != newMap.end(); newIter++) {
addFn(newIter);
}
}
}} // namespace facebook::fboss
Avoid duplicate source routing rules in Linux
Summary:
Linux doesn't handle `NLM_F_REPLACE` while adding source routing rules. Whenever
the interface status is flapped we add interface addresses and source routing
rules earlier. Which leads to piling up of source routing rules.
In this diff I am just programming intf-address on bringing up the interface and
not programming source routing rules.
Reviewed By: tfangit
Differential Revision: D3881368
fbshipit-source-id: d59176d1f087894bc469a4e01a96936ca5e69d27
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "TunManager.h"
extern "C" {
#include <netlink/route/link.h>
#include <netlink/route/addr.h>
#include <netlink/route/route.h>
#include <netlink/route/rule.h>
#include <linux/if.h>
#include <sys/ioctl.h>
}
#include "fboss/agent/NlError.h"
#include "fboss/agent/RxPacket.h"
#include "fboss/agent/SysError.h"
#include "fboss/agent/TunIntf.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/InterfaceMap.h"
#include "fboss/agent/state/Port.h"
#include "fboss/agent/state/SwitchState.h"
#include <folly/Demangle.h>
#include <folly/io/async/EventBase.h>
#include <boost/container/flat_set.hpp>
namespace {
const int kDefaultMtu = 1500;
}
namespace facebook { namespace fboss {
using folly::IPAddress;
using folly::EventBase;
TunManager::TunManager(SwSwitch *sw, EventBase *evb) : sw_(sw), evb_(evb) {
DCHECK(sw) << "NULL pointer to SwSwitch.";
DCHECK(evb) << "NULL pointer to EventBase";
sock_ = nl_socket_alloc();
if (!sock_) {
throw FbossError("failed to allocate libnl socket");
}
auto error = nl_connect(sock_, NETLINK_ROUTE);
nlCheckError(error, "failed to connect netlink socket to NETLINK_ROUTE");
}
TunManager::~TunManager() {
if (observingState_) {
sw_->unregisterStateObserver(this);
}
stop();
nl_close(sock_);
nl_socket_free(sock_);
}
void TunManager::startProbe() {
evb_->runInEventBaseThread([this]() {
this->probe();
});
}
void TunManager::startObservingUpdates() {
sw_->registerStateObserver(this, "TunManager");
observingState_ = true;
}
void TunManager::stateUpdated(const StateDelta& delta) {
// TODO(aeckert): We currently compare the entire interface map instead
// of using the iterator in this delta because some of the interfaces may get
// get probed from hardware, before they are in the SwitchState. It would be
// nicer if we did a little more work at startup to sync the state, perhaps
// updating the SwitchState with the probed interfaces. This would allow us
// to reuse the iterator in the delta for more readable code and also not
// have to worry about waiting to listen to updates until the SwSwitch is in
// the configured state. t4155406 should also help with that.
auto state = delta.newState();
evb_->runInEventBaseThread([this, state]() {
this->sync(state);
});
}
bool TunManager::sendPacketToHost(std::unique_ptr<RxPacket> pkt) {
auto ifID = InterfaceID(pkt->getSrcVlan());
std::lock_guard<std::mutex> lock(mutex_);
auto iter = intfs_.find(ifID);
if (iter == intfs_.end()) {
// the Interface ID has been deleted, make a log, and skip the pkt
VLOG(4) << "Dropping a packet for unknown unknwon " << ifID;
return false;
}
return iter->second->sendPacketToHost(std::move(pkt));
}
void TunManager::addExistingIntf(
const std::string& ifName,
int ifIndex) {
InterfaceID ifID = TunIntf::getIDFromTunIntfName(ifName);
auto ret = intfs_.emplace(ifID, nullptr);
if (!ret.second) {
throw FbossError("Duplicate interface ", ifName);
}
SCOPE_FAIL {
intfs_.erase(ret.first);
};
setIntfStatus(ifName, ifIndex, false);
ret.first->second.reset(
new TunIntf(sw_, evb_, ifID, ifIndex, getInterfaceMtu(ifID)));
}
void TunManager::addNewIntf(
InterfaceID ifID,
bool isUp,
const Interface::Addresses& addrs) {
auto ret = intfs_.emplace(ifID, nullptr);
if (!ret.second) {
throw FbossError("Duplicate interface for interface ", ifID);
}
SCOPE_FAIL {
intfs_.erase(ret.first);
};
auto intf = std::make_unique<TunIntf>(
sw_, evb_, ifID, isUp, addrs, getInterfaceMtu(ifID));
SCOPE_FAIL {
intf->setDelete();
};
const auto ifName = intf->getName();
auto ifIndex = intf->getIfIndex();
// bring up the interface so that we can add the default route in next step
setIntfStatus(ifName, ifIndex, isUp);
// create a new route table for this InterfaceID
addRouteTable(ifID, ifIndex);
// add all addresses
for (const auto& addr : addrs) {
addTunAddress(ifID, ifName, ifIndex, addr.first, addr.second);
}
// Store it in local map on success
ret.first->second = std::move(intf);
}
void TunManager::removeIntf(InterfaceID ifID) {
auto iter = intfs_.find(ifID);
if (iter == intfs_.end()) {
throw FbossError("Cannot find interface ", ifID, " for deleting.");
}
// Remove all addresses attached on this interface
auto& intf = iter->second;
for (auto const& addr : intf->getAddresses()) {
removeTunAddress(
ifID,
intf->getName(),
intf->getIfIndex(),
addr.first /* ip */,
addr.second /* mask */);
}
// Remove the route table and associated rule
removeRouteTable(ifID, intf->getIfIndex());
intf->setDelete();
intfs_.erase(iter);
}
void TunManager::addProbedAddr(
int ifIndex, const IPAddress& addr, uint8_t mask) {
for (auto& intf : intfs_) {
if (intf.second->getIfIndex() == ifIndex) {
intf.second->addAddress(addr, mask);
return;
}
}
// This function is called for all interface addresses discovered from
// the host. Since we only create TunIntf object for TUN interfaces,
// it is normal we cannot find the interface matching the ifIndex provided.
VLOG(3) << "Cannot find interface @ index " << ifIndex
<< " for probed address " << addr.str() << "/"
<< static_cast<int>(mask);
}
void TunManager::setIntfStatus(
const std::string& ifName,
int ifIndex,
bool status) {
/**
* NOTE: Why use `ioctl` instead of `netlink` ?
*
* netlink's `rtnl_link_change` API was in-effective. Internally netlink
* tries to pass a message with RTM_NEWLINK which some old kernel couldn't
* process. After messing my head around with netlink for few hours I decided
* to use `ioctl` which was much easy and straight-forward operation.
*/
// Prepare socket
auto sockFd = socket(PF_INET, SOCK_DGRAM, 0);
sysCheckError(sockFd, "Failed to open socket");
// Prepare request
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
folly::strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
// Get existing flags
int error = ioctl(sockFd, SIOCGIFFLAGS, static_cast<void*>(&ifr));
sysCheckError(error, "Failed to get existing interface flags of ", ifName);
// Mutate flags
if (status) {
ifr.ifr_flags |= IFF_UP;
} else {
ifr.ifr_flags &= ~IFF_UP;
}
// Set flags
error = ioctl(sockFd, SIOCSIFFLAGS, static_cast<void*>(&ifr));
sysCheckError(error, "Failed to set interface flags on ", ifName);
LOG(INFO) << "Brought " << (status ? "up" : "down") << " interface "
<< ifName << " @ index " << ifIndex;
}
int TunManager::getTableId(InterfaceID ifID) const {
// Kernel only supports up to 256 tables. The last few are used by kernel
// as main, default, and local. IDs 0, 254 and 255 are not available. So we
// use range 1-253 for our usecase.
// Special case to handle old front0 interfaces.
// XXX: Delete this case after 6 months (atleast one full rollout). 08-22-2016
if (ifID == InterfaceID(0)) {
return 100; // This was the old-ID used for creating front0
}
// Hacky. Need better solution but works for now. Our InterfaceID are
// Type-1: 2000, 2001, 2002, 2003 ...
// Type-2: 4000, 4001, 4002, 4003, 4004, ...
int tableId = static_cast<int>(ifID);
if (ifID >= InterfaceID(4000)) { // 4000, 4001, 4002, 4003 ...
tableId = ifID - 4000 + 201; // 201, 202, 203, ... [201-253]
} else { // 2000, 2001, ...
tableId = ifID - 2000 + 1; // 1, 2, 3, .... [1-200]
}
// Sanity checks. Generated ID must be in range [1-253]
CHECK_GE(tableId, 1);
CHECK_LE(tableId, 253);
return tableId;
}
int TunManager::getInterfaceMtu(InterfaceID ifID) const {
auto interface = sw_->getState()->getInterfaces()->getInterfaceIf(ifID);
return interface ? interface->getMtu() : kDefaultMtu;
}
void TunManager::addRemoveRouteTable(InterfaceID ifID, int ifIndex, bool add) {
// We just store default routes (one for IPv4 and one for IPv6) in each route
// table.
const folly::IPAddress addrs[] = {
IPAddress{"0.0.0.0"}, // v4 default
IPAddress{"::0"}, // v6 default
};
for (const auto& addr : addrs) {
auto route = rtnl_route_alloc();
SCOPE_EXIT { rtnl_route_put(route); };
auto error = rtnl_route_set_family(route, addr.family());
nlCheckError(error, "Failed to set family to", addr.family());
rtnl_route_set_table(route, getTableId(ifID));
rtnl_route_set_scope(route, RT_SCOPE_UNIVERSE);
rtnl_route_set_protocol(route, RTPROT_FBOSS);
error = rtnl_route_set_type(route, RTN_UNICAST);
nlCheckError(error, "Failed to set type to ", RTN_UNICAST);
auto destaddr = nl_addr_build(addr.family(),
const_cast<unsigned char *>(addr.bytes()), addr.byteCount());
if (!destaddr) {
throw FbossError("Failed to build destination address for ", addr);
}
SCOPE_EXIT { nl_addr_put(destaddr); };
nl_addr_set_prefixlen(destaddr, 0);
error = rtnl_route_set_dst(route, destaddr);
nlCheckError(error, "Failed to set destination route to ", addr);
auto nexthop = rtnl_route_nh_alloc();
if (!nexthop) {
throw FbossError("Failed to allocate nexthop");
}
rtnl_route_nh_set_ifindex(nexthop, ifIndex);
rtnl_route_add_nexthop(route, nexthop);
if (add) {
error = rtnl_route_add(sock_, route, NLM_F_REPLACE);
} else {
error = rtnl_route_delete(sock_, route, 0);
}
/**
* Disable: Because of some weird reason this CHECK fails while deleting
* v4 default route. However route actually gets wiped off from Linux
* routing table.
nlCheckError(error, "Failed to ", add ? "add" : "remove",
" default route ", addr, " @ index ", ifIndex,
" in table ", getTableId(ifID), " for interface ", ifID,
". ErrorCode: ", error);
*/
if (error < 0) {
LOG(WARNING) << "Failed to " << (add ? "add" : "remove")
<< " default route " << addr << " @index " << ifIndex
<< ". ErrorCode: " << error;
}
LOG(INFO) << (add ? "Added" : "Removed") << " default route " << addr
<< " @ index " << ifIndex << " in table " << getTableId(ifID)
<< " for interface " << ifID;
}
}
void TunManager::addRemoveSourceRouteRule(
InterfaceID ifID, const folly::IPAddress& addr, bool add) {
// We should not add source routing rule for link-local addresses because
// they can be re-used across interfaces.
if (addr.isLinkLocal()) {
VLOG(2) << "Ignoring source routing rule for link-local address " << addr;
return;
}
auto rule = rtnl_rule_alloc();
SCOPE_EXIT { rtnl_rule_put(rule); };
rtnl_rule_set_family(rule, addr.family());
rtnl_rule_set_table(rule, getTableId(ifID));
rtnl_rule_set_action(rule, FR_ACT_TO_TBL);
auto sourceaddr = nl_addr_build(addr.family(),
const_cast<unsigned char *>(addr.bytes()), addr.byteCount());
if (!sourceaddr) {
throw FbossError("Failed to build destination address for ", addr);
}
SCOPE_EXIT { nl_addr_put(sourceaddr); };
nl_addr_set_prefixlen(sourceaddr, addr.bitCount());
auto error = rtnl_rule_set_src(rule, sourceaddr);
nlCheckError(error, "Failed to set destination route to ", addr);
if (add) {
error = rtnl_rule_add(sock_, rule, NLM_F_REPLACE);
} else {
error = rtnl_rule_delete(sock_, rule, 0);
}
nlCheckError(error, "Failed to ", add ? "add" : "remove",
" rule for address ", addr,
" to lookup table ", getTableId(ifID),
" for interface ", ifID);
LOG(INFO) << (add ? "Added" : "Removed") << " rule for address " << addr
<< " to lookup table " << getTableId(ifID)
<< " for interface " << ifID;
}
void TunManager::addRemoveTunAddress(
const std::string& ifName,
uint32_t ifIndex,
const folly::IPAddress& addr,
uint8_t mask,
bool add) {
auto tunaddr = rtnl_addr_alloc();
if (!tunaddr) {
throw FbossError("Failed to allocate address");
}
SCOPE_EXIT { rtnl_addr_put(tunaddr); };
rtnl_addr_set_family(tunaddr, addr.family());
auto localaddr = nl_addr_build(addr.family(),
const_cast<unsigned char *>(addr.bytes()), addr.byteCount());
if (!localaddr) {
throw FbossError("Failed to build destination address for ", addr);
}
SCOPE_EXIT { nl_addr_put(localaddr); };
auto error = rtnl_addr_set_local(tunaddr, localaddr);
nlCheckError(error, "Failed to set local address to ", addr);
rtnl_addr_set_prefixlen(tunaddr, mask);
rtnl_addr_set_ifindex(tunaddr, ifIndex);
if (add) {
/**
* When you bring down interface some routes are purged but some still stay
* there (I tested from command line and v6 routes were gone but v4 were
* there). To be on safe side, when we bring up interface we always add
* addresses and routes for that interface with REPLACE flag overriding
* existing ones if any.
*/
error = rtnl_addr_add(sock_, tunaddr, NLM_F_REPLACE);
} else {
error = rtnl_addr_delete(sock_, tunaddr, 0);
}
nlCheckError(error, "Failed to ", add ? "add" : "remove",
" address ", addr, "/", static_cast<int>(mask),
" to interface ", ifName, " @ index ", ifIndex);
LOG(INFO) << (add ? "Added" : "Removed") << " address " << addr.str() << "/"
<< static_cast<int>(mask) << " on interface " << ifName
<< " @ index " << ifIndex;
}
void TunManager::addTunAddress(
InterfaceID ifID,
const std::string& ifName,
uint32_t ifIndex,
folly::IPAddress addr,
uint8_t mask) {
addRemoveSourceRouteRule(ifID, addr, true);
SCOPE_FAIL {
try {
addRemoveSourceRouteRule(ifID, addr, false);
} catch (const std::exception& ex) {
LOG(ERROR) << "Failed to removed partially added source rule on "
<< "interface " << ifName;
}
};
addRemoveTunAddress(ifName, ifIndex, addr, mask, true);
}
void TunManager::removeTunAddress(
InterfaceID ifID,
const std::string& ifName,
uint32_t ifIndex,
folly::IPAddress addr,
uint8_t mask) {
addRemoveSourceRouteRule(ifID, addr, false);
SCOPE_FAIL {
try {
addRemoveSourceRouteRule(ifID, addr, true);
} catch (const std::exception& ex) {
LOG(ERROR) << "Failed to add partially added source rule on "
<< "interface " << ifName;
}
};
addRemoveTunAddress(ifName, ifIndex, addr, mask, false);
}
void TunManager::start() const {
for (const auto& intf : intfs_) {
intf.second->start();
}
}
void TunManager::stop() const {
for (const auto& intf : intfs_) {
intf.second->stop();
}
}
void TunManager::linkProcessor(struct nl_object *obj, void *data) {
struct rtnl_link * link = reinterpret_cast<struct rtnl_link *>(obj);
// Get name of an interface
const auto name = rtnl_link_get_name(link);
if (!name) {
throw FbossError("Device @ index ",
rtnl_link_get_ifindex(link), " does not have a name");
}
// Only add interface if it is a Tun interface
if (!TunIntf::isTunIntfName(name)) {
VLOG(3) << "Ignore interface " << name
<< " because it is not a tun interface";
return;
}
static_cast<TunManager*>(data)->addExistingIntf(
std::string(name),
rtnl_link_get_ifindex(link));
}
void TunManager::addressProcessor(struct nl_object *obj, void *data) {
struct rtnl_addr *addr = reinterpret_cast<struct rtnl_addr *>(obj);
// Validate family
auto family = rtnl_addr_get_family(addr);
if (family != AF_INET && family != AF_INET6) {
VLOG(3) << "Skip address from device @ index "
<< rtnl_addr_get_ifindex(addr)
<< " because of its address family " << family;
return;
}
// Validate address
auto localaddr = rtnl_addr_get_local(addr);
if (!localaddr) {
VLOG(3) << "Skip address from device @ index "
<< rtnl_addr_get_ifindex(addr)
<< " because of it does not have a local address ";
return;
}
// Convert rtnl_addr to string representation
char buf[INET6_ADDRSTRLEN];
nl_addr2str(localaddr, buf, sizeof(buf));
if (!*buf) {
VLOG(3) << "Device @ index " << rtnl_addr_get_ifindex(addr)
<< " does not have an address at family " << family;
}
auto ipaddr = IPAddress::createNetwork(buf, -1, false).first;
static_cast<TunManager *>(data)->addProbedAddr(
rtnl_addr_get_ifindex(addr),
ipaddr,
nl_addr_get_prefixlen(localaddr)
);
}
void TunManager::probe() {
std::lock_guard<std::mutex> lock(mutex_);
if (!probeDone_) {
doProbe(lock);
}
}
void TunManager::doProbe(std::lock_guard<std::mutex>& /* lock */) {
CHECK(!probeDone_); // Callers must check for probeDone before calling
stop(); // stop all interfaces
intfs_.clear(); // clear all interface info
// get links
struct nl_cache *cache;
auto error = rtnl_link_alloc_cache(sock_, AF_UNSPEC, &cache);
nlCheckError(error, "Cannot get links from Kernel");
SCOPE_EXIT { nl_cache_free(cache); };
nl_cache_foreach(cache, &TunManager::linkProcessor, this);
// get addresses
struct nl_cache *addressCache;
error = rtnl_addr_alloc_cache(sock_, &addressCache);
nlCheckError(error, "Cannot get addresses from Kernel");
SCOPE_EXIT { nl_cache_free(addressCache); };
nl_cache_foreach(addressCache, &TunManager::addressProcessor, this);
start();
probeDone_ = true;
}
boost::container::flat_map<InterfaceID, bool>
TunManager::getInterfaceStatus(std::shared_ptr<SwitchState> state) {
boost::container::flat_map<InterfaceID, bool> statusMap;
// Derive all ports
auto portMap = state->getPorts();
auto vlanMap = state->getVlans();
for (const auto& portIDToObj : portMap->getAllNodes()) {
const auto& port = portIDToObj.second;
bool isPortUp = port->isPortUp();
for (const auto& vlanIDToInfo : port->getVlans()) {
auto vlan = vlanMap->getVlanIf(vlanIDToInfo.first);
if (!vlan) {
LOG(ERROR) << "Vlan " << vlanIDToInfo.first << " not found in state.";
continue;
}
auto intfID = vlan->getInterfaceID();
statusMap[intfID] |= isPortUp; // NOTE: We are applying `OR` operator
} // for vlanIDToInfo
} // for portIDToObj
return statusMap;
}
void TunManager::sync(std::shared_ptr<SwitchState> state) {
using Addresses = Interface::Addresses;
using ConstAddressesIter = Addresses::const_iterator;
using IntfInfo = std::pair<bool /* status */, Addresses>;
using IntfToAddrsMap = boost::container::flat_map<InterfaceID, IntfInfo>;
using ConstIntfToAddrsMapIter = IntfToAddrsMap::const_iterator;
// Get interface status.
auto intfStatusMap = getInterfaceStatus(state);
// prepare new addresses
IntfToAddrsMap newIntfToInfo;
auto intfMap = state->getInterfaces();
for (const auto& intf : intfMap->getAllNodes()) {
const auto& addrs = intf.second->getAddresses();
newIntfToInfo[intf.first] = {intfStatusMap[intf.first], addrs};
}
// Hold mutex while changing interfaces
std::lock_guard<std::mutex> lock(mutex_);
if (!probeDone_) {
doProbe(lock);
}
// prepare old addresses
IntfToAddrsMap oldIntfToInfo;
for (const auto& intf : intfs_) {
const auto& addrs = intf.second->getAddresses();
bool status = intf.second->getStatus();
oldIntfToInfo[intf.first] = {status, addrs};
// Change MTU if it has altered
auto interface = intfMap->getInterfaceIf(intf.first);
if (interface && interface->getMtu() != intf.second->getMtu()) {
intf.second->setMtu(interface->getMtu());
}
}
// Callback function for updating addresses for a particular interface
auto applyInterfaceAddrChanges =
[this](InterfaceID ifID, const std::string& ifName, int ifIndex,
const Addresses& oldAddrs, const Addresses& newAddrs) {
applyChanges(
oldAddrs, newAddrs,
[&](ConstAddressesIter& oldIter, ConstAddressesIter& newIter) {
if (oldIter->second == newIter->second) {
// addresses and masks are both same
return;
}
removeTunAddress(
ifID, ifName, ifIndex, oldIter->first, oldIter->second);
addTunAddress(ifID, ifName, ifIndex, newIter->first, newIter->second);
},
[&](ConstAddressesIter& newIter) {
addTunAddress(ifID, ifName, ifIndex, newIter->first, newIter->second);
},
[&](ConstAddressesIter& oldIter) {
removeTunAddress(
ifID, ifName, ifIndex, oldIter->first, oldIter->second);
});
};
// Apply changes for all interfaces
applyChanges(
oldIntfToInfo, newIntfToInfo,
[&](ConstIntfToAddrsMapIter& oldIter, ConstIntfToAddrsMapIter& newIter) {
auto oldStatus = oldIter->second.first;
auto newStatus = newIter->second.first;
const auto& oldAddrs = oldIter->second.second;
const auto& newAddrs = newIter->second.second;
// Interface must exists
const auto& intf = intfs_.at(oldIter->first);
auto ifID = intf->getInterfaceID();
int ifIndex = intf->getIfIndex();
const auto& ifName = intf->getName();
// mutate intf status and addresses
intf->setStatus(newStatus);
intf->setAddresses(newAddrs);
// Update interface status
if (oldStatus ^ newStatus) { // old and new status is different
setIntfStatus(ifName, ifIndex, newStatus);
}
// We need to add route-table and tun-addresses if interface is brought
// up recently.
// NOTE: Do not add source routing rules because kernel doesn't handle
// NLM_F_REPLACE flags and they just keep piling up :/
if (!oldStatus and newStatus) {
addRouteTable(ifID, ifIndex);
for (const auto& addr : newAddrs) {
addRemoveTunAddress(ifName, ifIndex, addr.first, addr.second, true);
}
}
// Update interface addresses only if interface was up before as well
// as now
if (oldStatus && newStatus) {
applyInterfaceAddrChanges(ifID, ifName, ifIndex, oldAddrs, newAddrs);
}
},
[&](ConstIntfToAddrsMapIter& newIter) {
auto& statusAddr = newIter->second;
addNewIntf(newIter->first, statusAddr.first, statusAddr.second);
},
[&](ConstIntfToAddrsMapIter& oldIter) {
removeIntf(oldIter->first);
});
start();
}
// TODO(aeckert): Find a way to reuse the iterator from NodeMapDelta here as
// this basically duplicates that code.
template<typename MAPNAME, typename CHANGEFN, typename ADDFN, typename REMOVEFN>
void TunManager::applyChanges(const MAPNAME& oldMap,
const MAPNAME& newMap,
CHANGEFN changeFn,
ADDFN addFn,
REMOVEFN removeFn) {
auto oldIter = oldMap.begin();
auto newIter = newMap.begin();
while (oldIter != oldMap.end() && newIter != newMap.end()) {
if (oldIter->first < newIter->first) {
removeFn(oldIter);
oldIter++;
} else if (oldIter->first > newIter->first) {
addFn(newIter);
newIter++;
} else {
changeFn(oldIter, newIter);
oldIter++;
newIter++;
}
}
for (; oldIter != oldMap.end(); oldIter++) {
removeFn(oldIter);
}
for (; newIter != newMap.end(); newIter++) {
addFn(newIter);
}
}
}} // namespace facebook::fboss
|
#include "queue thread safe.hpp"
#include "gtest/gtest.h"
#include <thread>
#include <algorithm>
#include "aux_tests.hpp"
TEST(Push,HandleBasicOperation){
std::threadsafe::queue<int> queue;
int out;
for (int i = 1;i <= 10;i++){
queue.push(i);
queue.wait_back(out);
EXPECT_EQ(i,out);
queue.wait_top(out);
EXPECT_EQ(out,1);
EXPECT_EQ(i,queue.size());
}
for (int i = 1;i <= 10;i++){
queue.wait_pop(out);
EXPECT_EQ(i,out);
EXPECT_EQ(10-i,queue.size());
}
}
TEST(Push,ThreadSafety){
std::threadsafe::queue<int> queue;
std::threadsafe::queue<int> another_queue;
constexpr int ITERATIONS = 10;
constexpr int PRODUCERS = ITERATIONS;
constexpr int CONSUMERS = ITERATIONS;
auto producer = [&](int id,int it){queue.push(id);};
auto consumer = [&](int id,int it){
int out;
queue.wait_pop(out);
ASSERT_LT(out,ITERATIONS);
ASSERT_GE(out,0);
another_queue.push(out);
};
launchThreads(producer,consumer,PRODUCERS,CONSUMERS,ITERATIONS);
ASSERT_EQ(ITERATIONS*ITERATIONS,another_queue.size());
int freq_table[ITERATIONS];
std::fill(freq_table,freq_table+ITERATIONS,0);
while (!another_queue.empty()){
int out;
another_queue.wait_pop(out);
freq_table[out]++;
}
for (int i = 0;i < ITERATIONS;i++)
{
ASSERT_EQ(ITERATIONS,freq_table[i]);
}
}
Added test upper bound in queue
#include "queue thread safe.hpp"
#include "gtest/gtest.h"
#include <thread>
#include <algorithm>
#include "aux_tests.hpp"
TEST(Push,HandleBasicOperation){
std::threadsafe::queue<int> queue;
int out;
for (int i = 1;i <= 10;i++){
queue.push(i);
queue.wait_back(out);
EXPECT_EQ(i,out);
queue.wait_top(out);
EXPECT_EQ(out,1);
EXPECT_EQ(i,queue.size());
}
for (int i = 1;i <= 10;i++){
queue.wait_pop(out);
EXPECT_EQ(i,out);
EXPECT_EQ(10-i,queue.size());
}
}
TEST(Push,ThreadSafety){
std::threadsafe::queue<int> queue;
std::threadsafe::queue<int> another_queue;
constexpr int ITERATIONS = 10;
constexpr int PRODUCERS = ITERATIONS;
constexpr int CONSUMERS = ITERATIONS;
auto producer = [&](int id,int it){queue.push(id);};
auto consumer = [&](int id,int it){
int out;
queue.wait_pop(out);
ASSERT_LT(out,ITERATIONS);
ASSERT_GE(out,0);
another_queue.push(out);
};
launchThreads(producer,consumer,PRODUCERS,CONSUMERS,ITERATIONS);
ASSERT_EQ(ITERATIONS*ITERATIONS,another_queue.size());
int freq_table[ITERATIONS];
std::fill(freq_table,freq_table+ITERATIONS,0);
while (!another_queue.empty()){
int out;
another_queue.wait_pop(out);
freq_table[out]++;
}
for (int i = 0;i < ITERATIONS;i++)
{
ASSERT_EQ(ITERATIONS,freq_table[i]);
}
}
TEST(Push,UpperBound){
std::threadsafe::queue<int> queue;
constexpr int ITERATIONS_PRODUCERS = 10;
constexpr int NUM_PRODUCERS = ITERATIONS_PRODUCERS;
constexpr int NUM_CONSUMERS = 1;
constexpr int SIZE = NUM_PRODUCERS/2;
constexpr int ITERATIONS_CONSUMERS = ITERATIONS_PRODUCERS*NUM_PRODUCERS;
queue.setLimit(SIZE);
auto producer = [&](int id,int it){
queue.push(id);
ASSERT_LE(queue.size(),SIZE);
};
auto consumer = [&](int id,int it){
int out;
ASSERT_LE(queue.size(),SIZE);
queue.wait_pop(out);
};
launchThreads(producer,consumer,NUM_PRODUCERS,NUM_CONSUMERS,ITERATIONS_PRODUCERS,ITERATIONS_CONSUMERS);
}
|
#include "Controller.h"
namespace ADBLib
{
ctrlCfg::ctrlCfg()
{
id = 0;
type = JOYSTICK;
inverse = false;
btn.toggle = false;
btn.cooldown = 0.250; //Seconds
btn.cooldownTimer = new Timer;
jys.maxVal = 1.0;
jys.minVal = -1.0;
jys.deadzone = 0.1;
jys.equ.parse("x"); //Start off with no alterations to the joystick equation
}
Controller::~Controller()
{
delete joystick;
}
ctrlCfg::btnCfg::~btnCfg()
{
delete cooldownTimer;
}
/**
* @brief Gets the raw button setting as true or false, disregarding any active cooldowns.
* @param ID The ID of the button. ID changes depending on controller mode (X-Mode or D-Mode)
*/
bool Controller::getButtonRaw(int ID)
{
if ((ID >= 15 || ID <= 0) && joystick != nullptr)
return false; //Out-of-bounds IDs not accepted.
return joystick->GetRawButton(ID);
}
/**
* @brief Gets the raw axis value.
* @param ID The ID of the joystick. ID changes depending on controller mode (X-Mode or D-Mode)
*/
double Controller::getJoystickRaw(int ID)
{
if (ID >= 0 && ID <= 15 && joystick != nullptr)
return joystick->GetRawAxis(ID);
else
return 0;
}
/**
* @brief Sets the joystick to get data from.
* @param newJoystick A shared pointer to the joystick to use.
*/
void Controller::setJoystick(Joystick* newJoystick)
{
joystick = newJoystick;
}
/**
* @brief Make the controller rumble using built-in rumbler thingies.
* @param side The side on which the joystick will rumble. Definedby WPILib.
* @param intensity The intensity of vibration on a scale from 0 to 1.
*/
void Controller::setRumble(Joystick::RumbleType side, float intensity)
{
if (joystick != nullptr)
joystick->SetRumble(side, intensity);
}
/**
* @brief Loads control settings from a config file, because hard-coded controls are awful.
*
* Config files should be structured as follows:
* * The root node should be called "ControlConfig".
* * The children underneath the root node should be called "profile" with an attribute "name".
* This name is the name for a specific control profile. There should also be an attribute "active",
* which should be either true or false. This sets which control profile is active.
* * Nodes underneath a profile node should be named "control". They should have an attribute "type"
* (either button or joystick), an attribute "name", which is how you will refer to the control in
* the code, and an "id" attribute, for the control ID.
* * A control node's children should vary depending on control type.
* * All children will name the type of parameter, whereas an XML attribute ("value") specifies the
* value.
* * Button controls need only have "toggle" (boolean) and "cooldown" (double) parameters..
* * Joystick controls have four parameters: maxInput, minInput, deadzone, and equation (how the resulting value is modified; negative-blind).
* * Both button and joystick controls can accept an "inverse" (boolean) parameter, to invert output.
*
* An example (tiny) XML config file follows (you might need to check the source code, doxygen screws up the tabs!):
*
* <ControlConfig>
* <profile name="Sourec" active="false">
* <control type="button" id="0" name="raiseForks">
* <toggle value="false"/>
* <cooldown value="0.250"/>
* </control>
* <control type="joystick" name="intakeWheels">
* <maxInput value="1.0"/>
* <minInput value="-1.0"/>
* <deadzone value="0.1"/>
* <equation value="x"/>
* </control>
* </profile>
* </ControlConfig>
*
* @param cfgFile The path/filename to the config file.
* @note RoboRIOs are LINUX BASED! This means that your directory (even if it's just the root directory!) should start out with a '/' !
* @note NOT SETTING A CONTROL PARAMETER IN THE FILE WILL CAUSE DEFAULT VALUES TO BE USED! IF YOU SUSPECT ERROR, CHECK THE LOG!
*/
void Controller::parseConfig(string filename)
{
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load(filename.c_str());
Hydra::Logger::log(result.description(), "sysLog", Hydra::hydsys);
for (auto profile = doc.child("ControlConfig").child("profile"); profile; profile = profile.next_sibling())
{ //Loop through all profiles
unordered_map<string, ctrlCfg> profileSet;
for (auto control = profile.child("control"); control; control = control.next_sibling())
{ //Loop through all controls
ctrlCfg newCtrl;
newCtrl.id = control.attribute("id").as_int();
if (control.attribute("type").as_string() == string("button"))
{
newCtrl.type = ctrlCfg::BUTTON;
newCtrl.inverse = control.child("inverse").attribute("value").as_bool();
newCtrl.btn.cooldown = control.child("cooldown").attribute("cooldown").as_double();
newCtrl.btn.toggle = control.child("toggle").attribute("value").as_bool();
}
else
{
newCtrl.type = ctrlCfg::JOYSTICK;
newCtrl.jys.maxVal = control.child("maxInput").attribute("value").as_double();
newCtrl.jys.minVal = control.child("minInput").attribute("value").as_double();
newCtrl.jys.deadzone = control.child("deadzone").attribute("value").as_double();
newCtrl.jys.equ.parse(control.child("equation").attribute("value").as_string());
}
//profileSet[control.attribute("name").as_string()] = newCtrl;
}
profiles[profile.attribute("name").as_string()] = profileSet;
if (profile.attribute("active").as_bool()) //Automatically switch to default active profiles
switchProfile(profile.attribute("name").as_string());
}
}
/**
* @brief Switches out the current control profile for another profile, specified by name.
* @param profileName The name of the profile to switch to as a string.
*/
void Controller::switchProfile(string profileName)
{
if (profiles.count(profileName) != 0)
currentProfile = profileName;
}
/**
* @brief Get the value of a set control, referenced by name
* @param name The name of the control. Referenced in the XML configuration file.
* @return If the control is a button, nonzero for true and zero for false (duh). Else, a double.
*/
double Controller::operator[](const string& name)
{
ctrlCfg control;// = profiles[currentProfile][name]; //NOT a 2D array!
if (control.type == ctrlCfg::BUTTON)
{
if (!control.btn.toggle)
return control.inverse ? !joystick->GetRawButton(control.id) : joystick->GetRawButton(control.id);
else if (joystick->GetRawButton(control.id) || (!joystick->GetRawButton(control.id) && control.inverse))
{
if (control.btn.cooldownTimer->Get() >= control.btn.cooldown)
{ //The cooldown expired
control.btn.cooldownTimer->Reset();
control.btn.cooldownTimer->Start();
return !control.inverse;
}
return control.inverse;
}
}
else
{ //It's a joystick
double value = joystick->GetRawAxis(control.id);
double temp = value;
value = control.jys.equ.evaluate(fabs(value));
value = std::copysign(temp, value); //Copysign from temp to value?
//scale values... should work
temp = value;
value = fabs(value) * ((control.jys.maxVal - control.jys.minVal) * 0.5f);
return std::copysign(temp, value) + control.jys.minVal; //TODO: Verify
}
return 0; //STOP YELLING AT ME, ECLIPSE
}
}
Potentially fixed controller class crash
A robot crash every time. This is probably the worst hindenbug I've ever written into a piece of software.
#include "Controller.h"
namespace ADBLib
{
ctrlCfg::ctrlCfg()
{
id = 0;
type = JOYSTICK;
inverse = false;
btn.toggle = false;
btn.cooldown = 0.250; //Seconds
btn.cooldownTimer = new Timer;
jys.maxVal = 1.0;
jys.minVal = -1.0;
jys.deadzone = 0.1;
jys.equ.parse("x"); //Start off with no alterations to the joystick equation
}
Controller::~Controller()
{
delete joystick;
}
ctrlCfg::btnCfg::~btnCfg()
{
delete cooldownTimer;
}
/**
* @brief Gets the raw button setting as true or false, disregarding any active cooldowns.
* @param ID The ID of the button. ID changes depending on controller mode (X-Mode or D-Mode)
*/
bool Controller::getButtonRaw(int ID)
{
if ((ID >= 15 || ID <= 0) && joystick != nullptr)
return false; //Out-of-bounds IDs not accepted.
return joystick->GetRawButton(ID);
}
/**
* @brief Gets the raw axis value.
* @param ID The ID of the joystick. ID changes depending on controller mode (X-Mode or D-Mode)
*/
double Controller::getJoystickRaw(int ID)
{
if (ID >= 0 && ID <= 15 && joystick != nullptr)
return joystick->GetRawAxis(ID);
else
return 0;
}
/**
* @brief Sets the joystick to get data from.
* @param newJoystick A shared pointer to the joystick to use.
*/
void Controller::setJoystick(Joystick* newJoystick)
{
joystick = newJoystick;
}
/**
* @brief Make the controller rumble using built-in rumbler thingies.
* @param side The side on which the joystick will rumble. Definedby WPILib.
* @param intensity The intensity of vibration on a scale from 0 to 1.
*/
void Controller::setRumble(Joystick::RumbleType side, float intensity)
{
if (joystick != nullptr)
joystick->SetRumble(side, intensity);
}
/**
* @brief Loads control settings from a config file, because hard-coded controls are awful.
*
* Config files should be structured as follows:
* * The root node should be called "ControlConfig".
* * The children underneath the root node should be called "profile" with an attribute "name".
* This name is the name for a specific control profile. There should also be an attribute "active",
* which should be either true or false. This sets which control profile is active.
* * Nodes underneath a profile node should be named "control". They should have an attribute "type"
* (either button or joystick), an attribute "name", which is how you will refer to the control in
* the code, and an "id" attribute, for the control ID.
* * A control node's children should vary depending on control type.
* * All children will name the type of parameter, whereas an XML attribute ("value") specifies the
* value.
* * Button controls need only have "toggle" (boolean) and "cooldown" (double) parameters..
* * Joystick controls have four parameters: maxInput, minInput, deadzone, and equation (how the resulting value is modified; negative-blind).
* * Both button and joystick controls can accept an "inverse" (boolean) parameter, to invert output.
*
* An example (tiny) XML config file follows (you might need to check the source code, doxygen screws up the tabs!):
*
* <ControlConfig>
* <profile name="Sourec" active="false">
* <control type="button" id="0" name="raiseForks">
* <toggle value="false"/>
* <cooldown value="0.250"/>
* </control>
* <control type="joystick" name="intakeWheels">
* <maxInput value="1.0"/>
* <minInput value="-1.0"/>
* <deadzone value="0.1"/>
* <equation value="x"/>
* </control>
* </profile>
* </ControlConfig>
*
* @param cfgFile The path/filename to the config file.
* @note RoboRIOs are LINUX BASED! This means that your directory (even if it's just the root directory!) should start out with a '/' !
* @note NOT SETTING A CONTROL PARAMETER IN THE FILE WILL CAUSE DEFAULT VALUES TO BE USED! IF YOU SUSPECT ERROR, CHECK THE LOG!
*/
void Controller::parseConfig(string filename)
{
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load(filename.c_str());
Hydra::Logger::log(result.description(), "sysLog", Hydra::hydsys);
for (auto profile = doc.child("ControlConfig").child("profile"); profile; profile = profile.next_sibling())
{ //Loop through all profiles
unordered_map<string, ctrlCfg> profileSet;
for (auto control = profile.child("control"); control; control = control.next_sibling())
{ //Loop through all controls
ctrlCfg newCtrl;
newCtrl.id = control.attribute("id").as_int();
if (control.attribute("type").as_string() == string("button"))
{
newCtrl.type = ctrlCfg::BUTTON;
newCtrl.inverse = control.child("inverse").attribute("value").as_bool();
newCtrl.btn.cooldown = control.child("cooldown").attribute("cooldown").as_double();
newCtrl.btn.toggle = control.child("toggle").attribute("value").as_bool();
}
else
{
newCtrl.type = ctrlCfg::JOYSTICK;
newCtrl.jys.maxVal = control.child("maxInput").attribute("value").as_double();
newCtrl.jys.minVal = control.child("minInput").attribute("value").as_double();
newCtrl.jys.deadzone = control.child("deadzone").attribute("value").as_double();
newCtrl.jys.equ.parse(control.child("equation").attribute("value").as_string());
}
//profileSet[control.attribute("name").as_string()] = newCtrl;
}
profiles[profile.attribute("name").as_string()] = profileSet;
if (profile.attribute("active").as_bool()) //Automatically switch to default active profiles
switchProfile(profile.attribute("name").as_string());
}
}
/**
* @brief Switches out the current control profile for another profile, specified by name.
* @param profileName The name of the profile to switch to as a string.
*/
void Controller::switchProfile(string profileName)
{
if (profiles.count(profileName) != 0)
currentProfile = profileName;
}
/**
* @brief Get the value of a set control, referenced by name
* @param name The name of the control. Referenced in the XML configuration file.
* @return If the control is a button, nonzero for true and zero for false (duh). Else, a double.
*/
double Controller::operator[](const string& name)
{
if (profiles[currentProfile].count(name) == 0)
return 0; //There IS no control by this name!
ctrlCfg control = profiles[currentProfile][name];
if (control.type == ctrlCfg::BUTTON)
{
if (!control.btn.toggle)
return control.inverse ? !joystick->GetRawButton(control.id) : joystick->GetRawButton(control.id);
else if (joystick->GetRawButton(control.id) || (!joystick->GetRawButton(control.id) && control.inverse))
{
if (control.btn.cooldownTimer->Get() >= control.btn.cooldown)
{ //The cooldown expired
control.btn.cooldownTimer->Reset();
control.btn.cooldownTimer->Start();
return !control.inverse;
}
return control.inverse;
}
}
else
{ //It's a joystick
double value = joystick->GetRawAxis(control.id);
double temp = value;
value = control.jys.equ.evaluate(fabs(value));
value = std::copysign(temp, value); //Copysign from temp to value?
//scale values... should work
temp = value;
value = fabs(value) * ((control.jys.maxVal - control.jys.minVal) * 0.5f);
return std::copysign(temp, value) + control.jys.minVal; //TODO: Verify
}
return 0; //STOP YELLING AT ME, ECLIPSE
}
}
|
/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "AbstractSocket.h"
#include "SocketDefinitions.h"
#include "InterruptedException.h"
#include "PeekInputStream.h"
#include "SocketInputStream.h"
#include "SocketOutputStream.h"
#include "Thread.h"
using namespace db::io;
using namespace db::net;
using namespace db::rt;
AbstractSocket::AbstractSocket()
{
// file descriptor is invalid at this point
mFileDescriptor = -1;
// not bound, listening, or connected
mBound = false;
mListening = false;
mConnected = false;
// input/output uninitialized
mInputStream = NULL;
mOutputStream = NULL;
// no receive or send timeouts (socket will block)
mReceiveTimeout = 0;
mSendTimeout = 0;
// default backlog is 50
mBacklog = 50;
}
AbstractSocket::~AbstractSocket()
{
// close socket
close();
}
bool AbstractSocket::create(int domain, int type, int protocol)
{
bool rval = false;
int fd = socket(domain, type, protocol);
if(fd >= 0)
{
// set reuse address flag
// disables "address already in use" errors by reclaiming ports that
// are waiting to be cleaned up
int reuse = 1;
int error = setsockopt(
fd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
if(error < 0)
{
// close socket
close();
Thread::setException(new SocketException(
"Could not create Socket!", strerror(errno)));
}
else
{
mFileDescriptor = fd;
rval = true;
}
}
else
{
Thread::setException(new SocketException(
"Could not create Socket!", strerror(errno)));
}
return rval;
}
bool AbstractSocket::select(bool read, long long timeout)
{
Exception* exception = NULL;
if(!Thread::interrupted(false))
{
// create a file descriptor set to select on
fd_set fds;
FD_ZERO(&fds);
// add file descriptor to set
FD_SET((unsigned int)mFileDescriptor, &fds);
// "n" parameter is the highest numbered descriptor plus 1
int n = mFileDescriptor + 1;
int error;
if(read)
{
// wait for data to arrive for reading or for an exception
error = Thread::select(n, &fds, NULL, &fds, timeout);
}
else
{
// wait for writability or for an exception
error = Thread::select(n, NULL, &fds, &fds, timeout);
}
if(error < 0)
{
if(errno == EINTR)
{
if(read)
{
// interrupted exception
exception = new InterruptedException(
"Socket read interrupted!", strerror(errno));
}
else
{
// interrupted exception
exception = new InterruptedException(
"Socket write interrupted!", strerror(errno));
}
}
if(read)
{
// error occurred, get string message
exception = new SocketException(
"Could not read from Socket!", strerror(errno));
}
else
{
// error occurred, get string message
exception = new SocketException(
"Could not write to Socket!", strerror(errno));
}
}
else if(error == 0)
{
if(read)
{
// read timeout occurred
exception = new SocketTimeoutException(
"Socket read timed out!", strerror(errno));
}
else
{
// write timeout occurred
exception = new SocketTimeoutException(
"Socket write timed out!", strerror(errno));
}
}
}
if(exception == NULL && Thread::interrupted(false))
{
if(read)
{
exception = new InterruptedException("Socket read interrupted!");
}
else
{
exception = new InterruptedException("Socket write interrupted!");
}
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
bool AbstractSocket::initializeInput()
{
if(mInputStream == NULL)
{
// create input stream
mInputStream = new PeekInputStream(new SocketInputStream(this), true);
}
return true;
}
bool AbstractSocket::initializeOutput()
{
if(mOutputStream == NULL)
{
// create output stream
mOutputStream = new SocketOutputStream(this);
}
return true;
}
bool AbstractSocket::shutdownInput()
{
// delete input stream
if(mInputStream == NULL)
{
delete mInputStream;
}
return true;
}
bool AbstractSocket::shutdownOutput()
{
// delete output stream
if(mOutputStream == NULL)
{
delete mOutputStream;
}
return true;
}
bool AbstractSocket::bind(SocketAddress* address)
{
// acquire file descriptor
if(acquireFileDescriptor(address->getProtocol()))
{
// populate address structure
unsigned int size = 130;
char addr[size];
address->toSockAddr((sockaddr*)&addr, size);
// bind
int error = ::bind(mFileDescriptor, (sockaddr*)&addr, size);
if(error < 0)
{
Thread::setException(new SocketException(
"Could not bind Socket!", strerror(errno)));
}
else
{
// initialize input and output
initializeInput();
initializeOutput();
// now bound
mBound = true;
}
}
return mBound;
}
bool AbstractSocket::listen(unsigned int backlog)
{
if(!isBound())
{
Thread::setException(new SocketException(
"Cannot listen on unbound Socket!"));
}
else
{
// set backlog
mBacklog = backlog;
// listen
int error = ::listen(mFileDescriptor, backlog);
if(error < 0)
{
Thread::setException(new SocketException(
"Could not listen on Socket!", strerror(errno)));
}
else
{
// now listening
mListening = true;
}
}
return mListening;
}
Socket* AbstractSocket::accept(unsigned int timeout)
{
Socket* rval = NULL;
if(!isListening())
{
Thread::setException(new SocketException(
"Cannot accept with a non-listening Socket!"));
}
else
{
// wait for a connection
if(select(true, timeout * 1000LL))
{
// accept a connection
int fd = ::accept(mFileDescriptor, NULL, NULL);
if(fd < 0)
{
Thread::setException(new SocketException(
"Could not accept connection!", strerror(errno)));
}
else
{
// create a connected Socket
rval = createConnectedSocket(fd);
}
}
}
return rval;
}
bool AbstractSocket::connect(SocketAddress* address, unsigned int timeout)
{
// acquire file descriptor
if(acquireFileDescriptor(address->getProtocol()))
{
// populate address structure
unsigned int size = 130;
char addr[size];
address->toSockAddr((sockaddr*)&addr, size);
// make socket non-blocking temporarily
fcntl(mFileDescriptor, F_SETFL, O_NONBLOCK);
// connect
int error = ::connect(mFileDescriptor, (sockaddr*)addr, size);
if(error < 0)
{
// wait until the connection can be written to
if(select(false, timeout * 1000LL))
{
// get the last error on the socket
int lastError;
socklen_t lastErrorLength = sizeof(lastError);
getsockopt(
mFileDescriptor, SOL_SOCKET, SO_ERROR,
(char*)&lastError, &lastErrorLength);
if(lastError == 0)
{
// now connected and bound
mBound = true;
mConnected = true;
}
else
{
Thread::setException(new SocketException(
"Could not connect Socket! Connection refused.",
strerror(lastError)));
}
}
}
else
{
// now connected and bound
mBound = true;
mConnected = true;
}
// restore socket to blocking
fcntl(mFileDescriptor, F_SETFL, 0);
if(mConnected)
{
// initialize input and output
initializeInput();
initializeOutput();
}
}
return mConnected;
}
bool AbstractSocket::send(const char* b, unsigned int length)
{
Exception* exception = NULL;
if(!isBound())
{
exception = new SocketException("Cannot write to unbound Socket!");
}
else
{
// send all data (send can fail to send all bytes in one go because the
// socket send buffer was full)
unsigned int offset = 0;
while(exception == NULL && length > 0)
{
// wait for socket to become writable
if(select(false, getSendTimeout()))
{
// send some data
int bytes = ::send(mFileDescriptor, b + offset, length, 0);
if(bytes < 0)
{
exception = new SocketException(
"Could not write to Socket!", strerror(errno));
}
else if(bytes > 0)
{
offset += bytes;
length -= bytes;
}
}
else
{
exception = Thread::getException();
}
}
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
int AbstractSocket::receive(char* b, unsigned int length)
{
int rval = -1;
if(!isBound())
{
Thread::setException(new SocketException(
"Cannot read from unbound Socket!"));
}
else
{
// wait for data to become available
if(select(true, getReceiveTimeout()))
{
// receive some data
rval = ::recv(mFileDescriptor, b, length, 0);
if(rval < -1)
{
rval = -1;
Thread::setException(new SocketException(
"Could not read from Socket!", strerror(errno)));
}
else if(rval == 0)
{
// socket is closed now
rval = -1;
}
}
}
return rval;
}
void AbstractSocket::close()
{
if(mFileDescriptor != -1)
{
// shutdown input and output
shutdownInput();
shutdownOutput();
// close the socket
::close(mFileDescriptor);
// file descriptor is invalid again
mFileDescriptor = -1;
// not bound, listening, or connected
mBound = false;
mListening = false;
mConnected = false;
}
}
bool AbstractSocket::isBound()
{
return mBound;
}
bool AbstractSocket::isListening()
{
return mListening;
}
bool AbstractSocket::isConnected()
{
return mConnected;
}
bool AbstractSocket::getLocalAddress(SocketAddress* address)
{
Exception* exception = NULL;
if(!isBound())
{
exception = new SocketException(
"Cannot get local address for an unbound Socket!");
}
else
{
// get address structure
socklen_t size = 130;
char addr[size];
// get local information
int error = getsockname(mFileDescriptor, (sockaddr*)&addr, &size);
if(error < 0)
{
exception = new SocketException(
"Could not get Socket local address!", strerror(errno));
}
// convert socket address
address->fromSockAddr((sockaddr*)&addr, size);
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
bool AbstractSocket::getRemoteAddress(SocketAddress* address)
{
Exception* exception = NULL;
if(!isConnected())
{
exception = new SocketException(
"Cannot get local address for an unconnected Socket!");
}
else
{
// get address structure
socklen_t size = 130;
char addr[size];
// get remote information
int error = getpeername(mFileDescriptor, (sockaddr*)&addr, &size);
if(error < 0)
{
exception = new SocketException(
"Could not get Socket remote address!", strerror(errno));
}
else
{
// convert socket address
address->fromSockAddr((sockaddr*)&addr, size);
}
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
InputStream* AbstractSocket::getInputStream()
{
return mInputStream;
}
OutputStream* AbstractSocket::getOutputStream()
{
return mOutputStream;
}
void AbstractSocket::setSendTimeout(unsigned long timeout)
{
mSendTimeout = timeout;
}
unsigned long AbstractSocket::getSendTimeout()
{
return mSendTimeout;
}
void AbstractSocket::setReceiveTimeout(unsigned long timeout)
{
mReceiveTimeout = timeout;
}
unsigned long AbstractSocket::getReceiveTimeout()
{
return mReceiveTimeout;
}
unsigned int AbstractSocket::getBacklog()
{
return mBacklog;
}
int AbstractSocket::getFileDescriptor()
{
return mFileDescriptor;
}
Fixed bug where input/output streams where not deleted properly.
/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "AbstractSocket.h"
#include "SocketDefinitions.h"
#include "InterruptedException.h"
#include "PeekInputStream.h"
#include "SocketInputStream.h"
#include "SocketOutputStream.h"
#include "Thread.h"
using namespace db::io;
using namespace db::net;
using namespace db::rt;
AbstractSocket::AbstractSocket()
{
// file descriptor is invalid at this point
mFileDescriptor = -1;
// not bound, listening, or connected
mBound = false;
mListening = false;
mConnected = false;
// input/output uninitialized
mInputStream = NULL;
mOutputStream = NULL;
// no receive or send timeouts (socket will block)
mReceiveTimeout = 0;
mSendTimeout = 0;
// default backlog is 50
mBacklog = 50;
}
AbstractSocket::~AbstractSocket()
{
// close socket
close();
}
bool AbstractSocket::create(int domain, int type, int protocol)
{
bool rval = false;
int fd = socket(domain, type, protocol);
if(fd >= 0)
{
// set reuse address flag
// disables "address already in use" errors by reclaiming ports that
// are waiting to be cleaned up
int reuse = 1;
int error = setsockopt(
fd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
if(error < 0)
{
// close socket
close();
Thread::setException(new SocketException(
"Could not create Socket!", strerror(errno)));
}
else
{
mFileDescriptor = fd;
rval = true;
}
}
else
{
Thread::setException(new SocketException(
"Could not create Socket!", strerror(errno)));
}
return rval;
}
bool AbstractSocket::select(bool read, long long timeout)
{
Exception* exception = NULL;
if(!Thread::interrupted(false))
{
// create a file descriptor set to select on
fd_set fds;
FD_ZERO(&fds);
// add file descriptor to set
FD_SET((unsigned int)mFileDescriptor, &fds);
// "n" parameter is the highest numbered descriptor plus 1
int n = mFileDescriptor + 1;
int error;
if(read)
{
// wait for data to arrive for reading or for an exception
error = Thread::select(n, &fds, NULL, &fds, timeout);
}
else
{
// wait for writability or for an exception
error = Thread::select(n, NULL, &fds, &fds, timeout);
}
if(error < 0)
{
if(errno == EINTR)
{
if(read)
{
// interrupted exception
exception = new InterruptedException(
"Socket read interrupted!", strerror(errno));
}
else
{
// interrupted exception
exception = new InterruptedException(
"Socket write interrupted!", strerror(errno));
}
}
if(read)
{
// error occurred, get string message
exception = new SocketException(
"Could not read from Socket!", strerror(errno));
}
else
{
// error occurred, get string message
exception = new SocketException(
"Could not write to Socket!", strerror(errno));
}
}
else if(error == 0)
{
if(read)
{
// read timeout occurred
exception = new SocketTimeoutException(
"Socket read timed out!", strerror(errno));
}
else
{
// write timeout occurred
exception = new SocketTimeoutException(
"Socket write timed out!", strerror(errno));
}
}
}
if(exception == NULL && Thread::interrupted(false))
{
if(read)
{
exception = new InterruptedException("Socket read interrupted!");
}
else
{
exception = new InterruptedException("Socket write interrupted!");
}
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
bool AbstractSocket::initializeInput()
{
if(mInputStream == NULL)
{
// create input stream
mInputStream = new PeekInputStream(new SocketInputStream(this), true);
}
return true;
}
bool AbstractSocket::initializeOutput()
{
if(mOutputStream == NULL)
{
// create output stream
mOutputStream = new SocketOutputStream(this);
}
return true;
}
bool AbstractSocket::shutdownInput()
{
// delete input stream
if(mInputStream != NULL)
{
delete mInputStream;
}
return true;
}
bool AbstractSocket::shutdownOutput()
{
// delete output stream
if(mOutputStream != NULL)
{
delete mOutputStream;
}
return true;
}
bool AbstractSocket::bind(SocketAddress* address)
{
// acquire file descriptor
if(acquireFileDescriptor(address->getProtocol()))
{
// populate address structure
unsigned int size = 130;
char addr[size];
address->toSockAddr((sockaddr*)&addr, size);
// bind
int error = ::bind(mFileDescriptor, (sockaddr*)&addr, size);
if(error < 0)
{
Thread::setException(new SocketException(
"Could not bind Socket!", strerror(errno)));
}
else
{
// initialize input and output
initializeInput();
initializeOutput();
// now bound
mBound = true;
}
}
return mBound;
}
bool AbstractSocket::listen(unsigned int backlog)
{
if(!isBound())
{
Thread::setException(new SocketException(
"Cannot listen on unbound Socket!"));
}
else
{
// set backlog
mBacklog = backlog;
// listen
int error = ::listen(mFileDescriptor, backlog);
if(error < 0)
{
Thread::setException(new SocketException(
"Could not listen on Socket!", strerror(errno)));
}
else
{
// now listening
mListening = true;
}
}
return mListening;
}
Socket* AbstractSocket::accept(unsigned int timeout)
{
Socket* rval = NULL;
if(!isListening())
{
Thread::setException(new SocketException(
"Cannot accept with a non-listening Socket!"));
}
else
{
// wait for a connection
if(select(true, timeout * 1000LL))
{
// accept a connection
int fd = ::accept(mFileDescriptor, NULL, NULL);
if(fd < 0)
{
Thread::setException(new SocketException(
"Could not accept connection!", strerror(errno)));
}
else
{
// create a connected Socket
rval = createConnectedSocket(fd);
}
}
}
return rval;
}
bool AbstractSocket::connect(SocketAddress* address, unsigned int timeout)
{
// acquire file descriptor
if(acquireFileDescriptor(address->getProtocol()))
{
// populate address structure
unsigned int size = 130;
char addr[size];
address->toSockAddr((sockaddr*)&addr, size);
// make socket non-blocking temporarily
fcntl(mFileDescriptor, F_SETFL, O_NONBLOCK);
// connect
int error = ::connect(mFileDescriptor, (sockaddr*)addr, size);
if(error < 0)
{
// wait until the connection can be written to
if(select(false, timeout * 1000LL))
{
// get the last error on the socket
int lastError;
socklen_t lastErrorLength = sizeof(lastError);
getsockopt(
mFileDescriptor, SOL_SOCKET, SO_ERROR,
(char*)&lastError, &lastErrorLength);
if(lastError == 0)
{
// now connected and bound
mBound = true;
mConnected = true;
}
else
{
Thread::setException(new SocketException(
"Could not connect Socket! Connection refused.",
strerror(lastError)));
}
}
}
else
{
// now connected and bound
mBound = true;
mConnected = true;
}
// restore socket to blocking
fcntl(mFileDescriptor, F_SETFL, 0);
if(mConnected)
{
// initialize input and output
initializeInput();
initializeOutput();
}
}
return mConnected;
}
bool AbstractSocket::send(const char* b, unsigned int length)
{
Exception* exception = NULL;
if(!isBound())
{
exception = new SocketException("Cannot write to unbound Socket!");
}
else
{
// send all data (send can fail to send all bytes in one go because the
// socket send buffer was full)
unsigned int offset = 0;
while(exception == NULL && length > 0)
{
// wait for socket to become writable
if(select(false, getSendTimeout()))
{
// send some data
int bytes = ::send(mFileDescriptor, b + offset, length, 0);
if(bytes < 0)
{
exception = new SocketException(
"Could not write to Socket!", strerror(errno));
}
else if(bytes > 0)
{
offset += bytes;
length -= bytes;
}
}
else
{
exception = Thread::getException();
}
}
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
int AbstractSocket::receive(char* b, unsigned int length)
{
int rval = -1;
if(!isBound())
{
Thread::setException(new SocketException(
"Cannot read from unbound Socket!"));
}
else
{
// wait for data to become available
if(select(true, getReceiveTimeout()))
{
// receive some data
rval = ::recv(mFileDescriptor, b, length, 0);
if(rval < -1)
{
rval = -1;
Thread::setException(new SocketException(
"Could not read from Socket!", strerror(errno)));
}
else if(rval == 0)
{
// socket is closed now
rval = -1;
}
}
}
return rval;
}
void AbstractSocket::close()
{
if(mFileDescriptor != -1)
{
// shutdown input and output
shutdownInput();
shutdownOutput();
// close the socket
::close(mFileDescriptor);
// file descriptor is invalid again
mFileDescriptor = -1;
// not bound, listening, or connected
mBound = false;
mListening = false;
mConnected = false;
}
}
bool AbstractSocket::isBound()
{
return mBound;
}
bool AbstractSocket::isListening()
{
return mListening;
}
bool AbstractSocket::isConnected()
{
return mConnected;
}
bool AbstractSocket::getLocalAddress(SocketAddress* address)
{
Exception* exception = NULL;
if(!isBound())
{
exception = new SocketException(
"Cannot get local address for an unbound Socket!");
}
else
{
// get address structure
socklen_t size = 130;
char addr[size];
// get local information
int error = getsockname(mFileDescriptor, (sockaddr*)&addr, &size);
if(error < 0)
{
exception = new SocketException(
"Could not get Socket local address!", strerror(errno));
}
// convert socket address
address->fromSockAddr((sockaddr*)&addr, size);
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
bool AbstractSocket::getRemoteAddress(SocketAddress* address)
{
Exception* exception = NULL;
if(!isConnected())
{
exception = new SocketException(
"Cannot get local address for an unconnected Socket!");
}
else
{
// get address structure
socklen_t size = 130;
char addr[size];
// get remote information
int error = getpeername(mFileDescriptor, (sockaddr*)&addr, &size);
if(error < 0)
{
exception = new SocketException(
"Could not get Socket remote address!", strerror(errno));
}
else
{
// convert socket address
address->fromSockAddr((sockaddr*)&addr, size);
}
}
if(exception != NULL)
{
Thread::setException(exception);
}
return exception == NULL;
}
InputStream* AbstractSocket::getInputStream()
{
return mInputStream;
}
OutputStream* AbstractSocket::getOutputStream()
{
return mOutputStream;
}
void AbstractSocket::setSendTimeout(unsigned long timeout)
{
mSendTimeout = timeout;
}
unsigned long AbstractSocket::getSendTimeout()
{
return mSendTimeout;
}
void AbstractSocket::setReceiveTimeout(unsigned long timeout)
{
mReceiveTimeout = timeout;
}
unsigned long AbstractSocket::getReceiveTimeout()
{
return mReceiveTimeout;
}
unsigned int AbstractSocket::getBacklog()
{
return mBacklog;
}
int AbstractSocket::getFileDescriptor()
{
return mFileDescriptor;
}
|
/*!
* \page bom_display_cpp C++ Utility Class Browsing and Dumping the StdAir BOM Tree
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <ostream>
// StdAir
#include <stdair/basic/BasConst_BomDisplay.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/LegDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/LegCabin.hpp>
#include <stdair/bom/SegmentCabin.hpp>
#include <stdair/bom/FareFamily.hpp>
#include <stdair/bom/BookingClass.hpp>
#include <stdair/bom/AirportPair.hpp>
#include <stdair/bom/PosChannel.hpp>
#include <stdair/bom/DatePeriod.hpp>
#include <stdair/bom/TimePeriod.hpp>
#include <stdair/bom/FareFeatures.hpp>
#include <stdair/bom/YieldFeatures.hpp>
#include <stdair/bom/AirlineClassList.hpp>
#include <stdair/bom/Bucket.hpp>
#include <stdair/bom/TravelSolutionTypes.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/BomDisplay.hpp>
namespace stdair {
/**
* Helper singleton structure to store the current formatting flags
* of any given output stream. The flags are re-set at the
* structure destruction.
*/
struct FlagSaver {
public:
/** Constructor. */
FlagSaver (std::ostream& oStream)
: _oStream (oStream), _streamFlags (oStream.flags()) {
}
/** Destructor. */
~FlagSaver() {
// Reset formatting flags of the given output stream
_oStream.flags (_streamFlags);
}
private:
/** Reference on the STL stream, for which the flags must be saved. */
std::ostream& _oStream;
/** Saved STL stream flags. */
std::ios::fmtflags _streamFlags;
};
// ////////////////////////////////////////////////////////////////////
std::string BomDisplay::csvDisplay (const EventQueue& iEventQueue) {
std::ostringstream oStream;
/**
* Event queue level (only)
*/
oStream << std::endl;
oStream << "==============================================================="
<< std::endl;
oStream << "EventQueue: " << iEventQueue.describeKey() << std::endl;
oStream << "==============================================================="
<< std::endl;
return oStream.str();
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::list (std::ostream& oStream, const BomRoot& iBomRoot,
const AirlineCode_T& iAirlineCode,
const FlightNumber_T& iFlightNumber) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Check whether there are Inventory objects
if (BomManager::hasList<Inventory> (iBomRoot) == false) {
return;
}
// Browse the inventories
unsigned short invIdx = 1;
const InventoryList_T& lInventoryList =
BomManager::getList<Inventory> (iBomRoot);
for (InventoryList_T::const_iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv, ++invIdx) {
const Inventory* lInv_ptr = *itInv;
assert (lInv_ptr != NULL);
// Retrieve the inventory key (airline code)
const AirlineCode_T& lAirlineCode = lInv_ptr->getAirlineCode();
// Display only the requested inventories
if (iAirlineCode == "all" || iAirlineCode == lAirlineCode) {
// Get the list of flight-dates for that inventory
list (oStream, *lInv_ptr, invIdx, iFlightNumber);
}
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::list (std::ostream& oStream, const Inventory& iInventory,
const unsigned short iInventoryIndex,
const FlightNumber_T& iFlightNumber) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Check whether there are FlightDate objects
if (BomManager::hasMap<FlightDate> (iInventory) == false) {
return;
}
/**
* \note It is assumed in this method that the flight-date key is made of
* a mere string, concatenating the flight number and the departure
* date. Hence, all the departure dates of a given flight number
* are assumed to be grouped in the flight-date map held by the
* inventory.
*/
//
const AirlineCode_T& lAirlineCode = iInventory.getAirlineCode();
oStream << iInventoryIndex << ". " << lAirlineCode << std::endl;
// Browse the flight-dates
unsigned short lCurrentFlightNumber = 0;
unsigned short flightNumberIdx = 0;
unsigned short departureDateIdx = 1;
const FlightDateMap_T& lFlightDateList =
BomManager::getMap<FlightDate> (iInventory);
for (FlightDateMap_T::const_iterator itFD = lFlightDateList.begin();
itFD != lFlightDateList.end(); ++itFD, ++departureDateIdx) {
const FlightDate* lFD_ptr = itFD->second;
assert (lFD_ptr != NULL);
// Retrieve the key of the flight-date
const FlightNumber_T& lFlightNumber = lFD_ptr->getFlightNumber();
const Date_T& lFlightDateDate = lFD_ptr->getDepartureDate();
// Display only the requested flight number
if (iFlightNumber == 0 || iFlightNumber == lFlightNumber) {
//
if (lCurrentFlightNumber != lFlightNumber) {
lCurrentFlightNumber = lFlightNumber;
++flightNumberIdx; departureDateIdx = 1;
oStream << " " << iInventoryIndex << "." << flightNumberIdx << ". "
<< lAirlineCode << lFlightNumber << std::endl;
}
oStream << " " << iInventoryIndex << "." << flightNumberIdx
<< "." << departureDateIdx << ". "
<< lAirlineCode << lFlightNumber << " / " << lFlightDateDate
<< std::endl;
}
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDisplay (std::ostream& oStream,
const BomRoot& iBomRoot) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Bom root level (only)
*/
oStream << std::endl;
oStream << "==============================================================="
<< std::endl;
oStream << "BomRoot: " << iBomRoot.describeKey() << std::endl;
oStream << "==============================================================="
<< std::endl;
// Check whether there are Inventory objects
if (BomManager::hasList<Inventory> (iBomRoot) == false) {
return;
}
// Browse the inventories
const InventoryList_T& lInventoryList =
BomManager::getList<Inventory> (iBomRoot);
for (InventoryList_T::const_iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv) {
const Inventory* lInv_ptr = *itInv;
assert (lInv_ptr != NULL);
// Display the inventory
csvDisplay (oStream, *lInv_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDisplay (std::ostream& oStream,
const Inventory& iInventory) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Inventory level (only)
*/
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
oStream << "Inventory: " << iInventory.describeKey() << std::endl;
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
// Check whether there are FlightDate objects
if (BomManager::hasList<FlightDate> (iInventory) == false) {
return;
}
// Browse the flight-dates
const FlightDateList_T& lFlightDateList =
BomManager::getList<FlightDate> (iInventory);
for (FlightDateList_T::const_iterator itFD = lFlightDateList.begin();
itFD != lFlightDateList.end(); ++itFD) {
const FlightDate* lFD_ptr = *itFD;
assert (lFD_ptr != NULL);
// Display the flight-date
csvDisplay (oStream, *lFD_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Flight-date level (only)
*/
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
oStream << "******************************************" << std::endl;
oStream << "FlightDate: " << lAirlineCode << iFlightDate.describeKey()
<< std::endl;
oStream << "******************************************" << std::endl;
//
csvLegDateDisplay (oStream, iFlightDate);
//
csvLegCabinDisplay (oStream, iFlightDate);
//
csvBucketDisplay (oStream, iFlightDate);
//
csvFareFamilyDisplay (oStream, iFlightDate);
//
csvBookingClassDisplay (oStream, iFlightDate);
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvLegDateDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Leg-date level (only).
*
* Display the header.
*/
oStream << "******************************************" << std::endl;
oStream << "Leg-Dates:" << std::endl
<< "----------" << std::endl;
oStream << "Flight, Leg, BoardDate, BoardTime, "
<< "OffDate, OffTime, Date Offset, Time Offset, Elapsed, "
<< "Distance, Capacity, " << std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are LegDate objects
if (BomManager::hasList<LegDate> (iFlightDate) == false) {
return;
}
// Browse the leg-dates
const LegDateList_T& lLegDateList =
BomManager::getList<LegDate> (iFlightDate);
for (LegDateList_T::const_iterator itLD = lLegDateList.begin();
itLD != lLegDateList.end(); ++itLD) {
const LegDate* lLD_ptr = *itLD;
assert (lLD_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lLD_ptr->getBoardingPoint() << "-"
<< lLD_ptr->getOffPoint() << ", "
<< lLD_ptr->getBoardingDate() << ", "
<< lLD_ptr->getBoardingTime() << ", "
<< lLD_ptr->getOffDate() << ", "
<< lLD_ptr->getOffTime() << ", "
<< lLD_ptr->getElapsedTime() << ", "
<< lLD_ptr->getDateOffset() << ", "
<< lLD_ptr->getTimeOffset() << ", "
<< lLD_ptr->getDistance() << ", "
<< lLD_ptr->getCapacity() << ", "
<< std::endl;
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvSegmentDateDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Segment-date level (only)
*/
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvLegCabinDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Leg-cabin level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "LegCabins:" << std::endl
<< "----------" << std::endl;
oStream << "Flight, Leg, Cabin, "
<< "OffedCAP, PhyCAP, RgdADJ, AU, UPR, SS, Staff, WL, Group, "
<< "CommSpace, AvPool, Avl, NAV, GAV, ACP, ETB, BidPrice, "
<< std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are LegDate objects
if (BomManager::hasList<LegDate> (iFlightDate) == false) {
return;
}
// Browse the leg-dates
const LegDateList_T& lLegDateList =
BomManager::getList<LegDate> (iFlightDate);
for (LegDateList_T::const_iterator itLD = lLegDateList.begin();
itLD != lLegDateList.end(); ++itLD) {
const LegDate* lLD_ptr = *itLD;
assert (lLD_ptr != NULL);
// Retrieve the key of the leg-date, as well as its off point
const Date_T& lLegDateDate = lLD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lLD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lLD_ptr->getOffPoint();
// Browse the leg-cabins
const LegCabinList_T& lLegCabinList =
BomManager::getList<LegCabin> (*lLD_ptr);
for (LegCabinList_T::const_iterator itLC = lLegCabinList.begin();
itLC != lLegCabinList.end(); ++itLC) {
const LegCabin* lLC_ptr = *itLC;
assert (lLC_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lBoardPoint << "-" << lOffPoint
<< " " << lLegDateDate << ", ";
oStream << lLC_ptr->getCabinCode() << ", ";
oStream << lLC_ptr->getOfferedCapacity() << ", "
<< lLC_ptr->getPhysicalCapacity() << ", "
<< lLC_ptr->getRegradeAdjustment() << ", "
<< lLC_ptr->getAuthorizationLevel() << ", "
<< lLC_ptr->getUPR() << ", "
<< lLC_ptr->getSoldSeat() << ", "
<< lLC_ptr->getStaffNbOfSeats() << ", "
<< lLC_ptr->getWLNbOfSeats() << ", "
<< lLC_ptr->getGroupNbOfSeats() << ", "
<< lLC_ptr->getCommittedSpace() << ", "
<< lLC_ptr->getAvailabilityPool() << ", "
<< lLC_ptr->getAvailability() << ", "
<< lLC_ptr->getNetAvailability() << ", "
<< lLC_ptr->getGrossAvailability() << ", "
<< lLC_ptr->getAvgCancellationPercentage() << ", "
<< lLC_ptr->getETB() << ", "
<< lLC_ptr->getCurrentBidPrice() << ", "
<< std::endl;
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvSegmentCabinDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Segment-cabin level (only)
*/
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvFareFamilyDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Fare family level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "SegmentCabins:" << std::endl
<< "--------------" << std::endl;
oStream << "Flight, Segment, Cabin, FF, Bkgs, MIN, UPR, "
<< "CommSpace, AvPool, BP, " << std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are SegmentDate objects
if (BomManager::hasList<SegmentDate> (iFlightDate) == false) {
return;
}
// Browse the segment-dates
const SegmentDateList_T& lSegmentDateList =
BomManager::getList<SegmentDate> (iFlightDate);
for (SegmentDateList_T::const_iterator itSD = lSegmentDateList.begin();
itSD != lSegmentDateList.end(); ++itSD) {
const SegmentDate* lSD_ptr = *itSD;
assert (lSD_ptr != NULL);
// Retrieve the key of the segment-date, as well as its dates
const Date_T& lSegmentDateDate = lSD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lSD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lSD_ptr->getOffPoint();
// Browse the segment-cabins
const SegmentCabinList_T& lSegmentCabinList =
BomManager::getList<SegmentCabin> (*lSD_ptr);
for (SegmentCabinList_T::const_iterator itSC = lSegmentCabinList.begin();
itSC != lSegmentCabinList.end(); ++itSC) {
const SegmentCabin* lSC_ptr = *itSC;
assert (lSC_ptr != NULL);
// Retrieve the key of the segment-cabin
const CabinCode_T& lCabinCode = lSC_ptr->getCabinCode();
// Check whether there are fare family objects
if (BomManager::hasList<FareFamily> (*lSC_ptr) == false) {
continue;
}
// Browse the fare families
const FareFamilyList_T& lFareFamilyList =
BomManager::getList<FareFamily> (*lSC_ptr);
for (FareFamilyList_T::const_iterator itFF = lFareFamilyList.begin();
itFF != lFareFamilyList.end(); ++itFF) {
const FareFamily* lFF_ptr = *itFF;
assert (lFF_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lBoardPoint << "-" << lOffPoint << " "
<< lSegmentDateDate << ", ";
oStream << lCabinCode << ", " << lFF_ptr->getFamilyCode() << ", ";
oStream << lSC_ptr->getBookingCounter() << ", "
<< lSC_ptr->getMIN() << ", "
<< lSC_ptr->getUPR() << ", "
<< lSC_ptr->getCommittedSpace() << ", "
<< lSC_ptr->getAvailabilityPool() << ", "
<< lSC_ptr->getCurrentBidPrice() << ", "
<< std::endl;
}
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvBucketDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Bucket level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "Buckets:" << std::endl
<< "--------" << std::endl;
oStream << "Flight, Leg, Cabin, Yield, AU/SI, SS, AV, "
<< std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are LegDate objects
if (BomManager::hasList<LegDate> (iFlightDate) == false) {
return;
}
// Browse the leg-dates
const LegDateList_T& lLegDateList =
BomManager::getList<LegDate> (iFlightDate);
for (LegDateList_T::const_iterator itLD = lLegDateList.begin();
itLD != lLegDateList.end(); ++itLD) {
const LegDate* lLD_ptr = *itLD;
assert (lLD_ptr != NULL);
// Retrieve the key of the leg-date, as well as its off point
const Date_T& lLegDateDate = lLD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lLD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lLD_ptr->getOffPoint();
// Browse the leg-cabins
const LegCabinList_T& lLegCabinList =
BomManager::getList<LegCabin> (*lLD_ptr);
for (LegCabinList_T::const_iterator itLC = lLegCabinList.begin();
itLC != lLegCabinList.end(); ++itLC) {
const LegCabin* lLC_ptr = *itLC;
assert (lLC_ptr != NULL);
// Check whether there are bucket objects
if (BomManager::hasList<Bucket> (*lLC_ptr) == false) {
continue;
}
// Retrieve the key of the leg-cabin
const CabinCode_T& lCabinCode = lLC_ptr->getCabinCode();
// Browse the buckets
const BucketList_T& lBucketList = BomManager::getList<Bucket> (*lLC_ptr);
for (BucketList_T::const_iterator itBuck = lBucketList.begin();
itBuck != lBucketList.end(); ++itBuck) {
const Bucket* lBucket_ptr = *itBuck;
assert (lBucket_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lBoardPoint << "-" << lOffPoint << " "
<< lLegDateDate << ", " << lCabinCode << ", ";
oStream << lBucket_ptr->getYieldRangeUpperValue() << ", "
<< lBucket_ptr->getSeatIndex() << ", "
<< lBucket_ptr->getSoldSeats() << ", "
<< lBucket_ptr->getAvailability() << ", ";
oStream << std::endl;
}
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvBookingClassDisplay (std::ostream& oStream,
const BookingClass& iBookingClass,
const std::string& iLeadingString) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Booking-class level (only)
*
* See the method below (csvBookingClassDisplay() at FlightDate level)
* for the details of the header.
*/
oStream << iLeadingString << iBookingClass.getClassCode();
if (iBookingClass.getSubclassCode() == 0) {
oStream << ", ";
} else {
oStream << iBookingClass.getSubclassCode() << ", ";
}
oStream << iBookingClass.getAuthorizationLevel() << " ("
<< iBookingClass.getProtection() << "), "
<< iBookingClass.getNegotiatedSpace() << ", "
<< iBookingClass.getNoShowPercentage() << ", "
<< iBookingClass.getCancellationPercentage() << ", "
<< iBookingClass.getNbOfBookings() << ", "
<< iBookingClass.getNbOfGroupBookings() << " ("
<< iBookingClass.getNbOfPendingGroupBookings() << "), "
<< iBookingClass.getNbOfStaffBookings() << ", "
<< iBookingClass.getNbOfWLBookings() << ", "
<< iBookingClass.getETB() << ", "
<< iBookingClass.getNetClassAvailability() << ", "
<< iBookingClass.getNetRevenueAvailability() << ", "
<< iBookingClass.getSegmentAvailability() << ", "
<< std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvBookingClassDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Headers
oStream << "******************************************" << std::endl;
oStream << "Subclasses:" << std::endl
<< "-----------" << std::endl;
oStream << "Flight, Segment, Cabin, FF, Subclass, MIN/AU (Prot), "
<< "Nego, NS%, OB%, "
<< "Bkgs, GrpBks (pdg), StfBkgs, WLBkgs, ETB, "
<< "ClassAvl, RevAvl, SegAvl, "
<< std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are SegmentDate objects
if (BomManager::hasList<SegmentDate> (iFlightDate) == false) {
return;
}
// Browse the segment-dates
const SegmentDateList_T& lSegmentDateList =
BomManager::getList<SegmentDate> (iFlightDate);
for (SegmentDateList_T::const_iterator itSD = lSegmentDateList.begin();
itSD != lSegmentDateList.end(); ++itSD) {
const SegmentDate* lSD_ptr = *itSD;
assert (lSD_ptr != NULL);
// Retrieve the key of the segment-date, as well as its dates
const Date_T& lSegmentDateDate = lSD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lSD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lSD_ptr->getOffPoint();
// Browse the segment-cabins
const SegmentCabinList_T& lSegmentCabinList =
BomManager::getList<SegmentCabin> (*lSD_ptr);
for (SegmentCabinList_T::const_iterator itSC = lSegmentCabinList.begin();
itSC != lSegmentCabinList.end(); ++itSC) {
const SegmentCabin* lSC_ptr = *itSC;
assert (lSC_ptr != NULL);
// Retrieve the key of the segment-cabin
const CabinCode_T& lCabinCode = lSC_ptr->getCabinCode();
// Build the leading string to be displayed
std::ostringstream oLeadingStr;
oLeadingStr << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", "
<< lBoardPoint << "-" << lOffPoint << " "
<< lSegmentDateDate << ", "
<< lCabinCode << ", ";
// Default Fare Family code, when there are no FF
FamilyCode_T lFamilyCode ("NoFF");
// Check whether there are FareFamily objects
if (BomManager::hasList<FareFamily> (*lSC_ptr) == true) {
// Browse the fare families
const FareFamilyList_T& lFareFamilyList =
BomManager::getList<FareFamily> (*lSC_ptr);
for (FareFamilyList_T::const_iterator itFF = lFareFamilyList.begin();
itFF != lFareFamilyList.end(); ++itFF) {
const FareFamily* lFF_ptr = *itFF;
assert (lFF_ptr != NULL);
// Retrieve the key of the segment-cabin
lFamilyCode = lFF_ptr->getFamilyCode();
// Complete the leading string to be displayed
oLeadingStr << lFamilyCode << ", ";
// Browse the booking-classes
const BookingClassList_T& lBookingClassList =
BomManager::getList<BookingClass> (*lFF_ptr);
for (BookingClassList_T::const_iterator itBC =
lBookingClassList.begin();
itBC != lBookingClassList.end(); ++itBC) {
const BookingClass* lBC_ptr = *itBC;
assert (lBC_ptr != NULL);
//
csvBookingClassDisplay (oStream, *lBC_ptr, oLeadingStr.str());
}
}
return;
}
assert (BomManager::hasList<FareFamily> (*lSC_ptr) == false);
// The fare family code is a fake one ('NoFF'), and therefore
// does not vary
oLeadingStr << lFamilyCode << ", ";
// Browse the booking-classes, directly from the segment-cabin object
const BookingClassList_T& lBookingClassList =
BomManager::getList<BookingClass> (*lSC_ptr);
for (BookingClassList_T::const_iterator itBC =
lBookingClassList.begin();
itBC != lBookingClassList.end(); ++itBC) {
const BookingClass* lBC_ptr = *itBC;
assert (lBC_ptr != NULL);
//
csvBookingClassDisplay (oStream, *lBC_ptr, oLeadingStr.str());
}
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::
csvDisplay (std::ostream& oStream,
const TravelSolutionList_T& iTravelSolutionList) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
oStream << "Travel solutions:";
unsigned short idx = 0;
for (TravelSolutionList_T::const_iterator itTS =
iTravelSolutionList.begin();
itTS != iTravelSolutionList.end(); ++itTS, ++idx) {
const TravelSolutionStruct& lTS = *itTS;
oStream << std::endl;
oStream << " [" << idx << "] " << lTS.display();
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::
csvDisplay (std::ostream& oStream,
const DatePeriodList_T& iDatePeriodList) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Browse the date-period objects
for (DatePeriodList_T::const_iterator itDP = iDatePeriodList.begin();
itDP != iDatePeriodList.end(); ++itDP) {
const DatePeriod* lDP_ptr = *itDP;
assert (lDP_ptr != NULL);
// Display the date-period object
csvDateDisplay (oStream, *lDP_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvSimFQTAirRACDisplay (std::ostream& oStream,
const BomRoot& iBomRoot) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Bom root level (only)
*/
oStream << std::endl;
oStream << "==============================================================="
<< std::endl;
oStream << "BomRoot: " << iBomRoot.describeKey() << std::endl;
oStream << "==============================================================="
<< std::endl;
// Check whether there are airport-pair objects
if (BomManager::hasList<AirportPair> (iBomRoot) == false) {
return;
}
// Browse the airport-pair objects
const AirportPairList_T& lAirportPairList =
BomManager::getList<AirportPair> (iBomRoot);
for (AirportPairList_T::const_iterator itAir = lAirportPairList.begin();
itAir != lAirportPairList.end(); ++itAir ) {
const AirportPair* lAir_ptr = *itAir;
assert (lAir_ptr != NULL);
// Display the airport pair object
csvAirportPairDisplay (oStream, *lAir_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvAirportPairDisplay (std::ostream& oStream,
const AirportPair& iAirportPair) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Airport pair level (only)
*/
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
oStream << "AirportPair: " << iAirportPair.describeKey() << std::endl;
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
// Check whether there are date-period objects
if (BomManager::hasList<DatePeriod> (iAirportPair) == false) {
return;
}
// Browse the date-period objects
const DatePeriodList_T& lDatePeriodList =
BomManager::getList<DatePeriod> (iAirportPair);
for (DatePeriodList_T::const_iterator itDP = lDatePeriodList.begin();
itDP != lDatePeriodList.end(); ++itDP) {
const DatePeriod* lDP_ptr = *itDP;
assert (lDP_ptr != NULL);
// Display the date-period object
csvDateDisplay (oStream, *lDP_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDateDisplay (std::ostream& oStream,
const DatePeriod& iDatePeriod) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Date-Period level (only).
*/
oStream << "------------------------------------------" << std::endl;
oStream << "DatePeriod: " << iDatePeriod.describeKey() << std::endl;
oStream << "------------------------------------------" << std::endl;
// Check whether there are pos-channel objects
if (BomManager::hasList<PosChannel> (iDatePeriod) == false) {
return;
}
// Browse the pos-channel objects
const PosChannelList_T& lPosChannelList =
BomManager::getList<PosChannel> (iDatePeriod);
for (PosChannelList_T::const_iterator itPC = lPosChannelList.begin();
itPC != lPosChannelList.end(); ++itPC) {
const PosChannel* lPC_ptr = *itPC;
assert (lPC_ptr != NULL);
// Display the pos-channel object
csvPosChannelDisplay (oStream, *lPC_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvPosChannelDisplay (std::ostream& oStream,
const PosChannel& iPosChannel) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* PosChannel level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "PosChannel: " << iPosChannel.describeKey() << std::endl;
oStream << "******************************************" << std::endl;
// Check whether there are time-period objects
if (BomManager::hasList<TimePeriod> (iPosChannel) == false) {
return;
}
// Browse the time-period objects
const TimePeriodList_T& lTimePeriodList =
BomManager::getList<TimePeriod> (iPosChannel);
for (TimePeriodList_T::const_iterator itTP = lTimePeriodList.begin();
itTP != lTimePeriodList.end(); ++itTP) {
const TimePeriod* lTP_ptr = *itTP;
assert (lTP_ptr != NULL);
// Display the time-period object
csvTimeDisplay (oStream, *lTP_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvTimeDisplay (std::ostream& oStream,
const TimePeriod& iTimePeriod) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Time-Period level (only).
*/
oStream << "----------------------------------------" << std::endl;
oStream << "TimePeriod: " << iTimePeriod.describeKey() << std::endl;
oStream << "----------------------------------------" << std::endl;
// Only one of the fare/yield feature list exists. Each of the following
// two methods will check for the existence of the list. So, only the
// existing list will be actually displayed.
csvFeatureListDisplay<FareFeatures> (oStream, iTimePeriod);
csvFeatureListDisplay<YieldFeatures> (oStream, iTimePeriod);
}
// ////////////////////////////////////////////////////////////////////
template <typename FEATURE_TYPE>
void BomDisplay::csvFeatureListDisplay (std::ostream& oStream,
const TimePeriod& iTimePeriod) {
// Check whether there are fare/yield-feature objects
if (BomManager::hasList<FEATURE_TYPE> (iTimePeriod) == false) {
return;
}
// Browse the fare/yield-feature objects
typedef typename BomHolder<FEATURE_TYPE>::BomList_T FeaturesList_T;
const FeaturesList_T& lFeaturesList =
BomManager::getList<FEATURE_TYPE> (iTimePeriod);
for (typename FeaturesList_T::const_iterator itFF = lFeaturesList.begin();
itFF != lFeaturesList.end(); ++itFF) {
const FEATURE_TYPE* lFF_ptr = *itFF;
assert (lFF_ptr != NULL);
// Display the fare-features object
csvFeaturesDisplay (oStream, *lFF_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
template <typename FEATURE_TYPE>
void BomDisplay::csvFeaturesDisplay (std::ostream& oStream,
const FEATURE_TYPE& iFeatures) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Fare/yield-Features level (only).
*/
oStream << "--------------------------------------" << std::endl;
oStream << "Fare/yield-Features: " << iFeatures.describeKey() << std::endl;
oStream << "--------------------------------------" << std::endl;
// Check whether there are airlineClassList objects
if (BomManager::hasList<AirlineClassList> (iFeatures) == false) {
return;
}
// Browse the airlineClassList objects
const AirlineClassListList_T& lAirlineClassListList =
BomManager::getList<AirlineClassList> (iFeatures);
for (AirlineClassListList_T::const_iterator itACL =
lAirlineClassListList.begin();
itACL != lAirlineClassListList.end(); ++itACL) {
const AirlineClassList* lACL_ptr = *itACL;
assert (lACL_ptr != NULL);
// Display the airlineClassList object
csvAirlineClassDisplay(oStream, *lACL_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::
csvAirlineClassDisplay (std::ostream& oStream,
const AirlineClassList& iAirlineClassList) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* AirlineClassList level (only).
*/
oStream << "------------------------------------" << std::endl;
oStream << "AirlineClassList: "
<< iAirlineClassList.describeKey() << std::endl;
oStream << "------------------------------------" << std::endl;
}
}
/*!
* \endcode
*/
[Dev] Fixed a bug in the CSV display, hindering the display of over one segment-cabin.
/*!
* \page bom_display_cpp C++ Utility Class Browsing and Dumping the StdAir BOM Tree
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <ostream>
// StdAir
#include <stdair/basic/BasConst_BomDisplay.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/LegDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/LegCabin.hpp>
#include <stdair/bom/SegmentCabin.hpp>
#include <stdair/bom/FareFamily.hpp>
#include <stdair/bom/BookingClass.hpp>
#include <stdair/bom/AirportPair.hpp>
#include <stdair/bom/PosChannel.hpp>
#include <stdair/bom/DatePeriod.hpp>
#include <stdair/bom/TimePeriod.hpp>
#include <stdair/bom/FareFeatures.hpp>
#include <stdair/bom/YieldFeatures.hpp>
#include <stdair/bom/AirlineClassList.hpp>
#include <stdair/bom/Bucket.hpp>
#include <stdair/bom/TravelSolutionTypes.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/BomDisplay.hpp>
namespace stdair {
/**
* Helper singleton structure to store the current formatting flags
* of any given output stream. The flags are re-set at the
* structure destruction.
*/
struct FlagSaver {
public:
/** Constructor. */
FlagSaver (std::ostream& oStream)
: _oStream (oStream), _streamFlags (oStream.flags()) {
}
/** Destructor. */
~FlagSaver() {
// Reset formatting flags of the given output stream
_oStream.flags (_streamFlags);
}
private:
/** Reference on the STL stream, for which the flags must be saved. */
std::ostream& _oStream;
/** Saved STL stream flags. */
std::ios::fmtflags _streamFlags;
};
// ////////////////////////////////////////////////////////////////////
std::string BomDisplay::csvDisplay (const EventQueue& iEventQueue) {
std::ostringstream oStream;
/**
* Event queue level (only)
*/
oStream << std::endl;
oStream << "==============================================================="
<< std::endl;
oStream << "EventQueue: " << iEventQueue.describeKey() << std::endl;
oStream << "==============================================================="
<< std::endl;
return oStream.str();
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::list (std::ostream& oStream, const BomRoot& iBomRoot,
const AirlineCode_T& iAirlineCode,
const FlightNumber_T& iFlightNumber) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Check whether there are Inventory objects
if (BomManager::hasList<Inventory> (iBomRoot) == false) {
return;
}
// Browse the inventories
unsigned short invIdx = 1;
const InventoryList_T& lInventoryList =
BomManager::getList<Inventory> (iBomRoot);
for (InventoryList_T::const_iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv, ++invIdx) {
const Inventory* lInv_ptr = *itInv;
assert (lInv_ptr != NULL);
// Retrieve the inventory key (airline code)
const AirlineCode_T& lAirlineCode = lInv_ptr->getAirlineCode();
// Display only the requested inventories
if (iAirlineCode == "all" || iAirlineCode == lAirlineCode) {
// Get the list of flight-dates for that inventory
list (oStream, *lInv_ptr, invIdx, iFlightNumber);
}
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::list (std::ostream& oStream, const Inventory& iInventory,
const unsigned short iInventoryIndex,
const FlightNumber_T& iFlightNumber) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Check whether there are FlightDate objects
if (BomManager::hasMap<FlightDate> (iInventory) == false) {
return;
}
/**
* \note It is assumed in this method that the flight-date key is made of
* a mere string, concatenating the flight number and the departure
* date. Hence, all the departure dates of a given flight number
* are assumed to be grouped in the flight-date map held by the
* inventory.
*/
//
const AirlineCode_T& lAirlineCode = iInventory.getAirlineCode();
oStream << iInventoryIndex << ". " << lAirlineCode << std::endl;
// Browse the flight-dates
unsigned short lCurrentFlightNumber = 0;
unsigned short flightNumberIdx = 0;
unsigned short departureDateIdx = 1;
const FlightDateMap_T& lFlightDateList =
BomManager::getMap<FlightDate> (iInventory);
for (FlightDateMap_T::const_iterator itFD = lFlightDateList.begin();
itFD != lFlightDateList.end(); ++itFD, ++departureDateIdx) {
const FlightDate* lFD_ptr = itFD->second;
assert (lFD_ptr != NULL);
// Retrieve the key of the flight-date
const FlightNumber_T& lFlightNumber = lFD_ptr->getFlightNumber();
const Date_T& lFlightDateDate = lFD_ptr->getDepartureDate();
// Display only the requested flight number
if (iFlightNumber == 0 || iFlightNumber == lFlightNumber) {
//
if (lCurrentFlightNumber != lFlightNumber) {
lCurrentFlightNumber = lFlightNumber;
++flightNumberIdx; departureDateIdx = 1;
oStream << " " << iInventoryIndex << "." << flightNumberIdx << ". "
<< lAirlineCode << lFlightNumber << std::endl;
}
oStream << " " << iInventoryIndex << "." << flightNumberIdx
<< "." << departureDateIdx << ". "
<< lAirlineCode << lFlightNumber << " / " << lFlightDateDate
<< std::endl;
}
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDisplay (std::ostream& oStream,
const BomRoot& iBomRoot) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Bom root level (only)
*/
oStream << std::endl;
oStream << "==============================================================="
<< std::endl;
oStream << "BomRoot: " << iBomRoot.describeKey() << std::endl;
oStream << "==============================================================="
<< std::endl;
// Check whether there are Inventory objects
if (BomManager::hasList<Inventory> (iBomRoot) == false) {
return;
}
// Browse the inventories
const InventoryList_T& lInventoryList =
BomManager::getList<Inventory> (iBomRoot);
for (InventoryList_T::const_iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv) {
const Inventory* lInv_ptr = *itInv;
assert (lInv_ptr != NULL);
// Display the inventory
csvDisplay (oStream, *lInv_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDisplay (std::ostream& oStream,
const Inventory& iInventory) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Inventory level (only)
*/
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
oStream << "Inventory: " << iInventory.describeKey() << std::endl;
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
// Check whether there are FlightDate objects
if (BomManager::hasList<FlightDate> (iInventory) == false) {
return;
}
// Browse the flight-dates
const FlightDateList_T& lFlightDateList =
BomManager::getList<FlightDate> (iInventory);
for (FlightDateList_T::const_iterator itFD = lFlightDateList.begin();
itFD != lFlightDateList.end(); ++itFD) {
const FlightDate* lFD_ptr = *itFD;
assert (lFD_ptr != NULL);
// Display the flight-date
csvDisplay (oStream, *lFD_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Flight-date level (only)
*/
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
oStream << "******************************************" << std::endl;
oStream << "FlightDate: " << lAirlineCode << iFlightDate.describeKey()
<< std::endl;
oStream << "******************************************" << std::endl;
//
csvLegDateDisplay (oStream, iFlightDate);
//
csvLegCabinDisplay (oStream, iFlightDate);
//
csvBucketDisplay (oStream, iFlightDate);
//
csvFareFamilyDisplay (oStream, iFlightDate);
//
csvBookingClassDisplay (oStream, iFlightDate);
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvLegDateDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Leg-date level (only).
*
* Display the header.
*/
oStream << "******************************************" << std::endl;
oStream << "Leg-Dates:" << std::endl
<< "----------" << std::endl;
oStream << "Flight, Leg, BoardDate, BoardTime, "
<< "OffDate, OffTime, Date Offset, Time Offset, Elapsed, "
<< "Distance, Capacity, " << std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are LegDate objects
if (BomManager::hasList<LegDate> (iFlightDate) == false) {
return;
}
// Browse the leg-dates
const LegDateList_T& lLegDateList =
BomManager::getList<LegDate> (iFlightDate);
for (LegDateList_T::const_iterator itLD = lLegDateList.begin();
itLD != lLegDateList.end(); ++itLD) {
const LegDate* lLD_ptr = *itLD;
assert (lLD_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lLD_ptr->getBoardingPoint() << "-"
<< lLD_ptr->getOffPoint() << ", "
<< lLD_ptr->getBoardingDate() << ", "
<< lLD_ptr->getBoardingTime() << ", "
<< lLD_ptr->getOffDate() << ", "
<< lLD_ptr->getOffTime() << ", "
<< lLD_ptr->getElapsedTime() << ", "
<< lLD_ptr->getDateOffset() << ", "
<< lLD_ptr->getTimeOffset() << ", "
<< lLD_ptr->getDistance() << ", "
<< lLD_ptr->getCapacity() << ", "
<< std::endl;
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvSegmentDateDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Segment-date level (only)
*/
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvLegCabinDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Leg-cabin level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "LegCabins:" << std::endl
<< "----------" << std::endl;
oStream << "Flight, Leg, Cabin, "
<< "OffedCAP, PhyCAP, RgdADJ, AU, UPR, SS, Staff, WL, Group, "
<< "CommSpace, AvPool, Avl, NAV, GAV, ACP, ETB, BidPrice, "
<< std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are LegDate objects
if (BomManager::hasList<LegDate> (iFlightDate) == false) {
return;
}
// Browse the leg-dates
const LegDateList_T& lLegDateList =
BomManager::getList<LegDate> (iFlightDate);
for (LegDateList_T::const_iterator itLD = lLegDateList.begin();
itLD != lLegDateList.end(); ++itLD) {
const LegDate* lLD_ptr = *itLD;
assert (lLD_ptr != NULL);
// Retrieve the key of the leg-date, as well as its off point
const Date_T& lLegDateDate = lLD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lLD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lLD_ptr->getOffPoint();
// Browse the leg-cabins
const LegCabinList_T& lLegCabinList =
BomManager::getList<LegCabin> (*lLD_ptr);
for (LegCabinList_T::const_iterator itLC = lLegCabinList.begin();
itLC != lLegCabinList.end(); ++itLC) {
const LegCabin* lLC_ptr = *itLC;
assert (lLC_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lBoardPoint << "-" << lOffPoint
<< " " << lLegDateDate << ", ";
oStream << lLC_ptr->getCabinCode() << ", ";
oStream << lLC_ptr->getOfferedCapacity() << ", "
<< lLC_ptr->getPhysicalCapacity() << ", "
<< lLC_ptr->getRegradeAdjustment() << ", "
<< lLC_ptr->getAuthorizationLevel() << ", "
<< lLC_ptr->getUPR() << ", "
<< lLC_ptr->getSoldSeat() << ", "
<< lLC_ptr->getStaffNbOfSeats() << ", "
<< lLC_ptr->getWLNbOfSeats() << ", "
<< lLC_ptr->getGroupNbOfSeats() << ", "
<< lLC_ptr->getCommittedSpace() << ", "
<< lLC_ptr->getAvailabilityPool() << ", "
<< lLC_ptr->getAvailability() << ", "
<< lLC_ptr->getNetAvailability() << ", "
<< lLC_ptr->getGrossAvailability() << ", "
<< lLC_ptr->getAvgCancellationPercentage() << ", "
<< lLC_ptr->getETB() << ", "
<< lLC_ptr->getCurrentBidPrice() << ", "
<< std::endl;
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvSegmentCabinDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Segment-cabin level (only)
*/
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvFareFamilyDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Fare family level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "SegmentCabins:" << std::endl
<< "--------------" << std::endl;
oStream << "Flight, Segment, Cabin, FF, Bkgs, MIN, UPR, "
<< "CommSpace, AvPool, BP, " << std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are SegmentDate objects
if (BomManager::hasList<SegmentDate> (iFlightDate) == false) {
return;
}
// Browse the segment-dates
const SegmentDateList_T& lSegmentDateList =
BomManager::getList<SegmentDate> (iFlightDate);
for (SegmentDateList_T::const_iterator itSD = lSegmentDateList.begin();
itSD != lSegmentDateList.end(); ++itSD) {
const SegmentDate* lSD_ptr = *itSD;
assert (lSD_ptr != NULL);
// Retrieve the key of the segment-date, as well as its dates
const Date_T& lSegmentDateDate = lSD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lSD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lSD_ptr->getOffPoint();
// Browse the segment-cabins
const SegmentCabinList_T& lSegmentCabinList =
BomManager::getList<SegmentCabin> (*lSD_ptr);
for (SegmentCabinList_T::const_iterator itSC = lSegmentCabinList.begin();
itSC != lSegmentCabinList.end(); ++itSC) {
const SegmentCabin* lSC_ptr = *itSC;
assert (lSC_ptr != NULL);
// Retrieve the key of the segment-cabin
const CabinCode_T& lCabinCode = lSC_ptr->getCabinCode();
// Check whether there are fare family objects
if (BomManager::hasList<FareFamily> (*lSC_ptr) == false) {
continue;
}
// Browse the fare families
const FareFamilyList_T& lFareFamilyList =
BomManager::getList<FareFamily> (*lSC_ptr);
for (FareFamilyList_T::const_iterator itFF = lFareFamilyList.begin();
itFF != lFareFamilyList.end(); ++itFF) {
const FareFamily* lFF_ptr = *itFF;
assert (lFF_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lBoardPoint << "-" << lOffPoint << " "
<< lSegmentDateDate << ", ";
oStream << lCabinCode << ", " << lFF_ptr->getFamilyCode() << ", ";
oStream << lSC_ptr->getBookingCounter() << ", "
<< lSC_ptr->getMIN() << ", "
<< lSC_ptr->getUPR() << ", "
<< lSC_ptr->getCommittedSpace() << ", "
<< lSC_ptr->getAvailabilityPool() << ", "
<< lSC_ptr->getCurrentBidPrice() << ", "
<< std::endl;
}
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvBucketDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Bucket level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "Buckets:" << std::endl
<< "--------" << std::endl;
oStream << "Flight, Leg, Cabin, Yield, AU/SI, SS, AV, "
<< std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are LegDate objects
if (BomManager::hasList<LegDate> (iFlightDate) == false) {
return;
}
// Browse the leg-dates
const LegDateList_T& lLegDateList =
BomManager::getList<LegDate> (iFlightDate);
for (LegDateList_T::const_iterator itLD = lLegDateList.begin();
itLD != lLegDateList.end(); ++itLD) {
const LegDate* lLD_ptr = *itLD;
assert (lLD_ptr != NULL);
// Retrieve the key of the leg-date, as well as its off point
const Date_T& lLegDateDate = lLD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lLD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lLD_ptr->getOffPoint();
// Browse the leg-cabins
const LegCabinList_T& lLegCabinList =
BomManager::getList<LegCabin> (*lLD_ptr);
for (LegCabinList_T::const_iterator itLC = lLegCabinList.begin();
itLC != lLegCabinList.end(); ++itLC) {
const LegCabin* lLC_ptr = *itLC;
assert (lLC_ptr != NULL);
// Check whether there are bucket objects
if (BomManager::hasList<Bucket> (*lLC_ptr) == false) {
continue;
}
// Retrieve the key of the leg-cabin
const CabinCode_T& lCabinCode = lLC_ptr->getCabinCode();
// Browse the buckets
const BucketList_T& lBucketList = BomManager::getList<Bucket> (*lLC_ptr);
for (BucketList_T::const_iterator itBuck = lBucketList.begin();
itBuck != lBucketList.end(); ++itBuck) {
const Bucket* lBucket_ptr = *itBuck;
assert (lBucket_ptr != NULL);
oStream << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", ";
oStream << lBoardPoint << "-" << lOffPoint << " "
<< lLegDateDate << ", " << lCabinCode << ", ";
oStream << lBucket_ptr->getYieldRangeUpperValue() << ", "
<< lBucket_ptr->getSeatIndex() << ", "
<< lBucket_ptr->getSoldSeats() << ", "
<< lBucket_ptr->getAvailability() << ", ";
oStream << std::endl;
}
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvBookingClassDisplay (std::ostream& oStream,
const BookingClass& iBookingClass,
const std::string& iLeadingString) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Booking-class level (only)
*
* See the method below (csvBookingClassDisplay() at FlightDate level)
* for the details of the header.
*/
oStream << iLeadingString << iBookingClass.getClassCode();
if (iBookingClass.getSubclassCode() == 0) {
oStream << ", ";
} else {
oStream << iBookingClass.getSubclassCode() << ", ";
}
oStream << iBookingClass.getAuthorizationLevel() << " ("
<< iBookingClass.getProtection() << "), "
<< iBookingClass.getNegotiatedSpace() << ", "
<< iBookingClass.getNoShowPercentage() << ", "
<< iBookingClass.getCancellationPercentage() << ", "
<< iBookingClass.getNbOfBookings() << ", "
<< iBookingClass.getNbOfGroupBookings() << " ("
<< iBookingClass.getNbOfPendingGroupBookings() << "), "
<< iBookingClass.getNbOfStaffBookings() << ", "
<< iBookingClass.getNbOfWLBookings() << ", "
<< iBookingClass.getETB() << ", "
<< iBookingClass.getNetClassAvailability() << ", "
<< iBookingClass.getNetRevenueAvailability() << ", "
<< iBookingClass.getSegmentAvailability() << ", "
<< std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvBookingClassDisplay (std::ostream& oStream,
const FlightDate& iFlightDate) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Headers
oStream << "******************************************" << std::endl;
oStream << "Subclasses:" << std::endl
<< "-----------" << std::endl;
oStream << "Flight, Segment, Cabin, FF, Subclass, MIN/AU (Prot), "
<< "Nego, NS%, OB%, "
<< "Bkgs, GrpBks (pdg), StfBkgs, WLBkgs, ETB, "
<< "ClassAvl, RevAvl, SegAvl, "
<< std::endl;
// Retrieve the key of the flight-date
const AirlineCode_T& lAirlineCode = iFlightDate.getAirlineCode();
const FlightNumber_T& lFlightNumber = iFlightDate.getFlightNumber();
const Date_T& lFlightDateDate = iFlightDate.getDepartureDate();
// Check whether there are SegmentDate objects
if (BomManager::hasList<SegmentDate> (iFlightDate) == false) {
return;
}
// Browse the segment-dates
const SegmentDateList_T& lSegmentDateList =
BomManager::getList<SegmentDate> (iFlightDate);
for (SegmentDateList_T::const_iterator itSD = lSegmentDateList.begin();
itSD != lSegmentDateList.end(); ++itSD) {
const SegmentDate* lSD_ptr = *itSD;
assert (lSD_ptr != NULL);
// Retrieve the key of the segment-date, as well as its dates
const Date_T& lSegmentDateDate = lSD_ptr->getBoardingDate();
const AirportCode_T& lBoardPoint = lSD_ptr->getBoardingPoint();
const AirportCode_T& lOffPoint = lSD_ptr->getOffPoint();
// Browse the segment-cabins
const SegmentCabinList_T& lSegmentCabinList =
BomManager::getList<SegmentCabin> (*lSD_ptr);
for (SegmentCabinList_T::const_iterator itSC = lSegmentCabinList.begin();
itSC != lSegmentCabinList.end(); ++itSC) {
const SegmentCabin* lSC_ptr = *itSC;
assert (lSC_ptr != NULL);
// Retrieve the key of the segment-cabin
const CabinCode_T& lCabinCode = lSC_ptr->getCabinCode();
// Build the leading string to be displayed
std::ostringstream oSCLeadingStr;
oSCLeadingStr << lAirlineCode << lFlightNumber << " "
<< lFlightDateDate << ", "
<< lBoardPoint << "-" << lOffPoint << " "
<< lSegmentDateDate << ", "
<< lCabinCode << ", ";
// Default Fare Family code, when there are no FF
FamilyCode_T lFamilyCode ("NoFF");
// Check whether there are FareFamily objects
if (BomManager::hasList<FareFamily> (*lSC_ptr) == true) {
// Browse the fare families
const FareFamilyList_T& lFareFamilyList =
BomManager::getList<FareFamily> (*lSC_ptr);
for (FareFamilyList_T::const_iterator itFF = lFareFamilyList.begin();
itFF != lFareFamilyList.end(); ++itFF) {
const FareFamily* lFF_ptr = *itFF;
assert (lFF_ptr != NULL);
// Retrieve the key of the segment-cabin
lFamilyCode = lFF_ptr->getFamilyCode();
// Complete the leading string to be displayed
std::ostringstream oFFLeadingStr;
oFFLeadingStr << oSCLeadingStr.str() << lFamilyCode << ", ";
// Browse the booking-classes
const BookingClassList_T& lBookingClassList =
BomManager::getList<BookingClass> (*lFF_ptr);
for (BookingClassList_T::const_iterator itBC =
lBookingClassList.begin();
itBC != lBookingClassList.end(); ++itBC) {
const BookingClass* lBC_ptr = *itBC;
assert (lBC_ptr != NULL);
//
csvBookingClassDisplay (oStream, *lBC_ptr, oFFLeadingStr.str());
}
}
// Go on to the next segment-cabin
continue;
}
assert (BomManager::hasList<FareFamily> (*lSC_ptr) == false);
// The fare family code is a fake one ('NoFF'), and therefore
// does not vary
std::ostringstream oFFLeadingStr;
oFFLeadingStr << oSCLeadingStr.str() << lFamilyCode << ", ";
// Browse the booking-classes, directly from the segment-cabin object
const BookingClassList_T& lBookingClassList =
BomManager::getList<BookingClass> (*lSC_ptr);
for (BookingClassList_T::const_iterator itBC =
lBookingClassList.begin();
itBC != lBookingClassList.end(); ++itBC) {
const BookingClass* lBC_ptr = *itBC;
assert (lBC_ptr != NULL);
//
csvBookingClassDisplay (oStream, *lBC_ptr, oFFLeadingStr.str());
}
}
}
oStream << "******************************************" << std::endl;
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::
csvDisplay (std::ostream& oStream,
const TravelSolutionList_T& iTravelSolutionList) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
oStream << "Travel solutions:";
unsigned short idx = 0;
for (TravelSolutionList_T::const_iterator itTS =
iTravelSolutionList.begin();
itTS != iTravelSolutionList.end(); ++itTS, ++idx) {
const TravelSolutionStruct& lTS = *itTS;
oStream << std::endl;
oStream << " [" << idx << "] " << lTS.display();
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::
csvDisplay (std::ostream& oStream,
const DatePeriodList_T& iDatePeriodList) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
// Browse the date-period objects
for (DatePeriodList_T::const_iterator itDP = iDatePeriodList.begin();
itDP != iDatePeriodList.end(); ++itDP) {
const DatePeriod* lDP_ptr = *itDP;
assert (lDP_ptr != NULL);
// Display the date-period object
csvDateDisplay (oStream, *lDP_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvSimFQTAirRACDisplay (std::ostream& oStream,
const BomRoot& iBomRoot) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Bom root level (only)
*/
oStream << std::endl;
oStream << "==============================================================="
<< std::endl;
oStream << "BomRoot: " << iBomRoot.describeKey() << std::endl;
oStream << "==============================================================="
<< std::endl;
// Check whether there are airport-pair objects
if (BomManager::hasList<AirportPair> (iBomRoot) == false) {
return;
}
// Browse the airport-pair objects
const AirportPairList_T& lAirportPairList =
BomManager::getList<AirportPair> (iBomRoot);
for (AirportPairList_T::const_iterator itAir = lAirportPairList.begin();
itAir != lAirportPairList.end(); ++itAir ) {
const AirportPair* lAir_ptr = *itAir;
assert (lAir_ptr != NULL);
// Display the airport pair object
csvAirportPairDisplay (oStream, *lAir_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvAirportPairDisplay (std::ostream& oStream,
const AirportPair& iAirportPair) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Airport pair level (only)
*/
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
oStream << "AirportPair: " << iAirportPair.describeKey() << std::endl;
oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
// Check whether there are date-period objects
if (BomManager::hasList<DatePeriod> (iAirportPair) == false) {
return;
}
// Browse the date-period objects
const DatePeriodList_T& lDatePeriodList =
BomManager::getList<DatePeriod> (iAirportPair);
for (DatePeriodList_T::const_iterator itDP = lDatePeriodList.begin();
itDP != lDatePeriodList.end(); ++itDP) {
const DatePeriod* lDP_ptr = *itDP;
assert (lDP_ptr != NULL);
// Display the date-period object
csvDateDisplay (oStream, *lDP_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvDateDisplay (std::ostream& oStream,
const DatePeriod& iDatePeriod) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Date-Period level (only).
*/
oStream << "------------------------------------------" << std::endl;
oStream << "DatePeriod: " << iDatePeriod.describeKey() << std::endl;
oStream << "------------------------------------------" << std::endl;
// Check whether there are pos-channel objects
if (BomManager::hasList<PosChannel> (iDatePeriod) == false) {
return;
}
// Browse the pos-channel objects
const PosChannelList_T& lPosChannelList =
BomManager::getList<PosChannel> (iDatePeriod);
for (PosChannelList_T::const_iterator itPC = lPosChannelList.begin();
itPC != lPosChannelList.end(); ++itPC) {
const PosChannel* lPC_ptr = *itPC;
assert (lPC_ptr != NULL);
// Display the pos-channel object
csvPosChannelDisplay (oStream, *lPC_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvPosChannelDisplay (std::ostream& oStream,
const PosChannel& iPosChannel) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* PosChannel level (only)
*/
oStream << "******************************************" << std::endl;
oStream << "PosChannel: " << iPosChannel.describeKey() << std::endl;
oStream << "******************************************" << std::endl;
// Check whether there are time-period objects
if (BomManager::hasList<TimePeriod> (iPosChannel) == false) {
return;
}
// Browse the time-period objects
const TimePeriodList_T& lTimePeriodList =
BomManager::getList<TimePeriod> (iPosChannel);
for (TimePeriodList_T::const_iterator itTP = lTimePeriodList.begin();
itTP != lTimePeriodList.end(); ++itTP) {
const TimePeriod* lTP_ptr = *itTP;
assert (lTP_ptr != NULL);
// Display the time-period object
csvTimeDisplay (oStream, *lTP_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::csvTimeDisplay (std::ostream& oStream,
const TimePeriod& iTimePeriod) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Time-Period level (only).
*/
oStream << "----------------------------------------" << std::endl;
oStream << "TimePeriod: " << iTimePeriod.describeKey() << std::endl;
oStream << "----------------------------------------" << std::endl;
// Only one of the fare/yield feature list exists. Each of the following
// two methods will check for the existence of the list. So, only the
// existing list will be actually displayed.
csvFeatureListDisplay<FareFeatures> (oStream, iTimePeriod);
csvFeatureListDisplay<YieldFeatures> (oStream, iTimePeriod);
}
// ////////////////////////////////////////////////////////////////////
template <typename FEATURE_TYPE>
void BomDisplay::csvFeatureListDisplay (std::ostream& oStream,
const TimePeriod& iTimePeriod) {
// Check whether there are fare/yield-feature objects
if (BomManager::hasList<FEATURE_TYPE> (iTimePeriod) == false) {
return;
}
// Browse the fare/yield-feature objects
typedef typename BomHolder<FEATURE_TYPE>::BomList_T FeaturesList_T;
const FeaturesList_T& lFeaturesList =
BomManager::getList<FEATURE_TYPE> (iTimePeriod);
for (typename FeaturesList_T::const_iterator itFF = lFeaturesList.begin();
itFF != lFeaturesList.end(); ++itFF) {
const FEATURE_TYPE* lFF_ptr = *itFF;
assert (lFF_ptr != NULL);
// Display the fare-features object
csvFeaturesDisplay (oStream, *lFF_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
template <typename FEATURE_TYPE>
void BomDisplay::csvFeaturesDisplay (std::ostream& oStream,
const FEATURE_TYPE& iFeatures) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* Fare/yield-Features level (only).
*/
oStream << "--------------------------------------" << std::endl;
oStream << "Fare/yield-Features: " << iFeatures.describeKey() << std::endl;
oStream << "--------------------------------------" << std::endl;
// Check whether there are airlineClassList objects
if (BomManager::hasList<AirlineClassList> (iFeatures) == false) {
return;
}
// Browse the airlineClassList objects
const AirlineClassListList_T& lAirlineClassListList =
BomManager::getList<AirlineClassList> (iFeatures);
for (AirlineClassListList_T::const_iterator itACL =
lAirlineClassListList.begin();
itACL != lAirlineClassListList.end(); ++itACL) {
const AirlineClassList* lACL_ptr = *itACL;
assert (lACL_ptr != NULL);
// Display the airlineClassList object
csvAirlineClassDisplay(oStream, *lACL_ptr);
}
}
// ////////////////////////////////////////////////////////////////////
void BomDisplay::
csvAirlineClassDisplay (std::ostream& oStream,
const AirlineClassList& iAirlineClassList) {
// Save the formatting flags for the given STL output stream
FlagSaver flagSaver (oStream);
/**
* AirlineClassList level (only).
*/
oStream << "------------------------------------" << std::endl;
oStream << "AirlineClassList: "
<< iAirlineClassList.describeKey() << std::endl;
oStream << "------------------------------------" << std::endl;
}
}
/*!
* \endcode
*/
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkFileReaderRegistry.h"
#include "mitkIMimeTypeProvider.h"
#include "mitkCoreServices.h"
// Microservices
#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include <usServiceProperties.h>
#include <usLDAPProp.h>
#include "itksys/SystemTools.hxx"
mitk::FileReaderRegistry::FileReaderRegistry()
{
}
mitk::FileReaderRegistry::~FileReaderRegistry()
{
for (std::map<mitk::IFileReader*, us::ServiceObjects<mitk::IFileReader> >::iterator iter = m_ServiceObjects.begin(),
end = m_ServiceObjects.end(); iter != end; ++iter)
{
iter->second.UngetService(iter->first);
}
}
mitk::MimeType mitk::FileReaderRegistry::GetMimeTypeForFile(const std::string& path, us::ModuleContext* context)
{
mitk::CoreServicePointer<mitk::IMimeTypeProvider> mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider(context));
std::vector<MimeType> mimeTypes = mimeTypeProvider->GetMimeTypesForFile(path);
if (mimeTypes.empty())
{
return MimeType();
}
else
{
return mimeTypes.front();
}
}
std::vector<mitk::FileReaderRegistry::ReaderReference> mitk::FileReaderRegistry::GetReferences(const MimeType& mimeType, us::ModuleContext* context)
{
std::string filter = us::LDAPProp(us::ServiceConstants::OBJECTCLASS()) == us_service_interface_iid<IFileReader>() &&
us::LDAPProp(IFileReader::PROP_MIMETYPE()) == mimeType.GetName();
return context->GetServiceReferences<IFileReader>(filter);
}
mitk::IFileReader* mitk::FileReaderRegistry::GetReader(const mitk::FileReaderRegistry::ReaderReference& ref, us::ModuleContext* context)
{
us::ServiceObjects<mitk::IFileReader> serviceObjects = context->GetServiceObjects(ref);
mitk::IFileReader* reader = serviceObjects.GetService();
m_ServiceObjects.insert(std::make_pair(reader, serviceObjects));
return reader;
}
std::vector <mitk::IFileReader*> mitk::FileReaderRegistry::GetReaders(const MimeType& mimeType, us::ModuleContext* context )
{
std::vector <mitk::IFileReader*> result;
if (!mimeType.IsValid()) return result;
std::vector <us::ServiceReference<IFileReader> > refs = GetReferences(mimeType, context);
std::sort(refs.begin(), refs.end());
result.reserve(refs.size());
// Translate List of ServiceRefs to List of Pointers
for (std::vector<us::ServiceReference<IFileReader> >::const_reverse_iterator iter = refs.rbegin(), end = refs.rend();
iter != end; ++iter)
{
us::ServiceObjects<mitk::IFileReader> serviceObjects = context->GetServiceObjects(*iter);
mitk::IFileReader* reader = serviceObjects.GetService();
m_ServiceObjects.insert(std::make_pair(reader, serviceObjects));
result.push_back(reader);
}
return result;
}
void mitk::FileReaderRegistry::UngetReader(mitk::IFileReader* reader)
{
std::map<mitk::IFileReader*, us::ServiceObjects<mitk::IFileReader> >::iterator readerIter =
m_ServiceObjects.find(reader);
if (readerIter != m_ServiceObjects.end())
{
readerIter->second.UngetService(reader);
m_ServiceObjects.erase(readerIter);
}
}
void mitk::FileReaderRegistry::UngetReaders(const std::vector<mitk::IFileReader*>& readers)
{
for (std::vector<mitk::IFileReader*>::const_iterator iter = readers.begin(), end = readers.end();
iter != end; ++iter)
{
this->UngetReader(*iter);
}
}
Added a check to the FileReader Registry
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkFileReaderRegistry.h"
#include "mitkIMimeTypeProvider.h"
#include "mitkCoreServices.h"
// Microservices
#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include <usServiceProperties.h>
#include <usLDAPProp.h>
#include "itksys/SystemTools.hxx"
mitk::FileReaderRegistry::FileReaderRegistry()
{
}
mitk::FileReaderRegistry::~FileReaderRegistry()
{
for (std::map<mitk::IFileReader*, us::ServiceObjects<mitk::IFileReader> >::iterator iter = m_ServiceObjects.begin(),
end = m_ServiceObjects.end(); iter != end; ++iter)
{
iter->second.UngetService(iter->first);
}
}
mitk::MimeType mitk::FileReaderRegistry::GetMimeTypeForFile(const std::string& path, us::ModuleContext* context)
{
if (path.empty()){
MITK_ERROR << "Warning: FileReaderRegistry::GetMimeTypeForFile was called with empty path. Returning empty MimeType, please report this error to the developers.";
return MimeType();
}
mitk::CoreServicePointer<mitk::IMimeTypeProvider> mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider(context));
std::vector<MimeType> mimeTypes = mimeTypeProvider->GetMimeTypesForFile(path);
if (mimeTypes.empty())
{
return MimeType();
}
else
{
return mimeTypes.front();
}
}
std::vector<mitk::FileReaderRegistry::ReaderReference> mitk::FileReaderRegistry::GetReferences(const MimeType& mimeType, us::ModuleContext* context)
{
std::string filter = us::LDAPProp(us::ServiceConstants::OBJECTCLASS()) == us_service_interface_iid<IFileReader>() &&
us::LDAPProp(IFileReader::PROP_MIMETYPE()) == mimeType.GetName();
return context->GetServiceReferences<IFileReader>(filter);
}
mitk::IFileReader* mitk::FileReaderRegistry::GetReader(const mitk::FileReaderRegistry::ReaderReference& ref, us::ModuleContext* context)
{
us::ServiceObjects<mitk::IFileReader> serviceObjects = context->GetServiceObjects(ref);
mitk::IFileReader* reader = serviceObjects.GetService();
m_ServiceObjects.insert(std::make_pair(reader, serviceObjects));
return reader;
}
std::vector <mitk::IFileReader*> mitk::FileReaderRegistry::GetReaders(const MimeType& mimeType, us::ModuleContext* context )
{
std::vector <mitk::IFileReader*> result;
if (!mimeType.IsValid()) return result;
std::vector <us::ServiceReference<IFileReader> > refs = GetReferences(mimeType, context);
std::sort(refs.begin(), refs.end());
result.reserve(refs.size());
// Translate List of ServiceRefs to List of Pointers
for (std::vector<us::ServiceReference<IFileReader> >::const_reverse_iterator iter = refs.rbegin(), end = refs.rend();
iter != end; ++iter)
{
us::ServiceObjects<mitk::IFileReader> serviceObjects = context->GetServiceObjects(*iter);
mitk::IFileReader* reader = serviceObjects.GetService();
m_ServiceObjects.insert(std::make_pair(reader, serviceObjects));
result.push_back(reader);
}
return result;
}
void mitk::FileReaderRegistry::UngetReader(mitk::IFileReader* reader)
{
std::map<mitk::IFileReader*, us::ServiceObjects<mitk::IFileReader> >::iterator readerIter =
m_ServiceObjects.find(reader);
if (readerIter != m_ServiceObjects.end())
{
readerIter->second.UngetService(reader);
m_ServiceObjects.erase(readerIter);
}
}
void mitk::FileReaderRegistry::UngetReaders(const std::vector<mitk::IFileReader*>& readers)
{
for (std::vector<mitk::IFileReader*>::const_iterator iter = readers.begin(), end = readers.end();
iter != end; ++iter)
{
this->UngetReader(*iter);
}
}
|
#include "gtest-1.7.0/include/gtest/gtest.h"
#include "xgldevice.h"
XglDevice::XglDevice(XGL_UINT id, XGL_PHYSICAL_GPU obj) :
m_flags(0),
XglGpu(id, obj)
{
init_device();
init_formats();
}
void XglDevice::init_device()
{
XGL_DEVICE_CREATE_INFO info = {};
XGL_RESULT err;
XGL_SIZE size;
XGL_UINT i;
info.sType = XGL_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
info.maxValidationLevel = XGL_VALIDATION_LEVEL_END_RANGE;
info.flags = XGL_DEVICE_CREATE_VALIDATION_BIT;
/* request all queues */
info.queueRecordCount = this->queue_count;
info.pRequestedQueues = this->queue_reqs;
/* enable all extensions */
info.extensionCount = this->extension_count;
info.ppEnabledExtensionNames = this->extensions;
err = xglCreateDevice(this->gpuObj, &info, &m_xgl_device_object);
ASSERT_XGL_SUCCESS(err);
err = xglGetMemoryHeapCount(m_xgl_device_object, &this->heap_count);
ASSERT_XGL_SUCCESS(err);
ASSERT_GE(1, this->heap_count) << "No memory heaps available";
this->heap_props = new XGL_MEMORY_HEAP_PROPERTIES [this->heap_count];
ASSERT_TRUE(NULL != this->heap_props) << "Out of memory";
for (i = 0; i < this->heap_count; i++) {
err = xglGetMemoryHeapInfo(m_xgl_device_object, i,
XGL_INFO_TYPE_MEMORY_HEAP_PROPERTIES,
&size, &this->heap_props[i]);
ASSERT_XGL_SUCCESS(err);
ASSERT_EQ(size, sizeof(this->heap_props[0])) << "Invalid heap property size";
}
}
void XglDevice::init_formats()
{
XGL_CHANNEL_FORMAT ch;
XGL_NUM_FORMAT num;
for (int chInt = XGL_CH_FMT_UNDEFINED; chInt < XGL_MAX_CH_FMT; chInt++) {
for (int numInt = 0; numInt < XGL_MAX_NUM_FMT; numInt++) {
XGL_FORMAT fmt = {};
XGL_RESULT err;
XGL_SIZE size;
fmt.channelFormat = static_cast<XGL_CHANNEL_FORMAT>(chInt);
fmt.numericFormat = static_cast<XGL_NUM_FORMAT>(numInt);
err = xglGetFormatInfo(m_xgl_device_object, fmt,
XGL_INFO_TYPE_FORMAT_PROPERTIES,
&size, &this->format_props[ch][num]);
if (err) {
memset(&this->format_props[ch][num], 0,
sizeof(this->format_props[ch][num]));
}
else if (size != sizeof(this->format_props[ch][num])) {
ASSERT_EQ(size, sizeof(this->format_props[ch][num])) << "Incorrect data size";
}
}
}
}
void XglDevice::get_device_queue(XGL_QUEUE_TYPE queue_type, XGL_UINT queue_idx)
{
XGL_RESULT err;
err = xglGetDeviceQueue(this->device(), queue_type, queue_idx, &this->m_queue);
ASSERT_XGL_SUCCESS(err) << "xglGetDeviceQueue failed";
}
XGL_RESULT XglDevice::AllocAndBindGpuMemory(XGL_OBJECT obj, const std::string &objName, XGL_GPU_MEMORY *pMem)
{
XGL_RESULT err;
XGL_MEMORY_REQUIREMENTS mem_req;
XGL_UINT data_size;
err = xglGetObjectInfo(obj, XGL_INFO_TYPE_MEMORY_REQUIREMENTS, &data_size, &mem_req);
if (err != XGL_SUCCESS) return err;
if (mem_req.size > 0) {
XGL_MEMORY_ALLOC_INFO mem_info = {
XGL_STRUCTURE_TYPE_MEMORY_ALLOC_INFO,
XGL_NULL_HANDLE,
mem_req.size, // allocationSize
mem_req.alignment, // alignment
XGL_MEMORY_ALLOC_SHAREABLE_BIT, // XGL_MEMORY_ALLOC_FLAGS
mem_req.heapCount, // heapCount
{0}, // heaps
XGL_MEMORY_PRIORITY_NORMAL // XGL_MEMORY_PRIORITY
};
memcpy(mem_info.heaps, mem_req.heaps, sizeof(XGL_UINT)*XGL_MAX_MEMORY_HEAPS);
err = xglAllocMemory(device(), &mem_info, pMem);
if (err != XGL_SUCCESS) return err;
err = xglBindObjectMemory(obj, *pMem, 0);
if (err != XGL_SUCCESS) return err;
}
return err;
}
tests: fix memory access with uninitialized values
ch and num are uninitialized.
#include "gtest-1.7.0/include/gtest/gtest.h"
#include "xgldevice.h"
XglDevice::XglDevice(XGL_UINT id, XGL_PHYSICAL_GPU obj) :
m_flags(0),
XglGpu(id, obj)
{
init_device();
init_formats();
}
void XglDevice::init_device()
{
XGL_DEVICE_CREATE_INFO info = {};
XGL_RESULT err;
XGL_SIZE size;
XGL_UINT i;
info.sType = XGL_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
info.maxValidationLevel = XGL_VALIDATION_LEVEL_END_RANGE;
info.flags = XGL_DEVICE_CREATE_VALIDATION_BIT;
/* request all queues */
info.queueRecordCount = this->queue_count;
info.pRequestedQueues = this->queue_reqs;
/* enable all extensions */
info.extensionCount = this->extension_count;
info.ppEnabledExtensionNames = this->extensions;
err = xglCreateDevice(this->gpuObj, &info, &m_xgl_device_object);
ASSERT_XGL_SUCCESS(err);
err = xglGetMemoryHeapCount(m_xgl_device_object, &this->heap_count);
ASSERT_XGL_SUCCESS(err);
ASSERT_GE(1, this->heap_count) << "No memory heaps available";
this->heap_props = new XGL_MEMORY_HEAP_PROPERTIES [this->heap_count];
ASSERT_TRUE(NULL != this->heap_props) << "Out of memory";
for (i = 0; i < this->heap_count; i++) {
err = xglGetMemoryHeapInfo(m_xgl_device_object, i,
XGL_INFO_TYPE_MEMORY_HEAP_PROPERTIES,
&size, &this->heap_props[i]);
ASSERT_XGL_SUCCESS(err);
ASSERT_EQ(size, sizeof(this->heap_props[0])) << "Invalid heap property size";
}
}
void XglDevice::init_formats()
{
for (int chInt = XGL_CH_FMT_UNDEFINED; chInt < XGL_MAX_CH_FMT; chInt++) {
for (int numInt = 0; numInt < XGL_MAX_NUM_FMT; numInt++) {
XGL_FORMAT fmt = {};
XGL_RESULT err;
XGL_SIZE size;
fmt.channelFormat = static_cast<XGL_CHANNEL_FORMAT>(chInt);
fmt.numericFormat = static_cast<XGL_NUM_FORMAT>(numInt);
err = xglGetFormatInfo(m_xgl_device_object, fmt,
XGL_INFO_TYPE_FORMAT_PROPERTIES,
&size, &this->format_props[chInt][numInt]);
if (err) {
memset(&this->format_props[chInt][numInt], 0,
sizeof(this->format_props[chInt][numInt]));
}
else if (size != sizeof(this->format_props[chInt][numInt])) {
ASSERT_EQ(size, sizeof(this->format_props[chInt][numInt])) << "Incorrect data size";
}
}
}
}
void XglDevice::get_device_queue(XGL_QUEUE_TYPE queue_type, XGL_UINT queue_idx)
{
XGL_RESULT err;
err = xglGetDeviceQueue(this->device(), queue_type, queue_idx, &this->m_queue);
ASSERT_XGL_SUCCESS(err) << "xglGetDeviceQueue failed";
}
XGL_RESULT XglDevice::AllocAndBindGpuMemory(XGL_OBJECT obj, const std::string &objName, XGL_GPU_MEMORY *pMem)
{
XGL_RESULT err;
XGL_MEMORY_REQUIREMENTS mem_req;
XGL_UINT data_size;
err = xglGetObjectInfo(obj, XGL_INFO_TYPE_MEMORY_REQUIREMENTS, &data_size, &mem_req);
if (err != XGL_SUCCESS) return err;
if (mem_req.size > 0) {
XGL_MEMORY_ALLOC_INFO mem_info = {
XGL_STRUCTURE_TYPE_MEMORY_ALLOC_INFO,
XGL_NULL_HANDLE,
mem_req.size, // allocationSize
mem_req.alignment, // alignment
XGL_MEMORY_ALLOC_SHAREABLE_BIT, // XGL_MEMORY_ALLOC_FLAGS
mem_req.heapCount, // heapCount
{0}, // heaps
XGL_MEMORY_PRIORITY_NORMAL // XGL_MEMORY_PRIORITY
};
memcpy(mem_info.heaps, mem_req.heaps, sizeof(XGL_UINT)*XGL_MAX_MEMORY_HEAPS);
err = xglAllocMemory(device(), &mem_info, pMem);
if (err != XGL_SUCCESS) return err;
err = xglBindObjectMemory(obj, *pMem, 0);
if (err != XGL_SUCCESS) return err;
}
return err;
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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.
=========================================================================*/
#include "mitkPointSetMapper2D.h"
#include "mitkPointSet.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "vtkLinearTransform.h"
#include "mitkStringProperty.h"
#include "mitkPointSet.h"
#include "mitkVtkPropRenderer.h"
#include "mitkGL.h"
//const float selectedColor[]={1.0,0.0,0.6}; //for selected!
mitk::PointSetMapper2D::PointSetMapper2D()
: m_Polygon(false),
m_ShowPoints(true),
m_ShowDistances(false),
m_DistancesDecimalDigits(1),
m_ShowAngles(false),
m_ShowDistantLines(true),
m_LineWidth(1)
{
}
mitk::PointSetMapper2D::~PointSetMapper2D()
{
}
const mitk::PointSet *mitk::PointSetMapper2D::GetInput(void)
{
return static_cast<const mitk::PointSet * > ( GetData() );
}
void mitk::PointSetMapper2D::ApplyProperties(mitk::BaseRenderer* renderer)
{
GLMapper2D::ApplyProperties( renderer );
const mitk::DataTreeNode* node=GetDataTreeNode();
if( node == NULL )
return;
node->GetBoolProperty("contour", m_Polygon);
node->GetBoolProperty("show points", m_ShowPoints);
node->GetBoolProperty("show distances", m_ShowDistances);
node->GetIntProperty("distance decimal digits", m_DistancesDecimalDigits);
node->GetBoolProperty("show angles", m_ShowAngles);
node->GetBoolProperty("show distant lines", m_ShowDistantLines);
node->GetIntProperty("line width", m_LineWidth);
}
static bool makePerpendicularVector2D(const mitk::Vector2D& in, mitk::Vector2D& out)
{
if((fabs(in[0])>0) && ( (fabs(in[0])>fabs(in[1])) || (in[1] == 0) ) )
{
out[0]=-in[1]/in[0];
out[1]=1;
out.Normalize();
return true;
}
else
if(fabs(in[1])>0)
{
out[0]=1;
out[1]=-in[0]/in[1];
out.Normalize();
return true;
}
else
return false;
}
void mitk::PointSetMapper2D::Paint( mitk::BaseRenderer *renderer )
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if( node == NULL )
return;
const int text2dDistance = 10;
if(IsVisible(renderer)==false) return;
// @FIXME: Logik fuer update
bool updateNeccesary=true;
if (updateNeccesary)
{
// ok, das ist aus GenerateData kopiert
mitk::PointSet::Pointer input = const_cast<mitk::PointSet*>(this->GetInput());
// Get the TimeSlicedGeometry of the input object
const TimeSlicedGeometry* inputTimeGeometry = input->GetTimeSlicedGeometry();
if (( inputTimeGeometry == NULL ) || ( inputTimeGeometry->GetTimeSteps() == 0 ) )
{
return;
}
//
// get the world time
//
const Geometry2D* worldGeometry = renderer->GetCurrentWorldGeometry2D();
assert( worldGeometry != NULL );
ScalarType time = worldGeometry->GetTimeBounds()[ 0 ];
//
// convert the world time in time steps of the input object
//
int timeStep=0;
if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
timeStep = inputTimeGeometry->MSToTimeStep( time );
if ( inputTimeGeometry->IsValidTime( timeStep ) == false )
{
return;
}
mitk::PointSet::DataType::Pointer itkPointSet = input->GetPointSet( timeStep );
if ( itkPointSet.GetPointer() == NULL)
{
return;
}
mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
assert(displayGeometry.IsNotNull());
//apply color and opacity read from the PropertyList
ApplyProperties(renderer);
vtkLinearTransform* transform = GetDataTreeNode()->GetVtkTransform();
//List of the Points
PointSet::DataType::PointsContainerConstIterator it, end;
it = itkPointSet->GetPoints()->Begin();
end = itkPointSet->GetPoints()->End();
//iterator on the additional data of each point
PointSet::DataType::PointDataContainerIterator selIt, selEnd;
bool pointDataBroken = (itkPointSet->GetPointData()->Size() != itkPointSet->GetPoints()->Size());
selIt = itkPointSet->GetPointData()->Begin();
selEnd = itkPointSet->GetPointData()->End();
int counter = 0;
//for writing text
int j = 0;
//for switching back to old color after using selected color
float recallColor[4];
glGetFloatv(GL_CURRENT_COLOR,recallColor);
//get the properties for coloring the points
float unselectedColor[4] = {1.0, 1.0, 0.0, 1.0};//yellow
//check if there is an unselected property
if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(renderer)->GetProperty("unselectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(renderer)->GetProperty("unselectedcolor"))->GetValue();
unselectedColor[0] = tmpColor[0];
unselectedColor[1] = tmpColor[1];
unselectedColor[2] = tmpColor[2];
unselectedColor[3] = 1.0f; //!!define a new ColorProp to be able to pass alpha value
}
else if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(NULL)->GetProperty("unselectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(NULL)->GetProperty("unselectedcolor"))->GetValue();
unselectedColor[0] = tmpColor[0];
unselectedColor[1] = tmpColor[1];
unselectedColor[2] = tmpColor[2];
unselectedColor[3] = 1.0f; //!!define a new ColorProp to be able to pass alpha value
}
else
{
//get the color from the dataTreeNode
node->GetColor(unselectedColor, NULL);
}
//get selected property
float selectedColor[4] = {1.0, 0.0, 0.6, 1.0};
if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(renderer)->GetProperty("selectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(renderer)->GetProperty("selectedcolor"))->GetValue();
selectedColor[0] = tmpColor[0];
selectedColor[1] = tmpColor[1];
selectedColor[2] = tmpColor[2];
selectedColor[3] = 1.0f;
}
else if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(NULL)->GetProperty("selectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(NULL)->GetProperty("selectedcolor"))->GetValue();
selectedColor[0] = tmpColor[0];
selectedColor[1] = tmpColor[1];
selectedColor[2] = tmpColor[2];
selectedColor[3] = 1.0f;
}
Point3D p; // currently visited point
Point3D lastP; // last visited point
Vector3D vec; // p - lastP
Vector3D lastVec; // lastP - point before lastP
vec.Fill(0);
mitk::Point3D projected_p; // p projected on viewplane
Point2D pt2d; // projected_p in display coordinates
Point2D lastPt2d; // last projected_p in display coordinates
Point2D preLastPt2d;// projected_p in display coordinates before lastPt2d
while(it!=end) // iterate over all points
{
lastP = p; // valid only for counter > 0
lastVec = vec; // valid only for counter > 1
preLastPt2d = lastPt2d; // valid only for counter > 1
lastPt2d = pt2d; // valid only for counter > 0
float vtkp[3];
itk2vtk(it->Value(), vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
vec = p-lastP; // valid only for counter > 0
displayGeometry->Project(p, projected_p);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetSquaredNorm();
//MouseOrientation
bool isInputDevice=false;
bool isRendererSlice = scalardiff < 0.00001; //cause roundoff error
if(this->GetDataTreeNode()->GetBoolProperty("inputdevice",isInputDevice) && isInputDevice && !isRendererSlice )
{
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
//Point size depending of distance to slice
float p_size = (1/scalardiff)*100;
if(p_size < 6.0 )
p_size = 6.0;
else if ( p_size > 10.0 )
p_size = 10.0;
//draw Point
float opacity = (p_size<8)?0.3:1.0;//don't get the opacity from the node? Feature not a bug! Otehrwise the 2D cross is hardly seen.
glColor4f(unselectedColor[0],unselectedColor[1],unselectedColor[2],opacity);
glPointSize(p_size);
//glShadeModel(GL_FLAT);
glBegin (GL_POINTS);
glVertex2fv(&pt2d[0]);
glEnd ();
}
//for point set
if(!isInputDevice && ( (scalardiff<4.0) || (m_Polygon)))
{
Point2D tmp;
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector2D horz,vert;
horz[0]=8.0-scalardiff*2; horz[1]=0;
vert[0]=0; vert[1]=8.0-scalardiff*2;
// now paint text if available
if (dynamic_cast<mitk::StringProperty *>(this->GetDataTreeNode()
->GetProperty("label")) != NULL)
{
const char * pointLabel = dynamic_cast<mitk::StringProperty *>(
this->GetDataTreeNode()->GetProperty("label"))->GetValue();
char buffer[20];
std::string l = pointLabel;
if (input->GetSize()>1)
{
sprintf(buffer,"%d",j+1);
l.append(buffer);
}
if (unselectedColor != NULL)
{
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
float rgb[3];//yellow
rgb[0] = unselectedColor[0]; rgb[1] = unselectedColor[1]; rgb[2] = unselectedColor[2];
OpenGLrenderer->WriteSimpleText(l, pt2d[0] + text2dDistance, pt2d[1] + text2dDistance,rgb[0], rgb[1],rgb[2]);
}
else
{
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
OpenGLrenderer->WriteSimpleText(l, pt2d[0] + text2dDistance, pt2d[1] + text2dDistance,0.0,1.0,0.0);
}
}
if((m_ShowPoints) && (scalardiff<4.0))
{
//check if the point is to be marked as selected
if(selIt != selEnd || pointDataBroken)
{
bool addAsSelected = false;
if (pointDataBroken)
addAsSelected = false;
else if (selIt->Value().selected)
addAsSelected = true;
else
addAsSelected = false;
if (addAsSelected)
{
horz[0]=8;
vert[1]=8;
glColor3f(selectedColor[0],selectedColor[1],selectedColor[2]);
//a diamond around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2fv(&tmp[0]);
tmp=pt2d+vert; glVertex2fv(&tmp[0]);
tmp=pt2d+horz; glVertex2fv(&tmp[0]);
tmp=pt2d-vert; glVertex2fv(&tmp[0]);
glEnd ();
//the actual point in the specified color to see the usual color of the point
glColor3f(unselectedColor[0],unselectedColor[1],unselectedColor[2]);
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2fv(&tmp[0]);
glEnd ();
}
else //if not selected
{
glColor3f(unselectedColor[0],unselectedColor[1],unselectedColor[2]);
//drawing crosses
glBegin (GL_LINES);
tmp=pt2d-horz; glVertex2fv(&tmp[0]);
tmp=pt2d+horz; glVertex2fv(&tmp[0]);
tmp=pt2d-vert; glVertex2fv(&tmp[0]);
tmp=pt2d+vert; glVertex2fv(&tmp[0]);
glEnd ();
}
}
}
bool drawLinesEtc = true;
if (!m_ShowDistantLines && counter > 0) // check, whether this line should be drawn
{
ScalarType currentDistance = displayGeometry->GetWorldGeometry()->SignedDistance(p);
ScalarType lastDistance = displayGeometry->GetWorldGeometry()->SignedDistance(lastP);
if ( currentDistance * lastDistance > 0.5 ) // points on same side of plane
drawLinesEtc = false;
}
if ( m_Polygon && counter > 0 && drawLinesEtc) // draw a line
{
//get contour color property
float contourColor[4] = {unselectedColor[0], unselectedColor[1], unselectedColor[2], unselectedColor[3]};//so if no property set, then use unselected color
if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(renderer)->GetProperty("contourcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(renderer)->GetProperty("contourcolor"))->GetValue();
contourColor[0] = tmpColor[0];
contourColor[1] = tmpColor[1];
contourColor[2] = tmpColor[2];
contourColor[3] = 1.0f;
}
else if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(NULL)->GetProperty("contourcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(NULL)->GetProperty("contourcolor"))->GetValue();
contourColor[0] = tmpColor[0];
contourColor[1] = tmpColor[1];
contourColor[2] = tmpColor[2];
contourColor[3] = 1.0f;
}
//set this color
glColor3f(contourColor[0],contourColor[1],contourColor[2]);
glLineWidth( m_LineWidth );
glBegin (GL_LINES);
glVertex2fv(&pt2d[0]);
glVertex2fv(&lastPt2d[0]);
glEnd ();
glLineWidth(1.0);
if(m_ShowDistances) // calculate and print a distance
{
std::stringstream buffer;
float distance = vec.GetNorm();
buffer<<std::fixed <<std::setprecision(m_DistancesDecimalDigits)<<distance<<" mm";
Vector2D vec2d = pt2d-lastPt2d;
makePerpendicularVector2D(vec2d, vec2d);
Vector2D pos2d = (lastPt2d.GetVectorFromOrigin()+pt2d)*0.5+vec2d*text2dDistance;
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
OpenGLrenderer->WriteSimpleText(buffer.str(), pos2d[0], pos2d[1]);
//this->WriteTextXY(pos2d[0], pos2d[1], buffer.str(),renderer);
}
if(m_ShowAngles && counter > 1 ) // calculate and print the angle btw. two lines
{
std::stringstream buffer;
buffer << angle(vec.Get_vnl_vector(), -lastVec.Get_vnl_vector())*180/vnl_math::pi << "�";
Vector2D vec2d = pt2d-lastPt2d;
vec2d.Normalize();
Vector2D lastVec2d = lastPt2d-preLastPt2d;
lastVec2d.Normalize();
vec2d=vec2d-lastVec2d;
vec2d.Normalize();
Vector2D pos2d = lastPt2d.GetVectorFromOrigin()+vec2d*text2dDistance*text2dDistance;
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
OpenGLrenderer->WriteSimpleText(buffer.str(), pos2d[0], pos2d[1]);
//this->WriteTextXY(pos2d[0], pos2d[1], buffer.str(),renderer);
}
}
counter++;
}
++it;
if(selIt != selEnd && !pointDataBroken)
++selIt;
j++;
}
//recall the color to the same color before this drawing
glColor3f(recallColor[0],recallColor[1],recallColor[2]);
}
}
void mitk::PointSetMapper2D::SetDefaultProperties(mitk::DataTreeNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
node->AddProperty( "line width", mitk::IntProperty::New(2), renderer, overwrite );
node->AddProperty( "pointsize", mitk::FloatProperty::New(1.0), renderer, overwrite);
node->AddProperty( "selectedcolor", mitk::ColorProperty::New(1.0f, 0.0f, 0.0f), renderer, overwrite); //red
node->AddProperty( "color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f), renderer, overwrite); //yellow
node->AddProperty( "contour", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "contourcolor", mitk::ColorProperty::New(1.0f, 0.0f, 0.0f), renderer, overwrite);
node->AddProperty( "close", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "show points", mitk::BoolProperty::New(true), renderer, overwrite );
node->AddProperty( "show distances", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "distance decimal digits", mitk::IntProperty::New(2), renderer, overwrite );
node->AddProperty( "show angles", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "show distant lines", mitk::BoolProperty::New(false), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
FIX (#1382): show degree character correctly
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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.
=========================================================================*/
#include "mitkPointSetMapper2D.h"
#include "mitkPointSet.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "vtkLinearTransform.h"
#include "mitkStringProperty.h"
#include "mitkPointSet.h"
#include "mitkVtkPropRenderer.h"
#include "mitkGL.h"
//const float selectedColor[]={1.0,0.0,0.6}; //for selected!
mitk::PointSetMapper2D::PointSetMapper2D()
: m_Polygon(false),
m_ShowPoints(true),
m_ShowDistances(false),
m_DistancesDecimalDigits(1),
m_ShowAngles(false),
m_ShowDistantLines(true),
m_LineWidth(1)
{
}
mitk::PointSetMapper2D::~PointSetMapper2D()
{
}
const mitk::PointSet *mitk::PointSetMapper2D::GetInput(void)
{
return static_cast<const mitk::PointSet * > ( GetData() );
}
void mitk::PointSetMapper2D::ApplyProperties(mitk::BaseRenderer* renderer)
{
GLMapper2D::ApplyProperties( renderer );
const mitk::DataTreeNode* node=GetDataTreeNode();
if( node == NULL )
return;
node->GetBoolProperty("contour", m_Polygon);
node->GetBoolProperty("show points", m_ShowPoints);
node->GetBoolProperty("show distances", m_ShowDistances);
node->GetIntProperty("distance decimal digits", m_DistancesDecimalDigits);
node->GetBoolProperty("show angles", m_ShowAngles);
node->GetBoolProperty("show distant lines", m_ShowDistantLines);
node->GetIntProperty("line width", m_LineWidth);
}
static bool makePerpendicularVector2D(const mitk::Vector2D& in, mitk::Vector2D& out)
{
if((fabs(in[0])>0) && ( (fabs(in[0])>fabs(in[1])) || (in[1] == 0) ) )
{
out[0]=-in[1]/in[0];
out[1]=1;
out.Normalize();
return true;
}
else
if(fabs(in[1])>0)
{
out[0]=1;
out[1]=-in[0]/in[1];
out.Normalize();
return true;
}
else
return false;
}
void mitk::PointSetMapper2D::Paint( mitk::BaseRenderer *renderer )
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if( node == NULL )
return;
const int text2dDistance = 10;
if(IsVisible(renderer)==false) return;
// @FIXME: Logik fuer update
bool updateNeccesary=true;
if (updateNeccesary)
{
// ok, das ist aus GenerateData kopiert
mitk::PointSet::Pointer input = const_cast<mitk::PointSet*>(this->GetInput());
// Get the TimeSlicedGeometry of the input object
const TimeSlicedGeometry* inputTimeGeometry = input->GetTimeSlicedGeometry();
if (( inputTimeGeometry == NULL ) || ( inputTimeGeometry->GetTimeSteps() == 0 ) )
{
return;
}
//
// get the world time
//
const Geometry2D* worldGeometry = renderer->GetCurrentWorldGeometry2D();
assert( worldGeometry != NULL );
ScalarType time = worldGeometry->GetTimeBounds()[ 0 ];
//
// convert the world time in time steps of the input object
//
int timeStep=0;
if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
timeStep = inputTimeGeometry->MSToTimeStep( time );
if ( inputTimeGeometry->IsValidTime( timeStep ) == false )
{
return;
}
mitk::PointSet::DataType::Pointer itkPointSet = input->GetPointSet( timeStep );
if ( itkPointSet.GetPointer() == NULL)
{
return;
}
mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
assert(displayGeometry.IsNotNull());
//apply color and opacity read from the PropertyList
ApplyProperties(renderer);
vtkLinearTransform* transform = GetDataTreeNode()->GetVtkTransform();
//List of the Points
PointSet::DataType::PointsContainerConstIterator it, end;
it = itkPointSet->GetPoints()->Begin();
end = itkPointSet->GetPoints()->End();
//iterator on the additional data of each point
PointSet::DataType::PointDataContainerIterator selIt, selEnd;
bool pointDataBroken = (itkPointSet->GetPointData()->Size() != itkPointSet->GetPoints()->Size());
selIt = itkPointSet->GetPointData()->Begin();
selEnd = itkPointSet->GetPointData()->End();
int counter = 0;
//for writing text
int j = 0;
//for switching back to old color after using selected color
float recallColor[4];
glGetFloatv(GL_CURRENT_COLOR,recallColor);
//get the properties for coloring the points
float unselectedColor[4] = {1.0, 1.0, 0.0, 1.0};//yellow
//check if there is an unselected property
if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(renderer)->GetProperty("unselectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(renderer)->GetProperty("unselectedcolor"))->GetValue();
unselectedColor[0] = tmpColor[0];
unselectedColor[1] = tmpColor[1];
unselectedColor[2] = tmpColor[2];
unselectedColor[3] = 1.0f; //!!define a new ColorProp to be able to pass alpha value
}
else if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(NULL)->GetProperty("unselectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(NULL)->GetProperty("unselectedcolor"))->GetValue();
unselectedColor[0] = tmpColor[0];
unselectedColor[1] = tmpColor[1];
unselectedColor[2] = tmpColor[2];
unselectedColor[3] = 1.0f; //!!define a new ColorProp to be able to pass alpha value
}
else
{
//get the color from the dataTreeNode
node->GetColor(unselectedColor, NULL);
}
//get selected property
float selectedColor[4] = {1.0, 0.0, 0.6, 1.0};
if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(renderer)->GetProperty("selectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(renderer)->GetProperty("selectedcolor"))->GetValue();
selectedColor[0] = tmpColor[0];
selectedColor[1] = tmpColor[1];
selectedColor[2] = tmpColor[2];
selectedColor[3] = 1.0f;
}
else if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(NULL)->GetProperty("selectedcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(NULL)->GetProperty("selectedcolor"))->GetValue();
selectedColor[0] = tmpColor[0];
selectedColor[1] = tmpColor[1];
selectedColor[2] = tmpColor[2];
selectedColor[3] = 1.0f;
}
Point3D p; // currently visited point
Point3D lastP; // last visited point
Vector3D vec; // p - lastP
Vector3D lastVec; // lastP - point before lastP
vec.Fill(0);
mitk::Point3D projected_p; // p projected on viewplane
Point2D pt2d; // projected_p in display coordinates
Point2D lastPt2d; // last projected_p in display coordinates
Point2D preLastPt2d;// projected_p in display coordinates before lastPt2d
while(it!=end) // iterate over all points
{
lastP = p; // valid only for counter > 0
lastVec = vec; // valid only for counter > 1
preLastPt2d = lastPt2d; // valid only for counter > 1
lastPt2d = pt2d; // valid only for counter > 0
float vtkp[3];
itk2vtk(it->Value(), vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
vec = p-lastP; // valid only for counter > 0
displayGeometry->Project(p, projected_p);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetSquaredNorm();
//MouseOrientation
bool isInputDevice=false;
bool isRendererSlice = scalardiff < 0.00001; //cause roundoff error
if(this->GetDataTreeNode()->GetBoolProperty("inputdevice",isInputDevice) && isInputDevice && !isRendererSlice )
{
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
//Point size depending of distance to slice
float p_size = (1/scalardiff)*100;
if(p_size < 6.0 )
p_size = 6.0;
else if ( p_size > 10.0 )
p_size = 10.0;
//draw Point
float opacity = (p_size<8)?0.3:1.0;//don't get the opacity from the node? Feature not a bug! Otehrwise the 2D cross is hardly seen.
glColor4f(unselectedColor[0],unselectedColor[1],unselectedColor[2],opacity);
glPointSize(p_size);
//glShadeModel(GL_FLAT);
glBegin (GL_POINTS);
glVertex2fv(&pt2d[0]);
glEnd ();
}
//for point set
if(!isInputDevice && ( (scalardiff<4.0) || (m_Polygon)))
{
Point2D tmp;
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector2D horz,vert;
horz[0]=8.0-scalardiff*2; horz[1]=0;
vert[0]=0; vert[1]=8.0-scalardiff*2;
// now paint text if available
if (dynamic_cast<mitk::StringProperty *>(this->GetDataTreeNode()
->GetProperty("label")) != NULL)
{
const char * pointLabel = dynamic_cast<mitk::StringProperty *>(
this->GetDataTreeNode()->GetProperty("label"))->GetValue();
char buffer[20];
std::string l = pointLabel;
if (input->GetSize()>1)
{
sprintf(buffer,"%d",j+1);
l.append(buffer);
}
if (unselectedColor != NULL)
{
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
float rgb[3];//yellow
rgb[0] = unselectedColor[0]; rgb[1] = unselectedColor[1]; rgb[2] = unselectedColor[2];
OpenGLrenderer->WriteSimpleText(l, pt2d[0] + text2dDistance, pt2d[1] + text2dDistance,rgb[0], rgb[1],rgb[2]);
}
else
{
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
OpenGLrenderer->WriteSimpleText(l, pt2d[0] + text2dDistance, pt2d[1] + text2dDistance,0.0,1.0,0.0);
}
}
if((m_ShowPoints) && (scalardiff<4.0))
{
//check if the point is to be marked as selected
if(selIt != selEnd || pointDataBroken)
{
bool addAsSelected = false;
if (pointDataBroken)
addAsSelected = false;
else if (selIt->Value().selected)
addAsSelected = true;
else
addAsSelected = false;
if (addAsSelected)
{
horz[0]=8;
vert[1]=8;
glColor3f(selectedColor[0],selectedColor[1],selectedColor[2]);
//a diamond around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2fv(&tmp[0]);
tmp=pt2d+vert; glVertex2fv(&tmp[0]);
tmp=pt2d+horz; glVertex2fv(&tmp[0]);
tmp=pt2d-vert; glVertex2fv(&tmp[0]);
glEnd ();
//the actual point in the specified color to see the usual color of the point
glColor3f(unselectedColor[0],unselectedColor[1],unselectedColor[2]);
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2fv(&tmp[0]);
glEnd ();
}
else //if not selected
{
glColor3f(unselectedColor[0],unselectedColor[1],unselectedColor[2]);
//drawing crosses
glBegin (GL_LINES);
tmp=pt2d-horz; glVertex2fv(&tmp[0]);
tmp=pt2d+horz; glVertex2fv(&tmp[0]);
tmp=pt2d-vert; glVertex2fv(&tmp[0]);
tmp=pt2d+vert; glVertex2fv(&tmp[0]);
glEnd ();
}
}
}
bool drawLinesEtc = true;
if (!m_ShowDistantLines && counter > 0) // check, whether this line should be drawn
{
ScalarType currentDistance = displayGeometry->GetWorldGeometry()->SignedDistance(p);
ScalarType lastDistance = displayGeometry->GetWorldGeometry()->SignedDistance(lastP);
if ( currentDistance * lastDistance > 0.5 ) // points on same side of plane
drawLinesEtc = false;
}
if ( m_Polygon && counter > 0 && drawLinesEtc) // draw a line
{
//get contour color property
float contourColor[4] = {unselectedColor[0], unselectedColor[1], unselectedColor[2], unselectedColor[3]};//so if no property set, then use unselected color
if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(renderer)->GetProperty("contourcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(renderer)->GetProperty("contourcolor"))->GetValue();
contourColor[0] = tmpColor[0];
contourColor[1] = tmpColor[1];
contourColor[2] = tmpColor[2];
contourColor[3] = 1.0f;
}
else if (dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList(NULL)->GetProperty("contourcolor")) != NULL)
{
mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataTreeNode()->GetPropertyList(NULL)->GetProperty("contourcolor"))->GetValue();
contourColor[0] = tmpColor[0];
contourColor[1] = tmpColor[1];
contourColor[2] = tmpColor[2];
contourColor[3] = 1.0f;
}
//set this color
glColor3f(contourColor[0],contourColor[1],contourColor[2]);
glLineWidth( m_LineWidth );
glBegin (GL_LINES);
glVertex2fv(&pt2d[0]);
glVertex2fv(&lastPt2d[0]);
glEnd ();
glLineWidth(1.0);
if(m_ShowDistances) // calculate and print a distance
{
std::stringstream buffer;
float distance = vec.GetNorm();
buffer<<std::fixed <<std::setprecision(m_DistancesDecimalDigits)<<distance<<" mm";
Vector2D vec2d = pt2d-lastPt2d;
makePerpendicularVector2D(vec2d, vec2d);
Vector2D pos2d = (lastPt2d.GetVectorFromOrigin()+pt2d)*0.5+vec2d*text2dDistance;
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
OpenGLrenderer->WriteSimpleText(buffer.str(), pos2d[0], pos2d[1]);
//this->WriteTextXY(pos2d[0], pos2d[1], buffer.str(),renderer);
}
if(m_ShowAngles && counter > 1 ) // calculate and print the angle btw. two lines
{
std::stringstream buffer;
//buffer << angle(vec.Get_vnl_vector(), -lastVec.Get_vnl_vector())*180/vnl_math::pi << "�";
buffer << angle(vec.Get_vnl_vector(), -lastVec.Get_vnl_vector())*180/vnl_math::pi << (char)176;
Vector2D vec2d = pt2d-lastPt2d;
vec2d.Normalize();
Vector2D lastVec2d = lastPt2d-preLastPt2d;
lastVec2d.Normalize();
vec2d=vec2d-lastVec2d;
vec2d.Normalize();
Vector2D pos2d = lastPt2d.GetVectorFromOrigin()+vec2d*text2dDistance*text2dDistance;
mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer );
OpenGLrenderer->WriteSimpleText(buffer.str(), pos2d[0], pos2d[1]);
//this->WriteTextXY(pos2d[0], pos2d[1], buffer.str(),renderer);
}
}
counter++;
}
++it;
if(selIt != selEnd && !pointDataBroken)
++selIt;
j++;
}
//recall the color to the same color before this drawing
glColor3f(recallColor[0],recallColor[1],recallColor[2]);
}
}
void mitk::PointSetMapper2D::SetDefaultProperties(mitk::DataTreeNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
node->AddProperty( "line width", mitk::IntProperty::New(2), renderer, overwrite );
node->AddProperty( "pointsize", mitk::FloatProperty::New(1.0), renderer, overwrite);
node->AddProperty( "selectedcolor", mitk::ColorProperty::New(1.0f, 0.0f, 0.0f), renderer, overwrite); //red
node->AddProperty( "color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f), renderer, overwrite); //yellow
node->AddProperty( "contour", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "contourcolor", mitk::ColorProperty::New(1.0f, 0.0f, 0.0f), renderer, overwrite);
node->AddProperty( "close", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "show points", mitk::BoolProperty::New(true), renderer, overwrite );
node->AddProperty( "show distances", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "distance decimal digits", mitk::IntProperty::New(2), renderer, overwrite );
node->AddProperty( "show angles", mitk::BoolProperty::New(false), renderer, overwrite );
node->AddProperty( "show distant lines", mitk::BoolProperty::New(false), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
|
#include "custom_pch.h"
#include "engine/core/math_types.h"
#include "engine/api/graphics_vm.h"
#include "engine/api/graphics_params.h"
#include "engine/impl/array.h"
#include "engine/impl/array_fixed.h"
#include "engine/impl/bytecode.h"
#if !defined(CUSTOM_PRECOMPILED_HEADER)
#include <glad/glad.h>
#include <new>
#endif
// https://www.khronos.org/registry/OpenGL/index_gl.php
// https://github.com/etodd/lasercrabs/blob/master/src/platform/glvm.cpp
typedef GLchar const * glstring;
namespace opengl {
struct Program
{
GLuint id;
custom::Array<GLuint> uniforms;
};
template struct custom::Array<Program>;
struct Texture
{
GLuint id;
};
template struct custom::Array<Texture>;
struct Attribute
{
u8 count;
};
template struct custom::Array<Attribute>;
struct Buffer
{
GLuint id;
custom::graphics::Data_Type type;
custom::Array<Attribute> attributes;
};
template struct custom::Array<Buffer>;
struct Indices
{
GLuint id;
u32 count;
};
struct Mesh
{
GLuint id;
custom::Array<Buffer> buffers;
Indices indices;
};
template struct custom::Array<Mesh>;
struct Data
{
custom::Array<Program> programs;
custom::Array<Texture> textures;
custom::Array<Mesh> meshes;
};
}
static opengl::Data ogl;
//
// API implementation
//
static void opengl_message_callback(
GLenum source, GLenum type, GLuint id, GLenum severity,
GLsizei length, glstring message, cmemory userParam
);
static GLuint create_program(cstring source, custom::graphics::Shader_Part parts);
namespace custom {
namespace graphics {
static void consume_single_instruction(Bytecode const & bc);
VM::VM()
{
#if !defined(GES_SHIPPING)
GLint version_major;
glGetIntegerv(GL_MAJOR_VERSION, &version_major);
GLint version_minor;
glGetIntegerv(GL_MINOR_VERSION, &version_minor);
CUSTOM_MESSAGE("OpenGL version %d.%d", version_major, version_minor);
if (version_major == 4 && version_minor >= 3 || version_major > 4) {
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(opengl_message_callback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
}
#endif
// glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// glDepthRangef(0.0f, 1.0f);
// glClearDepth(1.0f);
// glFrontFace(GL_CCW);
}
VM::~VM() = default;
void VM::update(Bytecode const & bc)
{
while (bc.offset < bc.buffer.count) {
consume_single_instruction(bc);
#if !defined(CUSTOM_SHIPPING)
static GLenum error = 0;
while ((error = glGetError()) != GL_NO_ERROR) {
CUSTOM_ASSERT(false, "OpenGL error 0x%x", error);
}
#endif
}
}
}}
//
// instruction implementation
//
namespace custom {
namespace graphics {
static GLenum get_comparison(Comparison value) {
switch (value) {
case Comparison::False: return GL_NONE;
case Comparison::Less: return GL_LESS;
case Comparison::LEqual: return GL_LEQUAL;
case Comparison::Equal: return GL_EQUAL;
case Comparison::NEqual: return GL_NOTEQUAL;
case Comparison::GEqual: return GL_GEQUAL;
case Comparison::Greater: return GL_GREATER;
case Comparison::True: return GL_ALWAYS;
}
CUSTOM_ASSERT(false, "unknown comparison %d", value);
return GL_NONE;
}
static GLenum get_operation(Operation value) {
switch (value) {
case Operation::Keep: return GL_KEEP;
case Operation::Zero: return GL_ZERO;
case Operation::Replace: return GL_REPLACE;
case Operation::Incr: return GL_INCR;
case Operation::Incr_Wrap: return GL_INCR_WRAP;
case Operation::Decr: return GL_DECR;
case Operation::Decr_Wrap: return GL_DECR_WRAP;
case Operation::Invert: return GL_INVERT;
}
CUSTOM_ASSERT(false, "unknown operation %d", value);
return GL_NONE;
}
static GLenum get_texture_internal_format(Texture_Type texture_type, Data_Type data_type, u8 channels) {
switch (texture_type) {
case Texture_Type::Color: switch (data_type) {
case Data_Type::u8: switch (channels) {
case 1: return GL_R8;
case 2: return GL_RG8;
case 3: return GL_RGB8;
case 4: return GL_RGBA8;
} break;
case Data_Type::u16: switch (channels) {
case 1: return GL_R16;
case 2: return GL_RG16;
case 3: return GL_RGB16;
case 4: return GL_RGBA16;
} break;
case Data_Type::u32: switch (channels) {
case 1: return GL_R32UI;
case 2: return GL_RG32UI;
case 3: return GL_RGB32UI;
case 4: return GL_RGBA32UI;
} break;
case Data_Type::r32: switch (channels) {
case 1: return GL_R32F;
case 2: return GL_RG32F;
case 3: return GL_RGB32F;
case 4: return GL_RGBA32F;
} break;
} break;
case Texture_Type::Depth: switch (data_type) {
case Data_Type::u16: return GL_DEPTH_COMPONENT16;
case Data_Type::u32: return GL_DEPTH_COMPONENT24;
case Data_Type::r32: return GL_DEPTH_COMPONENT32F;
} break;
case Texture_Type::DStencil: switch (data_type) {
case Data_Type::u32: return GL_DEPTH24_STENCIL8;
case Data_Type::r32: return GL_DEPTH32F_STENCIL8;
}
case Texture_Type::Stencil: switch (data_type) {
case Data_Type::u8: return GL_STENCIL_INDEX8;
}
}
CUSTOM_ASSERT(false, "unknown texture type %d with data type %d and channels count %d", texture_type, data_type, channels);
return GL_NONE;
}
static GLenum get_texture_data_format(Texture_Type texture_type, u8 channels) {
switch (texture_type) {
case Texture_Type::Color: switch (channels) {
case 1: return GL_RED;
case 2: return GL_RG;
case 3: return GL_RGB;
case 4: return GL_RGBA;
} break;
case Texture_Type::Depth:
return GL_DEPTH_COMPONENT;
case Texture_Type::DStencil:
return GL_DEPTH_STENCIL;
case Texture_Type::Stencil:
return GL_STENCIL_INDEX;
}
CUSTOM_ASSERT(false, "unknown texture type %d and channels count %d", texture_type, channels);
return GL_NONE;
}
static GLenum get_min_filter(Filter_Mode texture_filter, Filter_Mode mipmap_filter) {
switch (mipmap_filter) {
case Filter_Mode::None: switch (texture_filter) {
case Filter_Mode::None: return GL_NEAREST;
case Filter_Mode::Point: return GL_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR;
} break;
case Filter_Mode::Point: switch (texture_filter) {
case Filter_Mode::None: return GL_NEAREST_MIPMAP_NEAREST;
case Filter_Mode::Point: return GL_NEAREST_MIPMAP_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR_MIPMAP_NEAREST;
} break;
case Filter_Mode::Linear: switch (texture_filter) {
case Filter_Mode::None: return GL_LINEAR_MIPMAP_NEAREST;
case Filter_Mode::Point: return GL_LINEAR_MIPMAP_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR_MIPMAP_LINEAR;
} break;
}
CUSTOM_ASSERT(false, "unknown texture filter %d and mipmap filter %d", texture_filter, mipmap_filter);
return GL_NONE;
}
static GLenum get_mag_filter(Filter_Mode value) {
switch (value) {
case Filter_Mode::None: return GL_NEAREST;
case Filter_Mode::Point: return GL_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR;
}
CUSTOM_ASSERT(false, "unknown filter mode %d", value);
return GL_NONE;
}
static GLenum get_wrap_mode(Wrap_Mode value) {
switch (value) {
case Wrap_Mode::Repeat: return GL_REPEAT;
case Wrap_Mode::Clamp: return GL_CLAMP_TO_EDGE;
case Wrap_Mode::Mirror_Repeat: return GL_MIRRORED_REPEAT;
case Wrap_Mode::Mirror_Clamp: return GL_MIRROR_CLAMP_TO_EDGE;
}
CUSTOM_ASSERT(false, "unknown wrap mode %d", value);
return GL_NONE;
}
static GLenum get_texture_data_type(Texture_Type texture_type, Data_Type data_type) {
switch (texture_type) {
case Texture_Type::Color: switch (data_type) {
case Data_Type::u8: return GL_UNSIGNED_BYTE;
case Data_Type::u16: return GL_UNSIGNED_SHORT;
case Data_Type::u32: return GL_UNSIGNED_INT;
case Data_Type::r32: return GL_FLOAT;
} break;
case Texture_Type::Depth: switch (data_type) {
case Data_Type::u16: return GL_UNSIGNED_SHORT;
case Data_Type::u32: return GL_UNSIGNED_INT;
case Data_Type::r32: return GL_FLOAT;
} break;
case Texture_Type::DStencil: switch (data_type) {
case Data_Type::u32: return GL_UNSIGNED_INT_24_8;
case Data_Type::r32: return GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
}
case Texture_Type::Stencil: switch (data_type) {
case Data_Type::u8: return GL_UNSIGNED_BYTE;
}
}
CUSTOM_ASSERT(false, "unknown texture type %d with data type %d", texture_type, data_type);
return GL_NONE;
}
static GLenum get_data_type(Data_Type value) {
switch (value) {
case Data_Type::tex: return GL_INT;
//
case Data_Type::s8: return GL_BYTE;
case Data_Type::s16: return GL_SHORT;
case Data_Type::s32: return GL_INT;
//
case Data_Type::u8: return GL_UNSIGNED_BYTE;
case Data_Type::u16: return GL_UNSIGNED_SHORT;
case Data_Type::u32: return GL_UNSIGNED_INT;
//
case Data_Type::r32: return GL_FLOAT;
case Data_Type::r64: return GL_DOUBLE;
//
case Data_Type::vec2: return GL_FLOAT;
case Data_Type::vec3: return GL_FLOAT;
case Data_Type::vec4: return GL_FLOAT;
//
case Data_Type::ivec2: return GL_INT;
case Data_Type::ivec3: return GL_INT;
case Data_Type::ivec4: return GL_INT;
//
case Data_Type::uvec2: return GL_UNSIGNED_INT;
case Data_Type::uvec3: return GL_UNSIGNED_INT;
case Data_Type::uvec4: return GL_UNSIGNED_INT;
//
case Data_Type::mat2: return GL_FLOAT;
case Data_Type::mat3: return GL_FLOAT;
case Data_Type::mat4: return GL_FLOAT;
};
CUSTOM_ASSERT(false, "unknown data type %d", value);
return GL_NONE;
}
#define CASE_IMPL(T) case Data_Type::T: return sizeof(T)
static u16 get_type_size(Data_Type value) {
switch (value) {
CASE_IMPL(tex);
CASE_IMPL(s8); CASE_IMPL(s16); CASE_IMPL(s32);
CASE_IMPL(u8); CASE_IMPL(u16); CASE_IMPL(u32);
CASE_IMPL(r32); CASE_IMPL(r64);
CASE_IMPL(vec2); CASE_IMPL(vec3); CASE_IMPL(vec4);
CASE_IMPL(ivec2); CASE_IMPL(ivec3); CASE_IMPL(ivec4);
CASE_IMPL(uvec2); CASE_IMPL(uvec3); CASE_IMPL(uvec4);
CASE_IMPL(mat2); CASE_IMPL(mat3); CASE_IMPL(mat4);
}
CUSTOM_ASSERT(false, "unknown data type %d", value);
return 0;
}
#undef CASE_IMPL
#define CASE_IMPL(T) case Data_Type::T: return bc.read<T>(count)
static cmemory read_data(Bytecode const & bc, Data_Type type, u32 count) {
switch (type) {
CASE_IMPL(tex);
CASE_IMPL(s8); CASE_IMPL(s16); CASE_IMPL(s32);
CASE_IMPL(u8); CASE_IMPL(u16); CASE_IMPL(u32);
CASE_IMPL(r32); CASE_IMPL(r64);
CASE_IMPL(vec2); CASE_IMPL(vec3); CASE_IMPL(vec4);
CASE_IMPL(ivec2); CASE_IMPL(ivec3); CASE_IMPL(ivec4);
CASE_IMPL(uvec2); CASE_IMPL(uvec3); CASE_IMPL(uvec4);
CASE_IMPL(mat2); CASE_IMPL(mat3); CASE_IMPL(mat4);
}
CUSTOM_ASSERT(false, "unknown data type %d", type);
return NULL;
}
#undef CASE_IMPL
struct DT_Array { Data_Type type; u32 count; cmemory data; };
static DT_Array read_data_array(Bytecode const & bc) {
Data_Type type = *bc.read<Data_Type>();
u32 count = *bc.read<u32>();
cmemory data = read_data(bc, type, count);
return { type, count, data };
}
static void consume_single_instruction(Bytecode const & bc)
{
Instruction instruction = *bc.read<Instruction>();
switch (instruction)
{
//
case Instruction::Viewport: {
ivec2 pos = *bc.read<ivec2>();
ivec2 size = *bc.read<ivec2>();
glViewport(pos.x, pos.y, size.x, size.y);
} return;
case Instruction::Clear: {
GLbitfield gl_clear_flags = 0;
Clear_Flags clear_flags = *bc.read<Clear_Flags>();
if (bits_are_set(clear_flags, Clear_Flags::Color)) {
gl_clear_flags |= GL_COLOR_BUFFER_BIT;
}
if (bits_are_set(clear_flags, Clear_Flags::Depth)) {
gl_clear_flags |= GL_DEPTH_BUFFER_BIT;
}
if (bits_are_set(clear_flags, Clear_Flags::Stencil)) {
gl_clear_flags |= GL_STENCIL_BUFFER_BIT;
}
glClear(gl_clear_flags);
} return;
case Instruction::Depth_Read: {
u8 value = *bc.read<u8>();
if (value) {
glEnable(GL_DEPTH_TEST);
}
else {
glDisable(GL_DEPTH_TEST);
}
} return;
case Instruction::Depth_Write: {
u8 value = *bc.read<u8>();
glDepthMask(value);
} return;
case Instruction::Depth_Comparison: {
Comparison value = *bc.read<Comparison>();
glDepthFunc(get_comparison(value));
} return;
case Instruction::Color_Write: {
Color_Write value = *bc.read<Color_Write>();
glColorMask(
bits_are_set(value, Color_Write::R),
bits_are_set(value, Color_Write::G),
bits_are_set(value, Color_Write::B),
bits_are_set(value, Color_Write::A)
);
} return;
case Instruction::Stencil_Read: {
u8 value = *bc.read<u8>();
if (value) {
glEnable(GL_STENCIL_TEST);
}
else {
glDisable(GL_STENCIL_TEST);
}
} return;
case Instruction::Stencil_Write: {
u32 value = *bc.read<u32>();
glStencilMask(value);
} return;
case Instruction::Stencil_Comparison: {
Comparison value = *bc.read<Comparison>();
u8 ref = *bc.read<u8>();
u8 mask = *bc.read<u8>();
glStencilFunc(get_comparison(value), ref, mask);
} return;
case Instruction::Stencil_Operation: {
// stencil test + depth test
Operation fail_any = *bc.read<Operation>();
Operation succ_fail = *bc.read<Operation>();
Operation succ_succ = *bc.read<Operation>();
glStencilOp(
get_operation(fail_any),
get_operation(succ_fail),
get_operation(succ_succ)
);
} return;
case Instruction::Stencil_Mask: {
u8 mask = *bc.read<u8>();
glStencilMask(mask);
} return;
case Instruction::Blend_Mode: {
Blend_Mode value = *bc.read<Blend_Mode>();
if (value == Blend_Mode::Opaque) {
glDisable(GL_BLEND);
}
else {
glEnable(GL_BLEND);
}
switch (value) {
case Blend_Mode::Alpha:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // premultiply alpha
return;
case Blend_Mode::Additive:
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
// glBlendFunc(GL_ONE, GL_ONE); // premultiply additive
return;
case Blend_Mode::Multiply:
glBlendFunc(GL_DST_COLOR, GL_ZERO);
// glBlendFunc(GL_ZERO, GL_SRC_COLOR); // just the same
return;
}
CUSTOM_ASSERT(false, "unknown blend mode %d", value);
} return;
case Instruction::Cull_Mode: {
Cull_Mode value = *bc.read<Cull_Mode>();
if (value == Cull_Mode::None) {
glDisable(GL_CULL_FACE);
}
else {
glEnable(GL_CULL_FACE);
}
switch (value) {
case Cull_Mode::Back:
glCullFace(GL_BACK);
return;
case Cull_Mode::Front:
glCullFace(GL_FRONT);
return;
case Cull_Mode::Both:
glCullFace(GL_FRONT_AND_BACK);
return;
}
CUSTOM_ASSERT(false, "unknown cull mode %d", value);
} return;
//
case Instruction::Prepare_Uniform: {
CUSTOM_MESSAGE("// @Todo: Prepare_Uniform");
} return;
//
case Instruction::Allocate_Shader: {
u32 asset_id = *bc.read<u32>();
u32 length = *bc.read<u32>();
cstring source = bc.read<char>(length);
Shader_Part parts = *bc.read<Shader_Part>();
ogl.programs.ensure_capacity(asset_id + 1);
opengl::Program * resource = new (&ogl.programs[asset_id]) opengl::Program;
resource->id = create_program(source, parts);
// @Todo: process uniforms
// GLint uniform_location = glGetUniformLocation(id, uniform_name);
} return;
case Instruction::Allocate_Texture: {
u32 asset_id = *bc.read<u32>();
ivec2 size = *bc.read<ivec2>();
u8 channels = *bc.read<u8>();
Data_Type data_type = *bc.read<Data_Type>();
Texture_Type texture_type = *bc.read<Texture_Type>();
Filter_Mode min_tex = *bc.read<Filter_Mode>();
Filter_Mode min_mip = *bc.read<Filter_Mode>();
Filter_Mode mag_tex = *bc.read<Filter_Mode>();
Wrap_Mode wrap_mode_x = *bc.read<Wrap_Mode>();
Wrap_Mode wrap_mode_y = *bc.read<Wrap_Mode>();
ogl.textures.ensure_capacity(asset_id + 1);
opengl::Texture * resource = new (&ogl.textures[asset_id]) opengl::Texture;
glCreateTextures(GL_TEXTURE_2D, 1, &resource->id);
glTextureStorage2D(
resource->id, 1,
get_texture_internal_format(texture_type, data_type, channels),
size.x, size.y
);
glTextureParameteri(resource->id, GL_TEXTURE_MIN_FILTER, get_min_filter(min_tex, min_mip));
glTextureParameteri(resource->id, GL_TEXTURE_MAG_FILTER, get_mag_filter(mag_tex));
glTextureParameteri(resource->id, GL_TEXTURE_WRAP_S, get_wrap_mode(wrap_mode_x));
glTextureParameteri(resource->id, GL_TEXTURE_WRAP_T, get_wrap_mode(wrap_mode_y));
} return;
case Instruction::Allocate_Mesh: {
u32 asset_id = *bc.read<u32>();
ogl.meshes.ensure_capacity(asset_id + 1);
opengl::Mesh * resource = new (&ogl.meshes[asset_id]) opengl::Mesh;
// buffers
u32 buffers_count = *bc.read<u32>();
resource->buffers.set_capacity(buffers_count);
for (u32 i = 0; i < buffers_count; ++i) {
resource->buffers.push();
opengl::Buffer * buffer = new (&resource->buffers[i]) opengl::Buffer;
DT_Array in_buffer = read_data_array(bc);
buffer->type = in_buffer.type;
u32 attr_count = *bc.read<u32>();
buffer->attributes.set_capacity(attr_count);
for (u32 attr_i = 0; attr_i < attr_count; ++attr_i) {
buffer->attributes.push();
opengl::Attribute * attribute = new (&buffer->attributes[attr_i]) opengl::Attribute;
attribute->count = *bc.read<u8>();
}
glCreateBuffers(1, &buffer->id);
glBindBuffer(GL_ARRAY_BUFFER, buffer->id);
glBufferData(
GL_ARRAY_BUFFER,
in_buffer.count * get_type_size(in_buffer.type),
in_buffer.data, GL_STATIC_DRAW
);
}
// indices
{
DT_Array indices = read_data_array(bc);
resource->indices.count = indices.count;
glCreateBuffers(1, &resource->indices.id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->indices.id);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
indices.count * get_type_size(indices.type),
indices.data, GL_STATIC_DRAW
);
}
// vertex array
{
glGenVertexArrays(1, &resource->id);
glBindVertexArray(resource->id);
for (u8 i = 0; i < resource->buffers.count; ++i) {
opengl::Buffer & buffer = resource->buffers[i];
u16 element_size = get_type_size(buffer.type);
GLenum element_type = get_data_type(buffer.type);
GLsizei stride = 0;
for (u8 attr_i = 0; attr_i < buffer.attributes.count; ++attr_i) {
opengl::Attribute & attr = buffer.attributes[attr_i];
stride += attr.count * element_size;
}
uintptr_t attrib_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, buffer.id);
for (u8 attr_i = 0; attr_i < buffer.attributes.count; ++attr_i) {
opengl::Attribute & attr = buffer.attributes[attr_i];
glEnableVertexAttribArray(attr_i);
glVertexAttribPointer(
attr_i, attr.count, element_type, false,
stride, (cmemory)attrib_offset
);
attrib_offset += attr.count * element_size;
}
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->indices.id);
}
} return;
//
case Instruction::Free_Shader: {
u32 asset_id = *bc.read<u32>();
opengl::Program * resource = &ogl.programs[asset_id];
glDeleteProgram(resource->id);
resource->opengl::Program::~Program();
} return;
case Instruction::Free_Texture: {
u32 asset_id = *bc.read<u32>();
opengl::Texture * resource = &ogl.textures[asset_id];
glDeleteTextures(1, &resource->id);
resource->opengl::Texture::~Texture();
} return;
case Instruction::Free_Mesh: {
u32 asset_id = *bc.read<u32>();
opengl::Mesh * resource = &ogl.meshes[asset_id];
for (u32 i = 0; i < resource->buffers.count; ++i) {
glDeleteBuffers(GL_ARRAY_BUFFER, &resource->buffers[i].id);
}
glDeleteBuffers(GL_ELEMENT_ARRAY_BUFFER, &resource->indices.id);
glDeleteVertexArrays(1, &resource->id);
resource->opengl::Mesh::~Mesh();
} return;
//
case Instruction::Use_Shader: {
u32 asset_id = *bc.read<u32>();
opengl::Program * resource = &ogl.programs[asset_id];
glUseProgram(resource->id);
} return;
case Instruction::Use_Texture: {
u32 asset_id = *bc.read<u32>();
s32 slot = *bc.read<s32>();
opengl::Texture * resource = &ogl.textures[asset_id];
glBindTextureUnit(slot, resource->id);
} return;
case Instruction::Use_Mesh: {
u32 asset_id = *bc.read<u32>();
opengl::Mesh * resource = &ogl.meshes[asset_id];
glBindVertexArray(resource->id);
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->indices.id);
} return;
//
case Instruction::Load_Uniform: {
// @Todo: automize location with some asset_id
s32 location = *bc.read<s32>();
DT_Array uniform = read_data_array(bc);
switch (uniform.type) {
case Data_Type::tex: glUniform1iv(location, uniform.count, (s32 *)uniform.data); break;
//
case Data_Type::r32: glUniform1fv(location, uniform.count, (r32 *)uniform.data); break;
case Data_Type::vec2: glUniform2fv(location, uniform.count, (r32 *)uniform.data); break;
case Data_Type::vec3: glUniform3fv(location, uniform.count, (r32 *)uniform.data); break;
case Data_Type::vec4: glUniform4fv(location, uniform.count, (r32 *)uniform.data); break;
//
case Data_Type::s32: glUniform1iv(location, uniform.count, (s32 *)uniform.data); break;
case Data_Type::ivec2: glUniform2iv(location, uniform.count, (s32 *)uniform.data); break;
case Data_Type::ivec3: glUniform3iv(location, uniform.count, (s32 *)uniform.data); break;
case Data_Type::ivec4: glUniform4iv(location, uniform.count, (s32 *)uniform.data); break;
//
case Data_Type::u32: glUniform1uiv(location, uniform.count, (u32 *)uniform.data); break;
case Data_Type::uvec2: glUniform2uiv(location, uniform.count, (u32 *)uniform.data); break;
case Data_Type::uvec3: glUniform3uiv(location, uniform.count, (u32 *)uniform.data); break;
case Data_Type::uvec4: glUniform4uiv(location, uniform.count, (u32 *)uniform.data); break;
//
case Data_Type::mat2: glUniformMatrix2fv(location, uniform.count, false, (r32 *)uniform.data); break;
case Data_Type::mat3: glUniformMatrix3fv(location, uniform.count, false, (r32 *)uniform.data); break;
case Data_Type::mat4: glUniformMatrix4fv(location, uniform.count, false, (r32 *)uniform.data); break;
}
} return;
case Instruction::Load_Texture: {
u32 asset_id = *bc.read<u32>();
ivec2 size = *bc.read<ivec2>();
u8 channels = *bc.read<u8>();
Data_Type data_type = *bc.read<Data_Type>();
Texture_Type texture_type = *bc.read<Texture_Type>();
// @Change: receive a pointer instead, then free if needed?
cmemory data = read_data(bc, data_type, size.x * size.y * channels);
opengl::Texture * resource = &ogl.textures[asset_id];
glTextureSubImage2D(
resource->id,
0,
0, 0, size.x, size.y,
get_texture_data_format(texture_type, channels),
get_texture_data_type(texture_type, data_type),
data
);
} return;
//
case Instruction::Draw: {
u32 asset_id = *bc.read<u32>();
opengl::Mesh * resource = &ogl.meshes[asset_id];
glDrawElements(GL_TRIANGLES, resource->indices.count, GL_UNSIGNED_INT, nullptr);
} return;
case Instruction::Overlay: {
// send to a vertex shader indices [0, 1, 2]
glDrawArrays(GL_TRIANGLES, 0, 3);
// https://rauwendaal.net/2014/06/14/rendering-a-screen-covering-triangle-in-opengl/
// https://twitter.com/nice_byte/status/1093355080235999232
} return;
}
// message
switch (instruction)
{
case Instruction::Message_Pointer: {
cstring message = *bc.read<cstring>();
CUSTOM_MESSAGE("OpenGL VM: %s", message);
} return;
case Instruction::Message_Inline: {
u32 length = *bc.read<u32>();
cstring message = bc.read<char>(length);
CUSTOM_MESSAGE("OpenGL VM: %s", message);
} return;
}
// error
switch (instruction)
{
case Instruction::None: {
CUSTOM_ASSERT(false, "null instruction encountered");
} return;
case Instruction::Last: {
CUSTOM_ASSERT(false, "non-instruction encountered");
} return;
}
if (instruction < Instruction::Last) {
CUSTOM_ASSERT(false, "unhandled instruction encountered: %d", instruction);
}
CUSTOM_ASSERT(false, "unknown instruction encountered: %d", instruction);
}
}}
//
// platform implementation
//
#if !defined(GES_SHIPPING)
static void opengl_message_callback(
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
glstring message,
cmemory userParam)
{
// https://www.khronos.org/opengl/wiki/Debug_Output
// https://www.khronos.org/opengl/wiki/OpenGL_Error
cstring source_string = NULL;
switch (source)
{
case GL_DEBUG_SOURCE_API: source_string = "API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: source_string = "window system"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: source_string = "shader compiler"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: source_string = "thirdparty"; break;
case GL_DEBUG_SOURCE_APPLICATION: source_string = "application"; break;
case GL_DEBUG_SOURCE_OTHER: source_string = "other"; break;
default: source_string = "unknown"; break;
}
cstring type_string = NULL;
switch (type)
{
case GL_DEBUG_TYPE_ERROR: type_string = "error"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: type_string = "deprecated behavior"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: type_string = "undefined behavior"; break;
case GL_DEBUG_TYPE_PORTABILITY: type_string = "portability"; break;
case GL_DEBUG_TYPE_PERFORMANCE: type_string = "performance"; break;
case GL_DEBUG_TYPE_MARKER: type_string = "marker"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: type_string = "push group"; break;
case GL_DEBUG_TYPE_POP_GROUP: type_string = "pop group"; break;
case GL_DEBUG_TYPE_OTHER: type_string = "other"; break;
default: type_string = "unknown"; break;
}
cstring severity_string = NULL;
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: severity_string = "high"; break; // All OpenGL Errors, shader compilation/linking errors, or highly-dangerous undefined behavior
case GL_DEBUG_SEVERITY_MEDIUM: severity_string = "medium"; break; // Major performance warnings, shader compilation/linking warnings, or the use of deprecated functionality
case GL_DEBUG_SEVERITY_LOW: severity_string = "low"; break; // Redundant state change performance warning, or unimportant undefined behavior
case GL_DEBUG_SEVERITY_NOTIFICATION: severity_string = "notification"; break; // Anything that isn't an error or performance issue.
default: severity_string = "unknown"; break;
}
CUSTOM_MESSAGE(
"OpenGL message:"
"\n %d"
"\n %s"
"\n - type: %s"
"\n - severity: %s"
"\n - source: %s",
id,
message,
type_string,
severity_string,
source_string
);
}
#endif
static bool verify_compilation(GLuint id)
{
GLint status = 0;
glGetShaderiv(id, GL_COMPILE_STATUS, &status);
if (status) { return true; }
// @Note: linker will inform of the errors anyway
GLint max_length = 0;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &max_length);
custom::Array<GLchar> info_log(max_length);
glGetShaderInfoLog(id, max_length, &max_length, info_log.data);
CUSTOM_MESSAGE("failed to compile shader:\n%s", info_log.data);
return false;
}
static bool verify_linking(GLuint id)
{
GLint status = 0;
glGetProgramiv(id, GL_LINK_STATUS, &status);
if (status) { return true; }
GLint max_length = 0;
glGetProgramiv(id, GL_INFO_LOG_LENGTH, &max_length);
custom::Array<GLchar> info_log(max_length);
glGetProgramInfoLog(id, max_length, &max_length, info_log.data);
CUSTOM_MESSAGE("failed to link program:\n%s", info_log.data);
return false;
}
struct Shader_Props
{
GLenum type;
cstring version;
cstring defines;
};
static u8 fill_props(custom::graphics::Shader_Part parts, Shader_Props * props, u8 cap)
{
u8 count = 0;
if (bits_are_set(parts, custom::graphics::Shader_Part::Vertex)) {
props[count++] = { GL_VERTEX_SHADER, "#version 330 core\n", "#define VERTEX_SECTION\n" };
}
if (bits_are_set(parts, custom::graphics::Shader_Part::Pixel)) {
props[count++] = { GL_FRAGMENT_SHADER, "#version 330 core\n", "#define FRAGMENT_SECTION\n" };
}
if (bits_are_set(parts, custom::graphics::Shader_Part::Geometry)) {
props[count++] = { GL_GEOMETRY_SHADER, "#version 330 core\n", "#define GEOMETRY_SECTION\n" };
}
if (bits_are_set(parts, custom::graphics::Shader_Part::Compute)) {
props[count++] = { GL_COMPUTE_SHADER, "#version 430 core\n", "#define COMPUTE_SECTION\n" };
}
return count;
}
static GLuint create_program(cstring source, custom::graphics::Shader_Part parts)
{
u8 const props_cap = 4;
static Shader_Props props[props_cap];
static GLuint shaders[props_cap];
u8 props_count = fill_props(parts, props, props_cap);
// Compile shaders
for (u8 i = 0; i < props_count; ++i) {
glstring code[] = { props[i].version, props[i].defines, source };
GLuint shader_id = glCreateShader(props[i].type);
glShaderSource(shader_id, C_ARRAY_LENGTH(code), code, 0);
glCompileShader(shader_id);
shaders[i] = shader_id;
}
bool is_compiled = true;
for (u8 i = 0; i < props_count; ++i) {
bool isOk = verify_compilation(shaders[i]);
is_compiled = is_compiled && isOk;
}
// Link the program
GLuint program_id = glCreateProgram();
for (u8 i = 0; i < props_count; ++i) {
glAttachShader(program_id, shaders[i]);
}
glLinkProgram(program_id);
bool is_linked = verify_linking(program_id);
// Free shader resources
for (u8 i = 0; i < props_count; ++i) {
glDetachShader(program_id, shaders[i]);
}
for (u8 i = 0; i < props_count; ++i) {
glDeleteShader(shaders[i]);
}
if (!is_compiled || !is_linked) {
glDeleteProgram(program_id);
return 0;
}
return program_id;
}
use contemporary array format
#include "custom_pch.h"
#include "engine/core/math_types.h"
#include "engine/api/graphics_vm.h"
#include "engine/api/graphics_params.h"
#include "engine/impl/array.h"
#include "engine/impl/array_fixed.h"
#include "engine/impl/bytecode.h"
#if !defined(CUSTOM_PRECOMPILED_HEADER)
#include <glad/glad.h>
#include <new>
#endif
// https://www.khronos.org/registry/OpenGL/index_gl.php
// https://github.com/etodd/lasercrabs/blob/master/src/platform/glvm.cpp
typedef GLchar const * glstring;
namespace opengl {
struct Program
{
GLuint id;
custom::Array<GLuint> uniforms;
};
template struct custom::Array<Program>;
struct Texture
{
GLuint id;
};
template struct custom::Array<Texture>;
struct Attribute
{
u8 count;
};
template struct custom::Array<Attribute>;
struct Buffer
{
GLuint id;
custom::graphics::Data_Type type;
custom::Array<Attribute> attributes;
};
template struct custom::Array<Buffer>;
struct Indices
{
GLuint id;
u32 count;
};
struct Mesh
{
GLuint id;
custom::Array<Buffer> buffers;
Indices indices;
};
template struct custom::Array<Mesh>;
struct Data
{
custom::Array<Program> programs;
custom::Array<Texture> textures;
custom::Array<Mesh> meshes;
};
}
static opengl::Data ogl;
//
// API implementation
//
static void opengl_message_callback(
GLenum source, GLenum type, GLuint id, GLenum severity,
GLsizei length, glstring message, cmemory userParam
);
static GLuint create_program(cstring source, custom::graphics::Shader_Part parts);
namespace custom {
namespace graphics {
static void consume_single_instruction(Bytecode const & bc);
VM::VM()
{
#if !defined(GES_SHIPPING)
GLint version_major;
glGetIntegerv(GL_MAJOR_VERSION, &version_major);
GLint version_minor;
glGetIntegerv(GL_MINOR_VERSION, &version_minor);
CUSTOM_MESSAGE("OpenGL version %d.%d", version_major, version_minor);
if (version_major == 4 && version_minor >= 3 || version_major > 4) {
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(opengl_message_callback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
}
#endif
// glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// glDepthRangef(0.0f, 1.0f);
// glClearDepth(1.0f);
// glFrontFace(GL_CCW);
}
VM::~VM() = default;
void VM::update(Bytecode const & bc)
{
while (bc.offset < bc.buffer.count) {
consume_single_instruction(bc);
#if !defined(CUSTOM_SHIPPING)
static GLenum error = 0;
while ((error = glGetError()) != GL_NO_ERROR) {
CUSTOM_ASSERT(false, "OpenGL error 0x%x", error);
}
#endif
}
}
}}
//
// instruction implementation
//
namespace custom {
namespace graphics {
static GLenum get_comparison(Comparison value) {
switch (value) {
case Comparison::False: return GL_NONE;
case Comparison::Less: return GL_LESS;
case Comparison::LEqual: return GL_LEQUAL;
case Comparison::Equal: return GL_EQUAL;
case Comparison::NEqual: return GL_NOTEQUAL;
case Comparison::GEqual: return GL_GEQUAL;
case Comparison::Greater: return GL_GREATER;
case Comparison::True: return GL_ALWAYS;
}
CUSTOM_ASSERT(false, "unknown comparison %d", value);
return GL_NONE;
}
static GLenum get_operation(Operation value) {
switch (value) {
case Operation::Keep: return GL_KEEP;
case Operation::Zero: return GL_ZERO;
case Operation::Replace: return GL_REPLACE;
case Operation::Incr: return GL_INCR;
case Operation::Incr_Wrap: return GL_INCR_WRAP;
case Operation::Decr: return GL_DECR;
case Operation::Decr_Wrap: return GL_DECR_WRAP;
case Operation::Invert: return GL_INVERT;
}
CUSTOM_ASSERT(false, "unknown operation %d", value);
return GL_NONE;
}
static GLenum get_texture_internal_format(Texture_Type texture_type, Data_Type data_type, u8 channels) {
switch (texture_type) {
case Texture_Type::Color: switch (data_type) {
case Data_Type::u8: switch (channels) {
case 1: return GL_R8;
case 2: return GL_RG8;
case 3: return GL_RGB8;
case 4: return GL_RGBA8;
} break;
case Data_Type::u16: switch (channels) {
case 1: return GL_R16;
case 2: return GL_RG16;
case 3: return GL_RGB16;
case 4: return GL_RGBA16;
} break;
case Data_Type::u32: switch (channels) {
case 1: return GL_R32UI;
case 2: return GL_RG32UI;
case 3: return GL_RGB32UI;
case 4: return GL_RGBA32UI;
} break;
case Data_Type::r32: switch (channels) {
case 1: return GL_R32F;
case 2: return GL_RG32F;
case 3: return GL_RGB32F;
case 4: return GL_RGBA32F;
} break;
} break;
case Texture_Type::Depth: switch (data_type) {
case Data_Type::u16: return GL_DEPTH_COMPONENT16;
case Data_Type::u32: return GL_DEPTH_COMPONENT24;
case Data_Type::r32: return GL_DEPTH_COMPONENT32F;
} break;
case Texture_Type::DStencil: switch (data_type) {
case Data_Type::u32: return GL_DEPTH24_STENCIL8;
case Data_Type::r32: return GL_DEPTH32F_STENCIL8;
}
case Texture_Type::Stencil: switch (data_type) {
case Data_Type::u8: return GL_STENCIL_INDEX8;
}
}
CUSTOM_ASSERT(false, "unknown texture type %d with data type %d and channels count %d", texture_type, data_type, channels);
return GL_NONE;
}
static GLenum get_texture_data_format(Texture_Type texture_type, u8 channels) {
switch (texture_type) {
case Texture_Type::Color: switch (channels) {
case 1: return GL_RED;
case 2: return GL_RG;
case 3: return GL_RGB;
case 4: return GL_RGBA;
} break;
case Texture_Type::Depth:
return GL_DEPTH_COMPONENT;
case Texture_Type::DStencil:
return GL_DEPTH_STENCIL;
case Texture_Type::Stencil:
return GL_STENCIL_INDEX;
}
CUSTOM_ASSERT(false, "unknown texture type %d and channels count %d", texture_type, channels);
return GL_NONE;
}
static GLenum get_min_filter(Filter_Mode texture_filter, Filter_Mode mipmap_filter) {
switch (mipmap_filter) {
case Filter_Mode::None: switch (texture_filter) {
case Filter_Mode::None: return GL_NEAREST;
case Filter_Mode::Point: return GL_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR;
} break;
case Filter_Mode::Point: switch (texture_filter) {
case Filter_Mode::None: return GL_NEAREST_MIPMAP_NEAREST;
case Filter_Mode::Point: return GL_NEAREST_MIPMAP_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR_MIPMAP_NEAREST;
} break;
case Filter_Mode::Linear: switch (texture_filter) {
case Filter_Mode::None: return GL_LINEAR_MIPMAP_NEAREST;
case Filter_Mode::Point: return GL_LINEAR_MIPMAP_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR_MIPMAP_LINEAR;
} break;
}
CUSTOM_ASSERT(false, "unknown texture filter %d and mipmap filter %d", texture_filter, mipmap_filter);
return GL_NONE;
}
static GLenum get_mag_filter(Filter_Mode value) {
switch (value) {
case Filter_Mode::None: return GL_NEAREST;
case Filter_Mode::Point: return GL_NEAREST;
case Filter_Mode::Linear: return GL_LINEAR;
}
CUSTOM_ASSERT(false, "unknown filter mode %d", value);
return GL_NONE;
}
static GLenum get_wrap_mode(Wrap_Mode value) {
switch (value) {
case Wrap_Mode::Repeat: return GL_REPEAT;
case Wrap_Mode::Clamp: return GL_CLAMP_TO_EDGE;
case Wrap_Mode::Mirror_Repeat: return GL_MIRRORED_REPEAT;
case Wrap_Mode::Mirror_Clamp: return GL_MIRROR_CLAMP_TO_EDGE;
}
CUSTOM_ASSERT(false, "unknown wrap mode %d", value);
return GL_NONE;
}
static GLenum get_texture_data_type(Texture_Type texture_type, Data_Type data_type) {
switch (texture_type) {
case Texture_Type::Color: switch (data_type) {
case Data_Type::u8: return GL_UNSIGNED_BYTE;
case Data_Type::u16: return GL_UNSIGNED_SHORT;
case Data_Type::u32: return GL_UNSIGNED_INT;
case Data_Type::r32: return GL_FLOAT;
} break;
case Texture_Type::Depth: switch (data_type) {
case Data_Type::u16: return GL_UNSIGNED_SHORT;
case Data_Type::u32: return GL_UNSIGNED_INT;
case Data_Type::r32: return GL_FLOAT;
} break;
case Texture_Type::DStencil: switch (data_type) {
case Data_Type::u32: return GL_UNSIGNED_INT_24_8;
case Data_Type::r32: return GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
}
case Texture_Type::Stencil: switch (data_type) {
case Data_Type::u8: return GL_UNSIGNED_BYTE;
}
}
CUSTOM_ASSERT(false, "unknown texture type %d with data type %d", texture_type, data_type);
return GL_NONE;
}
static GLenum get_data_type(Data_Type value) {
switch (value) {
case Data_Type::tex: return GL_INT;
//
case Data_Type::s8: return GL_BYTE;
case Data_Type::s16: return GL_SHORT;
case Data_Type::s32: return GL_INT;
//
case Data_Type::u8: return GL_UNSIGNED_BYTE;
case Data_Type::u16: return GL_UNSIGNED_SHORT;
case Data_Type::u32: return GL_UNSIGNED_INT;
//
case Data_Type::r32: return GL_FLOAT;
case Data_Type::r64: return GL_DOUBLE;
//
case Data_Type::vec2: return GL_FLOAT;
case Data_Type::vec3: return GL_FLOAT;
case Data_Type::vec4: return GL_FLOAT;
//
case Data_Type::ivec2: return GL_INT;
case Data_Type::ivec3: return GL_INT;
case Data_Type::ivec4: return GL_INT;
//
case Data_Type::uvec2: return GL_UNSIGNED_INT;
case Data_Type::uvec3: return GL_UNSIGNED_INT;
case Data_Type::uvec4: return GL_UNSIGNED_INT;
//
case Data_Type::mat2: return GL_FLOAT;
case Data_Type::mat3: return GL_FLOAT;
case Data_Type::mat4: return GL_FLOAT;
};
CUSTOM_ASSERT(false, "unknown data type %d", value);
return GL_NONE;
}
#define CASE_IMPL(T) case Data_Type::T: return sizeof(T)
static u16 get_type_size(Data_Type value) {
switch (value) {
CASE_IMPL(tex);
CASE_IMPL(s8); CASE_IMPL(s16); CASE_IMPL(s32);
CASE_IMPL(u8); CASE_IMPL(u16); CASE_IMPL(u32);
CASE_IMPL(r32); CASE_IMPL(r64);
CASE_IMPL(vec2); CASE_IMPL(vec3); CASE_IMPL(vec4);
CASE_IMPL(ivec2); CASE_IMPL(ivec3); CASE_IMPL(ivec4);
CASE_IMPL(uvec2); CASE_IMPL(uvec3); CASE_IMPL(uvec4);
CASE_IMPL(mat2); CASE_IMPL(mat3); CASE_IMPL(mat4);
}
CUSTOM_ASSERT(false, "unknown data type %d", value);
return 0;
}
#undef CASE_IMPL
#define CASE_IMPL(T) case Data_Type::T: return bc.read<T>(count)
static cmemory read_data(Bytecode const & bc, Data_Type type, u32 count) {
switch (type) {
CASE_IMPL(tex);
CASE_IMPL(s8); CASE_IMPL(s16); CASE_IMPL(s32);
CASE_IMPL(u8); CASE_IMPL(u16); CASE_IMPL(u32);
CASE_IMPL(r32); CASE_IMPL(r64);
CASE_IMPL(vec2); CASE_IMPL(vec3); CASE_IMPL(vec4);
CASE_IMPL(ivec2); CASE_IMPL(ivec3); CASE_IMPL(ivec4);
CASE_IMPL(uvec2); CASE_IMPL(uvec3); CASE_IMPL(uvec4);
CASE_IMPL(mat2); CASE_IMPL(mat3); CASE_IMPL(mat4);
}
CUSTOM_ASSERT(false, "unknown data type %d", type);
return NULL;
}
#undef CASE_IMPL
struct DT_Array { Data_Type type; u32 count; cmemory data; };
static DT_Array read_data_array(Bytecode const & bc) {
Data_Type type = *bc.read<Data_Type>();
u32 count = *bc.read<u32>();
cmemory data = read_data(bc, type, count);
return { type, count, data };
}
static void consume_single_instruction(Bytecode const & bc)
{
Instruction instruction = *bc.read<Instruction>();
switch (instruction)
{
//
case Instruction::Viewport: {
ivec2 pos = *bc.read<ivec2>();
ivec2 size = *bc.read<ivec2>();
glViewport(pos.x, pos.y, size.x, size.y);
} return;
case Instruction::Clear: {
GLbitfield gl_clear_flags = 0;
Clear_Flags clear_flags = *bc.read<Clear_Flags>();
if (bits_are_set(clear_flags, Clear_Flags::Color)) {
gl_clear_flags |= GL_COLOR_BUFFER_BIT;
}
if (bits_are_set(clear_flags, Clear_Flags::Depth)) {
gl_clear_flags |= GL_DEPTH_BUFFER_BIT;
}
if (bits_are_set(clear_flags, Clear_Flags::Stencil)) {
gl_clear_flags |= GL_STENCIL_BUFFER_BIT;
}
glClear(gl_clear_flags);
} return;
case Instruction::Depth_Read: {
u8 value = *bc.read<u8>();
if (value) {
glEnable(GL_DEPTH_TEST);
}
else {
glDisable(GL_DEPTH_TEST);
}
} return;
case Instruction::Depth_Write: {
u8 value = *bc.read<u8>();
glDepthMask(value);
} return;
case Instruction::Depth_Comparison: {
Comparison value = *bc.read<Comparison>();
glDepthFunc(get_comparison(value));
} return;
case Instruction::Color_Write: {
Color_Write value = *bc.read<Color_Write>();
glColorMask(
bits_are_set(value, Color_Write::R),
bits_are_set(value, Color_Write::G),
bits_are_set(value, Color_Write::B),
bits_are_set(value, Color_Write::A)
);
} return;
case Instruction::Stencil_Read: {
u8 value = *bc.read<u8>();
if (value) {
glEnable(GL_STENCIL_TEST);
}
else {
glDisable(GL_STENCIL_TEST);
}
} return;
case Instruction::Stencil_Write: {
u32 value = *bc.read<u32>();
glStencilMask(value);
} return;
case Instruction::Stencil_Comparison: {
Comparison value = *bc.read<Comparison>();
u8 ref = *bc.read<u8>();
u8 mask = *bc.read<u8>();
glStencilFunc(get_comparison(value), ref, mask);
} return;
case Instruction::Stencil_Operation: {
// stencil test + depth test
Operation fail_any = *bc.read<Operation>();
Operation succ_fail = *bc.read<Operation>();
Operation succ_succ = *bc.read<Operation>();
glStencilOp(
get_operation(fail_any),
get_operation(succ_fail),
get_operation(succ_succ)
);
} return;
case Instruction::Stencil_Mask: {
u8 mask = *bc.read<u8>();
glStencilMask(mask);
} return;
case Instruction::Blend_Mode: {
Blend_Mode value = *bc.read<Blend_Mode>();
if (value == Blend_Mode::Opaque) {
glDisable(GL_BLEND);
}
else {
glEnable(GL_BLEND);
}
switch (value) {
case Blend_Mode::Alpha:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // premultiply alpha
return;
case Blend_Mode::Additive:
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
// glBlendFunc(GL_ONE, GL_ONE); // premultiply additive
return;
case Blend_Mode::Multiply:
glBlendFunc(GL_DST_COLOR, GL_ZERO);
// glBlendFunc(GL_ZERO, GL_SRC_COLOR); // just the same
return;
}
CUSTOM_ASSERT(false, "unknown blend mode %d", value);
} return;
case Instruction::Cull_Mode: {
Cull_Mode value = *bc.read<Cull_Mode>();
if (value == Cull_Mode::None) {
glDisable(GL_CULL_FACE);
}
else {
glEnable(GL_CULL_FACE);
}
switch (value) {
case Cull_Mode::Back:
glCullFace(GL_BACK);
return;
case Cull_Mode::Front:
glCullFace(GL_FRONT);
return;
case Cull_Mode::Both:
glCullFace(GL_FRONT_AND_BACK);
return;
}
CUSTOM_ASSERT(false, "unknown cull mode %d", value);
} return;
//
case Instruction::Prepare_Uniform: {
CUSTOM_MESSAGE("// @Todo: Prepare_Uniform");
} return;
//
case Instruction::Allocate_Shader: {
// @Change: receive a pointer instead, then free if needed?
u32 asset_id = *bc.read<u32>();
u32 length = *bc.read<u32>();
cstring source = bc.read<char>(length);
Shader_Part parts = *bc.read<Shader_Part>();
ogl.programs.ensure_capacity(asset_id + 1);
opengl::Program * resource = new (&ogl.programs[asset_id]) opengl::Program;
resource->id = create_program(source, parts);
// @Todo: process uniforms
// GLint uniform_location = glGetUniformLocation(id, uniform_name);
} return;
case Instruction::Allocate_Texture: {
u32 asset_id = *bc.read<u32>();
ivec2 size = *bc.read<ivec2>();
u8 channels = *bc.read<u8>();
Data_Type data_type = *bc.read<Data_Type>();
Texture_Type texture_type = *bc.read<Texture_Type>();
Filter_Mode min_tex = *bc.read<Filter_Mode>();
Filter_Mode min_mip = *bc.read<Filter_Mode>();
Filter_Mode mag_tex = *bc.read<Filter_Mode>();
Wrap_Mode wrap_mode_x = *bc.read<Wrap_Mode>();
Wrap_Mode wrap_mode_y = *bc.read<Wrap_Mode>();
ogl.textures.ensure_capacity(asset_id + 1);
opengl::Texture * resource = new (&ogl.textures[asset_id]) opengl::Texture;
glCreateTextures(GL_TEXTURE_2D, 1, &resource->id);
glTextureStorage2D(
resource->id, 1,
get_texture_internal_format(texture_type, data_type, channels),
size.x, size.y
);
glTextureParameteri(resource->id, GL_TEXTURE_MIN_FILTER, get_min_filter(min_tex, min_mip));
glTextureParameteri(resource->id, GL_TEXTURE_MAG_FILTER, get_mag_filter(mag_tex));
glTextureParameteri(resource->id, GL_TEXTURE_WRAP_S, get_wrap_mode(wrap_mode_x));
glTextureParameteri(resource->id, GL_TEXTURE_WRAP_T, get_wrap_mode(wrap_mode_y));
} return;
case Instruction::Allocate_Mesh: {
// @Change: receive a pointer instead, then free if needed?
u32 asset_id = *bc.read<u32>();
ogl.meshes.ensure_capacity(asset_id + 1);
opengl::Mesh * resource = new (&ogl.meshes[asset_id]) opengl::Mesh;
// buffers
u32 buffers_count = *bc.read<u32>();
resource->buffers.set_capacity(buffers_count);
for (u32 i = 0; i < buffers_count; ++i) {
resource->buffers.push();
opengl::Buffer * buffer = new (&resource->buffers[i]) opengl::Buffer;
DT_Array in_buffer = read_data_array(bc);
buffer->type = in_buffer.type;
u32 attr_count = *bc.read<u32>();
buffer->attributes.set_capacity(attr_count);
for (u32 attr_i = 0; attr_i < attr_count; ++attr_i) {
buffer->attributes.push();
opengl::Attribute * attribute = new (&buffer->attributes[attr_i]) opengl::Attribute;
attribute->count = *bc.read<u8>();
}
glCreateBuffers(1, &buffer->id);
glBindBuffer(GL_ARRAY_BUFFER, buffer->id);
glBufferData(
GL_ARRAY_BUFFER,
in_buffer.count * get_type_size(in_buffer.type),
in_buffer.data, GL_STATIC_DRAW
);
}
// indices
{
DT_Array indices = read_data_array(bc);
resource->indices.count = indices.count;
glCreateBuffers(1, &resource->indices.id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->indices.id);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
indices.count * get_type_size(indices.type),
indices.data, GL_STATIC_DRAW
);
}
// vertex array
{
glGenVertexArrays(1, &resource->id);
glBindVertexArray(resource->id);
for (u8 i = 0; i < resource->buffers.count; ++i) {
opengl::Buffer & buffer = resource->buffers[i];
u16 element_size = get_type_size(buffer.type);
GLenum element_type = get_data_type(buffer.type);
GLsizei stride = 0;
for (u8 attr_i = 0; attr_i < buffer.attributes.count; ++attr_i) {
opengl::Attribute & attr = buffer.attributes[attr_i];
stride += attr.count * element_size;
}
GLuint attrib_offset = 0;
// uintptr_t attrib_offset = 0;
// glBindBuffer(GL_ARRAY_BUFFER, buffer.id);
glBindVertexBuffer(i, buffer.id, 0, stride);
for (u8 attr_i = 0; attr_i < buffer.attributes.count; ++attr_i) {
opengl::Attribute & attr = buffer.attributes[attr_i];
glEnableVertexAttribArray(attr_i);
glVertexAttribFormat(
attr_i, attr.count, element_type, false, attrib_offset
);
glVertexAttribBinding(attr_i, i);
// glVertexAttribPointer(
// attr_i, attr.count, element_type, false,
// stride, (cmemory)attrib_offset
// );
attrib_offset += attr.count * element_size;
}
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->indices.id);
}
} return;
//
case Instruction::Free_Shader: {
u32 asset_id = *bc.read<u32>();
opengl::Program const * resource = &ogl.programs[asset_id];
glDeleteProgram(resource->id);
resource->opengl::Program::~Program();
} return;
case Instruction::Free_Texture: {
u32 asset_id = *bc.read<u32>();
opengl::Texture const * resource = &ogl.textures[asset_id];
glDeleteTextures(1, &resource->id);
resource->opengl::Texture::~Texture();
} return;
case Instruction::Free_Mesh: {
u32 asset_id = *bc.read<u32>();
opengl::Mesh const * resource = &ogl.meshes[asset_id];
for (u32 i = 0; i < resource->buffers.count; ++i) {
glDeleteBuffers(GL_ARRAY_BUFFER, &resource->buffers[i].id);
}
glDeleteBuffers(GL_ELEMENT_ARRAY_BUFFER, &resource->indices.id);
glDeleteVertexArrays(1, &resource->id);
resource->opengl::Mesh::~Mesh();
} return;
//
case Instruction::Use_Shader: {
u32 asset_id = *bc.read<u32>();
opengl::Program const * resource = &ogl.programs[asset_id];
glUseProgram(resource->id);
} return;
case Instruction::Use_Texture: {
u32 asset_id = *bc.read<u32>();
opengl::Texture const * resource = &ogl.textures[asset_id];
s32 slot = *bc.read<s32>();
glBindTextureUnit(slot, resource->id);
} return;
case Instruction::Use_Mesh: {
u32 asset_id = *bc.read<u32>();
opengl::Mesh const * resource = &ogl.meshes[asset_id];
glBindVertexArray(resource->id);
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->indices.id);
} return;
//
case Instruction::Load_Uniform: {
// @Todo: automize location with some asset_id
s32 location = *bc.read<s32>();
DT_Array uniform = read_data_array(bc);
switch (uniform.type) {
case Data_Type::tex: glUniform1iv(location, uniform.count, (s32 *)uniform.data); break;
//
case Data_Type::r32: glUniform1fv(location, uniform.count, (r32 *)uniform.data); break;
case Data_Type::vec2: glUniform2fv(location, uniform.count, (r32 *)uniform.data); break;
case Data_Type::vec3: glUniform3fv(location, uniform.count, (r32 *)uniform.data); break;
case Data_Type::vec4: glUniform4fv(location, uniform.count, (r32 *)uniform.data); break;
//
case Data_Type::s32: glUniform1iv(location, uniform.count, (s32 *)uniform.data); break;
case Data_Type::ivec2: glUniform2iv(location, uniform.count, (s32 *)uniform.data); break;
case Data_Type::ivec3: glUniform3iv(location, uniform.count, (s32 *)uniform.data); break;
case Data_Type::ivec4: glUniform4iv(location, uniform.count, (s32 *)uniform.data); break;
//
case Data_Type::u32: glUniform1uiv(location, uniform.count, (u32 *)uniform.data); break;
case Data_Type::uvec2: glUniform2uiv(location, uniform.count, (u32 *)uniform.data); break;
case Data_Type::uvec3: glUniform3uiv(location, uniform.count, (u32 *)uniform.data); break;
case Data_Type::uvec4: glUniform4uiv(location, uniform.count, (u32 *)uniform.data); break;
//
case Data_Type::mat2: glUniformMatrix2fv(location, uniform.count, false, (r32 *)uniform.data); break;
case Data_Type::mat3: glUniformMatrix3fv(location, uniform.count, false, (r32 *)uniform.data); break;
case Data_Type::mat4: glUniformMatrix4fv(location, uniform.count, false, (r32 *)uniform.data); break;
}
} return;
case Instruction::Load_Texture: {
// @Change: receive a pointer instead, then free if needed?
u32 asset_id = *bc.read<u32>();
ivec2 size = *bc.read<ivec2>();
u8 channels = *bc.read<u8>();
Data_Type data_type = *bc.read<Data_Type>();
Texture_Type texture_type = *bc.read<Texture_Type>();
cmemory data = read_data(bc, data_type, size.x * size.y * channels);
opengl::Texture const * resource = &ogl.textures[asset_id];
glTextureSubImage2D(
resource->id,
0,
0, 0, size.x, size.y,
get_texture_data_format(texture_type, channels),
get_texture_data_type(texture_type, data_type),
data
);
} return;
//
case Instruction::Draw: {
u32 asset_id = *bc.read<u32>();
opengl::Mesh const * resource = &ogl.meshes[asset_id];
glDrawElements(GL_TRIANGLES, resource->indices.count, GL_UNSIGNED_INT, nullptr);
} return;
case Instruction::Overlay: {
// send to a vertex shader indices [0, 1, 2]
glDrawArrays(GL_TRIANGLES, 0, 3);
// https://rauwendaal.net/2014/06/14/rendering-a-screen-covering-triangle-in-opengl/
// https://twitter.com/nice_byte/status/1093355080235999232
} return;
}
// message
switch (instruction)
{
case Instruction::Message_Pointer: {
cstring message = *bc.read<cstring>();
CUSTOM_MESSAGE("OpenGL VM: %s", message);
} return;
case Instruction::Message_Inline: {
u32 length = *bc.read<u32>();
cstring message = bc.read<char>(length);
CUSTOM_MESSAGE("OpenGL VM: %s", message);
} return;
}
// error
switch (instruction)
{
case Instruction::None: {
CUSTOM_ASSERT(false, "null instruction encountered");
} return;
case Instruction::Last: {
CUSTOM_ASSERT(false, "non-instruction encountered");
} return;
}
if (instruction < Instruction::Last) {
CUSTOM_ASSERT(false, "unhandled instruction encountered: %d", instruction);
}
CUSTOM_ASSERT(false, "unknown instruction encountered: %d", instruction);
}
}}
//
// platform implementation
//
#if !defined(GES_SHIPPING)
static void opengl_message_callback(
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
glstring message,
cmemory userParam)
{
// https://www.khronos.org/opengl/wiki/Debug_Output
// https://www.khronos.org/opengl/wiki/OpenGL_Error
cstring source_string = NULL;
switch (source)
{
case GL_DEBUG_SOURCE_API: source_string = "API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: source_string = "window system"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: source_string = "shader compiler"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: source_string = "thirdparty"; break;
case GL_DEBUG_SOURCE_APPLICATION: source_string = "application"; break;
case GL_DEBUG_SOURCE_OTHER: source_string = "other"; break;
default: source_string = "unknown"; break;
}
cstring type_string = NULL;
switch (type)
{
case GL_DEBUG_TYPE_ERROR: type_string = "error"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: type_string = "deprecated behavior"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: type_string = "undefined behavior"; break;
case GL_DEBUG_TYPE_PORTABILITY: type_string = "portability"; break;
case GL_DEBUG_TYPE_PERFORMANCE: type_string = "performance"; break;
case GL_DEBUG_TYPE_MARKER: type_string = "marker"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: type_string = "push group"; break;
case GL_DEBUG_TYPE_POP_GROUP: type_string = "pop group"; break;
case GL_DEBUG_TYPE_OTHER: type_string = "other"; break;
default: type_string = "unknown"; break;
}
cstring severity_string = NULL;
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: severity_string = "high"; break; // All OpenGL Errors, shader compilation/linking errors, or highly-dangerous undefined behavior
case GL_DEBUG_SEVERITY_MEDIUM: severity_string = "medium"; break; // Major performance warnings, shader compilation/linking warnings, or the use of deprecated functionality
case GL_DEBUG_SEVERITY_LOW: severity_string = "low"; break; // Redundant state change performance warning, or unimportant undefined behavior
case GL_DEBUG_SEVERITY_NOTIFICATION: severity_string = "notification"; break; // Anything that isn't an error or performance issue.
default: severity_string = "unknown"; break;
}
CUSTOM_MESSAGE(
"OpenGL message:"
"\n %d"
"\n %s"
"\n - type: %s"
"\n - severity: %s"
"\n - source: %s",
id,
message,
type_string,
severity_string,
source_string
);
}
#endif
static bool verify_compilation(GLuint id)
{
GLint status = 0;
glGetShaderiv(id, GL_COMPILE_STATUS, &status);
if (status) { return true; }
// @Note: linker will inform of the errors anyway
GLint max_length = 0;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &max_length);
custom::Array<GLchar> info_log(max_length);
glGetShaderInfoLog(id, max_length, &max_length, info_log.data);
CUSTOM_MESSAGE("failed to compile shader:\n%s", info_log.data);
return false;
}
static bool verify_linking(GLuint id)
{
GLint status = 0;
glGetProgramiv(id, GL_LINK_STATUS, &status);
if (status) { return true; }
GLint max_length = 0;
glGetProgramiv(id, GL_INFO_LOG_LENGTH, &max_length);
custom::Array<GLchar> info_log(max_length);
glGetProgramInfoLog(id, max_length, &max_length, info_log.data);
CUSTOM_MESSAGE("failed to link program:\n%s", info_log.data);
return false;
}
struct Shader_Props
{
GLenum type;
cstring version;
cstring defines;
};
static u8 fill_props(custom::graphics::Shader_Part parts, Shader_Props * props, u8 cap)
{
u8 count = 0;
if (bits_are_set(parts, custom::graphics::Shader_Part::Vertex)) {
props[count++] = { GL_VERTEX_SHADER, "#version 330 core\n", "#define VERTEX_SECTION\n" };
}
if (bits_are_set(parts, custom::graphics::Shader_Part::Pixel)) {
props[count++] = { GL_FRAGMENT_SHADER, "#version 330 core\n", "#define FRAGMENT_SECTION\n" };
}
if (bits_are_set(parts, custom::graphics::Shader_Part::Geometry)) {
props[count++] = { GL_GEOMETRY_SHADER, "#version 330 core\n", "#define GEOMETRY_SECTION\n" };
}
if (bits_are_set(parts, custom::graphics::Shader_Part::Compute)) {
props[count++] = { GL_COMPUTE_SHADER, "#version 430 core\n", "#define COMPUTE_SECTION\n" };
}
return count;
}
static GLuint create_program(cstring source, custom::graphics::Shader_Part parts)
{
u8 const props_cap = 4;
static Shader_Props props[props_cap];
static GLuint shaders[props_cap];
u8 props_count = fill_props(parts, props, props_cap);
// Compile shaders
for (u8 i = 0; i < props_count; ++i) {
glstring code[] = { props[i].version, props[i].defines, source };
GLuint shader_id = glCreateShader(props[i].type);
glShaderSource(shader_id, C_ARRAY_LENGTH(code), code, 0);
glCompileShader(shader_id);
shaders[i] = shader_id;
}
bool is_compiled = true;
for (u8 i = 0; i < props_count; ++i) {
bool isOk = verify_compilation(shaders[i]);
is_compiled = is_compiled && isOk;
}
// Link the program
GLuint program_id = glCreateProgram();
for (u8 i = 0; i < props_count; ++i) {
glAttachShader(program_id, shaders[i]);
}
glLinkProgram(program_id);
bool is_linked = verify_linking(program_id);
// Free shader resources
for (u8 i = 0; i < props_count; ++i) {
glDetachShader(program_id, shaders[i]);
}
for (u8 i = 0; i < props_count; ++i) {
glDeleteShader(shaders[i]);
}
if (!is_compiled || !is_linked) {
glDeleteProgram(program_id);
return 0;
}
return program_id;
}
|
/*************************************************************************
Analyse - Classe de [...]
-------------------
dbut : 06/05/17
copyright : (C) 2017 par VOGEL
e-mail : hugues.vogel@insa-lyon.fr
*************************************************************************/
//--------- Ralisation de la classe <Analyse> (fichier Analyse.cpp) ---------//
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include systme
//------------------------------------------------------ Include personnel
#include "Analyse.h"
//----------------------------------------------------------------- PUBLIC
Analyse & Analyse::ObtenirInstance()
{
// TODO: changer le retour par l'instance du singleton
return *((Analyse*) nullptr);
}
bool Analyse::AnalysePrecise(unsigned int size, const unsigned char genome[], const Maladie maladie) {
// TODO
}
bool Analyse::AnalyseGlobal(const unsigned char genome[], const Maladie maladie) {
// TODO
}
//----------------------------------------------------------------- PRIVEE
Analyse::Analyse()
{
}
Analyse::~Analyse()
{
}
correction du paramétage de AnalyseGlobal
/*************************************************************************
Analyse - Classe de [...]
-------------------
dbut : 06/05/17
copyright : (C) 2017 par VOGEL
e-mail : hugues.vogel@insa-lyon.fr
*************************************************************************/
//--------- Ralisation de la classe <Analyse> (fichier Analyse.cpp) ---------//
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include systme
//------------------------------------------------------ Include personnel
#include "Analyse.h"
//----------------------------------------------------------------- PUBLIC
Analyse & Analyse::ObtenirInstance()
{
// TODO: changer le retour par l'instance du singleton
return *((Analyse*) nullptr);
}
bool Analyse::AnalysePrecise(unsigned int size, const unsigned char genome[], const Maladie maladie) {
// TODO
return false;
}
unordered_map<const Maladie&, bool> Analyse::AnalyseGlobal(unsigned int size,const unsigned char genome[]) {
// TODO
return unordered_map<const Maladie&, bool>();
}
//----------------------------------------------------------------- PRIVEE
Analyse::Analyse()
{
}
Analyse::~Analyse()
{
}
|
#include "graphics.h"
#include "../common/Base64.h"
#include <string>
#include <iostream>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace NSGraphics
{
void CGraphics::init(NSNativeControl::CNativeControl* oNative, double width_px, double height_px, double width_mm, double height_mm)
{
m_sApplicationImagesDirectory = oNative->m_strImagesDirectory;
m_sApplicationFontsDirectory = oNative->m_strFontsDirectory;
#ifdef _DEBUG
std::wcout << L"init "<< m_sApplicationImagesDirectory << L" " << m_sApplicationFontsDirectory << L" " << width_px << L" " << height_px << L" " << width_mm << L" " << height_mm << std::endl;
#endif
m_pApplicationFonts = NSFonts::NSApplication::Create();
m_pApplicationFonts->InitializeFromFolder(m_sApplicationFontsDirectory.empty() ? NSFile::GetProcessDirectory() : m_sApplicationFontsDirectory);
NSFonts::IFontManager* pManager = m_pApplicationFonts->GenerateFontManager();
m_pRenderer = NSGraphics::Create();
m_pRenderer->SetFontManager(pManager);
int nRasterW = (int)width_px;
int nRasterH = (int)height_px;
BYTE* pData = new BYTE[4 * nRasterW * nRasterH];
unsigned int back = 0xffffff;
unsigned int* pData32 = (unsigned int*)pData;
unsigned int* pData32End = pData32 + nRasterW * nRasterH;
while (pData32 < pData32End)
*pData32++ = back;
m_oFrame.put_Data(pData);
m_oFrame.put_Width(nRasterW);
m_oFrame.put_Height(nRasterH);
m_oFrame.put_Stride(4 * nRasterW);
m_pRenderer->CreateFromBgraFrame(&m_oFrame);
m_pRenderer->SetSwapRGB(false);
m_pRenderer->put_Width(width_mm);
m_pRenderer->put_Height(height_mm);
}
void CGraphics::put_GlobalAlpha(bool enable, double alpha)
{
#ifdef _DEBUG
std::cout << "put_GlobalAlpha " << enable << " " << alpha << std::endl;
#endif
m_pRenderer->put_GlobalAlphaEnabled(enable, alpha);
}
void CGraphics::End_GlobalAlpha()
{
#ifdef _DEBUG
std::cout << "End_GlobalAlpha " << std::endl;
#endif
bool bIsInteger = m_pRenderer->get_IntegerGrid();
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->PathCommandEnd();
b_color1(255, 255, 255, 140);
m_pRenderer->AddRect(0.0, 0.0, m_pRenderer->GetPixW(), m_pRenderer->GetPixH());
m_pRenderer->Fill();
m_pRenderer->PathCommandEnd();
m_pRenderer->put_IntegerGrid(bIsInteger);
}
void CGraphics::p_color(int r, int g, int b, int a)
{
#ifdef _DEBUG
std::cout << "p_color " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_PenColor(r | (g << 8) | (b << 16));
m_pRenderer->put_PenAlpha(a);
}
void CGraphics::p_width(double w)
{
#ifdef _DEBUG
std::cout << "p_width " << w << std::endl;
#endif
m_pRenderer->put_PenSize(w / 1000.0);
}
void CGraphics::p_dash(size_t length, double* dash)
{
#ifdef _DEBUG
std::cout << "p_dash " << length << std::endl;
#endif
if(length > 0)
{
double dDpiX = 0;
m_pRenderer->get_DpiX(&dDpiX);
for(size_t i = 0; i < length; i++)
dash[i] *= (dDpiX / 25.4);
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, length);
}
else
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleSolid);
}
void CGraphics::b_color1(int r, int g, int b, int a)
{
#ifdef _DEBUG
std::cout << "b_color1 " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_BrushType(c_BrushTypeSolid);
m_pRenderer->put_BrushColor1(r | (g << 8) | (b << 16));
m_pRenderer->put_BrushAlpha1(a);
}
void CGraphics::b_color2(int r, int g, int b, int a)
{
#ifdef _DEBUG
std::cout << "b_color2 " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_BrushColor2(r | (g << 8) | (b << 16));
m_pRenderer->put_BrushAlpha2(a);
}
void CGraphics::transform(double sx, double shy, double shx, double sy, double tx, double ty)
{
#ifdef _DEBUG
std::cout << "transform " << sx << " " << shy << " " << shx << " " << sy << " " << tx << " " << ty << std::endl;
#endif
m_pRenderer->SetTransform(sx, shy, shx, sy, tx, ty);
}
void CGraphics::CalculateFullTransform()
{
#ifdef _DEBUG
std::cout << "CalculateFullTransform " << std::endl;
#endif
m_pRenderer->CalculateFullTransform();
}
void CGraphics::_s()
{
#ifdef _DEBUG
std::cout << "_s " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
}
void CGraphics::_e()
{
#ifdef _DEBUG
std::cout << "_e " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
}
void CGraphics::_z()
{
#ifdef _DEBUG
std::cout << "_z " << std::endl;
#endif
m_pRenderer->PathCommandClose();
}
void CGraphics::_m(double x, double y)
{
#ifdef _DEBUG
std::cout << "_m " << x << " " << y << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandMoveTo(x, y);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->PathCommandMoveTo((int)x + 0.5, (int)y + 0.5);
}
}
void CGraphics::_l(double x, double y)
{
#ifdef _DEBUG
std::cout << "_l " << x << " " << y << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandLineTo(x, y);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->PathCommandLineTo((int)x + 0.5, (int)y + 0.5);
}
}
void CGraphics::_c (double x1, double y1, double x2, double y2, double x3, double y3)
{
#ifdef _DEBUG
std::cout << "_c " << x1 << " " << y1 << " " << x2 << " " << y2 << " " << x3 << " " << y3 << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandCurveTo(x1, y1, x2, y2, x3, y3);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x1, y1);
m_pRenderer->GetFullTransform()->TransformPoint(x2, y2);
m_pRenderer->GetFullTransform()->TransformPoint(x3, y3);
m_pRenderer->PathCommandCurveTo((int)x1 + 0.5, (int)y1 + 0.5, (int)x2 + 0.5, (int)y2 + 0.5, (int)x3 + 0.5, (int)y3 + 0.5);
}
}
void CGraphics::_c2(double x1, double y1, double x2, double y2)
{
#ifdef _DEBUG
std::cout << "_c2 " << x1 << " " << y1 << " " << x2 << " " << y2 << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandCurveTo(x1, y1, x1, y1, x2, y2);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x1, y1);
m_pRenderer->GetFullTransform()->TransformPoint(x2, y2);
m_pRenderer->PathCommandCurveTo((int)x1 + 0.5, (int)y1 + 0.5, (int)x1 + 0.5, (int)y1 + 0.5, (int)x2 + 0.5, (int)y2 + 0.5);
}
}
void CGraphics::ds()
{
#ifdef _DEBUG
std::cout << "ds " << std::endl;
#endif
m_pRenderer->Stroke();
}
void CGraphics::df()
{
#ifdef _DEBUG
std::cout << "df " << std::endl;
#endif
m_pRenderer->Fill();
}
void CGraphics::save()
{
#ifdef _DEBUG
std::cout << "save " << std::endl;
#endif
m_oFrame.SaveFile(m_sApplicationImagesDirectory + L"/img.png", _CXIMAGE_FORMAT_PNG);
}
void CGraphics::restore()
{
#ifdef _DEBUG
std::cout << "restore " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nResetClipType);
m_pRenderer->EndCommand (c_nResetClipType);
}
void CGraphics::clip()
{
#ifdef _DEBUG
std::cout << "clip " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nClipType);
m_pRenderer->EndCommand (c_nClipType);
}
void CGraphics::reset()
{
#ifdef _DEBUG
std::cout << "reset " << std::endl;
#endif
m_pRenderer->ResetTransform();
}
void CGraphics::FreeFont()
{
#ifdef _DEBUG
std::cout << "FreeFont " << std::endl;
#endif
m_pRenderer->CloseFont();
}
void CGraphics::ClearLastFont()
{
#ifdef _DEBUG
std::cout << "ClearLastFont " << std::endl;
#endif
m_pRenderer->ClearInstallFont();
}
void CGraphics::drawImage(const std::wstring& img, double x, double y, double w, double h, BYTE alpha)
{
std::wstring strImage = (0 == img.find(L"theme") ? m_sApplicationThemesDirectory : m_sApplicationImagesDirectory) + L'/' + img;
#ifdef _DEBUG
std::wcout << L"drawImage " << strImage << L" " << x << " " << y << L" " << w << L" " << h << L" " << alpha << std::endl;
#endif
m_pRenderer->DrawImageFromFile(strImage, x, y, w, h, alpha);
}
std::wstring CGraphics::GetFont()
{
#ifdef _DEBUG
std::cout << "GetFont " << std::endl;
#endif
return m_pRenderer->GetFontManager()->GetName();
}
void CGraphics::SetFont(const std::wstring& name, int face, double size, int style)
{
#ifdef _DEBUG
std::wcout << L"SetFont " << name << L" " << face << L" " << size << L" " << style << std::endl;
#endif
double DpiX, DpiY;
m_pRenderer->get_DpiX(&DpiX);
m_pRenderer->get_DpiY(&DpiY);
m_pRenderer->GetFontManager()->LoadFontByName(name, size, style, DpiX, DpiY);
m_pRenderer->put_FontName (name);
m_pRenderer->put_FontFaceIndex(face);
m_pRenderer->put_FontSize (size);
m_pRenderer->put_FontStyle (style);
}
void CGraphics::FillText(double x, double y, int text)
{
#ifdef _DEBUG
std::wcout << L"FillText " << (wchar_t)text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->CommandDrawTextCHAR(text, x, y, 0, 0);
}
void CGraphics::t(double x, double y, const std::wstring& text)
{
#ifdef _DEBUG
std::wcout << L"t " << text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->CommandDrawText(text, x, y, 0, 0);
}
void CGraphics::tg(int text, double x, double y)
{
#ifdef _DEBUG
std::wcout << L"tg " << text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->put_FontStringGID(TRUE);
m_pRenderer->CommandDrawTextCHAR(text, x, y, 0, 0);
m_pRenderer->put_FontStringGID(FALSE);
}
void CGraphics::SetIntegerGrid(bool param)
{
#ifdef _DEBUG
std::cout << "SetIntegerGrid " << param << std::endl;
#endif
m_pRenderer->put_IntegerGrid(param);
}
bool CGraphics::GetIntegerGrid()
{
#ifdef _DEBUG
std::cout << "GetIntegerGrid " << std::endl;
#endif
return m_pRenderer->get_IntegerGrid();
}
void CGraphics::DrawStringASCII (const std::wstring& text, double x, double y)
{
#ifdef _DEBUG
std::wcout << L"DrawStringASCII " << text << L" " << x << L" " << y << std::endl;
#endif
double DpiY;
m_pRenderer->get_DpiY(&DpiY);
SavePenBrush();
b_color1(225, 225, 225, 255);
m_pRenderer->GetFontManager()->LoadString2(text, x, y);
TBBox oBox = m_pRenderer->GetFontManager()->MeasureString2();
rect(x, y, oBox.fMinX, oBox.fMinY);
df();
ds();
b_color1(68, 68, 68, 255);
t(x + 10.0 * 25.4 / DpiY, y - 5.0 * 25.4 / DpiY, text);
RestorePenBrush();
}
void CGraphics::DrawHeaderEdit(double yPos)
{
#ifdef _DEBUG
std::cout << "DrawHeaderEdit " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0;
m_pRenderer->get_PenSize(&dPenSize);
double _width;
m_pRenderer->get_Width(&_width);
pFull->TransformPoint(_width, yPos);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->put_PenSize(2);
m_pRenderer->PathCommandStart();
double dash[2] = { 6, 3 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBBBEC2);
m_pRenderer->PathCommandMoveTo(0, (int)(yPos));
m_pRenderer->PathCommandLineTo(_width, (int)(yPos));
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawFooterEdit(double yPos)
{
#ifdef _DEBUG
std::cout << "DrawFooterEdit " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0;
m_pRenderer->get_PenSize(&dPenSize);
double _width;
m_pRenderer->get_Width(&_width);
pFull->TransformPoint(_width, yPos);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->put_PenSize(2);
m_pRenderer->PathCommandStart();
double dash[2] = { 6, 3 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBBBEC2);
m_pRenderer->PathCommandMoveTo(0, (int)(yPos));
m_pRenderer->PathCommandLineTo(_width, (int)(yPos));
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawLockParagraph (double x, double y1, double y2)
{
#ifdef _DEBUG
std::cout << "DrawLockParagraph " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0.0;
m_pRenderer->get_PenSize(&dPenSize);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
m_pRenderer->put_PenColor(0x009C16);
double _x = x;
double _xT = x;
double _y1 = y1;
double _y2 = y2;
pFull->TransformPoint(_x, _y1);
pFull->TransformPoint(_xT, _y2);
_x = ((int)_x);
_xT = ((int)_xT);
_y1 = ((int)_y1) + 0.5;
_y2 = ((int)_y2) - 1.5;
m_pRenderer->put_PenSize(1);
m_pRenderer->PathCommandStart();
double dash[2] = { 2.0, 2.0 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
if(fabs(_x - _xT) > 0.001)
{
m_pRenderer->PathCommandMoveTo(x, y1);
m_pRenderer->PathCommandLineTo(x, y2);
m_pRenderer->PathCommandMoveTo(x, y1);
m_pRenderer->PathCommandLineTo(x + 3.0, y1);
m_pRenderer->PathCommandMoveTo(x, y2);
m_pRenderer->PathCommandLineTo(x + 3.0, y2);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
}
else
{
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->PathCommandMoveTo(_x + 0.5, _y1 - 0.5);
m_pRenderer->PathCommandLineTo(_x + 0.5, _y2 - 2.0);
m_pRenderer->PathCommandMoveTo(_x, _y1);
m_pRenderer->PathCommandLineTo(_x + 3.0, _y1);
m_pRenderer->PathCommandMoveTo(_x, _y2);
m_pRenderer->PathCommandLineTo(_x + 3.0, _y2);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
}
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawLockObjectRect(double x, double y, double w, double h)
{
#ifdef _DEBUG
std::cout << "DrawLockObjectRect " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
double dPenSize = 0.0;
m_pRenderer->get_PenSize(&dPenSize);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
m_pRenderer->put_PenColor(0x009C16);
m_pRenderer->put_PenSize(1);
double dash[2] = { 2.0, 2.0 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
double eps = 5.0;
rect(x - eps, y - eps, w + eps, h + eps);
m_pRenderer->Stroke();
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawEmptyTableLine(double x1, double y1, double x2, double y2)
{
#ifdef _DEBUG
std::cout << "DrawEmptyTableLine " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0;
m_pRenderer->get_PenSize(&dPenSize);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
double _x1 = x1;
double _y1 = y1;
double _x2 = x2;
double _y2 = y2;
pFull->TransformPoint(_x1, _y1);
pFull->TransformPoint(_x2, _y2);
if (fabs(_x1 - _x2) < 0.001 || fabs(_y1 - _y2) < 0.001)
{
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->put_PenSize(1);
m_pRenderer->PathCommandStart();
double dash[2] = { 2, 2 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBFA28A);
if (fabs(_x1 - _x2) < 0.001)
{
double _dx = ((int)_x1) + 0.5;
double _dy1 = ((int)_y1);
double _dy2 = ((int)_y2);
m_pRenderer->PathCommandMoveTo(_dx, _dy1);
m_pRenderer->PathCommandLineTo(_dx, _dy2);
}
else
{
double _dy = ((int)_y1) + 0.5;
double _dx1 = ((int)_x1);
double _dx2 = ((int)_x2);
m_pRenderer->PathCommandMoveTo(_dx1, _dy);
m_pRenderer->PathCommandLineTo(_dx2, _dy);
}
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
}
else
{
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(0);
m_pRenderer->PathCommandStart();
double dash[2] = { 2, 2 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBFA28A);
m_pRenderer->PathCommandMoveTo(x1, y1);
m_pRenderer->PathCommandLineTo(x2, y2);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
}
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawSpellingLine (double y0, double x0, double x1, double w)
{
#ifdef _DEBUG
std::cout << "DrawSpellingLine " << std::endl;
#endif
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (!m_pRenderer->get_IntegerGrid())
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLine(1, y0, x0, x1, w);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(w);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x0, y0);
m_pRenderer->PathCommandLineTo(x1, y0);
m_pRenderer->Stroke();
}
}
else
{
if(pMatrix->IsIdentity2())
{
m_pRenderer->drawHorLine(1, y0, x0, x1, w);
}
else
{
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(w);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x0, y0);
m_pRenderer->PathCommandLineTo(x1, y0);
m_pRenderer->Stroke();
m_pRenderer->put_IntegerGrid(true);
}
}
}
void CGraphics::drawHorLine (BYTE align, double y, double x, double r, double penW)
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (!m_pRenderer->get_IntegerGrid())
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLine(align, y, x, r, penW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(r, y);
m_pRenderer->Stroke();
}
}
else
{
if(pMatrix->IsIdentity2())
{
m_pRenderer->drawHorLine(align, y, x, r, penW);
}
else
{
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(r, y);
m_pRenderer->Stroke();
m_pRenderer->put_IntegerGrid(true);
}
}
}
void CGraphics::drawHorLine2 (BYTE align, double y, double x, double r, double penW)
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (!m_pRenderer->get_IntegerGrid())
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLine2(align, y, x, r, penW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
double _y1 = y - penW / 2;
double _y2 = _y1 + 2 * penW;
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y1);
m_pRenderer->PathCommandLineTo(r, _y1);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y2);
m_pRenderer->PathCommandLineTo(r, _y2);
m_pRenderer->Stroke();
}
}
else
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->drawHorLine2(align, y, x, r, penW);
}
else
{
m_pRenderer->put_IntegerGrid(false);
double _y1 = y - penW / 2;
double _y2 = _y1 + 2 * penW;
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y1);
m_pRenderer->PathCommandLineTo(r, _y1);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y2);
m_pRenderer->PathCommandLineTo(r, _y2);
m_pRenderer->Stroke();
m_pRenderer->put_IntegerGrid(true);
}
}
}
void CGraphics::drawVerLine (BYTE align, double x, double y, double b, double penW)
{
if (!m_pRenderer->get_IntegerGrid())
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawVerLine(align, x, y, b, penW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(x, b);
m_pRenderer->Stroke();
}
}
else
{
m_pRenderer->drawVerLine(align, x, y, b, penW);
}
}
void CGraphics::drawHorLineExt(BYTE align, double y, double x, double r, double penW, double leftMW, double rightMW)
{
if (!m_pRenderer->get_IntegerGrid())
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLineExt(align, y, x, r, penW, leftMW, rightMW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(r, y);
m_pRenderer->Stroke();
}
}
else
{
m_pRenderer->drawHorLineExt(align, y, x, r, penW, leftMW, rightMW);
}
}
void CGraphics::rect (double x, double y, double w, double h)
{
m_pRenderer->PathCommandEnd();
if (m_pRenderer->get_IntegerGrid())
{
double r = x + w;
double b = y + h;
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->GetFullTransform()->TransformPoint(r, b);
x = (int)(x + 0.5);
y = (int)(y + 0.5);
r = (int)(r + 0.5);
b = (int)(b + 0.5);
m_pRenderer->AddRect(x, y, r - x, b - y);
}
else
{
m_pRenderer->AddRect(x, y, w, h);
}
}
void CGraphics::TableRect (double x, double y, double w, double h)
{
m_pRenderer->PathCommandEnd();
if (m_pRenderer->get_IntegerGrid())
{
double r = x + w;
double b = y + h;
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->GetFullTransform()->TransformPoint(r, b);
x = (int)x;
y = (int)y;
r = (int)r;
b = (int)b;
m_pRenderer->AddRect(x, y, r - x + 1, b - y + 1);
}
else
{
m_pRenderer->AddRect(x, y, w, h);
}
m_pRenderer->Fill();
}
void CGraphics::AddClipRect(double x, double y, double w, double h)
{
CHist_Clip* _histClip = new CHist_Clip();
double sx, shy, shx, sy, tx, ty;
m_pRenderer->GetTransform(&sx, ­, &shx, &sy, &tx, &ty);
_histClip->Transform.SetElements(sx, shy, shx, sy, tx, ty);
_histClip->IsIntegerGrid = m_pRenderer->get_IntegerGrid();
_histClip->Rect.left = x;
_histClip->Rect.top = y;
_histClip->Rect.right = x + w;
_histClip->Rect.bottom = y + h;
m_oGrState.Clips.push_back(_histClip);
StartClipPath();
_s();
_m(x, y);
_l(x + w, y);
_l(x + w, y + h);
_l(x, y + h);
_l(x, y);
EndClipPath();
}
void CGraphics::RemoveClipRect()
{
if(m_oGrState.Clips.back())
{
delete m_oGrState.Clips.back();
m_oGrState.Clips.pop_back();
}
restore();
}
void CGraphics::SetClip (double x, double y, double w, double h)
{
rect(x, y, w, h);
clip();
}
void CGraphics::drawMailMergeField(double x, double y, double w, double h)
{
b_color1(206, 212, 223, 204);
rect(x, y, w, h);
df();
m_pRenderer->PathCommandEnd();
}
void CGraphics::drawSearchResult (double x, double y, double w, double h)
{
b_color1(255, 238, 128, 255);
rect(x, y, w, h);
df();
m_pRenderer->PathCommandEnd();
}
void CGraphics::SavePen()
{
CGrStatePen* pState = new CGrStatePen();
m_pRenderer->SavePen(pState->m_oPen);
m_oGrState.States.push_back(pState);
}
void CGraphics::RestorePen()
{
if(m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if(pState->m_eType == gstPen)
{
m_pRenderer->RestorePen(((CGrStatePen*)pState)->m_oPen);
m_oGrState.States.pop_back();
RELEASEOBJECT(pState);
}
}
void CGraphics::SaveBrush()
{
CGrStateBrush* pState = new CGrStateBrush();
m_pRenderer->SaveBrush(pState->m_oBrush);
m_oGrState.States.push_back(pState);
}
void CGraphics::RestoreBrush()
{
if (m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if (pState->m_eType == gstBrush)
{
m_pRenderer->RestoreBrush(((CGrStateBrush*)pState)->m_oBrush);
m_oGrState.States.pop_back();
RELEASEOBJECT(pState);
}
}
void CGraphics::SavePenBrush()
{
CGrStatePenBrush* pState = new CGrStatePenBrush();
m_pRenderer->SavePen(pState->m_oPen);
m_pRenderer->SaveBrush(pState->m_oBrush);
m_oGrState.States.push_back(pState);
}
void CGraphics::RestorePenBrush()
{
if (m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if (pState->m_eType == gstPenBrush)
{
m_pRenderer->RestorePen(((CGrStatePenBrush*)pState)->m_oPen);
m_pRenderer->RestoreBrush(((CGrStatePenBrush*)pState)->m_oBrush);
m_oGrState.States.pop_back();
RELEASEOBJECT(pState);
}
}
void CGraphics::SaveGrState()
{
#ifdef _DEBUG
std::cout << "SaveGrState " << std::endl;
#endif
CGrStateState* pState = new CGrStateState();
pState->IsIntegerGrid = m_pRenderer->get_IntegerGrid();
pState->Clips = m_oGrState.Clips;
double sx, shy, shx, sy, tx, ty;
m_pRenderer->GetTransform(&sx, ­, &shx, &sy, &tx, &ty);
pState->Transform.SetElements(sx, shy, shx, sy, tx, ty);
m_oGrState.Clips.clear();
m_oGrState.States.push_back(pState);
}
void CGraphics::RestoreGrState()
{
#ifdef _DEBUG
std::cout << "RestoreGrState " << std::endl;
#endif
if (m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if (pState->m_eType != gstState)
return;
CGrStateState* pGrState = (CGrStateState*)pState;
if (!m_oGrState.Clips.empty())
{
restore();
for (IGrState* i : m_oGrState.States)
{
if (i->m_eType == gstState)
{
std::vector<CHist_Clip*>& arr = ((CGrStateState*)i)->Clips;
for (CHist_Clip* j : arr)
{
Aggplus::CMatrix& oMatrix = j->Transform;
transform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), oMatrix.sy(), oMatrix.tx(), oMatrix.ty());
SetIntegerGrid(j->IsIntegerGrid);
StartClipPath();
double x = j->Rect.left;
double y = j->Rect.top;
double r = j->Rect.right;
double b = j->Rect.bottom;
_s();
_m(x, y);
_l(r, y);
_l(r, b);
_l(x, b);
_l(x, y);
EndClipPath();
}
}
}
}
for (CHist_Clip* pClip : m_oGrState.Clips)
RELEASEOBJECT(pClip);
m_oGrState.Clips.clear();
m_oGrState.Clips = pGrState->Clips;
pGrState->Clips.clear();
m_oGrState.States.pop_back();
Aggplus::CMatrix& oMatrix = pGrState->Transform;
transform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), oMatrix.sy(), oMatrix.tx(), oMatrix.ty());
SetIntegerGrid(pGrState->IsIntegerGrid);
RELEASEOBJECT(pState);
}
void CGraphics::StartClipPath()
{
#ifdef _DEBUG
std::cout << "StartClipPath " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nClipType);
}
void CGraphics::EndClipPath()
{
#ifdef _DEBUG
std::cout << "EndClipPath " << std::endl;
#endif
m_pRenderer->EndCommand(c_nClipType);
}
bool CGraphics::StartCheckTableDraw()
{
if(!m_pRenderer->get_IntegerGrid())
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if(pMatrix->IsIdentity2())
{
SaveGrState();
m_pRenderer->put_IntegerGrid(true);
return true;
}
}
return false;
}
void CGraphics::SetTextClipRect(double _l, double _t, double _r, double _b)
{
AddClipRect(_l, _t, _r - _l, _b - _t);
}
void CGraphics::DrawFootnoteRect(double x, double y, double w, double h)
{
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
double dash[2] = { 2.0, 2.0 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->PathCommandEnd();
double l = x;
double t = y;
double r = x + w;
double b = y + h;
drawHorLineExt(1, t, l, r, 0, 0, 0);
drawVerLine (1, l, t, b, 0);
drawVerLine (1, r, t, b, 0);
drawHorLineExt(1, b, l, r, 0, 0, 0);
m_pRenderer->PathCommandEnd();
m_pRenderer->Stroke();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
std::string CGraphics::toDataURL(std::wstring type)
{
std::wstring sPath = NSFile::CFileBinary::CreateTempFileWithUniqueName(m_sApplicationImagesDirectory, L"img");
#ifdef _DEBUG
std::wcout << "toDataURL " << sPath << std::endl;
#endif
m_oFrame.SaveFile(sPath, _CXIMAGE_FORMAT_PNG);
NSFile::CFileBinary oReader;
if (oReader.OpenFile(sPath))
{
DWORD dwFileSize = oReader.GetFileSize();
BYTE* pFileContent = new BYTE[dwFileSize];
DWORD dwReaded;
oReader.ReadFile(pFileContent, dwFileSize, dwReaded);
oReader.CloseFile();
NSFile::CFileBinary::Remove(sPath);
int nEncodeLen = NSBase64::Base64EncodeGetRequiredLength(dwFileSize);
BYTE* pImageData = new BYTE[nEncodeLen];
if (TRUE == NSBase64::Base64Encode(pFileContent, dwFileSize, pImageData, &nEncodeLen))
return "data:" + U_TO_UTF8(type) + ";base64, " + std::string((char*)pImageData, nEncodeLen);
}
return "";
}
CColor CGraphics::GetPenColor()
{
LONG color;
LONG a;
m_pRenderer->get_PenColor(&color);
m_pRenderer->get_PenAlpha(&a);
return {(int)(color & 0xFF), (int)((color >> 8) & 0xFF), (int)((color >> 16) & 0xFF), (int)a};
}
CColor CGraphics::GetBrushColor()
{
LONG color;
LONG a;
m_pRenderer->get_BrushColor1(&color);
m_pRenderer->get_BrushAlpha1(&a);
return {(int)(color & 0xFF), (int)((color >> 8) & 0xFF), (int)((color >> 16) & 0xFF), (int)a};
}
void CGraphics::put_brushTexture(std::wstring src, int type)
{
if (src.find(L"data:") == 0)
{
std::wstring strImage = m_sApplicationImagesDirectory + L"/texture.png";
bool bIsOnlyOfficeHatch = false;
if(src.find(L"onlyoffice_hatch") != std::wstring::npos)
bIsOnlyOfficeHatch = true;
#ifdef _DEBUG
std::wcout << L"put_brushTexture " << src << L" " << bIsOnlyOfficeHatch << std::endl;
#endif
src.erase(0, src.find(L',') + 1);
std::string sBase64MultyByte(src.begin(), src.end());
int nDecodeLen = NSBase64::Base64DecodeGetRequiredLength(sBase64MultyByte.length());
if(nDecodeLen == 0)
return;
BYTE* pImageData = new BYTE[nDecodeLen + 64];
if (TRUE == NSBase64::Base64Decode(sBase64MultyByte.c_str(), sBase64MultyByte.length(), pImageData, &nDecodeLen))
{
if(!bIsOnlyOfficeHatch)
{
NSFile::CFileBinary oImageWriter;
if (oImageWriter.CreateFileW(strImage))
{
oImageWriter.WriteFile(pImageData, (DWORD)nDecodeLen);
oImageWriter.CloseFile();
}
}
else
{
int nSize = (int)sqrt(nDecodeLen >> 2);
CBgraFrame oFrame;
oFrame.put_Data(pImageData);
oFrame.put_Width(nSize);
oFrame.put_Height(nSize);
oFrame.put_Stride(4 * nSize);
oFrame.put_IsRGBA(true);
oFrame.SaveFile(strImage, 4);
}
m_pRenderer->put_BrushType(c_BrushTypeTexture);
m_pRenderer->put_BrushTexturePath(strImage);
m_pRenderer->put_BrushTextureMode(type);
}
}
else
{
std::wstring strImage = (0 == src.find(L"theme") ? m_sApplicationThemesDirectory : m_sApplicationImagesDirectory) + L'/' + src;
#ifdef _DEBUG
std::wcout << L"put_brushTexture " << strImage << L" " << type << std::endl;
#endif
m_pRenderer->put_BrushType(c_BrushTypeTexture);
m_pRenderer->put_BrushTexturePath(strImage);
m_pRenderer->put_BrushTextureMode(type);
}
}
void CGraphics::put_brushTextureMode(int mode)
{
#ifdef _DEBUG
std::cout << "put_brushTextureMode " << mode << std::endl;
#endif
m_pRenderer->put_BrushTextureMode(mode);
}
void CGraphics::put_BrushTextureAlpha(int a)
{
#ifdef _DEBUG
std::cout << "put_BrushTextureAlpha " << a << std::endl;
#endif
m_pRenderer->put_BrushTextureAlpha(a == 0 ? 255 : a);
}
void CGraphics::put_BrushGradient(LONG* pColors, double* pPositions, size_t nCount, double x0, double y0, double x1, double y1, double r0, double r1)
{
#ifdef _DEBUG
std::cout << "put_BrushGradient " << nCount << " " << x0 << " " << y0 << " " << x1 << " " << y1 << " " << r0 << " " << r1 << std::endl;
for (size_t i = 0; i < nCount; i++)
std::cout << pPositions[i] << " " << pColors[i] << " ";
std::cout << std::endl;
#endif
if (std::isnan(r0))
{
// линейный
double dAngle = 0;
if (fabs(x1 - x0) >= FLT_EPSILON || fabs(y1 - y0) >= FLT_EPSILON)
dAngle = atan2(y1 - y0, x1 - x0) * 180 / M_PI;
m_pRenderer->put_BrushType(c_BrushTypePathGradient1);
m_pRenderer->put_BrushGradientColors(pColors, pPositions, nCount);
m_pRenderer->put_BrushLinearAngle(dAngle);
}
else
{
// радиальный
m_pRenderer->put_BrushType(c_BrushTypePathGradient2);
m_pRenderer->put_BrushGradientColors(pColors, pPositions, nCount);
}
}
double CGraphics::TransformPointX(double x, double y)
{
#ifdef _DEBUG
std::cout << "TransformPointX " << std::endl;
#endif
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
return x;
}
double CGraphics::TransformPointY(double x, double y)
{
#ifdef _DEBUG
std::cout << "TransformPointY " << std::endl;
#endif
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
return y;
}
void CGraphics::put_LineJoin(int nJoin)
{
#ifdef _DEBUG
std::cout << "put_LineJoin " << std::endl;
#endif
m_pRenderer->put_PenLineJoin(nJoin);
}
int CGraphics::GetLineJoin()
{
#ifdef _DEBUG
std::cout << "GetLineJoin " << std::endl;
#endif
BYTE nRes;
m_pRenderer->get_PenLineJoin(&nRes);
return nRes;
}
void CGraphics::put_TextureBounds(double x, double y, double w, double h)
{
#ifdef _DEBUG
std::cout << "put_TextureBounds " << L" " << x << " " << y << L" " << w << L" " << h << std::endl;
#endif
if(m_pRenderer->get_IntegerGrid())
{
double r = x + w;
double b = y + h;
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->GetFullTransform()->TransformPoint(r, b);
m_pRenderer->BrushBounds(x, y, r - x, b - y);
}
else
m_pRenderer->BrushBounds(x, y, w, h);
}
double CGraphics::GetlineWidth()
{
#ifdef _DEBUG
std::cout << "GetlineWidth " << std::endl;
#endif
double nRes;
m_pRenderer->get_PenSize(&nRes);
return nRes;
}
void CGraphics::DrawPath(int path)
{
#ifdef _DEBUG
std::cout << "DrawPath " << path << std::endl;
#endif
if(path == 257)
{
m_pRenderer->DrawPath(256);
m_pRenderer->DrawPath(1);
}
else
m_pRenderer->DrawPath(path);
}
void CGraphics::CoordTransformOffset(double tx, double ty)
{
#ifdef _DEBUG
std::cout << "CoordTransformOffset " << tx << " " << ty << std::endl;
#endif
m_pRenderer->SetCoordTransformOffset(tx, ty);
}
CTransform CGraphics::GetTransform()
{
CTransform oRes;
m_pRenderer->GetTransform(&oRes.sx, &oRes.shy, &oRes.shx, &oRes.sy, &oRes.tx, &oRes.ty);
return oRes;
}
}
Fix bug 49441
#include "graphics.h"
#include "../common/Base64.h"
#include <string>
#include <iostream>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace NSGraphics
{
void CGraphics::init(NSNativeControl::CNativeControl* oNative, double width_px, double height_px, double width_mm, double height_mm)
{
m_sApplicationImagesDirectory = oNative->m_strImagesDirectory;
m_sApplicationFontsDirectory = oNative->m_strFontsDirectory;
#ifdef _DEBUG
std::wcout << L"init "<< m_sApplicationImagesDirectory << L" " << m_sApplicationFontsDirectory << L" " << width_px << L" " << height_px << L" " << width_mm << L" " << height_mm << std::endl;
#endif
m_pApplicationFonts = NSFonts::NSApplication::Create();
m_pApplicationFonts->InitializeFromFolder(m_sApplicationFontsDirectory.empty() ? NSFile::GetProcessDirectory() : m_sApplicationFontsDirectory);
NSFonts::IFontManager* pManager = m_pApplicationFonts->GenerateFontManager();
m_pRenderer = NSGraphics::Create();
m_pRenderer->SetFontManager(pManager);
int nRasterW = (int)width_px;
int nRasterH = (int)height_px;
BYTE* pData = new BYTE[4 * nRasterW * nRasterH];
unsigned int back = 0xffffff;
unsigned int* pData32 = (unsigned int*)pData;
unsigned int* pData32End = pData32 + nRasterW * nRasterH;
while (pData32 < pData32End)
*pData32++ = back;
m_oFrame.put_Data(pData);
m_oFrame.put_Width(nRasterW);
m_oFrame.put_Height(nRasterH);
m_oFrame.put_Stride(4 * nRasterW);
m_pRenderer->CreateFromBgraFrame(&m_oFrame);
m_pRenderer->SetSwapRGB(false);
m_pRenderer->put_Width(width_mm);
m_pRenderer->put_Height(height_mm);
}
void CGraphics::put_GlobalAlpha(bool enable, double alpha)
{
#ifdef _DEBUG
std::cout << "put_GlobalAlpha " << enable << " " << alpha << std::endl;
#endif
m_pRenderer->put_GlobalAlphaEnabled(enable, alpha);
}
void CGraphics::End_GlobalAlpha()
{
#ifdef _DEBUG
std::cout << "End_GlobalAlpha " << std::endl;
#endif
bool bIsInteger = m_pRenderer->get_IntegerGrid();
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->PathCommandEnd();
b_color1(255, 255, 255, 140);
m_pRenderer->AddRect(0.0, 0.0, m_pRenderer->GetPixW(), m_pRenderer->GetPixH());
m_pRenderer->Fill();
m_pRenderer->PathCommandEnd();
m_pRenderer->put_IntegerGrid(bIsInteger);
}
void CGraphics::p_color(int r, int g, int b, int a)
{
#ifdef _DEBUG
std::cout << "p_color " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_PenColor(r | (g << 8) | (b << 16));
m_pRenderer->put_PenAlpha(a);
}
void CGraphics::p_width(double w)
{
#ifdef _DEBUG
std::cout << "p_width " << w << std::endl;
#endif
m_pRenderer->put_PenSize(w / 1000.0);
}
void CGraphics::p_dash(size_t length, double* dash)
{
#ifdef _DEBUG
std::cout << "p_dash " << length << std::endl;
#endif
if(length > 0)
{
double dDpiX = 0;
m_pRenderer->get_DpiX(&dDpiX);
for(size_t i = 0; i < length; i++)
dash[i] *= (dDpiX / 25.4);
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, length);
}
else
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleSolid);
}
void CGraphics::b_color1(int r, int g, int b, int a)
{
#ifdef _DEBUG
std::cout << "b_color1 " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_BrushType(c_BrushTypeSolid);
m_pRenderer->put_BrushColor1(r | (g << 8) | (b << 16));
m_pRenderer->put_BrushAlpha1(a);
}
void CGraphics::b_color2(int r, int g, int b, int a)
{
#ifdef _DEBUG
std::cout << "b_color2 " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_BrushColor2(r | (g << 8) | (b << 16));
m_pRenderer->put_BrushAlpha2(a);
}
void CGraphics::transform(double sx, double shy, double shx, double sy, double tx, double ty)
{
#ifdef _DEBUG
std::cout << "transform " << sx << " " << shy << " " << shx << " " << sy << " " << tx << " " << ty << std::endl;
#endif
m_pRenderer->SetTransform(sx, shy, shx, sy, tx, ty);
}
void CGraphics::CalculateFullTransform()
{
#ifdef _DEBUG
std::cout << "CalculateFullTransform " << std::endl;
#endif
m_pRenderer->CalculateFullTransform();
}
void CGraphics::_s()
{
#ifdef _DEBUG
std::cout << "_s " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
}
void CGraphics::_e()
{
#ifdef _DEBUG
std::cout << "_e " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
}
void CGraphics::_z()
{
#ifdef _DEBUG
std::cout << "_z " << std::endl;
#endif
m_pRenderer->PathCommandClose();
}
void CGraphics::_m(double x, double y)
{
#ifdef _DEBUG
std::cout << "_m " << x << " " << y << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandMoveTo(x, y);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->PathCommandMoveTo((int)x + 0.5, (int)y + 0.5);
}
}
void CGraphics::_l(double x, double y)
{
#ifdef _DEBUG
std::cout << "_l " << x << " " << y << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandLineTo(x, y);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->PathCommandLineTo((int)x + 0.5, (int)y + 0.5);
}
}
void CGraphics::_c (double x1, double y1, double x2, double y2, double x3, double y3)
{
#ifdef _DEBUG
std::cout << "_c " << x1 << " " << y1 << " " << x2 << " " << y2 << " " << x3 << " " << y3 << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandCurveTo(x1, y1, x2, y2, x3, y3);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x1, y1);
m_pRenderer->GetFullTransform()->TransformPoint(x2, y2);
m_pRenderer->GetFullTransform()->TransformPoint(x3, y3);
m_pRenderer->PathCommandCurveTo((int)x1 + 0.5, (int)y1 + 0.5, (int)x2 + 0.5, (int)y2 + 0.5, (int)x3 + 0.5, (int)y3 + 0.5);
}
}
void CGraphics::_c2(double x1, double y1, double x2, double y2)
{
#ifdef _DEBUG
std::cout << "_c2 " << x1 << " " << y1 << " " << x2 << " " << y2 << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
m_pRenderer->PathCommandCurveTo(x1, y1, x1, y1, x2, y2);
else
{
m_pRenderer->GetFullTransform()->TransformPoint(x1, y1);
m_pRenderer->GetFullTransform()->TransformPoint(x2, y2);
m_pRenderer->PathCommandCurveTo((int)x1 + 0.5, (int)y1 + 0.5, (int)x1 + 0.5, (int)y1 + 0.5, (int)x2 + 0.5, (int)y2 + 0.5);
}
}
void CGraphics::ds()
{
#ifdef _DEBUG
std::cout << "ds " << std::endl;
#endif
m_pRenderer->Stroke();
}
void CGraphics::df()
{
#ifdef _DEBUG
std::cout << "df " << std::endl;
#endif
m_pRenderer->Fill();
}
void CGraphics::save()
{
#ifdef _DEBUG
std::cout << "save " << std::endl;
#endif
m_oFrame.SaveFile(m_sApplicationImagesDirectory + L"/img.png", _CXIMAGE_FORMAT_PNG);
}
void CGraphics::restore()
{
#ifdef _DEBUG
std::cout << "restore " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nResetClipType);
m_pRenderer->EndCommand (c_nResetClipType);
}
void CGraphics::clip()
{
#ifdef _DEBUG
std::cout << "clip " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nClipType);
m_pRenderer->EndCommand (c_nClipType);
}
void CGraphics::reset()
{
#ifdef _DEBUG
std::cout << "reset " << std::endl;
#endif
m_pRenderer->ResetTransform();
}
void CGraphics::FreeFont()
{
#ifdef _DEBUG
std::cout << "FreeFont " << std::endl;
#endif
m_pRenderer->CloseFont();
}
void CGraphics::ClearLastFont()
{
#ifdef _DEBUG
std::cout << "ClearLastFont " << std::endl;
#endif
m_pRenderer->ClearInstallFont();
}
void CGraphics::drawImage(const std::wstring& img, double x, double y, double w, double h, BYTE alpha)
{
std::wstring strImage = (0 == img.find(L"theme") ? m_sApplicationThemesDirectory : m_sApplicationImagesDirectory) + L'/' + img;
#ifdef _DEBUG
std::wcout << L"drawImage " << strImage << L" " << x << " " << y << L" " << w << L" " << h << L" " << alpha << std::endl;
#endif
m_pRenderer->DrawImageFromFile(strImage, x, y, w, h, alpha);
}
std::wstring CGraphics::GetFont()
{
#ifdef _DEBUG
std::cout << "GetFont " << std::endl;
#endif
return m_pRenderer->GetFontManager()->GetName();
}
void CGraphics::SetFont(const std::wstring& name, int face, double size, int style)
{
#ifdef _DEBUG
std::wcout << L"SetFont " << name << L" " << face << L" " << size << L" " << style << std::endl;
#endif
double DpiX, DpiY;
m_pRenderer->get_DpiX(&DpiX);
m_pRenderer->get_DpiY(&DpiY);
m_pRenderer->GetFontManager()->LoadFontByName(name, size, style, DpiX, DpiY);
m_pRenderer->put_FontName (name);
m_pRenderer->put_FontFaceIndex(face);
m_pRenderer->put_FontSize (size);
m_pRenderer->put_FontStyle (style);
}
void CGraphics::FillText(double x, double y, int text)
{
#ifdef _DEBUG
std::wcout << L"FillText " << (wchar_t)text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->CommandDrawTextCHAR(text, x, y, 0, 0);
}
void CGraphics::t(double x, double y, const std::wstring& text)
{
#ifdef _DEBUG
std::wcout << L"t " << text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->CommandDrawText(text, x, y, 0, 0);
}
void CGraphics::tg(int text, double x, double y)
{
#ifdef _DEBUG
std::wcout << L"tg " << text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->put_FontStringGID(TRUE);
m_pRenderer->CommandDrawTextCHAR(text, x, y, 0, 0);
m_pRenderer->put_FontStringGID(FALSE);
}
void CGraphics::SetIntegerGrid(bool param)
{
#ifdef _DEBUG
std::cout << "SetIntegerGrid " << param << std::endl;
#endif
m_pRenderer->put_IntegerGrid(param);
}
bool CGraphics::GetIntegerGrid()
{
#ifdef _DEBUG
std::cout << "GetIntegerGrid " << std::endl;
#endif
return m_pRenderer->get_IntegerGrid();
}
void CGraphics::DrawStringASCII (const std::wstring& text, double x, double y)
{
#ifdef _DEBUG
std::wcout << L"DrawStringASCII " << text << L" " << x << L" " << y << std::endl;
#endif
double DpiY;
m_pRenderer->get_DpiY(&DpiY);
SavePenBrush();
b_color1(225, 225, 225, 255);
m_pRenderer->GetFontManager()->LoadString2(text, x, y);
TBBox oBox = m_pRenderer->GetFontManager()->MeasureString2();
rect(x, y, oBox.fMinX, oBox.fMinY);
df();
ds();
b_color1(68, 68, 68, 255);
t(x + 10.0 * 25.4 / DpiY, y - 5.0 * 25.4 / DpiY, text);
RestorePenBrush();
}
void CGraphics::DrawHeaderEdit(double yPos)
{
#ifdef _DEBUG
std::cout << "DrawHeaderEdit " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0;
m_pRenderer->get_PenSize(&dPenSize);
double _width;
m_pRenderer->get_Width(&_width);
pFull->TransformPoint(_width, yPos);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->put_PenSize(2);
m_pRenderer->PathCommandStart();
double dash[2] = { 6, 3 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBBBEC2);
m_pRenderer->PathCommandMoveTo(0, (int)(yPos));
m_pRenderer->PathCommandLineTo(_width, (int)(yPos));
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawFooterEdit(double yPos)
{
#ifdef _DEBUG
std::cout << "DrawFooterEdit " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0;
m_pRenderer->get_PenSize(&dPenSize);
double _width;
m_pRenderer->get_Width(&_width);
pFull->TransformPoint(_width, yPos);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->put_PenSize(2);
m_pRenderer->PathCommandStart();
double dash[2] = { 6, 3 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBBBEC2);
m_pRenderer->PathCommandMoveTo(0, (int)(yPos));
m_pRenderer->PathCommandLineTo(_width, (int)(yPos));
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawLockParagraph (double x, double y1, double y2)
{
#ifdef _DEBUG
std::cout << "DrawLockParagraph " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0.0;
m_pRenderer->get_PenSize(&dPenSize);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
m_pRenderer->put_PenColor(0x009C16);
double _x = x;
double _xT = x;
double _y1 = y1;
double _y2 = y2;
pFull->TransformPoint(_x, _y1);
pFull->TransformPoint(_xT, _y2);
_x = ((int)_x);
_xT = ((int)_xT);
_y1 = ((int)_y1) + 0.5;
_y2 = ((int)_y2) - 1.5;
m_pRenderer->put_PenSize(1);
m_pRenderer->PathCommandStart();
double dash[2] = { 2.0, 2.0 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
if(fabs(_x - _xT) > 0.001)
{
m_pRenderer->PathCommandMoveTo(x, y1);
m_pRenderer->PathCommandLineTo(x, y2);
m_pRenderer->PathCommandMoveTo(x, y1);
m_pRenderer->PathCommandLineTo(x + 3.0, y1);
m_pRenderer->PathCommandMoveTo(x, y2);
m_pRenderer->PathCommandLineTo(x + 3.0, y2);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
}
else
{
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->PathCommandMoveTo(_x + 0.5, _y1 - 0.5);
m_pRenderer->PathCommandLineTo(_x + 0.5, _y2 - 2.0);
m_pRenderer->PathCommandMoveTo(_x, _y1);
m_pRenderer->PathCommandLineTo(_x + 3.0, _y1);
m_pRenderer->PathCommandMoveTo(_x, _y2);
m_pRenderer->PathCommandLineTo(_x + 3.0, _y2);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
}
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawLockObjectRect(double x, double y, double w, double h)
{
#ifdef _DEBUG
std::cout << "DrawLockObjectRect " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
double dPenSize = 0.0;
m_pRenderer->get_PenSize(&dPenSize);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
m_pRenderer->put_PenColor(0x009C16);
m_pRenderer->put_PenSize(1);
double dash[2] = { 2.0, 2.0 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
double eps = 5.0;
rect(x - eps, y - eps, w + eps, h + eps);
m_pRenderer->Stroke();
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawEmptyTableLine(double x1, double y1, double x2, double y2)
{
#ifdef _DEBUG
std::cout << "DrawEmptyTableLine " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
Aggplus::CMatrix* pFull = m_pRenderer->GetFullTransform();
double dPenSize = 0;
m_pRenderer->get_PenSize(&dPenSize);
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
double _x1 = x1;
double _y1 = y1;
double _x2 = x2;
double _y2 = y2;
pFull->TransformPoint(_x1, _y1);
pFull->TransformPoint(_x2, _y2);
if (fabs(_x1 - _x2) < 0.001 || fabs(_y1 - _y2) < 0.001)
{
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->put_PenSize(1);
m_pRenderer->PathCommandStart();
double dash[2] = { 2, 2 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBFA28A);
if (fabs(_x1 - _x2) < 0.001)
{
double _dx = ((int)_x1) + 0.5;
double _dy1 = ((int)_y1);
double _dy2 = ((int)_y2);
m_pRenderer->PathCommandMoveTo(_dx, _dy1);
m_pRenderer->PathCommandLineTo(_dx, _dy2);
}
else
{
double _dy = ((int)_y1) + 0.5;
double _dx1 = ((int)_x1);
double _dx2 = ((int)_x2);
m_pRenderer->PathCommandMoveTo(_dx1, _dy);
m_pRenderer->PathCommandLineTo(_dx2, _dy);
}
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
}
else
{
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(0);
m_pRenderer->PathCommandStart();
double dash[2] = { 2, 2 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->put_PenColor(0xBFA28A);
m_pRenderer->PathCommandMoveTo(x1, y1);
m_pRenderer->PathCommandLineTo(x2, y2);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
if (bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
}
m_pRenderer->put_PenSize(dPenSize);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
void CGraphics::DrawSpellingLine (double y0, double x0, double x1, double w)
{
#ifdef _DEBUG
std::cout << "DrawSpellingLine " << std::endl;
#endif
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (!m_pRenderer->get_IntegerGrid())
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLine(1, y0, x0, x1, w);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(w);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x0, y0);
m_pRenderer->PathCommandLineTo(x1, y0);
m_pRenderer->Stroke();
}
}
else
{
if(pMatrix->IsIdentity2())
{
m_pRenderer->drawHorLine(1, y0, x0, x1, w);
}
else
{
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(w);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x0, y0);
m_pRenderer->PathCommandLineTo(x1, y0);
m_pRenderer->Stroke();
m_pRenderer->put_IntegerGrid(true);
}
}
}
void CGraphics::drawHorLine (BYTE align, double y, double x, double r, double penW)
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (!m_pRenderer->get_IntegerGrid())
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLine(align, y, x, r, penW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(r, y);
m_pRenderer->Stroke();
}
}
else
{
if(pMatrix->IsIdentity2())
{
m_pRenderer->drawHorLine(align, y, x, r, penW);
}
else
{
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(r, y);
m_pRenderer->Stroke();
m_pRenderer->put_IntegerGrid(true);
}
}
}
void CGraphics::drawHorLine2 (BYTE align, double y, double x, double r, double penW)
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (!m_pRenderer->get_IntegerGrid())
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLine2(align, y, x, r, penW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
double _y1 = y - penW / 2;
double _y2 = _y1 + 2 * penW;
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y1);
m_pRenderer->PathCommandLineTo(r, _y1);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y2);
m_pRenderer->PathCommandLineTo(r, _y2);
m_pRenderer->Stroke();
}
}
else
{
if (pMatrix->IsIdentity2())
{
m_pRenderer->drawHorLine2(align, y, x, r, penW);
}
else
{
m_pRenderer->put_IntegerGrid(false);
double _y1 = y - penW / 2;
double _y2 = _y1 + 2 * penW;
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y1);
m_pRenderer->PathCommandLineTo(r, _y1);
m_pRenderer->Stroke();
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, _y2);
m_pRenderer->PathCommandLineTo(r, _y2);
m_pRenderer->Stroke();
m_pRenderer->put_IntegerGrid(true);
}
}
}
void CGraphics::drawVerLine (BYTE align, double x, double y, double b, double penW)
{
if (!m_pRenderer->get_IntegerGrid())
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawVerLine(align, x, y, b, penW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(x, b);
m_pRenderer->Stroke();
}
}
else
{
m_pRenderer->drawVerLine(align, x, y, b, penW);
}
}
void CGraphics::drawHorLineExt(BYTE align, double y, double x, double r, double penW, double leftMW, double rightMW)
{
if (!m_pRenderer->get_IntegerGrid())
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if (pMatrix->IsIdentity2())
{
m_pRenderer->put_IntegerGrid(true);
m_pRenderer->drawHorLineExt(align, y, x, r, penW, leftMW, rightMW);
m_pRenderer->put_IntegerGrid(false);
}
else
{
m_pRenderer->put_PenSize(penW);
m_pRenderer->PathCommandEnd();
m_pRenderer->PathCommandMoveTo(x, y);
m_pRenderer->PathCommandLineTo(r, y);
m_pRenderer->Stroke();
}
}
else
{
m_pRenderer->drawHorLineExt(align, y, x, r, penW, leftMW, rightMW);
}
}
void CGraphics::rect (double x, double y, double w, double h)
{
m_pRenderer->PathCommandEnd();
if (m_pRenderer->get_IntegerGrid())
{
double r = x + w;
double b = y + h;
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->GetFullTransform()->TransformPoint(r, b);
x = (int)(x + 0.5);
y = (int)(y + 0.5);
r = (int)(r + 0.5);
b = (int)(b + 0.5);
m_pRenderer->AddRect(x, y, r - x, b - y);
}
else
{
m_pRenderer->AddRect(x, y, w, h);
}
}
void CGraphics::TableRect (double x, double y, double w, double h)
{
m_pRenderer->PathCommandEnd();
if (m_pRenderer->get_IntegerGrid())
{
double r = x + w;
double b = y + h;
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->GetFullTransform()->TransformPoint(r, b);
x = (int)x;
y = (int)y;
r = (int)r;
b = (int)b;
m_pRenderer->AddRect(x, y, r - x + 1, b - y + 1);
}
else
{
m_pRenderer->AddRect(x, y, w, h);
}
m_pRenderer->Fill();
}
void CGraphics::AddClipRect(double x, double y, double w, double h)
{
CHist_Clip* _histClip = new CHist_Clip();
double sx, shy, shx, sy, tx, ty;
m_pRenderer->GetTransform(&sx, ­, &shx, &sy, &tx, &ty);
_histClip->Transform.SetElements(sx, shy, shx, sy, tx, ty);
_histClip->IsIntegerGrid = m_pRenderer->get_IntegerGrid();
_histClip->Rect.left = x;
_histClip->Rect.top = y;
_histClip->Rect.right = x + w;
_histClip->Rect.bottom = y + h;
m_oGrState.Clips.push_back(_histClip);
StartClipPath();
_s();
_m(x, y);
_l(x + w, y);
_l(x + w, y + h);
_l(x, y + h);
_l(x, y);
EndClipPath();
}
void CGraphics::RemoveClipRect()
{
if(m_oGrState.Clips.back())
{
delete m_oGrState.Clips.back();
m_oGrState.Clips.pop_back();
}
restore();
}
void CGraphics::SetClip (double x, double y, double w, double h)
{
rect(x, y, w, h);
clip();
}
void CGraphics::drawMailMergeField(double x, double y, double w, double h)
{
b_color1(206, 212, 223, 204);
rect(x, y, w, h);
df();
m_pRenderer->PathCommandEnd();
}
void CGraphics::drawSearchResult (double x, double y, double w, double h)
{
b_color1(255, 238, 128, 255);
rect(x, y, w, h);
df();
m_pRenderer->PathCommandEnd();
}
void CGraphics::SavePen()
{
CGrStatePen* pState = new CGrStatePen();
m_pRenderer->SavePen(pState->m_oPen);
m_oGrState.States.push_back(pState);
}
void CGraphics::RestorePen()
{
if(m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if(pState->m_eType == gstPen)
{
m_pRenderer->RestorePen(((CGrStatePen*)pState)->m_oPen);
m_oGrState.States.pop_back();
RELEASEOBJECT(pState);
}
}
void CGraphics::SaveBrush()
{
CGrStateBrush* pState = new CGrStateBrush();
m_pRenderer->SaveBrush(pState->m_oBrush);
m_oGrState.States.push_back(pState);
}
void CGraphics::RestoreBrush()
{
if (m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if (pState->m_eType == gstBrush)
{
m_pRenderer->RestoreBrush(((CGrStateBrush*)pState)->m_oBrush);
m_oGrState.States.pop_back();
RELEASEOBJECT(pState);
}
}
void CGraphics::SavePenBrush()
{
CGrStatePenBrush* pState = new CGrStatePenBrush();
m_pRenderer->SavePen(pState->m_oPen);
m_pRenderer->SaveBrush(pState->m_oBrush);
m_oGrState.States.push_back(pState);
}
void CGraphics::RestorePenBrush()
{
if (m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if (pState->m_eType == gstPenBrush)
{
m_pRenderer->RestorePen(((CGrStatePenBrush*)pState)->m_oPen);
m_pRenderer->RestoreBrush(((CGrStatePenBrush*)pState)->m_oBrush);
m_oGrState.States.pop_back();
RELEASEOBJECT(pState);
}
}
void CGraphics::SaveGrState()
{
#ifdef _DEBUG
std::cout << "SaveGrState " << std::endl;
#endif
CGrStateState* pState = new CGrStateState();
pState->IsIntegerGrid = m_pRenderer->get_IntegerGrid();
pState->Clips = m_oGrState.Clips;
double sx, shy, shx, sy, tx, ty;
m_pRenderer->GetTransform(&sx, ­, &shx, &sy, &tx, &ty);
pState->Transform.SetElements(sx, shy, shx, sy, tx, ty);
m_oGrState.Clips.clear();
m_oGrState.States.push_back(pState);
}
void CGraphics::RestoreGrState()
{
#ifdef _DEBUG
std::cout << "RestoreGrState " << std::endl;
#endif
if (m_oGrState.States.empty())
return;
IGrState* pState = m_oGrState.States.back();
if (pState->m_eType != gstState)
return;
CGrStateState* pGrState = (CGrStateState*)pState;
if (!m_oGrState.Clips.empty())
{
restore();
for (IGrState* i : m_oGrState.States)
{
if (i->m_eType == gstState)
{
std::vector<CHist_Clip*>& arr = ((CGrStateState*)i)->Clips;
for (CHist_Clip* j : arr)
{
Aggplus::CMatrix& oMatrix = j->Transform;
transform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), oMatrix.sy(), oMatrix.tx(), oMatrix.ty());
SetIntegerGrid(j->IsIntegerGrid);
StartClipPath();
double x = j->Rect.left;
double y = j->Rect.top;
double r = j->Rect.right;
double b = j->Rect.bottom;
_s();
_m(x, y);
_l(r, y);
_l(r, b);
_l(x, b);
_l(x, y);
EndClipPath();
}
}
}
}
for (CHist_Clip* pClip : m_oGrState.Clips)
RELEASEOBJECT(pClip);
m_oGrState.Clips.clear();
m_oGrState.Clips = pGrState->Clips;
pGrState->Clips.clear();
m_oGrState.States.pop_back();
Aggplus::CMatrix& oMatrix = pGrState->Transform;
transform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), oMatrix.sy(), oMatrix.tx(), oMatrix.ty());
SetIntegerGrid(pGrState->IsIntegerGrid);
RELEASEOBJECT(pState);
}
void CGraphics::StartClipPath()
{
#ifdef _DEBUG
std::cout << "StartClipPath " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nClipType);
}
void CGraphics::EndClipPath()
{
#ifdef _DEBUG
std::cout << "EndClipPath " << std::endl;
#endif
m_pRenderer->EndCommand(c_nClipType);
}
bool CGraphics::StartCheckTableDraw()
{
if(!m_pRenderer->get_IntegerGrid())
{
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
if(pMatrix->IsIdentity2())
{
SaveGrState();
m_pRenderer->put_IntegerGrid(true);
return true;
}
}
return false;
}
void CGraphics::SetTextClipRect(double _l, double _t, double _r, double _b)
{
AddClipRect(_l, _t, _r - _l, _b - _t);
}
void CGraphics::DrawFootnoteRect(double x, double y, double w, double h)
{
BYTE nPenDashStyle = 0;
m_pRenderer->get_PenDashStyle(&nPenDashStyle);
bool bIsIntegerGrid = m_pRenderer->get_IntegerGrid();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(true);
double dash[2] = { 2.0, 2.0 };
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->PenDashPattern(dash, 2);
m_pRenderer->PathCommandEnd();
double l = x;
double t = y;
double r = x + w;
double b = y + h;
drawHorLineExt(1, t, l, r, 0, 0, 0);
drawVerLine (1, l, t, b, 0);
drawVerLine (1, r, t, b, 0);
drawHorLineExt(1, b, l, r, 0, 0, 0);
m_pRenderer->PathCommandEnd();
m_pRenderer->Stroke();
if (!bIsIntegerGrid)
m_pRenderer->put_IntegerGrid(false);
m_pRenderer->put_PenDashStyle(nPenDashStyle);
}
std::string CGraphics::toDataURL(std::wstring type)
{
std::wstring sPath = NSFile::CFileBinary::CreateTempFileWithUniqueName(m_sApplicationImagesDirectory, L"img");
#ifdef _DEBUG
std::wcout << "toDataURL " << sPath << std::endl;
#endif
m_oFrame.SaveFile(sPath, _CXIMAGE_FORMAT_PNG);
NSFile::CFileBinary oReader;
if (oReader.OpenFile(sPath))
{
DWORD dwFileSize = oReader.GetFileSize();
BYTE* pFileContent = new BYTE[dwFileSize];
DWORD dwReaded;
oReader.ReadFile(pFileContent, dwFileSize, dwReaded);
oReader.CloseFile();
NSFile::CFileBinary::Remove(sPath);
int nEncodeLen = NSBase64::Base64EncodeGetRequiredLength(dwFileSize);
BYTE* pImageData = new BYTE[nEncodeLen];
if (TRUE == NSBase64::Base64Encode(pFileContent, dwFileSize, pImageData, &nEncodeLen))
return "data:" + U_TO_UTF8(type) + ";base64, " + std::string((char*)pImageData, nEncodeLen);
}
return "";
}
CColor CGraphics::GetPenColor()
{
LONG color;
LONG a;
m_pRenderer->get_PenColor(&color);
m_pRenderer->get_PenAlpha(&a);
return {(int)(color & 0xFF), (int)((color >> 8) & 0xFF), (int)((color >> 16) & 0xFF), (int)a};
}
CColor CGraphics::GetBrushColor()
{
LONG color;
LONG a;
m_pRenderer->get_BrushColor1(&color);
m_pRenderer->get_BrushAlpha1(&a);
return {(int)(color & 0xFF), (int)((color >> 8) & 0xFF), (int)((color >> 16) & 0xFF), (int)a};
}
void CGraphics::put_brushTexture(std::wstring src, int type)
{
if (src.find(L"data:") == 0)
{
std::wstring strImage = m_sApplicationImagesDirectory + L"/texture.png";
bool bIsOnlyOfficeHatch = false;
if(src.find(L"onlyoffice_hatch") != std::wstring::npos)
bIsOnlyOfficeHatch = true;
#ifdef _DEBUG
std::wcout << L"put_brushTexture " << src << L" " << bIsOnlyOfficeHatch << std::endl;
#endif
src.erase(0, src.find(L',') + 1);
std::string sBase64MultyByte(src.begin(), src.end());
int nDecodeLen = NSBase64::Base64DecodeGetRequiredLength(sBase64MultyByte.length());
if(nDecodeLen == 0)
return;
BYTE* pImageData = new BYTE[nDecodeLen + 64];
if (TRUE == NSBase64::Base64Decode(sBase64MultyByte.c_str(), sBase64MultyByte.length(), pImageData, &nDecodeLen))
{
if(!bIsOnlyOfficeHatch)
{
NSFile::CFileBinary oImageWriter;
if (oImageWriter.CreateFileW(strImage))
{
oImageWriter.WriteFile(pImageData, (DWORD)nDecodeLen);
oImageWriter.CloseFile();
}
}
else
{
int nSize = (int)sqrt(nDecodeLen >> 2);
CBgraFrame oFrame;
oFrame.put_Data(pImageData);
oFrame.put_Width(nSize);
oFrame.put_Height(nSize);
oFrame.put_Stride(4 * nSize);
oFrame.put_IsRGBA(true);
oFrame.SaveFile(strImage, 4);
}
m_pRenderer->put_BrushType(c_BrushTypeTexture);
m_pRenderer->put_BrushTexturePath(strImage);
m_pRenderer->put_BrushTextureMode(type);
}
}
else
{
std::wstring strImage = (0 == src.find(L"theme") ? m_sApplicationThemesDirectory : m_sApplicationImagesDirectory) + L'/' + src;
std::wstring sName = strImage.substr(0, strImage.rfind(L'.') + 1);
std::wstring sExt = src.substr(src.rfind(L'.') + 1);
if (sExt == L"svg")
{
MetaFile::IMetaFile* pMetafile = MetaFile::Create(m_pApplicationFonts);
pMetafile->LoadFromFile(strImage.c_str());
double x = 0, y = 0, w = 0, h = 0;
pMetafile->GetBounds(&x, &y, &w, &h);
sName += L"png";
pMetafile->ConvertToRaster(sName.c_str(), 4, 1000);
RELEASEOBJECT(pMetafile);
/*
if (NSFile::CFileBinary::Exists(sName + L"wmf"))
sName += L"wmf";
else if (NSFile::CFileBinary::Exists(sName + L"emf"))
sName += L"emf";
else
sName += L"svg";
*/
}
else
sName += sExt;
#ifdef _DEBUG
std::wcout << L"put_brushTexture " << sName << L" " << type << std::endl;
#endif
m_pRenderer->put_BrushType(c_BrushTypeTexture);
m_pRenderer->put_BrushTexturePath(sName);
m_pRenderer->put_BrushTextureMode(type);
}
}
void CGraphics::put_brushTextureMode(int mode)
{
#ifdef _DEBUG
std::cout << "put_brushTextureMode " << mode << std::endl;
#endif
m_pRenderer->put_BrushTextureMode(mode);
}
void CGraphics::put_BrushTextureAlpha(int a)
{
#ifdef _DEBUG
std::cout << "put_BrushTextureAlpha " << a << std::endl;
#endif
m_pRenderer->put_BrushTextureAlpha(a == 0 ? 255 : a);
}
void CGraphics::put_BrushGradient(LONG* pColors, double* pPositions, size_t nCount, double x0, double y0, double x1, double y1, double r0, double r1)
{
#ifdef _DEBUG
std::cout << "put_BrushGradient " << nCount << " " << x0 << " " << y0 << " " << x1 << " " << y1 << " " << r0 << " " << r1 << std::endl;
for (size_t i = 0; i < nCount; i++)
std::cout << pPositions[i] << " " << pColors[i] << " ";
std::cout << std::endl;
#endif
if (std::isnan(r0))
{
// линейный
double dAngle = 0;
if (fabs(x1 - x0) >= FLT_EPSILON || fabs(y1 - y0) >= FLT_EPSILON)
dAngle = atan2(y1 - y0, x1 - x0) * 180 / M_PI;
m_pRenderer->put_BrushType(c_BrushTypePathGradient1);
m_pRenderer->put_BrushGradientColors(pColors, pPositions, nCount);
m_pRenderer->put_BrushLinearAngle(dAngle);
}
else
{
// радиальный
m_pRenderer->put_BrushType(c_BrushTypePathGradient2);
m_pRenderer->put_BrushGradientColors(pColors, pPositions, nCount);
}
}
double CGraphics::TransformPointX(double x, double y)
{
#ifdef _DEBUG
std::cout << "TransformPointX " << std::endl;
#endif
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
return x;
}
double CGraphics::TransformPointY(double x, double y)
{
#ifdef _DEBUG
std::cout << "TransformPointY " << std::endl;
#endif
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
return y;
}
void CGraphics::put_LineJoin(int nJoin)
{
#ifdef _DEBUG
std::cout << "put_LineJoin " << std::endl;
#endif
m_pRenderer->put_PenLineJoin(nJoin);
}
int CGraphics::GetLineJoin()
{
#ifdef _DEBUG
std::cout << "GetLineJoin " << std::endl;
#endif
BYTE nRes;
m_pRenderer->get_PenLineJoin(&nRes);
return nRes;
}
void CGraphics::put_TextureBounds(double x, double y, double w, double h)
{
#ifdef _DEBUG
std::cout << "put_TextureBounds " << L" " << x << " " << y << L" " << w << L" " << h << std::endl;
#endif
if(m_pRenderer->get_IntegerGrid())
{
double r = x + w;
double b = y + h;
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
m_pRenderer->GetFullTransform()->TransformPoint(r, b);
m_pRenderer->BrushBounds(x, y, r - x, b - y);
}
else
m_pRenderer->BrushBounds(x, y, w, h);
}
double CGraphics::GetlineWidth()
{
#ifdef _DEBUG
std::cout << "GetlineWidth " << std::endl;
#endif
double nRes;
m_pRenderer->get_PenSize(&nRes);
return nRes;
}
void CGraphics::DrawPath(int path)
{
#ifdef _DEBUG
std::cout << "DrawPath " << path << std::endl;
#endif
if(path == 257)
{
m_pRenderer->DrawPath(256);
m_pRenderer->DrawPath(1);
}
else
m_pRenderer->DrawPath(path);
}
void CGraphics::CoordTransformOffset(double tx, double ty)
{
#ifdef _DEBUG
std::cout << "CoordTransformOffset " << tx << " " << ty << std::endl;
#endif
m_pRenderer->SetCoordTransformOffset(tx, ty);
}
CTransform CGraphics::GetTransform()
{
CTransform oRes;
m_pRenderer->GetTransform(&oRes.sx, &oRes.shy, &oRes.shx, &oRes.sy, &oRes.tx, &oRes.ty);
return oRes;
}
}
|
/*
* VHDL code generation for processes.
*
* Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk)
*
* 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) 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "vhdl_target.h"
#include "vhdl_element.hh"
#include <iostream>
#include <cassert>
#include <sstream>
#include <map>
/*
* Implementing blocking assignment is a little tricky since
* the semantics are a little different to VHDL:
*
* In Verilog a blocking assignment (=) can be used anywhere
* non-blocking assignment (<=) can be. In VHDL blocking
* assignment (:=) can only be used with variables, and
* non-blocking assignment (<=) can only be used with signals.
* All Verilog variables are translated into signals in the
* VHDL architecture. This means we cannot use the VHDL :=
* operator directly. Furthermore, VHDL variables can only
* be declared within processes, so it wouldn't help to
* make all Verilog variables VHDL variables.
*
* The solution is to generate a VHDL variable in a process
* whenever a blocking assignment is made to a signal. The
* assignment is made to this variable instead, and
* g_assign_vars below remembers the temporary variables
* that have been generated. Any subsequent blocking assignments
* are made to the same variable. At either the end of the
* process or a `wait' statement, the temporaries are assigned
* back to the signals, and the temporaries are forgotten. This
* has exactly the same (external) behaviour as the Verilog
* blocking assignment, since no external process will be able
* to observe that the assignment wasn't made immediately.
*
* For example:
*
* initial begin
* a = 5;
* b = a + 3;
* end
*
* Is translated to:
*
* process is
* variable a_Var : Some_Type;
* variable b_Var : Some_Type;
* begin
* a_Var := 5;
* b_Var := a_Var + 3;
* a <= a_Var;
* b <= b_Var;
* end process;
*/
typedef std::map<std::string, ivl_signal_t> var_temp_set_t;
static var_temp_set_t g_assign_vars;
/*
* Called whenever a blocking assignment is made to sig.
*/
void blocking_assign_to(vhdl_process *proc, ivl_signal_t sig)
{
std::string var(get_renamed_signal(sig));
std::string tmpname(var + "_Var");
if (g_assign_vars.find(var) == g_assign_vars.end()) {
// This is the first time a non-blocking assignment
// has been made to this signal: create a variable
// to shadow it.
if (!proc->have_declared_var(tmpname)) {
vhdl_decl *decl = proc->get_parent()->get_decl(var);
assert(decl);
vhdl_type *type = new vhdl_type(*decl->get_type());
proc->add_decl(new vhdl_var_decl(tmpname.c_str(), type));
}
rename_signal(sig, tmpname);
g_assign_vars[tmpname] = sig;
}
}
/*
* Assign all _Var variables to the corresponding signals. This makes
* the new values visible outside the current process. This should be
* called before any `wait' statement or the end of the process.
*/
void draw_blocking_assigns(vhdl_process *proc)
{
var_temp_set_t::const_iterator it;
for (it = g_assign_vars.begin(); it != g_assign_vars.end(); ++it) {
std::string stripped(strip_var((*it).first));
vhdl_decl *decl = proc->get_decl(stripped);
assert(decl);
vhdl_type *type = new vhdl_type(*decl->get_type());
vhdl_var_ref *lhs = new vhdl_var_ref(stripped.c_str(), NULL);
vhdl_expr *rhs = new vhdl_var_ref((*it).first.c_str(), type);
// TODO: I'm not sure this will work properly if, e.g., the delay
// is inside a `if' statement
proc->get_container()->add_stmt(new vhdl_nbassign_stmt(lhs, rhs));
// Undo the renaming (since the temporary is no longer needed)
rename_signal((*it).second, stripped);
}
g_assign_vars.clear();
}
/*
* Remove _Var from the end of a string, if it is present.
*/
std::string strip_var(const std::string &str)
{
std::string result(str);
size_t pos = result.find("_Var");
if (pos != std::string::npos)
result.erase(pos, 4);
return result;
}
/*
* Convert a Verilog process to VHDL and add it to the architecture
* of the given entity.
*/
static int generate_vhdl_process(vhdl_entity *ent, ivl_process_t proc)
{
// Create a new process and store it in the entity's
// architecture. This needs to be done first or the
// parent link won't be valid (and draw_stmt needs this
// to add information to the architecture)
vhdl_process *vhdl_proc = new vhdl_process();
ent->get_arch()->add_stmt(vhdl_proc);
// If this is an initial process, push signal initialisation
// into the declarations
if (ivl_process_type(proc) == IVL_PR_INITIAL)
vhdl_proc->set_initial(true);
ivl_statement_t stmt = ivl_process_stmt(proc);
int rc = draw_stmt(vhdl_proc, vhdl_proc->get_container(), stmt);
if (rc != 0)
return rc;
// Initial processes are translated to VHDL processes with
// no sensitivity list and and indefinite wait statement at
// the end
// However, if no statements were added to the container
// by draw_stmt, don't bother adding a wait as `emit'
// will optimise the process out of the output
if (ivl_process_type(proc) == IVL_PR_INITIAL
&& !vhdl_proc->get_container()->empty()) {
vhdl_wait_stmt *wait = new vhdl_wait_stmt();
vhdl_proc->get_container()->add_stmt(wait);
}
// Add a comment indicating where it came from
ivl_scope_t scope = ivl_process_scope(proc);
const char *type = ivl_process_type(proc) == IVL_PR_INITIAL
? "initial" : "always";
std::ostringstream ss;
ss << "Generated from " << type << " process in ";
ss << ivl_scope_tname(scope);
vhdl_proc->set_comment(ss.str());
// Output any remaning blocking assignments
draw_blocking_assigns(vhdl_proc);
return 0;
}
int draw_process(ivl_process_t proc, void *cd)
{
ivl_scope_t scope = ivl_process_scope(proc);
const char *scope_name = ivl_scope_name(scope);
// A process should occur in a module scope, therefore it
// should have already been assigned a VHDL entity
assert(ivl_scope_type(scope) == IVL_SCT_MODULE);
vhdl_entity *ent = find_entity(ivl_scope_tname(scope));
assert(ent != NULL);
// If the scope this process belongs to is the same as the
// VHDL entity was generated from, then create a VHDL process
// from this Verilog process. This ensures that each process
// is translated at most once, no matter how many times it
// appears in the hierarchy.
if (ent->get_derived_from() == scope_name)
return generate_vhdl_process(ent, proc);
else
return 0;
}
Statements might be emitted in wrong order
/*
* VHDL code generation for processes.
*
* Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk)
*
* 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) 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "vhdl_target.h"
#include "vhdl_element.hh"
#include <iostream>
#include <cassert>
#include <sstream>
#include <map>
/*
* Implementing blocking assignment is a little tricky since
* the semantics are a little different to VHDL:
*
* In Verilog a blocking assignment (=) can be used anywhere
* non-blocking assignment (<=) can be. In VHDL blocking
* assignment (:=) can only be used with variables, and
* non-blocking assignment (<=) can only be used with signals.
* All Verilog variables are translated into signals in the
* VHDL architecture. This means we cannot use the VHDL :=
* operator directly. Furthermore, VHDL variables can only
* be declared within processes, so it wouldn't help to
* make all Verilog variables VHDL variables.
*
* The solution is to generate a VHDL variable in a process
* whenever a blocking assignment is made to a signal. The
* assignment is made to this variable instead, and
* g_assign_vars below remembers the temporary variables
* that have been generated. Any subsequent blocking assignments
* are made to the same variable. At either the end of the
* process or a `wait' statement, the temporaries are assigned
* back to the signals, and the temporaries are forgotten. This
* has exactly the same (external) behaviour as the Verilog
* blocking assignment, since no external process will be able
* to observe that the assignment wasn't made immediately.
*
* For example:
*
* initial begin
* a = 5;
* b = a + 3;
* end
*
* Is translated to:
*
* process is
* variable a_Var : Some_Type;
* variable b_Var : Some_Type;
* begin
* a_Var := 5;
* b_Var := a_Var + 3;
* a <= a_Var;
* b <= b_Var;
* end process;
*/
typedef std::map<std::string, ivl_signal_t> var_temp_set_t;
static var_temp_set_t g_assign_vars;
/*
* Called whenever a blocking assignment is made to sig.
*/
void blocking_assign_to(vhdl_process *proc, ivl_signal_t sig)
{
std::string var(get_renamed_signal(sig));
std::string tmpname(var + "_Var");
if (g_assign_vars.find(var) == g_assign_vars.end()) {
// This is the first time a non-blocking assignment
// has been made to this signal: create a variable
// to shadow it.
if (!proc->have_declared_var(tmpname)) {
vhdl_decl *decl = proc->get_parent()->get_decl(var);
assert(decl);
vhdl_type *type = new vhdl_type(*decl->get_type());
proc->add_decl(new vhdl_var_decl(tmpname.c_str(), type));
}
rename_signal(sig, tmpname);
g_assign_vars[tmpname] = sig;
}
}
/*
* Assign all _Var variables to the corresponding signals. This makes
* the new values visible outside the current process. This should be
* called before any `wait' statement or the end of the process.
*/
void draw_blocking_assigns(vhdl_process *proc)
{
var_temp_set_t::const_iterator it;
for (it = g_assign_vars.begin(); it != g_assign_vars.end(); ++it) {
std::string stripped(strip_var((*it).first));
vhdl_decl *decl = proc->get_decl(stripped);
assert(decl);
vhdl_type *type = new vhdl_type(*decl->get_type());
vhdl_var_ref *lhs = new vhdl_var_ref(stripped.c_str(), NULL);
vhdl_expr *rhs = new vhdl_var_ref((*it).first.c_str(), type);
// TODO: I'm not sure this will work properly if, e.g., the delay
// is inside a `if' statement
proc->get_container()->add_stmt(new vhdl_nbassign_stmt(lhs, rhs));
// Undo the renaming (since the temporary is no longer needed)
rename_signal((*it).second, stripped);
}
g_assign_vars.clear();
}
/*
* Remove _Var from the end of a string, if it is present.
*/
std::string strip_var(const std::string &str)
{
std::string result(str);
size_t pos = result.find("_Var");
if (pos != std::string::npos)
result.erase(pos, 4);
return result;
}
/*
* Convert a Verilog process to VHDL and add it to the architecture
* of the given entity.
*/
static int generate_vhdl_process(vhdl_entity *ent, ivl_process_t proc)
{
// Create a new process and store it in the entity's
// architecture. This needs to be done first or the
// parent link won't be valid (and draw_stmt needs this
// to add information to the architecture)
vhdl_process *vhdl_proc = new vhdl_process();
ent->get_arch()->add_stmt(vhdl_proc);
// If this is an initial process, push signal initialisation
// into the declarations
if (ivl_process_type(proc) == IVL_PR_INITIAL)
vhdl_proc->set_initial(true);
ivl_statement_t stmt = ivl_process_stmt(proc);
int rc = draw_stmt(vhdl_proc, vhdl_proc->get_container(), stmt);
if (rc != 0)
return rc;
// Output any remaning blocking assignments
draw_blocking_assigns(vhdl_proc);
// Initial processes are translated to VHDL processes with
// no sensitivity list and and indefinite wait statement at
// the end
// However, if no statements were added to the container
// by draw_stmt, don't bother adding a wait as `emit'
// will optimise the process out of the output
if (ivl_process_type(proc) == IVL_PR_INITIAL
&& !vhdl_proc->get_container()->empty()) {
vhdl_wait_stmt *wait = new vhdl_wait_stmt();
vhdl_proc->get_container()->add_stmt(wait);
}
// Add a comment indicating where it came from
ivl_scope_t scope = ivl_process_scope(proc);
const char *type = ivl_process_type(proc) == IVL_PR_INITIAL
? "initial" : "always";
std::ostringstream ss;
ss << "Generated from " << type << " process in ";
ss << ivl_scope_tname(scope);
vhdl_proc->set_comment(ss.str());
return 0;
}
int draw_process(ivl_process_t proc, void *cd)
{
ivl_scope_t scope = ivl_process_scope(proc);
const char *scope_name = ivl_scope_name(scope);
// A process should occur in a module scope, therefore it
// should have already been assigned a VHDL entity
assert(ivl_scope_type(scope) == IVL_SCT_MODULE);
vhdl_entity *ent = find_entity(ivl_scope_tname(scope));
assert(ent != NULL);
// If the scope this process belongs to is the same as the
// VHDL entity was generated from, then create a VHDL process
// from this Verilog process. This ensures that each process
// is translated at most once, no matter how many times it
// appears in the hierarchy.
if (ent->get_derived_from() == scope_name)
return generate_vhdl_process(ent, proc);
else
return 0;
}
|
#include "MoonSchlyterModel.h"
#include "EarthSchlyterModel.h"
#include "Time/J2000.h"
/*
N = 125.1228 - 0.0529538083 * d
i = 5.1454
w = 318.0634 + 0.1643573223 * d
a = 60.2666 (Earth radii)
e = 0.054900
M = 115.3654 + 13.0649929509 * d
*/
const double kdEarthRadiiAU = 0.01;
const KeplerElements MoonSchlyterOrbitalEphemeris::kxBaseElements =
{
PDE::Deg2Rad( 125.1228 ),
PDE::Deg2Rad( 5.1454 ),
PDE::Deg2Rad( 282.9404 ),
-60.2666 * kdEarthRadiiAU,
0.054900,
PDE::Deg2Rad( 115.3654 ),
PDE::Deg2Rad( 13.0649929509 ),
static_cast< double >( J2000 - 1.5 ) // SE - NOTE: these elements have an epoch of '0' Jan 2000, 1.5 days before J2000.0
};
const KeplerElements MoonSchlyterOrbitalEphemeris::kxLinearPerturbations =
{
PDE::Deg2Rad( 0.0529538083 ),
0.0,
PDE::Deg2Rad( 0.1643573223 ),
0.0,
0.000000001151,
0.0,
0.0,
0.0
};
EphemerisVector4 MoonSchlyterOrbitalEphemeris::Perturb( const EphemerisVector4 xPosition, const double dT ) const
{
const double dEclipticLongitude = CalculateLongitude( xPosition );
const double dEclipticLatitude = CalculateLatitude( xPosition );
const double dMeanAnomalyMoon = MeanAnomaly( dT );
const double dMeanAnomalyEarth = EarthSchlyterOrbitalEphemeris::MeanAnomaly( dT );
EarthSchlyterOrbitalEphemeris xEarthEphemeris;
MoonSchlyterOrbitalEphemeris xMoonEphemeris;
const double dArgumentOfPerifocusEarth = xEarthEphemeris.EvaluateArgumentOfPerifocus( dT );
//const double dTrueAnomalyEarth = xEarthEphemeris.EvaluateTrueAnomaly( dT );
const double dLongitudeOfAscendingNodeMoon = xMoonEphemeris.EvaluateLongitudeOfAscendingNode( dT );
const double dArgumentOfPerifocusMoon = xMoonEphemeris.EvaluateArgumentOfPerifocus( dT );
//const double dTrueAnomalyMoon = xMoonEphemeris.EvaluateTrueAnomaly( dT );
const double dLongitudeSun = dMeanAnomalyEarth + dArgumentOfPerifocusEarth;
const double dLongitudeMoon = dMeanAnomalyMoon + dArgumentOfPerifocusMoon + dLongitudeOfAscendingNodeMoon;
const double dElongationMoon = dLongitudeMoon - dLongitudeSun;
const double dArgumentOfLatitudeMoon = dLongitudeMoon - dLongitudeOfAscendingNodeMoon;
// D = elongation moon
// F = latitude thing
const double dCorrectedLongitude = dEclipticLongitude
- 1.274 * PDE::Sin( dMeanAnomalyEarth - 2 * dElongationMoon ) // evection
+ 0.658 * PDE::Sin( 2.0 * dElongationMoon ) // variation
- 0.186 * PDE::Sin( dMeanAnomalyEarth ) // yearly equation
- 0.059 * PDE::Sin( 2.0 * ( dMeanAnomalyMoon - dElongationMoon ) )
- 0.057 * PDE::Sin( dMeanAnomalyMoon - 2.0 * dElongationMoon + dMeanAnomalyEarth )
+ 0.053 * PDE::Sin( dMeanAnomalyMoon + 2.0 * dElongationMoon )
+ 0.046 * PDE::Sin( 2.0 * dElongationMoon - dMeanAnomalyEarth )
+ 0.041 * PDE::Sin( dMeanAnomalyMoon - dMeanAnomalyEarth )
- 0.035 * PDE::Sin( dElongationMoon ) // parallactic equation
- 0.031 * PDE::Sin( dMeanAnomalyMoon + dMeanAnomalyEarth )
- 0.015 * PDE::Sin( 2.0 * ( dArgumentOfLatitudeMoon - dElongationMoon ) )
+ 0.011 * PDE::Sin( dMeanAnomalyMoon - 4.0 * dElongationMoon );
const double dCorrectedLatitude = dEclipticLatitude
- 0.173 * PDE::Sin( dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
- 0.055 * PDE::Sin( dMeanAnomalyMoon - dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
- 0.046 * PDE::Sin( dMeanAnomalyMoon + dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
+ 0.033 * PDE::Sin( dArgumentOfLatitudeMoon + 2.0 * dElongationMoon )
+ 0.017 * PDE::Sin( 2.0 * dMeanAnomalyMoon + dArgumentOfLatitudeMoon );
const double dCorrectedDistance = xPosition.xyz().Magnitude();
return PositionFromLatLonRad( dCorrectedLatitude, dCorrectedLongitude, dCorrectedDistance );
}
corrections to lunar schlyter model
#include "MoonSchlyterModel.h"
#include "EarthSchlyterModel.h"
#include "Time/J2000.h"
/*
N = 125.1228 - 0.0529538083 * d
i = 5.1454
w = 318.0634 + 0.1643573223 * d
a = 60.2666 (Earth radii)
e = 0.054900
M = 115.3654 + 13.0649929509 * d
*/
const double kdEarthRadiiAU = 6371.009 / 149597870.7;
const KeplerElements MoonSchlyterOrbitalEphemeris::kxBaseElements =
{
PDE::Deg2Rad( 125.1228 ),
PDE::Deg2Rad( 5.1454 ),
PDE::Deg2Rad( 282.9404 ),
-60.2666 * kdEarthRadiiAU,
0.054900,
PDE::Deg2Rad( 115.3654 ),
PDE::Deg2Rad( 13.0649929509 ),
static_cast< double >( J2000 - 1.5 ) // SE - NOTE: these elements have an epoch of '0' Jan 2000, 1.5 days before J2000.0
};
const KeplerElements MoonSchlyterOrbitalEphemeris::kxLinearPerturbations =
{
PDE::Deg2Rad( 0.0529538083 ),
0.0,
PDE::Deg2Rad( 0.1643573223 ),
0.0,
0.000000001151,
0.0,
0.0,
0.0
};
EphemerisVector4 MoonSchlyterOrbitalEphemeris::Perturb( const EphemerisVector4 xPosition, const double dT ) const
{
const double dEclipticLongitude = CalculateLongitude( xPosition );
const double dEclipticLatitude = CalculateLatitude( xPosition );
const double dMeanAnomalyMoon = MeanAnomaly( dT );
const double dMeanAnomalyEarth = EarthSchlyterOrbitalEphemeris::MeanAnomaly( dT );
EarthSchlyterOrbitalEphemeris xEarthEphemeris;
MoonSchlyterOrbitalEphemeris xMoonEphemeris;
const double dArgumentOfPerifocusEarth = xEarthEphemeris.EvaluateArgumentOfPerifocus( dT );
//const double dTrueAnomalyEarth = xEarthEphemeris.EvaluateTrueAnomaly( dT );
const double dLongitudeOfAscendingNodeMoon = xMoonEphemeris.EvaluateLongitudeOfAscendingNode( dT );
const double dArgumentOfPerifocusMoon = xMoonEphemeris.EvaluateArgumentOfPerifocus( dT );
//const double dTrueAnomalyMoon = xMoonEphemeris.EvaluateTrueAnomaly( dT );
const double dLongitudeSun = dMeanAnomalyEarth + dArgumentOfPerifocusEarth;
const double dLongitudeMoon = dMeanAnomalyMoon + dArgumentOfPerifocusMoon + dLongitudeOfAscendingNodeMoon;
const double dElongationMoon = dLongitudeMoon - dLongitudeSun;
const double dArgumentOfLatitudeMoon = dLongitudeMoon - dLongitudeOfAscendingNodeMoon;
// D = elongation moon
// F = latitude thing
const double dCorrectedLongitude = dEclipticLongitude
- 1.274 * PDE::Sin( dMeanAnomalyEarth - 2.0 * dElongationMoon ) // evection
+ 0.658 * PDE::Sin( 2.0 * dElongationMoon ) // variation
- 0.186 * PDE::Sin( dMeanAnomalyEarth ) // yearly equation
- 0.059 * PDE::Sin( 2.0 * ( dMeanAnomalyMoon - dElongationMoon ) )
- 0.057 * PDE::Sin( dMeanAnomalyMoon - 2.0 * dElongationMoon + dMeanAnomalyEarth )
+ 0.053 * PDE::Sin( dMeanAnomalyMoon + 2.0 * dElongationMoon )
+ 0.046 * PDE::Sin( 2.0 * dElongationMoon - dMeanAnomalyEarth )
+ 0.041 * PDE::Sin( dMeanAnomalyMoon - dMeanAnomalyEarth )
- 0.035 * PDE::Sin( dElongationMoon ) // parallactic equation
- 0.031 * PDE::Sin( dMeanAnomalyMoon + dMeanAnomalyEarth )
- 0.015 * PDE::Sin( 2.0 * ( dArgumentOfLatitudeMoon - dElongationMoon ) )
+ 0.011 * PDE::Sin( dMeanAnomalyMoon - 4.0 * dElongationMoon );
const double dCorrectedLatitude = dEclipticLatitude
- 0.173 * PDE::Sin( dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
- 0.055 * PDE::Sin( dMeanAnomalyMoon - dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
- 0.046 * PDE::Sin( dMeanAnomalyMoon + dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
+ 0.033 * PDE::Sin( dArgumentOfLatitudeMoon + 2.0 * dElongationMoon )
+ 0.017 * PDE::Sin( 2.0 * dMeanAnomalyMoon + dArgumentOfLatitudeMoon );
const double dCorrectedDistance = xPosition.xyz().Magnitude()
- 0.58 * kdEarthRadiiAU * PDE::Cos( dMeanAnomalyMoon - 2.0 * dElongationMoon )
- 0.46 * kdEarthRadiiAU * PDE::Cos( 2.0 * dElongationMoon );
;
return PositionFromLatLonRad( dCorrectedLatitude, dCorrectedLongitude, dCorrectedDistance );
}
|
#include "cpu.hpp"
#include "mmu.hpp"
#include "iostream"
#include "debug.hpp"
#include "disassembler.hpp"
CPU::CPU () {}
CPU::~CPU () {}
void CPU::Initialize (MMU* _mmu, bool doBootrom) {
/* Initialize Registers */
if (doBootrom) {
AF = 0;
BC = 0;
DE = 0;
HL = 0;
SP = 0x0;
PC = 0x0;
SetZ(0); SetN(0); SetH(0); SetC(0);
}
else {
AF = 0x01B0;
BC = 0x0013;
DE = 0x00D8;
HL = 0x014D;
SP = 0xFFFE;
PC = 0x100;
SetZ(1); SetN(0); SetH(1); SetC(1);
}
clockCycles = 0;
assert("Assigned MMU wasn't initialized" && _mmu != nullptr);
mmu = _mmu;
InitializeOpcodeTable();
}
void CPU::EmulateCycle () {
if (PC == 0x100) {
mmu->isInBios = false;
areInterruptsEnabled = true;
}
if (PC == 0x100 || PC == 0xC16B) {
isHalted = true;
}
uint8_t opcode = mmu->ReadByte(PC);
std::cout << std::hex << PC << ' ' << DisassembleOpcode(mmu->GetMemoryRef(PC)) << '\n';
// std::cout << std::hex << opcode << '\n';
PC += 1;
(this->*opcodes[opcode])(); // Wtf C++
}
void CPU::RequestInterrupt (uint8_t id) {
uint8_t requestRegister = mmu->ReadByte(IF);
requestRegister |= 0x10 >> (4 - id); // SET bit ID
mmu->WriteByte(IF, requestRegister);
// std::cout << "Interrupt requested!\n" ;
}
void CPU::ProcessInterrupts () {
if (areInterruptsEnabled == false)
return;
uint8_t requestRegister = mmu->ReadByte(IF);
if (requestRegister == 0)
return;
uint8_t enabledRegister = mmu->ReadByte(IF);
for (size_t id = 0; id < 5; id++) {
bool isInterruptRequested = requestRegister & (0x10 >> (4 - id));
bool isInterruptEnabled = enabledRegister & (0x10 >> (4 - id));
if (isInterruptRequested && isInterruptEnabled)
DoInterrupt(id);
}
}
void CPU::DoInterrupt (uint8_t id) {
areInterruptsEnabled = false;
uint8_t requestRegister = mmu->ReadByte(IF);
// Reset bit id, we use XOR because the bit has to be 1 before this function
requestRegister ^= 0x10 >> (4 - id);
mmu->WriteByte(IF, requestRegister);
PushWord(PC);
switch (id) {
case 0: PC = 0x40; break;
case 1: PC = 0x48; break;
case 2: PC = 0x50; break;
case 4: PC = 0x60; break;
default: assert("Invalid interrupt ID" && 0); break;
}
// std::cout << "Interrupting!" << "\n";
// isHalted = true;
}
void CPU::SetZ (bool value) {
AF.lo = (AF.lo & ~0x80) | 0x80 * value;
}
void CPU::SetN (bool value) {
AF.lo = (AF.lo & ~0x40) | 0x40 * value;
}
void CPU::SetH (bool value) {
AF.lo = (AF.lo & ~0x20) | 0x20 * value;
}
void CPU::SetC (bool value) {
AF.lo = (AF.lo & ~0x10) | 0x10 * value;
}
bool CPU::GetZ () {
return (AF.lo & 0x80);
}
bool CPU::GetN () {
return (AF.lo & 0x40);
}
bool CPU::GetH () {
return (AF.lo & 0x20);
}
bool CPU::GetC () {
return (AF.lo & 0x10);
}
uint8_t CPU::ReadByte () {
uint8_t value = mmu->ReadByte(PC);
PC += 1;
return value;
}
uint16_t CPU::ReadWord () {
uint16_t value = mmu->ReadWord(PC);
PC += 2;
return value;
}
void CPU::PushWord (uint16_t value) {
SP -= 2;
mmu->WriteWord(SP, value);
}
uint16_t CPU::PopWord () {
SP += 2;
return mmu->ReadWord(SP - 2);
}
// FIXME: Double check C flag computation
void CPU::RotateLeft (uint8_t& value) {
uint8_t oldBit7 = (value >> 7);
value = (value << 1) | GetC();
SetZ(value == 0);
SetN(0), SetH(0);
SetC(oldBit7);
}
void CPU::Decrement (uint8_t& value) {
uint8_t oldBit4 = value & 0x8;
value -= 1;
SetZ(value == 0);
SetN(1);
SetH( (value & 0x8) ^ oldBit4 && oldBit4 != 0x8 );
}
void CPU::Decrement (uint16_t& value) {
uint8_t oldBit4 = value & 0x8;
value -= 1;
SetZ(value == 0);
SetN(1);
SetH( (value & 0x8) ^ oldBit4 && oldBit4 != 0x8 );
}
void CPU::Decrement (reg16_t& value) {
Decrement(value.word);
}
void CPU::Increment (uint8_t& value) {
uint8_t prev = value;
value += 1;
SetZ(value == 0);
SetN(0);
SetH((prev & 0xF) == 0xF);
}
// FIXME: Halfcarry in a 16bit value isn't on bit 4
void CPU::Increment (uint16_t& value) {
uint16_t prev = value;
value += 1;
SetZ(value == 0);
SetN(0);
SetH((prev & 0xFF) == 0xFF);
}
void CPU::Increment (reg16_t& value) {
Increment(value.word);
}
void CPU::AddA (uint8_t value) {
AF.hi += value;
SetZ(AF.hi == 0);
SetN(0);
SetH((AF.hi & 0xF) + (value & 0xF) > 0xF);
SetC(AF.hi + value > 0xFF);
}
void CPU::Add (uint16_t& x, uint16_t value) {
x += value;
SetZ(x == 0);
SetN(0);
SetH((x & 0xF) + (value & 0xF) > 0xF);
SetC(x + value > 0xFF);
}
void CPU::SubtractA (uint8_t value) {
AF.hi -= value;
SetZ(AF.hi == 0);
SetN(1);
SetH((AF.hi & 0xF) < (value & 0xF));
SetC(AF.hi < value);
}
void CPU::CompareA (uint8_t value) {
SetZ(AF.hi == value);
SetN(1);
SetH((AF.hi & 0xF) < (value & 0xF));
SetC(AF.hi < value);
}
void CPU::OrA (uint8_t value) {
AF.hi |= value;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
}
void CPU::Swap (uint8_t& value) {
uint8_t hi = value & 0xF0;
uint8_t lo = value & 0x0F;
value = (hi >> 4) | (lo << 4);
}
/* Instructions specific code */
void CPU::InitializeOpcodeTable () {
opcodes[0x00] = &CPU::op0x00; opcodes[0x01] = &CPU::op0x01;
opcodes[0x02] = &CPU::op0x02; opcodes[0x03] = &CPU::op0x03;
opcodes[0x04] = &CPU::op0x04; opcodes[0x05] = &CPU::op0x05;
opcodes[0x06] = &CPU::op0x06; opcodes[0x07] = &CPU::op0x07;
opcodes[0x08] = &CPU::op0x08; opcodes[0x09] = &CPU::op0x09;
opcodes[0x0A] = &CPU::op0x0A; opcodes[0x0B] = &CPU::op0x0B;
opcodes[0x0C] = &CPU::op0x0C; opcodes[0x0D] = &CPU::op0x0D;
opcodes[0x0E] = &CPU::op0x0E; opcodes[0x0F] = &CPU::op0x0F;
opcodes[0x10] = &CPU::opNull; opcodes[0x11] = &CPU::op0x11;
opcodes[0x12] = &CPU::op0x12; opcodes[0x13] = &CPU::op0x13;
opcodes[0x14] = &CPU::op0x14; opcodes[0x15] = &CPU::op0x15;
opcodes[0x16] = &CPU::op0x16; opcodes[0x17] = &CPU::op0x17;
opcodes[0x18] = &CPU::op0x18; opcodes[0x19] = &CPU::op0x19;
opcodes[0x1A] = &CPU::op0x1A; opcodes[0x1B] = &CPU::op0x1B;
opcodes[0x1C] = &CPU::op0x1C; opcodes[0x1D] = &CPU::op0x1D;
opcodes[0x1E] = &CPU::op0x1E; opcodes[0x1F] = &CPU::opNull;
opcodes[0x20] = &CPU::op0x20; opcodes[0x21] = &CPU::op0x21;
opcodes[0x22] = &CPU::op0x22; opcodes[0x23] = &CPU::op0x23;
opcodes[0x24] = &CPU::op0x24; opcodes[0x25] = &CPU::op0x25;
opcodes[0x26] = &CPU::op0x26; opcodes[0x27] = &CPU::opNull;
opcodes[0x28] = &CPU::op0x28; opcodes[0x29] = &CPU::op0x29;
opcodes[0x2A] = &CPU::op0x2A; opcodes[0x2B] = &CPU::op0x2B;
opcodes[0x2C] = &CPU::op0x2C; opcodes[0x2D] = &CPU::op0x2D;
opcodes[0x2E] = &CPU::op0x2E; opcodes[0x2F] = &CPU::op0x2F;
opcodes[0x30] = &CPU::op0x30; opcodes[0x31] = &CPU::op0x31;
opcodes[0x32] = &CPU::op0x32; opcodes[0x33] = &CPU::op0x33;
opcodes[0x34] = &CPU::op0x34; opcodes[0x35] = &CPU::op0x35;
opcodes[0x36] = &CPU::op0x36; opcodes[0x37] = &CPU::opNull;
opcodes[0x38] = &CPU::op0x38; opcodes[0x39] = &CPU::op0x39;
opcodes[0x3A] = &CPU::op0x3A; opcodes[0x3B] = &CPU::op0x3B;
opcodes[0x3C] = &CPU::op0x3C; opcodes[0x3D] = &CPU::op0x3D;
opcodes[0x3E] = &CPU::op0x3E; opcodes[0x3F] = &CPU::opNull;
opcodes[0x40] = &CPU::op0x40; opcodes[0x41] = &CPU::op0x41;
opcodes[0x42] = &CPU::op0x42; opcodes[0x43] = &CPU::op0x43;
opcodes[0x44] = &CPU::op0x44; opcodes[0x45] = &CPU::op0x45;
opcodes[0x46] = &CPU::op0x46; opcodes[0x47] = &CPU::op0x47;
opcodes[0x48] = &CPU::op0x48; opcodes[0x49] = &CPU::op0x49;
opcodes[0x4A] = &CPU::op0x4A; opcodes[0x4B] = &CPU::op0x4B;
opcodes[0x4C] = &CPU::op0x4C; opcodes[0x4D] = &CPU::op0x4D;
opcodes[0x4E] = &CPU::op0x4E; opcodes[0x4F] = &CPU::op0x4F;
opcodes[0x50] = &CPU::op0x50; opcodes[0x51] = &CPU::op0x51;
opcodes[0x52] = &CPU::op0x52; opcodes[0x53] = &CPU::op0x53;
opcodes[0x54] = &CPU::op0x54; opcodes[0x55] = &CPU::op0x55;
opcodes[0x56] = &CPU::op0x56; opcodes[0x57] = &CPU::op0x57;
opcodes[0x58] = &CPU::op0x58; opcodes[0x59] = &CPU::op0x59;
opcodes[0x5A] = &CPU::op0x5A; opcodes[0x5B] = &CPU::op0x5B;
opcodes[0x5C] = &CPU::op0x5C; opcodes[0x5D] = &CPU::op0x5D;
opcodes[0x5E] = &CPU::op0x5E; opcodes[0x5F] = &CPU::op0x5F;
opcodes[0x60] = &CPU::op0x60; opcodes[0x61] = &CPU::op0x61;
opcodes[0x62] = &CPU::op0x62; opcodes[0x63] = &CPU::op0x63;
opcodes[0x64] = &CPU::op0x64; opcodes[0x65] = &CPU::op0x65;
opcodes[0x66] = &CPU::op0x66; opcodes[0x67] = &CPU::op0x67;
opcodes[0x68] = &CPU::op0x68; opcodes[0x69] = &CPU::op0x69;
opcodes[0x6A] = &CPU::op0x6A; opcodes[0x6B] = &CPU::op0x6B;
opcodes[0x6C] = &CPU::op0x6C; opcodes[0x6D] = &CPU::op0x6D;
opcodes[0x6E] = &CPU::op0x6E; opcodes[0x6F] = &CPU::op0x6F;
opcodes[0x70] = &CPU::op0x70; opcodes[0x71] = &CPU::op0x71;
opcodes[0x72] = &CPU::op0x72; opcodes[0x73] = &CPU::op0x73;
opcodes[0x74] = &CPU::op0x74; opcodes[0x75] = &CPU::op0x75;
opcodes[0x76] = &CPU::opNull; opcodes[0x77] = &CPU::op0x77;
opcodes[0x78] = &CPU::op0x78; opcodes[0x79] = &CPU::op0x79;
opcodes[0x7A] = &CPU::op0x7A; opcodes[0x7B] = &CPU::op0x7B;
opcodes[0x7C] = &CPU::op0x7C; opcodes[0x7D] = &CPU::op0x7D;
opcodes[0x7E] = &CPU::op0x7E; opcodes[0x7F] = &CPU::op0x7F;
opcodes[0x80] = &CPU::op0x80; opcodes[0x81] = &CPU::op0x81;
opcodes[0x82] = &CPU::op0x82; opcodes[0x83] = &CPU::op0x83;
opcodes[0x84] = &CPU::op0x84; opcodes[0x85] = &CPU::op0x85;
opcodes[0x86] = &CPU::op0x86; opcodes[0x87] = &CPU::op0x87;
opcodes[0x88] = &CPU::opNull; opcodes[0x89] = &CPU::opNull;
opcodes[0x8A] = &CPU::opNull; opcodes[0x8B] = &CPU::opNull;
opcodes[0x8C] = &CPU::opNull; opcodes[0x8D] = &CPU::opNull;
opcodes[0x8E] = &CPU::opNull; opcodes[0x8F] = &CPU::opNull;
opcodes[0x90] = &CPU::op0x90; opcodes[0x91] = &CPU::op0x91;
opcodes[0x92] = &CPU::op0x92; opcodes[0x93] = &CPU::op0x93;
opcodes[0x94] = &CPU::op0x94; opcodes[0x95] = &CPU::op0x95;
opcodes[0x96] = &CPU::op0x96; opcodes[0x97] = &CPU::op0x97;
opcodes[0x98] = &CPU::opNull; opcodes[0x99] = &CPU::opNull;
opcodes[0x9A] = &CPU::opNull; opcodes[0x9B] = &CPU::opNull;
opcodes[0x9C] = &CPU::opNull; opcodes[0x9D] = &CPU::opNull;
opcodes[0x9E] = &CPU::opNull; opcodes[0x9F] = &CPU::opNull;
opcodes[0xA0] = &CPU::op0xA0; opcodes[0xA1] = &CPU::op0xA1;
opcodes[0xA2] = &CPU::op0xA2; opcodes[0xA3] = &CPU::op0xA3;
opcodes[0xA4] = &CPU::op0xA4; opcodes[0xA5] = &CPU::op0xA5;
opcodes[0xA6] = &CPU::op0xA6; opcodes[0xA7] = &CPU::op0xA7;
opcodes[0xA8] = &CPU::op0xA8; opcodes[0xA9] = &CPU::op0xA9;
opcodes[0xAA] = &CPU::op0xAA; opcodes[0xAB] = &CPU::op0xAB;
opcodes[0xAC] = &CPU::op0xAC; opcodes[0xAD] = &CPU::op0xAD;
opcodes[0xAE] = &CPU::op0xAE; opcodes[0xAF] = &CPU::op0xAF;
opcodes[0xB0] = &CPU::op0xB0; opcodes[0xB1] = &CPU::op0xB1;
opcodes[0xB2] = &CPU::op0xB2; opcodes[0xB3] = &CPU::op0xB3;
opcodes[0xB4] = &CPU::op0xB4; opcodes[0xB5] = &CPU::op0xB5;
opcodes[0xB6] = &CPU::op0xB6; opcodes[0xB7] = &CPU::op0xB7;
opcodes[0xB8] = &CPU::op0xB8; opcodes[0xB9] = &CPU::op0xB9;
opcodes[0xBA] = &CPU::op0xBA; opcodes[0xBB] = &CPU::op0xBB;
opcodes[0xBC] = &CPU::op0xBC; opcodes[0xBD] = &CPU::op0xBD;
opcodes[0xBE] = &CPU::op0xBE; opcodes[0xBF] = &CPU::op0xBF;
opcodes[0xC0] = &CPU::op0xC0; opcodes[0xC1] = &CPU::op0xC1;
opcodes[0xC2] = &CPU::op0xC2; opcodes[0xC3] = &CPU::op0xC3;
opcodes[0xC4] = &CPU::opNull; opcodes[0xC5] = &CPU::op0xC5;
opcodes[0xC6] = &CPU::opNull; opcodes[0xC7] = &CPU::op0xC7;
opcodes[0xC8] = &CPU::op0xC8; opcodes[0xC9] = &CPU::op0xC9;
opcodes[0xCA] = &CPU::op0xCA; opcodes[0xCB] = &CPU::op0xCB;
opcodes[0xCC] = &CPU::opNull; opcodes[0xCD] = &CPU::op0xCD;
opcodes[0xCE] = &CPU::opNull; opcodes[0xCF] = &CPU::op0xCF;
opcodes[0xD0] = &CPU::opNull; opcodes[0xD1] = &CPU::op0xD1;
opcodes[0xD2] = &CPU::opNull; opcodes[0xD3] = &CPU::opNull;
opcodes[0xD4] = &CPU::opNull; opcodes[0xD5] = &CPU::op0xD5;
opcodes[0xD6] = &CPU::op0xD6; opcodes[0xD7] = &CPU::op0xD7;
opcodes[0xD8] = &CPU::opNull; opcodes[0xD9] = &CPU::op0xD9;
opcodes[0xDA] = &CPU::op0xDA; opcodes[0xDB] = &CPU::opNull;
opcodes[0xDC] = &CPU::opNull; opcodes[0xDD] = &CPU::opNull;
opcodes[0xDE] = &CPU::opNull; opcodes[0xDF] = &CPU::op0xDF;
opcodes[0xE0] = &CPU::op0xE0; opcodes[0xE1] = &CPU::op0xE1;
opcodes[0xE2] = &CPU::op0xE2; opcodes[0xE3] = &CPU::opNull;
opcodes[0xE4] = &CPU::opNull; opcodes[0xE5] = &CPU::op0xE5;
opcodes[0xE6] = &CPU::op0xE6; opcodes[0xE7] = &CPU::op0xE7;
opcodes[0xE8] = &CPU::opNull; opcodes[0xE9] = &CPU::op0xE9;
opcodes[0xEA] = &CPU::op0xEA; opcodes[0xEB] = &CPU::opNull;
opcodes[0xEC] = &CPU::opNull; opcodes[0xED] = &CPU::opNull;
opcodes[0xEE] = &CPU::opNull; opcodes[0xEF] = &CPU::op0xEF;
opcodes[0xF0] = &CPU::op0xF0; opcodes[0xF1] = &CPU::op0xF1;
opcodes[0xF2] = &CPU::op0xF2; opcodes[0xF3] = &CPU::op0xF3;
opcodes[0xF4] = &CPU::opNull; opcodes[0xF5] = &CPU::op0xF5;
opcodes[0xF6] = &CPU::opNull; opcodes[0xF7] = &CPU::op0xF7;
opcodes[0xF8] = &CPU::opNull; opcodes[0xF9] = &CPU::op0xF9;
opcodes[0xFA] = &CPU::op0xFA; opcodes[0xFB] = &CPU::op0xFB;
opcodes[0xFC] = &CPU::opNull; opcodes[0xFD] = &CPU::opNull;
opcodes[0xFE] = &CPU::op0xFE; opcodes[0xFF] = &CPU::op0xFF;
/* -------------------------------------- */
/* Initialize CB prefixed functions table */
/* -------------------------------------- */
opcodesCB[0x10] = &CPU::cb0x10; opcodesCB[0x11] = &CPU::cb0x11;
opcodesCB[0x12] = &CPU::cb0x12; opcodesCB[0x13] = &CPU::cb0x13;
opcodesCB[0x14] = &CPU::cb0x14; opcodesCB[0x15] = &CPU::cb0x15;
opcodesCB[0x16] = &CPU::cb0x16; opcodesCB[0x17] = &CPU::opNull;
opcodesCB[0x18] = &CPU::opNull; opcodesCB[0x19] = &CPU::opNull;
opcodesCB[0x1A] = &CPU::opNull; opcodesCB[0x1B] = &CPU::opNull;
opcodesCB[0x1C] = &CPU::opNull; opcodesCB[0x1D] = &CPU::opNull;
opcodesCB[0x1E] = &CPU::opNull; opcodesCB[0x1F] = &CPU::opNull;
opcodesCB[0x30] = &CPU::opNull; opcodesCB[0x31] = &CPU::opNull;
opcodesCB[0x32] = &CPU::opNull; opcodesCB[0x33] = &CPU::opNull;
opcodesCB[0x34] = &CPU::opNull; opcodesCB[0x35] = &CPU::opNull;
opcodesCB[0x36] = &CPU::opNull; opcodesCB[0x37] = &CPU::cb0x37;
opcodesCB[0x38] = &CPU::opNull; opcodesCB[0x39] = &CPU::opNull;
opcodesCB[0x3A] = &CPU::opNull; opcodesCB[0x3B] = &CPU::opNull;
opcodesCB[0x3C] = &CPU::opNull; opcodesCB[0x3D] = &CPU::opNull;
opcodesCB[0x3E] = &CPU::opNull; opcodesCB[0x3F] = &CPU::opNull;
opcodesCB[0x70] = &CPU::opNull; opcodesCB[0x71] = &CPU::opNull;
opcodesCB[0x72] = &CPU::opNull; opcodesCB[0x73] = &CPU::opNull;
opcodesCB[0x74] = &CPU::opNull; opcodesCB[0x75] = &CPU::opNull;
opcodesCB[0x76] = &CPU::opNull; opcodesCB[0x77] = &CPU::opNull;
opcodesCB[0x78] = &CPU::opNull; opcodesCB[0x79] = &CPU::opNull;
opcodesCB[0x7A] = &CPU::cb0x7A; opcodesCB[0x7B] = &CPU::cb0x7B;
opcodesCB[0x7C] = &CPU::cb0x7C; opcodesCB[0x7D] = &CPU::cb0x7D;
opcodesCB[0x7E] = &CPU::cb0x7E; opcodesCB[0x7F] = &CPU::cb0x7F;
}
// NOP
void CPU::op0x00 () {
clockCycles = 4;
}
// STOP 0
void CPU::op0x10 () {
clockCycles = 4;
}
// JR NZ,r8
void CPU::op0x20 () {
uint8_t value = ReadByte();
if (GetZ() == 0) {
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
else
clockCycles = 8;
}
// JR NC,r8
void CPU::op0x30 () {
uint8_t value = ReadByte();
if (GetC() == 0) {
PC += value;
clockCycles = 12;
}
else
clockCycles = 8;
}
// LD BC,D16
void CPU::op0x01 () {
BC = ReadWord();
clockCycles = 12;
}
// LD DE,D16
void CPU::op0x11 () {
DE = ReadWord();
clockCycles = 12;
}
// LD HL,D16
void CPU::op0x21 () {
HL = ReadWord();
clockCycles = 12;
}
// LD SP,D16
void CPU::op0x31 () {
SP = ReadWord();
clockCycles = 12;
}
// LD (BC),A
void CPU::op0x02 () {
mmu->WriteByte(BC, AF.hi);
clockCycles = 8;
}
// LD (DE),A
void CPU::op0x12 () {
mmu->WriteByte(DE, AF.hi);
clockCycles = 8;
}
// LD (HL+),A
void CPU::op0x22 () {
mmu->WriteByte(HL, AF.hi);
HL += 1;
clockCycles = 8;
}
// LD (HL-),A
void CPU::op0x32 () {
mmu->WriteByte(HL, AF.hi);
HL -= 1;
clockCycles = 8;
}
// INC BC
void CPU::op0x03 () {
BC += 1;
clockCycles = 8;
}
// INC DE
void CPU::op0x13 () {
DE += 1;
clockCycles = 8;
}
// INC HL
void CPU::op0x23 () {
HL += 1;
clockCycles = 8;
}
// INC SP
void CPU::op0x33 () {
SP += 1;
clockCycles = 8;
}
// INC B
void CPU::op0x04 () {
Increment(BC.hi);
clockCycles = 4;
}
// INC D
void CPU::op0x14 () {
Increment(DE.hi);
clockCycles = 4;
}
// INC H
void CPU::op0x24 () {
Increment(HL.hi);
clockCycles = 4;
}
// INC (HL)
void CPU::op0x34 () {
uint8_t value = mmu->ReadByte(HL);
Increment(value);
mmu->WriteByte(HL, value);
clockCycles = 4;
}
// DEC B
void CPU::op0x05 () {
Decrement(BC.hi);
clockCycles = 4;
}
// DEC D
void CPU::op0x15 () {
Decrement(DE.hi);
clockCycles = 4;
}
// DEC H
void CPU::op0x25 () {
Decrement(HL.hi);
clockCycles = 4;
}
// DEC (HL)
void CPU::op0x35 () {
uint8_t value = mmu->ReadByte(HL);
Decrement(value);
mmu->WriteByte(HL, value);
clockCycles = 4;
}
// LD B,d8
void CPU::op0x06 () {
BC.hi = ReadByte();
clockCycles = 8;
}
// LD D,d8
void CPU::op0x16 () {
DE.hi = ReadByte();
clockCycles = 12;
}
// LD H,d8
void CPU::op0x26 () {
HL.hi = ReadByte();
clockCycles = 12;
}
// LD (HL),d8
void CPU::op0x36 () {
mmu->WriteByte(HL, ReadByte());
clockCycles = 12;
}
// RLCA
void CPU::op0x07 () {
opNull();
clockCycles = 4;
}
// RLA
// FIXME: Maybe RLA isn't the same as RL A, check Flags on pastraiser
void CPU::op0x17 () {
RotateLeft(AF.hi);
clockCycles = 4;
}
// DAA
// SCF
// LD (a16),SP
void CPU::op0x08 () {
mmu->WriteByte(ReadWord(), SP);
clockCycles = 20;
}
// JR r8
void CPU::op0x18 () {
uint8_t value = ReadByte();
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
// JR Z,r8
void CPU::op0x28 () {
uint8_t value = ReadByte();
if (GetZ() == 1) {
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
else
clockCycles = 8;
}
// JR C,r8
void CPU::op0x38 () {
uint8_t value = ReadByte();
if (GetC() == 1) {
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
else
clockCycles = 8;
}
// ADD HL,BC
void CPU::op0x09 () {
Add(HL.word, BC);
clockCycles = 8;
}
// ADD HL,DE
void CPU::op0x19 () {
Add(HL.word, DE);
clockCycles = 8;
}
// ADD HL,HL
void CPU::op0x29 () {
Add(HL.word, HL);
clockCycles = 8;
}
// ADD HL,SP
void CPU::op0x39 () {
Add(HL.word, SP);
clockCycles = 8;
}
// LD A,(BC)
void CPU::op0x0A () {
AF.hi = mmu->ReadByte(BC);
clockCycles = 8;
}
// LD A,(DE)
void CPU::op0x1A () {
AF.hi = mmu->ReadByte(DE);
clockCycles = 8;
}
// LD A,(HL+)
void CPU::op0x2A () {
AF.hi = mmu->ReadByte(HL);
HL += 1;
clockCycles = 8;
}
// LD A,(HL-)
void CPU::op0x3A () {
AF.hi = mmu->ReadByte(HL);
HL -= 1;
clockCycles = 8;
}
// DEC BC
void CPU::op0x0B () {
Decrement(BC);
clockCycles = 8;
}
// DEC DE
void CPU::op0x1B () {
Decrement(DE);
clockCycles = 8;
}
// DEC HL
void CPU::op0x2B () {
Decrement(HL);
clockCycles = 8;
}
// DEC SP
void CPU::op0x3B () {
Decrement(SP);
clockCycles = 8;
}
// INC C
void CPU::op0x0C () {
Increment(BC.lo);
clockCycles = 4;
}
// INC E
void CPU::op0x1C () {
Increment(DE.lo);
clockCycles = 4;
}
// INC L
void CPU::op0x2C () {
Increment(HL.lo);
clockCycles = 4;
}
// INC A
void CPU::op0x3C () {
Increment(AF.hi);
clockCycles = 4;
}
// DEC C
void CPU::op0x0D () {
Decrement(BC.lo);
clockCycles = 4;
}
// DEC E
void CPU::op0x1D () {
Decrement(DE.lo);
clockCycles = 4;
}
// DEC L
void CPU::op0x2D () {
Decrement(HL.lo);
clockCycles = 4;
}
// DEC A
void CPU::op0x3D () {
Decrement(AF.hi);
clockCycles = 4;
}
// LD C,d8
void CPU::op0x0E () {
BC.lo = ReadByte();
clockCycles = 8;
}
// LD E,d8
void CPU::op0x1E () {
DE.lo = ReadByte();
clockCycles = 8;
}
// LD L,d8
void CPU::op0x2E () {
HL.lo = ReadByte();
clockCycles = 8;
}
// LD A,d8
void CPU::op0x3E () {
AF.hi = ReadByte();
clockCycles = 8;
}
// RRCA
void CPU::op0x0F () {
opNull();
clockCycles = 4;
}
// RRA
// CPL
void CPU::op0x2F () {
AF.hi ^= 0xFF;
SetN(1), SetH(1);
clockCycles = 4;
}
// CCF
/* 4. instructions */
// LD B,B
void CPU::op0x40 () {
BC.hi = BC.hi;
clockCycles = 4;
}
// LD B,C
void CPU::op0x41 () {
BC.hi = BC.lo;
clockCycles = 4;
}
// LD B,D
void CPU::op0x42 () {
BC.hi = DE.hi;
clockCycles = 4;
}
// LD B,E
void CPU::op0x43 () {
BC.hi = DE.lo;
clockCycles = 4;
}
// LD B,H
void CPU::op0x44 () {
BC.hi = HL.hi;
clockCycles = 4;
}
// LD B,L
void CPU::op0x45 () {
BC.hi = HL.lo;
clockCycles = 4;
}
// LD B,(HL)
void CPU::op0x46 () {
BC.hi = mmu->ReadByte(HL);
clockCycles = 8;
}
// LD B,A
void CPU::op0x47 () {
BC.hi = AF.hi;
clockCycles = 4;
}
// LD C,B
void CPU::op0x48 () {
BC.lo = BC.hi;
clockCycles = 4;
}
// LD C,C
void CPU::op0x49 () { // Copying C to C? Is this Right?
BC.lo = BC.lo;
clockCycles = 4;
}
// LD C,D
void CPU::op0x4A () {
BC.lo = DE.hi;
clockCycles = 4;
}
// LD C,E
void CPU::op0x4B () {
BC.lo = DE.lo;
clockCycles = 4;
}
// LD C,H
void CPU::op0x4C () {
BC.lo = HL.hi;
clockCycles = 4;
}
// LD C,L
void CPU::op0x4D () {
BC.lo = HL.lo;
clockCycles = 4;
}
// LD C,(HL)
void CPU::op0x4E () {
BC.lo = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD C,A
void CPU::op0x4F () {
BC.lo = AF.hi;
clockCycles = 4;
}
/* 5. instructions */
// LD D,B
void CPU::op0x50 () {
DE.hi = BC.hi;
clockCycles = 4;
}
// LD D,C
void CPU::op0x51 () {
DE.hi = BC.lo;
clockCycles = 4;
}
// LD D,D
void CPU::op0x52 () {
DE.hi = DE.hi;
clockCycles = 4;
}
// LD D,E
void CPU::op0x53 () {
DE.hi = HL.hi;
clockCycles = 4;
}
// LD D,H
void CPU::op0x54 () {
DE.hi = HL.hi;
clockCycles = 4;
}
// LD D,L
void CPU::op0x55 () {
DE.hi = HL.lo;
clockCycles = 4;
}
// LD D,(HL)
void CPU::op0x56 () {
DE.hi = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD D,A
void CPU::op0x57 () {
DE.hi = AF.hi;
clockCycles = 4;
}
// LD E,B
void CPU::op0x58 () {
DE.lo = BC.hi;
clockCycles = 4;
}
// LD E,C
void CPU::op0x59 () {
DE.lo = BC.lo;
clockCycles = 4;
}
// LD E,D
void CPU::op0x5A () {
DE.lo = DE.hi;
clockCycles = 4;
}
// LD E,E
void CPU::op0x5B () {
DE.lo = DE.lo;
clockCycles = 4;
}
// LD E,H
void CPU::op0x5C () {
DE.lo = HL.hi;
clockCycles = 4;
}
// LD E,L
void CPU::op0x5D () {
DE.lo = HL.lo;
clockCycles = 4;
}
// LD E,(HL)
void CPU::op0x5E () {
DE.lo = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD E,A
void CPU::op0x5F () {
DE.lo = AF.hi;
clockCycles = 4;
}
/* 6. instructions */
// LD H,B
void CPU::op0x60 () {
HL.hi = BC.hi;
clockCycles = 4;
}
// LD H,C
void CPU::op0x61 () {
HL.hi = BC.lo;
clockCycles = 4;
}
// LD H,D
void CPU::op0x62 () {
HL.hi = DE.hi;
clockCycles = 4;
}
// LD H,E
void CPU::op0x63 () {
HL.hi = DE.lo;
clockCycles = 4;
}
// LD H,H
void CPU::op0x64 () {
HL.hi = HL.hi;
clockCycles = 4;
}
// LD H,L
void CPU::op0x65 () {
AF.lo = HL.lo;
clockCycles = 4;
}
// LD H,(HL)
void CPU::op0x66 () {
HL.hi = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD H,A
void CPU::op0x67 () {
HL.hi = AF.hi;
clockCycles = 4;
}
// LD L,B
void CPU::op0x68 () {
HL.lo = BC.hi;
clockCycles = 4;
}
// LD L,C
void CPU::op0x69 () {
HL.lo = BC.lo;
clockCycles = 4;
}
// LD L,D
void CPU::op0x6A () {
HL.lo = DE.hi;
clockCycles = 4;
}
// LD L,E
void CPU::op0x6B () {
HL.lo = DE.lo;
clockCycles = 4;
}
// LD L,H
void CPU::op0x6C () {
HL.lo = HL.hi;
clockCycles = 4;
}
// LD L,L
void CPU::op0x6D () {
HL.lo = HL.lo;
clockCycles = 4;
}
// LD L,(HL)
void CPU::op0x6E () {
HL.lo = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD L,A
void CPU::op0x6F () {
HL.lo = AF.hi;
clockCycles = 4;
}
/* 7. instructions */
// LD (HL),B
void CPU::op0x70 () {
mmu->WriteByte(HL, BC.hi);
clockCycles = 8;
}
// LD (HL),C
void CPU::op0x71 () {
mmu->WriteByte(HL, BC.lo);
clockCycles = 8;
}
// LD (HL),D
void CPU::op0x72 () {
mmu->WriteByte(HL, DE.hi);
clockCycles = 8;
}
// LD (HL),E
void CPU::op0x73 () {
mmu->WriteByte(HL, DE.lo);
clockCycles = 8;
}
// LD (HL),H
void CPU::op0x74 () {
mmu->WriteByte(HL, HL.hi);
clockCycles = 8;
}
// LD (HL),L
void CPU::op0x75 () {
mmu->WriteByte(HL, HL.lo);
clockCycles = 8;
}
// HALT
// LD (HL),A
void CPU::op0x77 () {
mmu->WriteByte(HL, AF.hi);
clockCycles = 8;
}
// LD A,B
void CPU::op0x78 () {
AF.hi = BC.hi;
clockCycles = 4;
}
// LD A,C
void CPU::op0x79 () {
AF.hi = BC.lo;
clockCycles = 4;
}
// LD A,D
void CPU::op0x7A () {
AF.hi = DE.hi;
clockCycles = 4;
}
// LD A,E
void CPU::op0x7B () {
AF.hi = DE.lo;
clockCycles = 4;
}
// LD A,H
void CPU::op0x7C () {
AF.hi = HL.hi;
clockCycles = 4;
}
// LD A,L
void CPU::op0x7D () {
AF.hi = HL.lo;
clockCycles = 4;
}
// LD A,(HL)
void CPU::op0x7E () {
AF.hi = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD A,A
void CPU::op0x7F () {
AF.hi = AF.hi;
clockCycles = 4;
}
/* 8. instructions */
// ADD A,B
void CPU::op0x80() {
AddA(BC.hi);
clockCycles = 4;
}
// ADD A,C
void CPU::op0x81() {
AddA(BC.lo);
clockCycles = 4;
}
// ADD A,D
void CPU::op0x82() {
AddA(DE.hi);
clockCycles = 4;
}
// ADD A,E
void CPU::op0x83() {
AddA(DE.lo);
clockCycles = 4;
}
// ADD A,H
void CPU::op0x84() {
AddA(HL.hi);
clockCycles = 4;
}
// ADD A,L
void CPU::op0x85() {
AddA(HL.lo);
clockCycles = 4;
}
// ADD A,(HL)
void CPU::op0x86() {
AddA(mmu->ReadByte(HL));
clockCycles = 8;
}
// ADD A,A
void CPU::op0x87() {
AddA(AF.hi);
clockCycles = 4;
}
// ADC A,B
// ADC A,C
// ADC A,D
// ADC A,E
// ADC A,H
// ADC A,L
// ADC A,(HL)
// ADC A,A
/* 9. instructions */
// SUB B
void CPU::op0x90() {
SubtractA(BC.hi);
clockCycles = 4;
}
// SUB C
void CPU::op0x91() {
SubtractA(BC.lo);
clockCycles = 4;
}
// SUB D
void CPU::op0x92() {
SubtractA(DE.hi);
clockCycles = 4;
}
// SUB E
void CPU::op0x93() {
SubtractA(DE.lo);
clockCycles = 4;
}
// SUB H
void CPU::op0x94() {
SubtractA(HL.hi);
clockCycles = 4;
}
// SUB L
void CPU::op0x95() {
SubtractA(HL.lo);
clockCycles = 4;
}
// SUB (HL)
void CPU::op0x96() {
SubtractA(mmu->ReadByte(HL));
clockCycles = 8;
}
// SUB A
void CPU::op0x97() {
SubtractA(AF.hi);
clockCycles = 4;
}
// SBC A,B
// SBC A,C
// SBC A,D
// SBC A,E
// SBC A,H
// SBC A,L
// SBC A,(HL)
// SBC A,A
/* A. instructions */
// AND B
void CPU::op0xA0() {
AF.hi &= BC.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND C
void CPU::op0xA1() {
AF.hi &= BC.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND D
void CPU::op0xA2() {
AF.hi &= DE.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND E
void CPU::op0xA3() {
AF.hi &= DE.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND H
void CPU::op0xA4() {
AF.hi &= HL.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND L
void CPU::op0xA5() {
AF.hi &= HL.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND (HL)
void CPU::op0xA6() {
AF.hi &= mmu->ReadByte(HL);
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 8;
}
// AND A
void CPU::op0xA7() {
AF.hi &= AF.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// XOR B
void CPU::op0xA8() {
AF.hi ^= BC.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR C
void CPU::op0xA9() {
AF.hi ^= BC.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR D
void CPU::op0xAA() {
AF.hi ^= DE.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR E
void CPU::op0xAB() {
AF.hi ^= DE.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR H
void CPU::op0xAC() {
AF.hi ^= HL.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR L
void CPU::op0xAD() {
AF.hi ^= HL.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR (HL)
void CPU::op0xAE() {
AF.hi ^= mmu->ReadByte(HL);
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 8;
}
// XOR A
void CPU::op0xAF() {
AF.hi ^= AF.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
/* B. instructions */
// OR B
void CPU::op0xB0 () {
OrA(BC.hi);
clockCycles = 4;
}
// OR C
void CPU::op0xB1 () {
OrA(BC.lo);
clockCycles = 4;
}
// OR D
void CPU::op0xB2 () {
OrA(DE.hi);
clockCycles = 4;
}
// OR E
void CPU::op0xB3 () {
OrA(DE.lo);
clockCycles = 4;
}
// OR H
void CPU::op0xB4 () {
OrA(HL.hi);
clockCycles = 4;
}
// OR L
void CPU::op0xB5 () {
OrA(HL.lo);
clockCycles = 4;
}
// OR (HL)
void CPU::op0xB6 () {
OrA(mmu->ReadByte(HL));
clockCycles = 4;
}
// OR A
void CPU::op0xB7 () {
OrA(AF.hi);
clockCycles = 4;
}
// CP B
void CPU::op0xB8() {
CompareA(BC.hi);
clockCycles = 4;
}
// CP C
void CPU::op0xB9() {
CompareA(BC.lo);
clockCycles = 4;
}
// CP D
void CPU::op0xBA() {
CompareA(DE.hi);
clockCycles = 4;
}
// CP E
void CPU::op0xBB() {
CompareA(DE.lo);
clockCycles = 4;
}
// CP H
void CPU::op0xBC() {
CompareA(HL.hi);
clockCycles = 4;
}
// CP L
void CPU::op0xBD() {
CompareA(HL.lo);
clockCycles = 4;
}
// CP (HL)
void CPU::op0xBE() {
CompareA(mmu->ReadByte(HL));
clockCycles = 4;
}
// CP A
void CPU::op0xBF() {
CompareA(AF.hi);
clockCycles = 4;
}
/* */
// RET NZ
void CPU::op0xC0 () {
if (GetZ() == 0)
PC = PopWord();
clockCycles = 8;
}
// RET NC
// LDH (a8),A
void CPU::op0xE0 () {
mmu->WriteByte(ReadByte() + 0xFF00, AF.hi);
clockCycles = 12;
}
// LDH A,(a8)
void CPU::op0xF0 () {
AF.hi = mmu->ReadByte(ReadByte() + 0xFF00);
clockCycles = 12;
}
// POP BC
void CPU::op0xC1 () {
BC = PopWord();
clockCycles = 12;
}
// POP DE
void CPU::op0xD1 () {
DE = PopWord();
clockCycles = 12;
}
// POP HL
void CPU::op0xE1 () {
DE = PopWord();
clockCycles = 12;
}
// POP AF
void CPU::op0xF1 () {
AF = PopWord();
clockCycles = 12;
}
// JP NZ,a16
void CPU::op0xC2 () {
uint16_t value = ReadWord();
if (GetZ() == 0)
PC = value;
clockCycles = 12;
}
// JP NC,a16
// LD (C),A
void CPU::op0xE2 () {
mmu->WriteByte(BC.lo + 0xFF00, AF.hi);
clockCycles = 8;
}
// LD A,(C)
void CPU::op0xF2 () {
AF.hi = mmu->ReadByte(BC.lo + 0xFF00);
clockCycles = 8;
}
// JP a16
void CPU::op0xC3 () {
PC = ReadWord();
clockCycles = 12;
}
// D3..: I don't exist
// E3..: I don't exist
// DI
void CPU::op0xF3 () {
areInterruptsEnabled = false;
clockCycles = 4;
}
// CALL NZ,a16
// CALL NC,a16
// E4..: I don't exist
// F4..: I don't exist
// PUSH BC
void CPU::op0xC5 () {
PushWord(BC);
clockCycles += 16;
}
// PUSH DE
void CPU::op0xD5 () {
PushWord(DE);
clockCycles += 16;
}
// PUSH HL
void CPU::op0xE5 () {
PushWord(HL);
clockCycles += 16;
}
// PUSH AF // FIXME: There is NO value in F because of our flags hack
void CPU::op0xF5 () {
PushWord(AF);
clockCycles += 16;
}
// ADD A,d8
// SUB d8
void CPU::op0xD6 () {
SubtractA(ReadByte());
clockCycles += 8;
}
// AND d8
void CPU::op0xE6 () {
AF.hi &= ReadByte();
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles += 8;
}
// OR d8
// RST 00H
void CPU::op0xC7 () {
PushWord(PC);
PC = 0x00;
clockCycles = 32;
}
// RST 10H
void CPU::op0xD7 () {
PushWord(PC);
PC = 0x10;
clockCycles = 32;
}
// RST 20H
void CPU::op0xE7 () {
PushWord(PC);
PC = 0x20;
clockCycles = 32;
}
// RST 30H
void CPU::op0xF7 () {
PushWord(PC);
PC = 0x30;
clockCycles = 32;
}
// RET Z
void CPU::op0xC8 () {
if (GetZ() != 0)
PC = PopWord();
clockCycles = 8;
}
// RET C
// ADD SP,r8
// LD HL,SP+r8
// RET
void CPU::op0xC9 () {
PC = PopWord();
clockCycles = 8;
}
// RETI
void CPU::op0xD9 () {
PC = PopWord();
areInterruptsEnabled = true;
clockCycles = 8;
}
// JP (HL)
void CPU::op0xE9 () {
PC = HL;
clockCycles = 4;
}
// LD SP,HL
void CPU::op0xF9 () {
SP = HL;
clockCycles = 8;
}
// JP Z,a16
void CPU::op0xCA () {
uint16_t address = ReadWord();
if (GetZ() != 0)
PC = address;
clockCycles = 16;
}
// JP C,a16
void CPU::op0xDA () {
uint16_t address = ReadWord();
if (GetC() != 0)
PC = address;
clockCycles = 16;
}
// LD (a16),A
void CPU::op0xEA () {
mmu->WriteByte(ReadWord(), AF.hi);
clockCycles = 16;
}
// LD A,(a16)
void CPU::op0xFA () {
AF.hi = mmu->ReadByte(ReadWord());
clockCycles = 16;
}
// PREFIX CB
void CPU::op0xCB () {
uint8_t secondByte = ReadByte();
(this->*opcodesCB[secondByte])();
clockCycles = 8;
/* In very few instructions, 16 cycles are needed instead,
which are added when the instruction is called.
e.g. 0xCB06, 0xCB16, 0xCB26...
*/
}
// DB..: I don't exist
// EB..: I don't exist
// EI
void CPU::op0xFB () {
areInterruptsEnabled = true;
clockCycles = 4;
}
// CALL Z,a16
// CALL C,a16
// EC..: I don't exist
// FC..: I don't exist
// CALL a16
void CPU::op0xCD () {
PushWord(PC + 2);
PC = ReadWord();
clockCycles = 24;
}
// DD..: I don't exist
// ED..: I don't exist
// FD..: I don't exist
// ADC A,d8
// SBC A,d8
// XOR d8
// CP d8
void CPU::op0xFE () {
CompareA(ReadByte());
clockCycles = 8;
}
// RST 08H
void CPU::op0xCF () {
PushWord(PC);
PC = 0x08;
clockCycles = 32;
}
// RST 18H
void CPU::op0xDF () {
PushWord(PC);
PC = 0x18;
clockCycles = 32;
}
// RST 28H
void CPU::op0xEF () {
PushWord(PC);
PC = 0x28;
clockCycles = 32;
}
// RST 38H
void CPU::op0xFF () {
PushWord(PC);
PC = 0x38;
clockCycles = 32;
}
// CB0. instructions
// RLC B
// RLC C
// RLC D
// RLC E
// RLC H
// RLC L
// RLC (HL)
// RLC A
// RRC B
// RRC C
// RRC D
// RRC E
// RRC H
// RRC L
// RRC (HL)
// RRC A
// CB1. instructions
// RL B
void CPU::cb0x10() {
RotateLeft(BC.hi);
}
// RL C
void CPU::cb0x11() {
RotateLeft(BC.lo);
}
// RL D
void CPU::cb0x12() {
RotateLeft(DE.hi);
}
// RL E
void CPU::cb0x13() {
RotateLeft(DE.lo);
}
// RL H
void CPU::cb0x14() {
RotateLeft(HL.hi);
}
// RL L
void CPU::cb0x15() {
RotateLeft(HL.lo);
}
// RL (HL)
void CPU::cb0x16() {
uint8_t value = mmu->ReadByte(HL);
RotateLeft(value);
mmu->WriteByte(HL, value);
}
// RL A
// RR B
// RR C
// RR D
// RR E
// RR H
// RR L
// RR (HL)
// RR A
// CB2. instructions
// SLA B
// SLA C
// SLA D
// SLA E
// SLA H
// SLA L
// SLA (HL)
// SLA A
// SRA B
// SRA C
// SRA D
// SRA E
// SRA H
// SRA L
// SRA (HL)
// SRA A
// CB3. instructions
// SWAP B
// SWAP C
// SWAP D
// SWAP E
// SWAP H
// SWAP L
// SWAP (HL)
// SWAP A
void CPU::cb0x37 () {
Swap(AF.hi);
}
// SRL B
// SRL C
// SRL D
// SRL E
// SRL H
// SRL L
// SRL (HL)
// SRL A
// CB4.
// BIT 0,B
// BIT 0,C
// BIT 0,D
// BIT 0,E
// BIT 0,H
// BIT 0,L
// BIT 0,(HL)
// BIT 0,A
// BIT 1,B
// BIT 1,C
// BIT 1,D
// BIT 1,E
// BIT 1,H
// BIT 1,L
// BIT 1,(HL)
// BIT 1,A
// CB5. instructions
// BIT 2,B
// BIT 2,C
// BIT 2,D
// BIT 2,E
// BIT 2,H
// BIT 2,L
// BIT 2,(HL)
// BIT 2,A
// BIT 3,B
// BIT 3,C
// BIT 3,D
// BIT 3,E
// BIT 3,H
// BIT 3,L
// BIT 3,(HL)
// BIT 3,A
// CB6. instructions
// BIT 4,B
// BIT 4,C
// BIT 4,D
// BIT 4,E
// BIT 4,H
// BIT 4,L
// BIT 4,(HL)
// BIT 4,A
// BIT 5,B
// BIT 5,C
// BIT 5,D
// BIT 5,E
// BIT 5,H
// BIT 5,L
// BIT 5,(HL)
// BIT 5,A
// CB7. instructions
// BIT 6,B
// BIT 6,C
// BIT 6,D
// BIT 6,E
// BIT 6,H
// BIT 6,L
// BIT 6,(HL)
// BIT 6,A
// BIT 7,B
// BIT 7,C
// BIT 7,D
void CPU::cb0x7A () {
SetZ((DE.hi & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,E
void CPU::cb0x7B () {
SetZ((DE.lo & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,H
void CPU::cb0x7C () {
SetZ((HL.hi & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,L
void CPU::cb0x7D () {
SetZ((HL.lo & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,(HL)
void CPU::cb0x7E () {
SetZ((HL.lo & 0x80) == 0);
SetN(0), SetH(1);
clockCycles = 16;
}
// BIT 7,A
void CPU::cb0x7F () {
SetZ((AF.hi & 0x80) == 0);
SetN(0), SetH(1);
}
// CB8. instructions
// RES 0,B
// RES 0,C
// RES 0,D
// RES 0,E
// RES 0,H
// RES 0,L
// RES 0,(HL)
// RES 0,A
// RES 1,B
// RES 1,C
// RES 1,D
// RES 1,E
// RES 1,H
// RES 1,L
// RES 1,(HL)
// RES 1,A
// CB9. instructions
// RES 2,B
// RES 2,C
// RES 2,D
// RES 2,E
// RES 2,H
// RES 2,L
// RES 2,(HL)
// RES 2,A
// RES 3,B
// RES 3,C
// RES 3,D
// RES 3,E
// RES 3,H
// RES 3,L
// RES 3,(HL)
// RES 3,A
// CBA. instructions
// RES 4,B
// RES 4,C
// RES 4,D
// RES 4,E
// RES 4,H
// RES 4,L
// RES 4,(HL)
// RES 4,A
// RES 5,B
// RES 5,C
// RES 5,D
// RES 5,E
// RES 5,H
// RES 5,L
// RES 5,(HL)
// RES 5,A
// CBB. instructions
// RES 6,B
// RES 6,C
// RES 6,D
// RES 6,E
// RES 6,H
// RES 6,L
// RES 6,(HL)
// RES 6,A
// RES 7,B
// RES 7,C
// RES 7,D
// RES 7,E
// RES 7,H
// RES 7,L
// RES 7,(HL)
// RES 7,A
// CBC. instructions
// SET 0,B
// SET 0,C
// SET 0,D
// SET 0,E
// SET 0,H
// SET 0,L
// SET 0,(HL)
// SET 0,A
// SET 1,B
// SET 1,C
// SET 1,D
// SET 1,E
// SET 1,H
// SET 1,L
// SET 1,(HL)
// SET 1,A
// CBD. instructions
// SET 2,B
// SET 2,C
// SET 2,D
// SET 2,E
// SET 2,H
// SET 2,L
// SET 2,(HL)
// SET 2,A
// SET 3,B
// SET 3,C
// SET 3,D
// SET 3,E
// SET 3,H
// SET 3,L
// SET 3,(HL)
// SET 3,A
// CBE. instructions
// SET 4,B
// SET 4,C
// SET 4,D
// SET 4,E
// SET 4,H
// SET 4,L
// SET 4,(HL)
// SET 4,A
// SET 5,B
// SET 5,C
// SET 5,D
// SET 5,E
// SET 5,H
// SET 5,L
// SET 5,(HL)
// SET 5,A
// CBF. instructions
// SET 6,B
// SET 6,C
// SET 6,D
// SET 6,E
// SET 6,H
// SET 6,L
// SET 6,(HL)
// SET 6,A
// SET 7,B
// SET 7,C
// SET 7,D
// SET 7,E
// SET 7,H
// SET 7,L
// SET 7,(HL)
// SET 7,A
/* Not implemented instructions call this function */
void CPU::opNull () {
isHalted = true;
std::cout << "Instruction not implemented\n";
// assert("Not implemented" && 0);
}
Fixed flag computation in subtraction
#include "cpu.hpp"
#include "mmu.hpp"
#include "iostream"
#include "debug.hpp"
#include "disassembler.hpp"
CPU::CPU () {}
CPU::~CPU () {}
void CPU::Initialize (MMU* _mmu, bool doBootrom) {
/* Initialize Registers */
if (doBootrom) {
AF = 0;
BC = 0;
DE = 0;
HL = 0;
SP = 0x0;
PC = 0x0;
SetZ(0); SetN(0); SetH(0); SetC(0);
}
else {
AF = 0x01B0;
BC = 0x0013;
DE = 0x00D8;
HL = 0x014D;
SP = 0xFFFE;
PC = 0x100;
SetZ(1); SetN(0); SetH(1); SetC(1);
}
clockCycles = 0;
assert("Assigned MMU wasn't initialized" && _mmu != nullptr);
mmu = _mmu;
InitializeOpcodeTable();
}
void CPU::EmulateCycle () {
if (PC == 0x100) {
mmu->isInBios = false;
areInterruptsEnabled = true;
}
if (PC == 0x100 || PC == 0x86) {
isHalted = true;
}
uint8_t opcode = mmu->ReadByte(PC);
std::cout << std::hex << PC << ' ' << DisassembleOpcode(mmu->GetMemoryRef(PC)) << '\n';
// std::cout << std::hex << opcode << '\n';
PC += 1;
(this->*opcodes[opcode])(); // Wtf C++
}
void CPU::RequestInterrupt (uint8_t id) {
uint8_t requestRegister = mmu->ReadByte(IF);
requestRegister |= 0x10 >> (4 - id); // SET bit ID
mmu->WriteByte(IF, requestRegister);
// std::cout << "Interrupt requested!\n" ;
}
void CPU::ProcessInterrupts () {
if (areInterruptsEnabled == false)
return;
uint8_t requestRegister = mmu->ReadByte(IF);
if (requestRegister == 0)
return;
uint8_t enabledRegister = mmu->ReadByte(IF);
for (size_t id = 0; id < 5; id++) {
bool isInterruptRequested = requestRegister & (0x10 >> (4 - id));
bool isInterruptEnabled = enabledRegister & (0x10 >> (4 - id));
if (isInterruptRequested && isInterruptEnabled)
DoInterrupt(id);
}
}
void CPU::DoInterrupt (uint8_t id) {
areInterruptsEnabled = false;
uint8_t requestRegister = mmu->ReadByte(IF);
// Reset bit id, we use XOR because the bit has to be 1 before this function
requestRegister ^= 0x10 >> (4 - id);
mmu->WriteByte(IF, requestRegister);
PushWord(PC);
switch (id) {
case 0: PC = 0x40; break;
case 1: PC = 0x48; break;
case 2: PC = 0x50; break;
case 4: PC = 0x60; break;
default: assert("Invalid interrupt ID" && 0); break;
}
// std::cout << "Interrupting!" << "\n";
// isHalted = true;
}
void CPU::SetZ (bool value) {
AF.lo = (AF.lo & ~0x80) | 0x80 * value;
}
void CPU::SetN (bool value) {
AF.lo = (AF.lo & ~0x40) | 0x40 * value;
}
void CPU::SetH (bool value) {
AF.lo = (AF.lo & ~0x20) | 0x20 * value;
}
void CPU::SetC (bool value) {
AF.lo = (AF.lo & ~0x10) | 0x10 * value;
}
bool CPU::GetZ () {
return (AF.lo & 0x80);
}
bool CPU::GetN () {
return (AF.lo & 0x40);
}
bool CPU::GetH () {
return (AF.lo & 0x20);
}
bool CPU::GetC () {
return (AF.lo & 0x10);
}
uint8_t CPU::ReadByte () {
uint8_t value = mmu->ReadByte(PC);
PC += 1;
return value;
}
uint16_t CPU::ReadWord () {
uint16_t value = mmu->ReadWord(PC);
PC += 2;
return value;
}
void CPU::PushWord (uint16_t value) {
SP -= 2;
mmu->WriteWord(SP, value);
}
uint16_t CPU::PopWord () {
SP += 2;
return mmu->ReadWord(SP - 2);
}
// FIXME: Double check C flag computation
void CPU::RotateLeft (uint8_t& value) {
uint8_t oldBit7 = (value >> 7);
value = (value << 1) | GetC();
SetZ(value == 0);
SetN(0), SetH(0);
SetC(oldBit7);
}
void CPU::Decrement (uint8_t& value) {
uint8_t oldBit4 = value & 0x8;
value -= 1;
SetZ(value == 0);
SetN(1);
SetH( (value & 0x8) ^ oldBit4 && oldBit4 != 0x8 );
}
void CPU::Decrement (uint16_t& value) {
uint8_t oldBit4 = value & 0x8;
value -= 1;
SetZ(value == 0);
SetN(1);
SetH( (value & 0x8) ^ oldBit4 && oldBit4 != 0x8 );
}
void CPU::Decrement (reg16_t& value) {
Decrement(value.word);
}
void CPU::Increment (uint8_t& value) {
uint8_t prev = value;
value += 1;
SetZ(value == 0);
SetN(0);
SetH((prev & 0xF) == 0xF);
}
// FIXME: Halfcarry in a 16bit value isn't on bit 4
void CPU::Increment (uint16_t& value) {
uint16_t prev = value;
value += 1;
SetZ(value == 0);
SetN(0);
SetH((prev & 0xFF) == 0xFF);
}
void CPU::Increment (reg16_t& value) {
Increment(value.word);
}
void CPU::AddA (uint8_t value) {
uint8_t oldA = AF.hi;
AF.hi += value;
SetZ(AF.hi == 0);
SetN(0);
SetH((AF.hi & 0xF) + (value & 0xF) > 0xF);
SetC(oldA + value > 0xFF);
}
void CPU::Add (uint16_t& x, uint16_t value) {
uint8_t oldX = x;
x += value;
SetZ(x == 0);
SetN(0);
SetH((x & 0xF) + (value & 0xF) > 0xF);
SetC(oldX + value > 0xFF);
}
void CPU::SubtractA (uint8_t value) {
uint8_t oldA = AF.hi;
AF.hi -= value;
SetZ(AF.hi == 0);
SetN(1);
SetH((oldA & 0xF) < (value & 0xF));
SetC(oldA < value);
}
void CPU::CompareA (uint8_t value) {
SetZ(AF.hi == value);
SetN(1);
SetH((AF.hi & 0xF) < (value & 0xF));
SetC(AF.hi < value);
}
void CPU::OrA (uint8_t value) {
AF.hi |= value;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
}
void CPU::Swap (uint8_t& value) {
uint8_t hi = value & 0xF0;
uint8_t lo = value & 0x0F;
value = (hi >> 4) | (lo << 4);
}
/* Instructions specific code */
void CPU::InitializeOpcodeTable () {
opcodes[0x00] = &CPU::op0x00; opcodes[0x01] = &CPU::op0x01;
opcodes[0x02] = &CPU::op0x02; opcodes[0x03] = &CPU::op0x03;
opcodes[0x04] = &CPU::op0x04; opcodes[0x05] = &CPU::op0x05;
opcodes[0x06] = &CPU::op0x06; opcodes[0x07] = &CPU::op0x07;
opcodes[0x08] = &CPU::op0x08; opcodes[0x09] = &CPU::op0x09;
opcodes[0x0A] = &CPU::op0x0A; opcodes[0x0B] = &CPU::op0x0B;
opcodes[0x0C] = &CPU::op0x0C; opcodes[0x0D] = &CPU::op0x0D;
opcodes[0x0E] = &CPU::op0x0E; opcodes[0x0F] = &CPU::op0x0F;
opcodes[0x10] = &CPU::opNull; opcodes[0x11] = &CPU::op0x11;
opcodes[0x12] = &CPU::op0x12; opcodes[0x13] = &CPU::op0x13;
opcodes[0x14] = &CPU::op0x14; opcodes[0x15] = &CPU::op0x15;
opcodes[0x16] = &CPU::op0x16; opcodes[0x17] = &CPU::op0x17;
opcodes[0x18] = &CPU::op0x18; opcodes[0x19] = &CPU::op0x19;
opcodes[0x1A] = &CPU::op0x1A; opcodes[0x1B] = &CPU::op0x1B;
opcodes[0x1C] = &CPU::op0x1C; opcodes[0x1D] = &CPU::op0x1D;
opcodes[0x1E] = &CPU::op0x1E; opcodes[0x1F] = &CPU::opNull;
opcodes[0x20] = &CPU::op0x20; opcodes[0x21] = &CPU::op0x21;
opcodes[0x22] = &CPU::op0x22; opcodes[0x23] = &CPU::op0x23;
opcodes[0x24] = &CPU::op0x24; opcodes[0x25] = &CPU::op0x25;
opcodes[0x26] = &CPU::op0x26; opcodes[0x27] = &CPU::opNull;
opcodes[0x28] = &CPU::op0x28; opcodes[0x29] = &CPU::op0x29;
opcodes[0x2A] = &CPU::op0x2A; opcodes[0x2B] = &CPU::op0x2B;
opcodes[0x2C] = &CPU::op0x2C; opcodes[0x2D] = &CPU::op0x2D;
opcodes[0x2E] = &CPU::op0x2E; opcodes[0x2F] = &CPU::op0x2F;
opcodes[0x30] = &CPU::op0x30; opcodes[0x31] = &CPU::op0x31;
opcodes[0x32] = &CPU::op0x32; opcodes[0x33] = &CPU::op0x33;
opcodes[0x34] = &CPU::op0x34; opcodes[0x35] = &CPU::op0x35;
opcodes[0x36] = &CPU::op0x36; opcodes[0x37] = &CPU::opNull;
opcodes[0x38] = &CPU::op0x38; opcodes[0x39] = &CPU::op0x39;
opcodes[0x3A] = &CPU::op0x3A; opcodes[0x3B] = &CPU::op0x3B;
opcodes[0x3C] = &CPU::op0x3C; opcodes[0x3D] = &CPU::op0x3D;
opcodes[0x3E] = &CPU::op0x3E; opcodes[0x3F] = &CPU::opNull;
opcodes[0x40] = &CPU::op0x40; opcodes[0x41] = &CPU::op0x41;
opcodes[0x42] = &CPU::op0x42; opcodes[0x43] = &CPU::op0x43;
opcodes[0x44] = &CPU::op0x44; opcodes[0x45] = &CPU::op0x45;
opcodes[0x46] = &CPU::op0x46; opcodes[0x47] = &CPU::op0x47;
opcodes[0x48] = &CPU::op0x48; opcodes[0x49] = &CPU::op0x49;
opcodes[0x4A] = &CPU::op0x4A; opcodes[0x4B] = &CPU::op0x4B;
opcodes[0x4C] = &CPU::op0x4C; opcodes[0x4D] = &CPU::op0x4D;
opcodes[0x4E] = &CPU::op0x4E; opcodes[0x4F] = &CPU::op0x4F;
opcodes[0x50] = &CPU::op0x50; opcodes[0x51] = &CPU::op0x51;
opcodes[0x52] = &CPU::op0x52; opcodes[0x53] = &CPU::op0x53;
opcodes[0x54] = &CPU::op0x54; opcodes[0x55] = &CPU::op0x55;
opcodes[0x56] = &CPU::op0x56; opcodes[0x57] = &CPU::op0x57;
opcodes[0x58] = &CPU::op0x58; opcodes[0x59] = &CPU::op0x59;
opcodes[0x5A] = &CPU::op0x5A; opcodes[0x5B] = &CPU::op0x5B;
opcodes[0x5C] = &CPU::op0x5C; opcodes[0x5D] = &CPU::op0x5D;
opcodes[0x5E] = &CPU::op0x5E; opcodes[0x5F] = &CPU::op0x5F;
opcodes[0x60] = &CPU::op0x60; opcodes[0x61] = &CPU::op0x61;
opcodes[0x62] = &CPU::op0x62; opcodes[0x63] = &CPU::op0x63;
opcodes[0x64] = &CPU::op0x64; opcodes[0x65] = &CPU::op0x65;
opcodes[0x66] = &CPU::op0x66; opcodes[0x67] = &CPU::op0x67;
opcodes[0x68] = &CPU::op0x68; opcodes[0x69] = &CPU::op0x69;
opcodes[0x6A] = &CPU::op0x6A; opcodes[0x6B] = &CPU::op0x6B;
opcodes[0x6C] = &CPU::op0x6C; opcodes[0x6D] = &CPU::op0x6D;
opcodes[0x6E] = &CPU::op0x6E; opcodes[0x6F] = &CPU::op0x6F;
opcodes[0x70] = &CPU::op0x70; opcodes[0x71] = &CPU::op0x71;
opcodes[0x72] = &CPU::op0x72; opcodes[0x73] = &CPU::op0x73;
opcodes[0x74] = &CPU::op0x74; opcodes[0x75] = &CPU::op0x75;
opcodes[0x76] = &CPU::opNull; opcodes[0x77] = &CPU::op0x77;
opcodes[0x78] = &CPU::op0x78; opcodes[0x79] = &CPU::op0x79;
opcodes[0x7A] = &CPU::op0x7A; opcodes[0x7B] = &CPU::op0x7B;
opcodes[0x7C] = &CPU::op0x7C; opcodes[0x7D] = &CPU::op0x7D;
opcodes[0x7E] = &CPU::op0x7E; opcodes[0x7F] = &CPU::op0x7F;
opcodes[0x80] = &CPU::op0x80; opcodes[0x81] = &CPU::op0x81;
opcodes[0x82] = &CPU::op0x82; opcodes[0x83] = &CPU::op0x83;
opcodes[0x84] = &CPU::op0x84; opcodes[0x85] = &CPU::op0x85;
opcodes[0x86] = &CPU::op0x86; opcodes[0x87] = &CPU::op0x87;
opcodes[0x88] = &CPU::opNull; opcodes[0x89] = &CPU::opNull;
opcodes[0x8A] = &CPU::opNull; opcodes[0x8B] = &CPU::opNull;
opcodes[0x8C] = &CPU::opNull; opcodes[0x8D] = &CPU::opNull;
opcodes[0x8E] = &CPU::opNull; opcodes[0x8F] = &CPU::opNull;
opcodes[0x90] = &CPU::op0x90; opcodes[0x91] = &CPU::op0x91;
opcodes[0x92] = &CPU::op0x92; opcodes[0x93] = &CPU::op0x93;
opcodes[0x94] = &CPU::op0x94; opcodes[0x95] = &CPU::op0x95;
opcodes[0x96] = &CPU::op0x96; opcodes[0x97] = &CPU::op0x97;
opcodes[0x98] = &CPU::opNull; opcodes[0x99] = &CPU::opNull;
opcodes[0x9A] = &CPU::opNull; opcodes[0x9B] = &CPU::opNull;
opcodes[0x9C] = &CPU::opNull; opcodes[0x9D] = &CPU::opNull;
opcodes[0x9E] = &CPU::opNull; opcodes[0x9F] = &CPU::opNull;
opcodes[0xA0] = &CPU::op0xA0; opcodes[0xA1] = &CPU::op0xA1;
opcodes[0xA2] = &CPU::op0xA2; opcodes[0xA3] = &CPU::op0xA3;
opcodes[0xA4] = &CPU::op0xA4; opcodes[0xA5] = &CPU::op0xA5;
opcodes[0xA6] = &CPU::op0xA6; opcodes[0xA7] = &CPU::op0xA7;
opcodes[0xA8] = &CPU::op0xA8; opcodes[0xA9] = &CPU::op0xA9;
opcodes[0xAA] = &CPU::op0xAA; opcodes[0xAB] = &CPU::op0xAB;
opcodes[0xAC] = &CPU::op0xAC; opcodes[0xAD] = &CPU::op0xAD;
opcodes[0xAE] = &CPU::op0xAE; opcodes[0xAF] = &CPU::op0xAF;
opcodes[0xB0] = &CPU::op0xB0; opcodes[0xB1] = &CPU::op0xB1;
opcodes[0xB2] = &CPU::op0xB2; opcodes[0xB3] = &CPU::op0xB3;
opcodes[0xB4] = &CPU::op0xB4; opcodes[0xB5] = &CPU::op0xB5;
opcodes[0xB6] = &CPU::op0xB6; opcodes[0xB7] = &CPU::op0xB7;
opcodes[0xB8] = &CPU::op0xB8; opcodes[0xB9] = &CPU::op0xB9;
opcodes[0xBA] = &CPU::op0xBA; opcodes[0xBB] = &CPU::op0xBB;
opcodes[0xBC] = &CPU::op0xBC; opcodes[0xBD] = &CPU::op0xBD;
opcodes[0xBE] = &CPU::op0xBE; opcodes[0xBF] = &CPU::op0xBF;
opcodes[0xC0] = &CPU::op0xC0; opcodes[0xC1] = &CPU::op0xC1;
opcodes[0xC2] = &CPU::op0xC2; opcodes[0xC3] = &CPU::op0xC3;
opcodes[0xC4] = &CPU::opNull; opcodes[0xC5] = &CPU::op0xC5;
opcodes[0xC6] = &CPU::opNull; opcodes[0xC7] = &CPU::op0xC7;
opcodes[0xC8] = &CPU::op0xC8; opcodes[0xC9] = &CPU::op0xC9;
opcodes[0xCA] = &CPU::op0xCA; opcodes[0xCB] = &CPU::op0xCB;
opcodes[0xCC] = &CPU::opNull; opcodes[0xCD] = &CPU::op0xCD;
opcodes[0xCE] = &CPU::opNull; opcodes[0xCF] = &CPU::op0xCF;
opcodes[0xD0] = &CPU::opNull; opcodes[0xD1] = &CPU::op0xD1;
opcodes[0xD2] = &CPU::opNull; opcodes[0xD3] = &CPU::opNull;
opcodes[0xD4] = &CPU::opNull; opcodes[0xD5] = &CPU::op0xD5;
opcodes[0xD6] = &CPU::op0xD6; opcodes[0xD7] = &CPU::op0xD7;
opcodes[0xD8] = &CPU::opNull; opcodes[0xD9] = &CPU::op0xD9;
opcodes[0xDA] = &CPU::op0xDA; opcodes[0xDB] = &CPU::opNull;
opcodes[0xDC] = &CPU::opNull; opcodes[0xDD] = &CPU::opNull;
opcodes[0xDE] = &CPU::opNull; opcodes[0xDF] = &CPU::op0xDF;
opcodes[0xE0] = &CPU::op0xE0; opcodes[0xE1] = &CPU::op0xE1;
opcodes[0xE2] = &CPU::op0xE2; opcodes[0xE3] = &CPU::opNull;
opcodes[0xE4] = &CPU::opNull; opcodes[0xE5] = &CPU::op0xE5;
opcodes[0xE6] = &CPU::op0xE6; opcodes[0xE7] = &CPU::op0xE7;
opcodes[0xE8] = &CPU::opNull; opcodes[0xE9] = &CPU::op0xE9;
opcodes[0xEA] = &CPU::op0xEA; opcodes[0xEB] = &CPU::opNull;
opcodes[0xEC] = &CPU::opNull; opcodes[0xED] = &CPU::opNull;
opcodes[0xEE] = &CPU::opNull; opcodes[0xEF] = &CPU::op0xEF;
opcodes[0xF0] = &CPU::op0xF0; opcodes[0xF1] = &CPU::op0xF1;
opcodes[0xF2] = &CPU::op0xF2; opcodes[0xF3] = &CPU::op0xF3;
opcodes[0xF4] = &CPU::opNull; opcodes[0xF5] = &CPU::op0xF5;
opcodes[0xF6] = &CPU::opNull; opcodes[0xF7] = &CPU::op0xF7;
opcodes[0xF8] = &CPU::opNull; opcodes[0xF9] = &CPU::op0xF9;
opcodes[0xFA] = &CPU::op0xFA; opcodes[0xFB] = &CPU::op0xFB;
opcodes[0xFC] = &CPU::opNull; opcodes[0xFD] = &CPU::opNull;
opcodes[0xFE] = &CPU::op0xFE; opcodes[0xFF] = &CPU::op0xFF;
/* -------------------------------------- */
/* Initialize CB prefixed functions table */
/* -------------------------------------- */
opcodesCB[0x10] = &CPU::cb0x10; opcodesCB[0x11] = &CPU::cb0x11;
opcodesCB[0x12] = &CPU::cb0x12; opcodesCB[0x13] = &CPU::cb0x13;
opcodesCB[0x14] = &CPU::cb0x14; opcodesCB[0x15] = &CPU::cb0x15;
opcodesCB[0x16] = &CPU::cb0x16; opcodesCB[0x17] = &CPU::opNull;
opcodesCB[0x18] = &CPU::opNull; opcodesCB[0x19] = &CPU::opNull;
opcodesCB[0x1A] = &CPU::opNull; opcodesCB[0x1B] = &CPU::opNull;
opcodesCB[0x1C] = &CPU::opNull; opcodesCB[0x1D] = &CPU::opNull;
opcodesCB[0x1E] = &CPU::opNull; opcodesCB[0x1F] = &CPU::opNull;
opcodesCB[0x30] = &CPU::opNull; opcodesCB[0x31] = &CPU::opNull;
opcodesCB[0x32] = &CPU::opNull; opcodesCB[0x33] = &CPU::opNull;
opcodesCB[0x34] = &CPU::opNull; opcodesCB[0x35] = &CPU::opNull;
opcodesCB[0x36] = &CPU::opNull; opcodesCB[0x37] = &CPU::cb0x37;
opcodesCB[0x38] = &CPU::opNull; opcodesCB[0x39] = &CPU::opNull;
opcodesCB[0x3A] = &CPU::opNull; opcodesCB[0x3B] = &CPU::opNull;
opcodesCB[0x3C] = &CPU::opNull; opcodesCB[0x3D] = &CPU::opNull;
opcodesCB[0x3E] = &CPU::opNull; opcodesCB[0x3F] = &CPU::opNull;
opcodesCB[0x70] = &CPU::opNull; opcodesCB[0x71] = &CPU::opNull;
opcodesCB[0x72] = &CPU::opNull; opcodesCB[0x73] = &CPU::opNull;
opcodesCB[0x74] = &CPU::opNull; opcodesCB[0x75] = &CPU::opNull;
opcodesCB[0x76] = &CPU::opNull; opcodesCB[0x77] = &CPU::opNull;
opcodesCB[0x78] = &CPU::opNull; opcodesCB[0x79] = &CPU::opNull;
opcodesCB[0x7A] = &CPU::cb0x7A; opcodesCB[0x7B] = &CPU::cb0x7B;
opcodesCB[0x7C] = &CPU::cb0x7C; opcodesCB[0x7D] = &CPU::cb0x7D;
opcodesCB[0x7E] = &CPU::cb0x7E; opcodesCB[0x7F] = &CPU::cb0x7F;
}
// NOP
void CPU::op0x00 () {
clockCycles = 4;
}
// STOP 0
void CPU::op0x10 () {
clockCycles = 4;
}
// JR NZ,r8
void CPU::op0x20 () {
uint8_t value = ReadByte();
if (GetZ() == 0) {
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
else
clockCycles = 8;
}
// JR NC,r8
void CPU::op0x30 () {
uint8_t value = ReadByte();
if (GetC() == 0) {
PC += value;
clockCycles = 12;
}
else
clockCycles = 8;
}
// LD BC,D16
void CPU::op0x01 () {
BC = ReadWord();
clockCycles = 12;
}
// LD DE,D16
void CPU::op0x11 () {
DE = ReadWord();
clockCycles = 12;
}
// LD HL,D16
void CPU::op0x21 () {
HL = ReadWord();
clockCycles = 12;
}
// LD SP,D16
void CPU::op0x31 () {
SP = ReadWord();
clockCycles = 12;
}
// LD (BC),A
void CPU::op0x02 () {
mmu->WriteByte(BC, AF.hi);
clockCycles = 8;
}
// LD (DE),A
void CPU::op0x12 () {
mmu->WriteByte(DE, AF.hi);
clockCycles = 8;
}
// LD (HL+),A
void CPU::op0x22 () {
mmu->WriteByte(HL, AF.hi);
HL += 1;
clockCycles = 8;
}
// LD (HL-),A
void CPU::op0x32 () {
mmu->WriteByte(HL, AF.hi);
HL -= 1;
clockCycles = 8;
}
// INC BC
void CPU::op0x03 () {
BC += 1;
clockCycles = 8;
}
// INC DE
void CPU::op0x13 () {
DE += 1;
clockCycles = 8;
}
// INC HL
void CPU::op0x23 () {
HL += 1;
clockCycles = 8;
}
// INC SP
void CPU::op0x33 () {
SP += 1;
clockCycles = 8;
}
// INC B
void CPU::op0x04 () {
Increment(BC.hi);
clockCycles = 4;
}
// INC D
void CPU::op0x14 () {
Increment(DE.hi);
clockCycles = 4;
}
// INC H
void CPU::op0x24 () {
Increment(HL.hi);
clockCycles = 4;
}
// INC (HL)
void CPU::op0x34 () {
uint8_t value = mmu->ReadByte(HL);
Increment(value);
mmu->WriteByte(HL, value);
clockCycles = 4;
}
// DEC B
void CPU::op0x05 () {
Decrement(BC.hi);
clockCycles = 4;
}
// DEC D
void CPU::op0x15 () {
Decrement(DE.hi);
clockCycles = 4;
}
// DEC H
void CPU::op0x25 () {
Decrement(HL.hi);
clockCycles = 4;
}
// DEC (HL)
void CPU::op0x35 () {
uint8_t value = mmu->ReadByte(HL);
Decrement(value);
mmu->WriteByte(HL, value);
clockCycles = 4;
}
// LD B,d8
void CPU::op0x06 () {
BC.hi = ReadByte();
clockCycles = 8;
}
// LD D,d8
void CPU::op0x16 () {
DE.hi = ReadByte();
clockCycles = 12;
}
// LD H,d8
void CPU::op0x26 () {
HL.hi = ReadByte();
clockCycles = 12;
}
// LD (HL),d8
void CPU::op0x36 () {
mmu->WriteByte(HL, ReadByte());
clockCycles = 12;
}
// RLCA
void CPU::op0x07 () {
opNull();
clockCycles = 4;
}
// RLA
// FIXME: Maybe RLA isn't the same as RL A, check Flags on pastraiser
void CPU::op0x17 () {
RotateLeft(AF.hi);
clockCycles = 4;
}
// DAA
// SCF
// LD (a16),SP
void CPU::op0x08 () {
mmu->WriteByte(ReadWord(), SP);
clockCycles = 20;
}
// JR r8
void CPU::op0x18 () {
uint8_t value = ReadByte();
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
// JR Z,r8
void CPU::op0x28 () {
uint8_t value = ReadByte();
if (GetZ() == 1) {
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
else
clockCycles = 8;
}
// JR C,r8
void CPU::op0x38 () {
uint8_t value = ReadByte();
if (GetC() == 1) {
PC += reinterpret_cast<int8_t&>(value);
clockCycles = 12;
}
else
clockCycles = 8;
}
// ADD HL,BC
void CPU::op0x09 () {
Add(HL.word, BC);
clockCycles = 8;
}
// ADD HL,DE
void CPU::op0x19 () {
Add(HL.word, DE);
clockCycles = 8;
}
// ADD HL,HL
void CPU::op0x29 () {
Add(HL.word, HL);
clockCycles = 8;
}
// ADD HL,SP
void CPU::op0x39 () {
Add(HL.word, SP);
clockCycles = 8;
}
// LD A,(BC)
void CPU::op0x0A () {
AF.hi = mmu->ReadByte(BC);
clockCycles = 8;
}
// LD A,(DE)
void CPU::op0x1A () {
AF.hi = mmu->ReadByte(DE);
clockCycles = 8;
}
// LD A,(HL+)
void CPU::op0x2A () {
AF.hi = mmu->ReadByte(HL);
HL += 1;
clockCycles = 8;
}
// LD A,(HL-)
void CPU::op0x3A () {
AF.hi = mmu->ReadByte(HL);
HL -= 1;
clockCycles = 8;
}
// DEC BC
void CPU::op0x0B () {
Decrement(BC);
clockCycles = 8;
}
// DEC DE
void CPU::op0x1B () {
Decrement(DE);
clockCycles = 8;
}
// DEC HL
void CPU::op0x2B () {
Decrement(HL);
clockCycles = 8;
}
// DEC SP
void CPU::op0x3B () {
Decrement(SP);
clockCycles = 8;
}
// INC C
void CPU::op0x0C () {
Increment(BC.lo);
clockCycles = 4;
}
// INC E
void CPU::op0x1C () {
Increment(DE.lo);
clockCycles = 4;
}
// INC L
void CPU::op0x2C () {
Increment(HL.lo);
clockCycles = 4;
}
// INC A
void CPU::op0x3C () {
Increment(AF.hi);
clockCycles = 4;
}
// DEC C
void CPU::op0x0D () {
Decrement(BC.lo);
clockCycles = 4;
}
// DEC E
void CPU::op0x1D () {
Decrement(DE.lo);
clockCycles = 4;
}
// DEC L
void CPU::op0x2D () {
Decrement(HL.lo);
clockCycles = 4;
}
// DEC A
void CPU::op0x3D () {
Decrement(AF.hi);
clockCycles = 4;
}
// LD C,d8
void CPU::op0x0E () {
BC.lo = ReadByte();
clockCycles = 8;
}
// LD E,d8
void CPU::op0x1E () {
DE.lo = ReadByte();
clockCycles = 8;
}
// LD L,d8
void CPU::op0x2E () {
HL.lo = ReadByte();
clockCycles = 8;
}
// LD A,d8
void CPU::op0x3E () {
AF.hi = ReadByte();
clockCycles = 8;
}
// RRCA
void CPU::op0x0F () {
opNull();
clockCycles = 4;
}
// RRA
// CPL
void CPU::op0x2F () {
AF.hi ^= 0xFF;
SetN(1), SetH(1);
clockCycles = 4;
}
// CCF
/* 4. instructions */
// LD B,B
void CPU::op0x40 () {
BC.hi = BC.hi;
clockCycles = 4;
}
// LD B,C
void CPU::op0x41 () {
BC.hi = BC.lo;
clockCycles = 4;
}
// LD B,D
void CPU::op0x42 () {
BC.hi = DE.hi;
clockCycles = 4;
}
// LD B,E
void CPU::op0x43 () {
BC.hi = DE.lo;
clockCycles = 4;
}
// LD B,H
void CPU::op0x44 () {
BC.hi = HL.hi;
clockCycles = 4;
}
// LD B,L
void CPU::op0x45 () {
BC.hi = HL.lo;
clockCycles = 4;
}
// LD B,(HL)
void CPU::op0x46 () {
BC.hi = mmu->ReadByte(HL);
clockCycles = 8;
}
// LD B,A
void CPU::op0x47 () {
BC.hi = AF.hi;
clockCycles = 4;
}
// LD C,B
void CPU::op0x48 () {
BC.lo = BC.hi;
clockCycles = 4;
}
// LD C,C
void CPU::op0x49 () { // Copying C to C? Is this Right?
BC.lo = BC.lo;
clockCycles = 4;
}
// LD C,D
void CPU::op0x4A () {
BC.lo = DE.hi;
clockCycles = 4;
}
// LD C,E
void CPU::op0x4B () {
BC.lo = DE.lo;
clockCycles = 4;
}
// LD C,H
void CPU::op0x4C () {
BC.lo = HL.hi;
clockCycles = 4;
}
// LD C,L
void CPU::op0x4D () {
BC.lo = HL.lo;
clockCycles = 4;
}
// LD C,(HL)
void CPU::op0x4E () {
BC.lo = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD C,A
void CPU::op0x4F () {
BC.lo = AF.hi;
clockCycles = 4;
}
/* 5. instructions */
// LD D,B
void CPU::op0x50 () {
DE.hi = BC.hi;
clockCycles = 4;
}
// LD D,C
void CPU::op0x51 () {
DE.hi = BC.lo;
clockCycles = 4;
}
// LD D,D
void CPU::op0x52 () {
DE.hi = DE.hi;
clockCycles = 4;
}
// LD D,E
void CPU::op0x53 () {
DE.hi = HL.hi;
clockCycles = 4;
}
// LD D,H
void CPU::op0x54 () {
DE.hi = HL.hi;
clockCycles = 4;
}
// LD D,L
void CPU::op0x55 () {
DE.hi = HL.lo;
clockCycles = 4;
}
// LD D,(HL)
void CPU::op0x56 () {
DE.hi = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD D,A
void CPU::op0x57 () {
DE.hi = AF.hi;
clockCycles = 4;
}
// LD E,B
void CPU::op0x58 () {
DE.lo = BC.hi;
clockCycles = 4;
}
// LD E,C
void CPU::op0x59 () {
DE.lo = BC.lo;
clockCycles = 4;
}
// LD E,D
void CPU::op0x5A () {
DE.lo = DE.hi;
clockCycles = 4;
}
// LD E,E
void CPU::op0x5B () {
DE.lo = DE.lo;
clockCycles = 4;
}
// LD E,H
void CPU::op0x5C () {
DE.lo = HL.hi;
clockCycles = 4;
}
// LD E,L
void CPU::op0x5D () {
DE.lo = HL.lo;
clockCycles = 4;
}
// LD E,(HL)
void CPU::op0x5E () {
DE.lo = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD E,A
void CPU::op0x5F () {
DE.lo = AF.hi;
clockCycles = 4;
}
/* 6. instructions */
// LD H,B
void CPU::op0x60 () {
HL.hi = BC.hi;
clockCycles = 4;
}
// LD H,C
void CPU::op0x61 () {
HL.hi = BC.lo;
clockCycles = 4;
}
// LD H,D
void CPU::op0x62 () {
HL.hi = DE.hi;
clockCycles = 4;
}
// LD H,E
void CPU::op0x63 () {
HL.hi = DE.lo;
clockCycles = 4;
}
// LD H,H
void CPU::op0x64 () {
HL.hi = HL.hi;
clockCycles = 4;
}
// LD H,L
void CPU::op0x65 () {
AF.lo = HL.lo;
clockCycles = 4;
}
// LD H,(HL)
void CPU::op0x66 () {
HL.hi = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD H,A
void CPU::op0x67 () {
HL.hi = AF.hi;
clockCycles = 4;
}
// LD L,B
void CPU::op0x68 () {
HL.lo = BC.hi;
clockCycles = 4;
}
// LD L,C
void CPU::op0x69 () {
HL.lo = BC.lo;
clockCycles = 4;
}
// LD L,D
void CPU::op0x6A () {
HL.lo = DE.hi;
clockCycles = 4;
}
// LD L,E
void CPU::op0x6B () {
HL.lo = DE.lo;
clockCycles = 4;
}
// LD L,H
void CPU::op0x6C () {
HL.lo = HL.hi;
clockCycles = 4;
}
// LD L,L
void CPU::op0x6D () {
HL.lo = HL.lo;
clockCycles = 4;
}
// LD L,(HL)
void CPU::op0x6E () {
HL.lo = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD L,A
void CPU::op0x6F () {
HL.lo = AF.hi;
clockCycles = 4;
}
/* 7. instructions */
// LD (HL),B
void CPU::op0x70 () {
mmu->WriteByte(HL, BC.hi);
clockCycles = 8;
}
// LD (HL),C
void CPU::op0x71 () {
mmu->WriteByte(HL, BC.lo);
clockCycles = 8;
}
// LD (HL),D
void CPU::op0x72 () {
mmu->WriteByte(HL, DE.hi);
clockCycles = 8;
}
// LD (HL),E
void CPU::op0x73 () {
mmu->WriteByte(HL, DE.lo);
clockCycles = 8;
}
// LD (HL),H
void CPU::op0x74 () {
mmu->WriteByte(HL, HL.hi);
clockCycles = 8;
}
// LD (HL),L
void CPU::op0x75 () {
mmu->WriteByte(HL, HL.lo);
clockCycles = 8;
}
// HALT
// LD (HL),A
void CPU::op0x77 () {
mmu->WriteByte(HL, AF.hi);
clockCycles = 8;
}
// LD A,B
void CPU::op0x78 () {
AF.hi = BC.hi;
clockCycles = 4;
}
// LD A,C
void CPU::op0x79 () {
AF.hi = BC.lo;
clockCycles = 4;
}
// LD A,D
void CPU::op0x7A () {
AF.hi = DE.hi;
clockCycles = 4;
}
// LD A,E
void CPU::op0x7B () {
AF.hi = DE.lo;
clockCycles = 4;
}
// LD A,H
void CPU::op0x7C () {
AF.hi = HL.hi;
clockCycles = 4;
}
// LD A,L
void CPU::op0x7D () {
AF.hi = HL.lo;
clockCycles = 4;
}
// LD A,(HL)
void CPU::op0x7E () {
AF.hi = mmu->ReadByte(HL);
clockCycles = 4;
}
// LD A,A
void CPU::op0x7F () {
AF.hi = AF.hi;
clockCycles = 4;
}
/* 8. instructions */
// ADD A,B
void CPU::op0x80() {
AddA(BC.hi);
clockCycles = 4;
}
// ADD A,C
void CPU::op0x81() {
AddA(BC.lo);
clockCycles = 4;
}
// ADD A,D
void CPU::op0x82() {
AddA(DE.hi);
clockCycles = 4;
}
// ADD A,E
void CPU::op0x83() {
AddA(DE.lo);
clockCycles = 4;
}
// ADD A,H
void CPU::op0x84() {
AddA(HL.hi);
clockCycles = 4;
}
// ADD A,L
void CPU::op0x85() {
AddA(HL.lo);
clockCycles = 4;
}
// ADD A,(HL)
void CPU::op0x86() {
AddA(mmu->ReadByte(HL));
clockCycles = 8;
}
// ADD A,A
void CPU::op0x87() {
AddA(AF.hi);
clockCycles = 4;
}
// ADC A,B
// ADC A,C
// ADC A,D
// ADC A,E
// ADC A,H
// ADC A,L
// ADC A,(HL)
// ADC A,A
/* 9. instructions */
// SUB B
void CPU::op0x90() {
SubtractA(BC.hi);
clockCycles = 4;
}
// SUB C
void CPU::op0x91() {
SubtractA(BC.lo);
clockCycles = 4;
}
// SUB D
void CPU::op0x92() {
SubtractA(DE.hi);
clockCycles = 4;
}
// SUB E
void CPU::op0x93() {
SubtractA(DE.lo);
clockCycles = 4;
}
// SUB H
void CPU::op0x94() {
SubtractA(HL.hi);
clockCycles = 4;
}
// SUB L
void CPU::op0x95() {
SubtractA(HL.lo);
clockCycles = 4;
}
// SUB (HL)
void CPU::op0x96() {
SubtractA(mmu->ReadByte(HL));
clockCycles = 8;
}
// SUB A
void CPU::op0x97() {
SubtractA(AF.hi);
clockCycles = 4;
}
// SBC A,B
// SBC A,C
// SBC A,D
// SBC A,E
// SBC A,H
// SBC A,L
// SBC A,(HL)
// SBC A,A
/* A. instructions */
// AND B
void CPU::op0xA0() {
AF.hi &= BC.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND C
void CPU::op0xA1() {
AF.hi &= BC.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND D
void CPU::op0xA2() {
AF.hi &= DE.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND E
void CPU::op0xA3() {
AF.hi &= DE.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND H
void CPU::op0xA4() {
AF.hi &= HL.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND L
void CPU::op0xA5() {
AF.hi &= HL.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// AND (HL)
void CPU::op0xA6() {
AF.hi &= mmu->ReadByte(HL);
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 8;
}
// AND A
void CPU::op0xA7() {
AF.hi &= AF.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(1), SetC(0);
clockCycles = 4;
}
// XOR B
void CPU::op0xA8() {
AF.hi ^= BC.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR C
void CPU::op0xA9() {
AF.hi ^= BC.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR D
void CPU::op0xAA() {
AF.hi ^= DE.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR E
void CPU::op0xAB() {
AF.hi ^= DE.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR H
void CPU::op0xAC() {
AF.hi ^= HL.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR L
void CPU::op0xAD() {
AF.hi ^= HL.lo;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
// XOR (HL)
void CPU::op0xAE() {
AF.hi ^= mmu->ReadByte(HL);
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 8;
}
// XOR A
void CPU::op0xAF() {
AF.hi ^= AF.hi;
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles = 4;
}
/* B. instructions */
// OR B
void CPU::op0xB0 () {
OrA(BC.hi);
clockCycles = 4;
}
// OR C
void CPU::op0xB1 () {
OrA(BC.lo);
clockCycles = 4;
}
// OR D
void CPU::op0xB2 () {
OrA(DE.hi);
clockCycles = 4;
}
// OR E
void CPU::op0xB3 () {
OrA(DE.lo);
clockCycles = 4;
}
// OR H
void CPU::op0xB4 () {
OrA(HL.hi);
clockCycles = 4;
}
// OR L
void CPU::op0xB5 () {
OrA(HL.lo);
clockCycles = 4;
}
// OR (HL)
void CPU::op0xB6 () {
OrA(mmu->ReadByte(HL));
clockCycles = 4;
}
// OR A
void CPU::op0xB7 () {
OrA(AF.hi);
clockCycles = 4;
}
// CP B
void CPU::op0xB8() {
CompareA(BC.hi);
clockCycles = 4;
}
// CP C
void CPU::op0xB9() {
CompareA(BC.lo);
clockCycles = 4;
}
// CP D
void CPU::op0xBA() {
CompareA(DE.hi);
clockCycles = 4;
}
// CP E
void CPU::op0xBB() {
CompareA(DE.lo);
clockCycles = 4;
}
// CP H
void CPU::op0xBC() {
CompareA(HL.hi);
clockCycles = 4;
}
// CP L
void CPU::op0xBD() {
CompareA(HL.lo);
clockCycles = 4;
}
// CP (HL)
void CPU::op0xBE() {
CompareA(mmu->ReadByte(HL));
clockCycles = 4;
}
// CP A
void CPU::op0xBF() {
CompareA(AF.hi);
clockCycles = 4;
}
/* */
// RET NZ
void CPU::op0xC0 () {
if (GetZ() == 0)
PC = PopWord();
clockCycles = 8;
}
// RET NC
// LDH (a8),A
void CPU::op0xE0 () {
mmu->WriteByte(ReadByte() + 0xFF00, AF.hi);
clockCycles = 12;
}
// LDH A,(a8)
void CPU::op0xF0 () {
AF.hi = mmu->ReadByte(ReadByte() + 0xFF00);
clockCycles = 12;
}
// POP BC
void CPU::op0xC1 () {
BC = PopWord();
clockCycles = 12;
}
// POP DE
void CPU::op0xD1 () {
DE = PopWord();
clockCycles = 12;
}
// POP HL
void CPU::op0xE1 () {
DE = PopWord();
clockCycles = 12;
}
// POP AF
void CPU::op0xF1 () {
AF = PopWord();
clockCycles = 12;
}
// JP NZ,a16
void CPU::op0xC2 () {
uint16_t value = ReadWord();
if (GetZ() == 0)
PC = value;
clockCycles = 12;
}
// JP NC,a16
// LD (C),A
void CPU::op0xE2 () {
mmu->WriteByte(BC.lo + 0xFF00, AF.hi);
clockCycles = 8;
}
// LD A,(C)
void CPU::op0xF2 () {
AF.hi = mmu->ReadByte(BC.lo + 0xFF00);
clockCycles = 8;
}
// JP a16
void CPU::op0xC3 () {
PC = ReadWord();
clockCycles = 12;
}
// D3..: I don't exist
// E3..: I don't exist
// DI
void CPU::op0xF3 () {
areInterruptsEnabled = false;
clockCycles = 4;
}
// CALL NZ,a16
// CALL NC,a16
// E4..: I don't exist
// F4..: I don't exist
// PUSH BC
void CPU::op0xC5 () {
PushWord(BC);
clockCycles += 16;
}
// PUSH DE
void CPU::op0xD5 () {
PushWord(DE);
clockCycles += 16;
}
// PUSH HL
void CPU::op0xE5 () {
PushWord(HL);
clockCycles += 16;
}
// PUSH AF // FIXME: There is NO value in F because of our flags hack
void CPU::op0xF5 () {
PushWord(AF);
clockCycles += 16;
}
// ADD A,d8
// SUB d8
void CPU::op0xD6 () {
SubtractA(ReadByte());
clockCycles += 8;
}
// AND d8
void CPU::op0xE6 () {
AF.hi &= ReadByte();
SetZ(AF.hi == 0);
SetN(0), SetH(0), SetC(0);
clockCycles += 8;
}
// OR d8
// RST 00H
void CPU::op0xC7 () {
PushWord(PC);
PC = 0x00;
clockCycles = 32;
}
// RST 10H
void CPU::op0xD7 () {
PushWord(PC);
PC = 0x10;
clockCycles = 32;
}
// RST 20H
void CPU::op0xE7 () {
PushWord(PC);
PC = 0x20;
clockCycles = 32;
}
// RST 30H
void CPU::op0xF7 () {
PushWord(PC);
PC = 0x30;
clockCycles = 32;
}
// RET Z
void CPU::op0xC8 () {
if (GetZ() != 0)
PC = PopWord();
clockCycles = 8;
}
// RET C
// ADD SP,r8
// LD HL,SP+r8
// RET
void CPU::op0xC9 () {
PC = PopWord();
clockCycles = 8;
}
// RETI
void CPU::op0xD9 () {
PC = PopWord();
areInterruptsEnabled = true;
clockCycles = 8;
}
// JP (HL)
void CPU::op0xE9 () {
PC = HL;
clockCycles = 4;
}
// LD SP,HL
void CPU::op0xF9 () {
SP = HL;
clockCycles = 8;
}
// JP Z,a16
void CPU::op0xCA () {
uint16_t address = ReadWord();
if (GetZ() != 0)
PC = address;
clockCycles = 16;
}
// JP C,a16
void CPU::op0xDA () {
uint16_t address = ReadWord();
if (GetC() != 0)
PC = address;
clockCycles = 16;
}
// LD (a16),A
void CPU::op0xEA () {
mmu->WriteByte(ReadWord(), AF.hi);
clockCycles = 16;
}
// LD A,(a16)
void CPU::op0xFA () {
AF.hi = mmu->ReadByte(ReadWord());
clockCycles = 16;
}
// PREFIX CB
void CPU::op0xCB () {
uint8_t secondByte = ReadByte();
(this->*opcodesCB[secondByte])();
clockCycles = 8;
/* In very few instructions, 16 cycles are needed instead,
which are added when the instruction is called.
e.g. 0xCB06, 0xCB16, 0xCB26...
*/
}
// DB..: I don't exist
// EB..: I don't exist
// EI
void CPU::op0xFB () {
areInterruptsEnabled = true;
clockCycles = 4;
}
// CALL Z,a16
// CALL C,a16
// EC..: I don't exist
// FC..: I don't exist
// CALL a16
void CPU::op0xCD () {
PushWord(PC + 2);
PC = ReadWord();
clockCycles = 24;
}
// DD..: I don't exist
// ED..: I don't exist
// FD..: I don't exist
// ADC A,d8
// SBC A,d8
// XOR d8
// CP d8
void CPU::op0xFE () {
CompareA(ReadByte());
clockCycles = 8;
}
// RST 08H
void CPU::op0xCF () {
PushWord(PC);
PC = 0x08;
clockCycles = 32;
}
// RST 18H
void CPU::op0xDF () {
PushWord(PC);
PC = 0x18;
clockCycles = 32;
}
// RST 28H
void CPU::op0xEF () {
PushWord(PC);
PC = 0x28;
clockCycles = 32;
}
// RST 38H
void CPU::op0xFF () {
PushWord(PC);
PC = 0x38;
clockCycles = 32;
}
// CB0. instructions
// RLC B
// RLC C
// RLC D
// RLC E
// RLC H
// RLC L
// RLC (HL)
// RLC A
// RRC B
// RRC C
// RRC D
// RRC E
// RRC H
// RRC L
// RRC (HL)
// RRC A
// CB1. instructions
// RL B
void CPU::cb0x10() {
RotateLeft(BC.hi);
}
// RL C
void CPU::cb0x11() {
RotateLeft(BC.lo);
}
// RL D
void CPU::cb0x12() {
RotateLeft(DE.hi);
}
// RL E
void CPU::cb0x13() {
RotateLeft(DE.lo);
}
// RL H
void CPU::cb0x14() {
RotateLeft(HL.hi);
}
// RL L
void CPU::cb0x15() {
RotateLeft(HL.lo);
}
// RL (HL)
void CPU::cb0x16() {
uint8_t value = mmu->ReadByte(HL);
RotateLeft(value);
mmu->WriteByte(HL, value);
}
// RL A
// RR B
// RR C
// RR D
// RR E
// RR H
// RR L
// RR (HL)
// RR A
// CB2. instructions
// SLA B
// SLA C
// SLA D
// SLA E
// SLA H
// SLA L
// SLA (HL)
// SLA A
// SRA B
// SRA C
// SRA D
// SRA E
// SRA H
// SRA L
// SRA (HL)
// SRA A
// CB3. instructions
// SWAP B
// SWAP C
// SWAP D
// SWAP E
// SWAP H
// SWAP L
// SWAP (HL)
// SWAP A
void CPU::cb0x37 () {
Swap(AF.hi);
}
// SRL B
// SRL C
// SRL D
// SRL E
// SRL H
// SRL L
// SRL (HL)
// SRL A
// CB4.
// BIT 0,B
// BIT 0,C
// BIT 0,D
// BIT 0,E
// BIT 0,H
// BIT 0,L
// BIT 0,(HL)
// BIT 0,A
// BIT 1,B
// BIT 1,C
// BIT 1,D
// BIT 1,E
// BIT 1,H
// BIT 1,L
// BIT 1,(HL)
// BIT 1,A
// CB5. instructions
// BIT 2,B
// BIT 2,C
// BIT 2,D
// BIT 2,E
// BIT 2,H
// BIT 2,L
// BIT 2,(HL)
// BIT 2,A
// BIT 3,B
// BIT 3,C
// BIT 3,D
// BIT 3,E
// BIT 3,H
// BIT 3,L
// BIT 3,(HL)
// BIT 3,A
// CB6. instructions
// BIT 4,B
// BIT 4,C
// BIT 4,D
// BIT 4,E
// BIT 4,H
// BIT 4,L
// BIT 4,(HL)
// BIT 4,A
// BIT 5,B
// BIT 5,C
// BIT 5,D
// BIT 5,E
// BIT 5,H
// BIT 5,L
// BIT 5,(HL)
// BIT 5,A
// CB7. instructions
// BIT 6,B
// BIT 6,C
// BIT 6,D
// BIT 6,E
// BIT 6,H
// BIT 6,L
// BIT 6,(HL)
// BIT 6,A
// BIT 7,B
// BIT 7,C
// BIT 7,D
void CPU::cb0x7A () {
SetZ((DE.hi & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,E
void CPU::cb0x7B () {
SetZ((DE.lo & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,H
void CPU::cb0x7C () {
SetZ((HL.hi & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,L
void CPU::cb0x7D () {
SetZ((HL.lo & 0x80) == 0);
SetN(0), SetH(1);
}
// BIT 7,(HL)
void CPU::cb0x7E () {
SetZ((HL.lo & 0x80) == 0);
SetN(0), SetH(1);
clockCycles = 16;
}
// BIT 7,A
void CPU::cb0x7F () {
SetZ((AF.hi & 0x80) == 0);
SetN(0), SetH(1);
}
// CB8. instructions
// RES 0,B
// RES 0,C
// RES 0,D
// RES 0,E
// RES 0,H
// RES 0,L
// RES 0,(HL)
// RES 0,A
// RES 1,B
// RES 1,C
// RES 1,D
// RES 1,E
// RES 1,H
// RES 1,L
// RES 1,(HL)
// RES 1,A
// CB9. instructions
// RES 2,B
// RES 2,C
// RES 2,D
// RES 2,E
// RES 2,H
// RES 2,L
// RES 2,(HL)
// RES 2,A
// RES 3,B
// RES 3,C
// RES 3,D
// RES 3,E
// RES 3,H
// RES 3,L
// RES 3,(HL)
// RES 3,A
// CBA. instructions
// RES 4,B
// RES 4,C
// RES 4,D
// RES 4,E
// RES 4,H
// RES 4,L
// RES 4,(HL)
// RES 4,A
// RES 5,B
// RES 5,C
// RES 5,D
// RES 5,E
// RES 5,H
// RES 5,L
// RES 5,(HL)
// RES 5,A
// CBB. instructions
// RES 6,B
// RES 6,C
// RES 6,D
// RES 6,E
// RES 6,H
// RES 6,L
// RES 6,(HL)
// RES 6,A
// RES 7,B
// RES 7,C
// RES 7,D
// RES 7,E
// RES 7,H
// RES 7,L
// RES 7,(HL)
// RES 7,A
// CBC. instructions
// SET 0,B
// SET 0,C
// SET 0,D
// SET 0,E
// SET 0,H
// SET 0,L
// SET 0,(HL)
// SET 0,A
// SET 1,B
// SET 1,C
// SET 1,D
// SET 1,E
// SET 1,H
// SET 1,L
// SET 1,(HL)
// SET 1,A
// CBD. instructions
// SET 2,B
// SET 2,C
// SET 2,D
// SET 2,E
// SET 2,H
// SET 2,L
// SET 2,(HL)
// SET 2,A
// SET 3,B
// SET 3,C
// SET 3,D
// SET 3,E
// SET 3,H
// SET 3,L
// SET 3,(HL)
// SET 3,A
// CBE. instructions
// SET 4,B
// SET 4,C
// SET 4,D
// SET 4,E
// SET 4,H
// SET 4,L
// SET 4,(HL)
// SET 4,A
// SET 5,B
// SET 5,C
// SET 5,D
// SET 5,E
// SET 5,H
// SET 5,L
// SET 5,(HL)
// SET 5,A
// CBF. instructions
// SET 6,B
// SET 6,C
// SET 6,D
// SET 6,E
// SET 6,H
// SET 6,L
// SET 6,(HL)
// SET 6,A
// SET 7,B
// SET 7,C
// SET 7,D
// SET 7,E
// SET 7,H
// SET 7,L
// SET 7,(HL)
// SET 7,A
/* Not implemented instructions call this function */
void CPU::opNull () {
isHalted = true;
std::cout << "Instruction not implemented\n";
// assert("Not implemented" && 0);
}
|
#include "broker.h"
#include "frame.h"
#include <sstream>
Broker::Broker() {
}
Broker::~Broker() {
}
MQTT_ERROR Broker::Start() {
return NO_ERROR;
}
std::string Broker::ApplyDummyClientID() {
std::stringstream ss;
ss << "DummyClientID" << clients.size() + 1;
return ss.str();
}
BrokerSideClient::BrokerSideClient(Transport* ct, Broker* b) : broker(b), Terminal("", NULL, 0, NULL) {
this->ct = ct;
}
BrokerSideClient::~BrokerSideClient() {}
MQTT_ERROR BrokerSideClient::recvConnectMessage(ConnectMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvConnackMessage(ConnackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPublishMessage(PublishMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubackMessage(PubackMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrecMessage(PubrecMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrelMessage(PubrelMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubcompMessage(PubcompMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubscribeMessage(SubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubackMessage(SubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvUnsubscribeMessage(UnsubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvUnsubackMessage(UnsubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPingreqMessage(PingreqMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPingrespMessage(PingrespMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvDisconnectMessage(DisconnectMessage* m) {return NO_ERROR;}
add inside of constractor and destractor
#include "broker.h"
#include "frame.h"
#include <sstream>
Broker::Broker() {
topicRoot = new TopicNode("");
}
Broker::~Broker() {
delete topicRoot;
}
MQTT_ERROR Broker::Start() {
return NO_ERROR;
}
std::string Broker::ApplyDummyClientID() {
std::stringstream ss;
ss << "DummyClientID" << clients.size() + 1;
return ss.str();
}
BrokerSideClient::BrokerSideClient(Transport* ct, Broker* b) : broker(b), Terminal("", NULL, 0, NULL) {
this->ct = ct;
}
BrokerSideClient::~BrokerSideClient() {}
MQTT_ERROR BrokerSideClient::recvConnectMessage(ConnectMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvConnackMessage(ConnackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPublishMessage(PublishMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubackMessage(PubackMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrecMessage(PubrecMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrelMessage(PubrelMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubcompMessage(PubcompMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubscribeMessage(SubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubackMessage(SubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvUnsubscribeMessage(UnsubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvUnsubackMessage(UnsubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPingreqMessage(PingreqMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPingrespMessage(PingrespMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvDisconnectMessage(DisconnectMessage* m) {return NO_ERROR;}
|
/*
* This file is part of DGD, https://github.com/dworkin/dgd
* Copyright (C) 1993-2010 Dworkin B.V.
* Copyright (C) 2010-2019 DGD Authors (see the commit log for details)
*
* This program 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.
*
* 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 "dgd.h"
# include "str.h"
# include "array.h"
# include "object.h"
# include "xfloat.h"
# include "data.h"
# include "control.h"
# include "interpret.h"
# include "comm.h"
# include "table.h"
# include <float.h>
# include <math.h>
# define EXTENSION_MAJOR 1
# define EXTENSION_MINOR 0
/*
* NAME: ext->frame_object()
* DESCRIPTION: return the current object
*/
static Object *ext_frame_object(Frame *f)
{
return (f->lwobj == NULL) ? OBJW(f->oindex) : NULL;
}
/*
* NAME: ext->frame_dataspace()
* DESCRIPTION: return the current dataspace
*/
static Dataspace *ext_frame_dataspace(Frame *f)
{
return f->data;
}
/*
* NAME: ext->frame_arg()
* DESCRIPTION: return the given argument
*/
static Value *ext_frame_arg(Frame *f, int nargs, int arg)
{
return f->sp + nargs - arg - 1;
}
/*
* NAME: ext->frame_atomic()
* DESCRIPTION: running atomically?
*/
static int ext_frame_atomic(Frame *f)
{
return (f->level != 0);
}
/*
* NAME: ext->value_type()
* DESCRIPTION: return the type of a value
*/
static int ext_value_type(Value *val)
{
return val->type;
}
/*
* NAME: ext->value_nil()
* DESCRIPTION: return nil
*/
static Value *ext_value_nil()
{
return &Value::nil;
}
/*
* NAME: ext->value_temp()
* DESCRIPTION: return a scratch value
*/
Value *ext_value_temp(Dataspace *data)
{
static Value temp;
UNREFERENCED_PARAMETER(data);
return &temp;
}
/*
* NAME: ext->value_temp2()
* DESCRIPTION: return another scratch value
*/
static Value *ext_value_temp2(Dataspace *data)
{
static Value temp2;
UNREFERENCED_PARAMETER(data);
return &temp2;
}
/*
* NAME: ext->int_getval()
* DESCRIPTION: retrieve an int from a value
*/
static Int ext_int_getval(Value *val)
{
return val->number;
}
/*
* NAME: ext->int_putval()
* DESCRIPTION: store an int in a value
*/
static void ext_int_putval(Value *val, Int i)
{
PUT_INTVAL(val, i);
}
# ifndef NOFLOAT
/*
* NAME: ext->float_getval()
* DESCRIPTION: retrieve a float from a value
*/
static long double ext_float_getval(Value *val)
{
Float flt;
double d;
GET_FLT(val, flt);
if ((flt.high | flt.low) == 0) {
return 0.0;
} else {
d = ldexp((double) (0x10 | (flt.high & 0xf)), 32);
d = ldexp(d + flt.low, ((flt.high >> 4) & 0x7ff) - 1023 - 36);
return (long double) ((flt.high >> 15) ? -d : d);
}
}
/*
* NAME: ext->float_putval()
* DESCRIPTION: store a float in a value
*/
static int ext_float_putval(Value *val, long double ld)
{
double d;
Float flt;
unsigned short sign;
int e;
Uuint m;
d = (double) ld;
if (d == 0.0) {
flt.high = 0;
flt.low = 0;
} else {
sign = (d < 0.0);
d = frexp(fabs(d), &e);
# if (DBL_MANT_DIG > 37)
d += (double) (1 << (DBL_MANT_DIG - 38));
d -= (double) (1 << (DBL_MANT_DIG - 38));
if (d >= 1.0) {
if (++e > 1023) {
return FALSE;
}
d = ldexp(d, -1);
}
# endif
if (e <= -1023) {
flt.high = 0;
flt.low = 0;
} else {
m = (Uuint) ldexp(d, 37);
flt.high = (sign << 15) | ((e - 1 + 1023) << 4) |
((unsigned short) (m >> 32) & 0xf);
flt.low = (Uuint) m;
}
}
PUT_FLTVAL(val, flt);
return TRUE;
}
# endif
/*
* NAME: ext->string_getval()
* DESCRIPTION: retrieve a string from a value
*/
static String *ext_string_getval(Value *val)
{
return val->string;
}
/*
* NAME: ext->string_putval()
* DESCRIPTION: store a string in a value
*/
static void ext_string_putval(Value *val, String *str)
{
PUT_STRVAL_NOREF(val, str);
}
/*
* NAME: ext->string_new()
* DESCRIPTION: create a new string
*/
static String *ext_string_new(Dataspace *data, char *text, int len)
{
UNREFERENCED_PARAMETER(data);
try {
return String::create(text, len);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->string_text()
* DESCRIPTION: return string text
*/
static char *ext_string_text(String *str)
{
return str->text;
}
/*
* NAME: ext->string_length()
* DESCRIPTION: return string length
*/
static int ext_string_length(String *str)
{
return str->len;
}
/*
* NAME: ext->object_putval()
* DESCRIPTION: store an object in a value
*/
static void ext_object_putval(Value *val, Object *obj)
{
PUT_OBJVAL(val, obj);
}
/*
* NAME: ext->object_name()
* DESCRIPTION: store the name of an object
*/
static const char *ext_object_name(Frame *f, Object *obj, char *buf)
{
UNREFERENCED_PARAMETER(f);
return obj->objName(buf);
}
/*
* NAME: ext->object_isspecial()
* DESCRIPTION: return TRUE if the given object is special, FALSE otherwise
*/
static int ext_object_isspecial(Object *obj)
{
return ((obj->flags & O_SPECIAL) != 0);
}
/*
* NAME: ext->object_ismarked()
* DESCRIPTION: return TRUE if the given object is marked, FALSE otherwise
*/
static int ext_object_ismarked(Object *obj)
{
return ((obj->flags & O_SPECIAL) == O_SPECIAL);
}
/*
* NAME: ext->object_mark()
* DESCRIPTION: mark the given object
*/
static void ext_object_mark(Object *obj)
{
obj->flags |= O_SPECIAL;
}
/*
* NAME: ext->object_unmark()
* DESCRIPTION: unmark the given object
*/
static void ext_object_unmark(Object *obj)
{
obj->flags &= ~O_SPECIAL;
}
/*
* NAME: ext->array_getval()
* DESCRIPTION: retrieve an array from a value
*/
static Array *ext_array_getval(Value *val)
{
return val->array;
}
/*
* NAME: ext->array_putval()
* DESCRIPTION: store an array in a value
*/
static void ext_array_putval(Value *val, Array *a)
{
PUT_ARRVAL_NOREF(val, a);
}
/*
* NAME: ext->array_new()
* DESCRIPTION: create a new array
*/
static Array *ext_array_new(Dataspace *data, int size)
{
try {
return Array::createNil(data, size);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->array_index()
* DESCRIPTION: return an array element
*/
static Value *ext_array_index(Array *a, int i)
{
return &Dataspace::elts(a)[i];
}
/*
* NAME: ext->array_assign()
* DESCRIPTION: assign a value to an array element
*/
static void ext_array_assign(Dataspace *data, Array *a, int i, Value *val)
{
data->assignElt(a, &Dataspace::elts(a)[i], val);
}
/*
* NAME: ext->array_size()
* DESCRIPTION: return the size of an array
*/
static int ext_array_size(Array *a)
{
return a->size;
}
/*
* NAME: ext->mapping_putval()
* DESCRIPTION: store a mapping in a value
*/
static void ext_mapping_putval(Value *val, Array *m)
{
PUT_MAPVAL_NOREF(val, m);
}
/*
* NAME: ext->mapping_new()
* DESCRIPTION: create a new mapping
*/
static Array *ext_mapping_new(Dataspace *data)
{
return Array::mapCreate(data, 0);
}
/*
* NAME: ext->mapping_index()
* DESCRIPTION: return a value from a mapping
*/
static Value *ext_mapping_index(Array *m, Value *idx)
{
try {
return m->mapIndex(m->primary->data, idx, (Value *) NULL,
(Value *) NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->mapping_assign()
* DESCRIPTION: assign to a mapping value
*/
static void ext_mapping_assign(Dataspace *data, Array *m, Value *idx,
Value *val)
{
try {
m->mapIndex(data, idx, val, (Value *) NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->mapping_enum()
* DESCRIPTION: return the nth enumerated index
*/
static Value *ext_mapping_enum(Array *m, int i)
{
m->mapCompact(m->primary->data);
return &Dataspace::elts(m)[i];
}
/*
* NAME: ext->mapping_size()
* DESCRIPTION: return the size of a mapping
*/
static int ext_mapping_size(Array *m)
{
return m->mapSize(m->primary->data);
}
/*
* NAME: ext->runtime_error()
* DESCRIPTION: handle an error at runtime
*/
void ext_runtime_error(Frame *f, const char *mesg)
{
UNREFERENCED_PARAMETER(f);
try {
error(mesg);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* push int on the stack
*/
static void ext_vm_int(Frame *f, Int n)
{
PUSH_INTVAL(f, n);
}
/*
* push float on the stack
*/
static void ext_vm_float(Frame *f, double flt)
{
ext_float_putval(--f->sp, flt);
}
/*
* push string on the stack
*/
static void ext_vm_string(Frame *f, uint16_t inherit, uint16_t index)
{
PUSH_STRVAL(f, f->p_ctrl->strconst(inherit, index));
}
/*
* push parameter on the stack
*/
static void ext_vm_param(Frame *f, uint8_t param)
{
f->pushValue(f->argp + param);
}
/*
* get int parameter
*/
static Int ext_vm_param_int(Frame *f, uint8_t param)
{
return f->argp[param].number;
}
/*
* get float parameter
*/
static double ext_vm_param_float(Frame *f, uint8_t param)
{
return ext_float_getval(f->argp + param);
}
/*
* push local variable on the stack
*/
static void ext_vm_local(Frame *f, uint8_t local)
{
f->pushValue(f->fp - local);
}
/*
* get int local variable
*/
static Int ext_vm_local_int(Frame *f, uint8_t local)
{
return (f->fp - local)->number;
}
/*
* get float local variable
*/
static double ext_vm_local_float(Frame *f, uint8_t local)
{
return ext_float_getval(f->fp - local);
}
/*
* get global variable
*/
static void ext_vm_global(Frame *f, uint16_t inherit, uint8_t index)
{
f->pushValue(f->global(inherit, index));
}
/*
* get integer global variable
*/
static Int ext_vm_global_int(Frame *f, uint16_t inherit, uint8_t index)
{
return f->global(inherit, index)->number;
}
/*
* get float global variable
*/
static double ext_vm_global_float(Frame *f, uint16_t inherit, uint8_t index)
{
return ext_float_getval(f->global(inherit, index));
}
/*
* index value on the stack
*/
static void ext_vm_index(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, FALSE);
*++f->sp = val;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* index string
*/
static Int ext_vm_index_int(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, FALSE);
f->sp += 2;
return val.number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* index and keep
*/
static void ext_vm_index2(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, TRUE);
*--f->sp = val;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* index string and keep, and return int
*/
static Int ext_vm_index2_int(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, TRUE);
return val.number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* array aggregate
*/
static void ext_vm_aggregate(Frame *f, uint16_t size)
{
try {
f->aggregate(size);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* mapping aggregate
*/
static void ext_vm_map_aggregate(Frame *f, uint16_t size)
{
try {
f->mapAggregate(size);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* cast value to a type
*/
static void ext_vm_cast(Frame *f, uint8_t type, uint16_t inherit,
uint16_t index)
{
try {
f->cast(f->sp, type, ((Uint) inherit << 16) + index);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* cast value to an int
*/
static Int ext_vm_cast_int(Frame *f)
{
if (f->sp->type != T_INT) {
ext_runtime_error(f, "Value is not an int");
}
return (f->sp++)->number;
}
/*
* cast value to a float
*/
static double ext_vm_cast_float(Frame *f)
{
if (f->sp->type != T_FLOAT) {
ext_runtime_error(f, "Value is not a float");
}
return ext_float_getval(f->sp++);
}
/*
* obj <= "/path/to/thing"
*/
static Int ext_vm_instanceof(Frame *f, uint16_t inherit, uint16_t index)
{
Int instance;
instance = f->instanceOf(((Uint) inherit << 16) + index);
f->sp++;
return instance;
}
/*
* check range
*/
static void ext_vm_range(Frame *f)
{
try {
kf_ckrangeft(f, 0, NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* check range from
*/
static void ext_vm_range_from(Frame *f)
{
try {
kf_ckrangef(f, 0, NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* check range to
*/
static void ext_vm_range_to(Frame *f)
{
try {
kf_ckranget(f, 0, NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* store parameter
*/
static void ext_vm_store_param(Frame *f, uint8_t param)
{
f->storeParam(param, f->sp);
}
/*
* store int in parameter
*/
static void ext_vm_store_param_int(Frame *f, uint8_t param, Int number)
{
Value val;
PUT_INTVAL(&val, number);
f->storeParam(param, &val);
}
/*
* store float in parameter
*/
static void ext_vm_store_param_float(Frame *f, uint8_t param, double flt)
{
Value val;
ext_float_putval(&val, flt);
f->storeParam(param, &val);
}
/*
* store local variable
*/
static void ext_vm_store_local(Frame *f, uint8_t local)
{
f->storeLocal(local, f->sp);
}
/*
* store int in local variable
*/
static void ext_vm_store_local_int(Frame *f, uint8_t local, Int number)
{
Value val;
PUT_INTVAL(&val, number);
f->storeLocal(local, &val);
}
/*
* store float in local variable
*/
static void ext_vm_store_local_float(Frame *f, uint8_t local, double flt)
{
Value val;
ext_float_putval(&val, flt);
f->storeLocal(local, &val);
}
/*
* store global variable
*/
static void ext_vm_store_global(Frame *f, uint16_t inherit, uint8_t index)
{
f->storeGlobal(inherit, index, f->sp);
}
/*
* store int in global variable
*/
static void ext_vm_store_global_int(Frame *f, uint16_t inherit,
uint8_t index, Int number)
{
Value val;
PUT_INTVAL(&val, number);
f->storeGlobal(inherit, index, &val);
}
/*
* store float in global variable
*/
static void ext_vm_store_global_float(Frame *f, uint16_t inherit,
uint8_t index, double flt)
{
Value val;
ext_float_putval(&val, flt);
f->storeGlobal(inherit, index, &val);
}
/*
* indexed store
*/
static void ext_vm_store_index(Frame *f)
{
try {
f->storeIndex(f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in parameter
*/
static void ext_vm_store_param_index(Frame *f, uint8_t param)
{
try {
f->storeParamIndex(param, f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in local variable
*/
static void ext_vm_store_local_index(Frame *f, uint8_t local)
{
try {
f->storeLocalIndex(local, f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in global variable
*/
static void ext_vm_store_global_index(Frame *f, uint16_t inherit, uint8_t index)
{
try {
f->storeGlobalIndex(inherit, index, f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed indexed store
*/
static void ext_vm_store_index_index(Frame *f)
{
try {
f->storeIndexIndex(f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* prepare for a number of stores
*/
static void ext_vm_stores(Frame *f, uint8_t n)
{
if (f->sp->type != T_ARRAY) {
ext_runtime_error(f, "Value is not an array");
}
if (n > f->sp->array->size) {
ext_runtime_error(f, "Wrong number of lvalues");
}
Dataspace::elts(f->sp->array);
f->nStores = n;
}
/*
* prepare for a number of stores
*/
static void ext_vm_stores_lval(Frame *f, uint8_t n)
{
if (n < f->sp->array->size) {
ext_runtime_error(f, "Missing lvalue");
}
f->nStores = n;
}
/*
* prepare for a number of stores
*/
static void ext_vm_stores_spread(Frame *f, uint8_t n, uint8_t offset,
uint8_t type, uint16_t inherit, uint16_t index)
{
--n;
if (n < f->storesSpread(n, offset, type, ((Uint) inherit << 16) + index)) {
ext_runtime_error(f, "Missing lvalue");
}
f->nStores = n;
}
/*
* cast value to a type
*/
static void ext_vm_stores_cast(Frame *f, uint8_t type,
uint16_t inherit, uint16_t index)
{
try {
if (f->nStores <= f->sp->array->size) {
f->cast(&f->sp->array->elts[f->nStores - 1], type,
((Uint) inherit << 16) + index);
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* store value in parameter
*/
static void ext_vm_stores_param(Frame *f, uint8_t param)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeParam(param, &f->sp->array->elts[f->nStores]);
}
}
/*
* store int in parameter
*/
static Int ext_vm_stores_param_int(Frame *f, uint8_t param)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeParam(param, &f->sp->array->elts[f->nStores]);
}
return f->argp[param].number;
}
/*
* store float in parameter
*/
static double ext_vm_stores_param_float(Frame *f, uint8_t param)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeParam(param, &f->sp->array->elts[f->nStores]);
}
return ext_float_getval(f->argp + param);
}
/*
* store value in local variable
*/
static void ext_vm_stores_local(Frame *f, uint8_t local)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeLocal(local, &f->sp->array->elts[f->nStores]);
}
}
/*
* store int in local variable
*/
static Int ext_vm_stores_local_int(Frame *f, uint8_t local, Int n)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeLocal(local, &f->sp->array->elts[f->nStores]);
return (f->fp - local)->number;
}
return n;
}
/*
* store float in local variable
*/
static double ext_vm_stores_local_float(Frame *f, uint8_t local, double flt)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeLocal(local, &f->sp->array->elts[f->nStores]);
return ext_float_getval(f->fp - local);
}
return flt;
}
/*
* store value in global variable
*/
static void ext_vm_stores_global(Frame *f, uint16_t inherit, uint8_t index)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeGlobal(inherit, index, &f->sp->array->elts[f->nStores]);
}
}
/*
* indexed store
*/
static void ext_vm_stores_index(Frame *f)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeIndex(&f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in parameter
*/
static void ext_vm_stores_param_index(Frame *f, uint8_t param)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeParamIndex(param, &f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in local variable
*/
static void ext_vm_stores_local_index(Frame *f, uint8_t local)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeLocalIndex(local, &f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in global variable
*/
static void ext_vm_stores_global_index(Frame *f, uint16_t inherit,
uint8_t index)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeGlobalIndex(inherit, index,
&f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed indexed store
*/
static void ext_vm_stores_index_index(Frame *f)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeIndexIndex(&f->sp->array->elts[f->nStores]);
} else {
f->storeSkipSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer division
*/
static Int ext_vm_div_int(Frame *f, Int num, Int denom)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::div(num, denom);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer left shift
*/
static Int ext_vm_lshift_int(Frame *f, Int num, Int shift)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::lshift(num, shift);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer modulus
*/
static Int ext_vm_mod_int(Frame *f, Int num, Int denom)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::mod(num, denom);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer right shift
*/
static Int ext_vm_rshift_int(Frame *f, Int num, Int shift)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::rshift(num, shift);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* convert to float
*/
static double ext_vm_tofloat(Frame *f)
{
try {
Float flt;
Value val;
f->toFloat(&flt);
PUT_FLT(&val, flt);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* convert to int
*/
static Int ext_vm_toint(Frame *f)
{
try {
return f->toInt();
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* convert float to int
*/
static Int ext_vm_toint_float(Frame *f, double iflt)
{
UNREFERENCED_PARAMETER(f);
try {
Value val;
Float flt;
ext_float_putval(&val, iflt);
GET_FLT(&val, flt);
return flt.ftoi();
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* nil
*/
static void ext_vm_nil(Frame *f)
{
*--f->sp = Value::nil;
}
/*
* float addition
*/
static double ext_vm_add_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.add(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* float division
*/
static double ext_vm_div_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.div(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* float multiplication
*/
static double ext_vm_mult_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.mult(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* float subtraction
*/
static double ext_vm_sub_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.sub(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kernel function
*/
static void ext_vm_kfunc(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kernel function with int result
*/
static Int ext_vm_kfunc_int(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs);
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with float result
*/
static double ext_vm_kfunc_float(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs);
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with spread
*/
static void ext_vm_kfunc_spread(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs + f->spread(-1));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with spread and int result
*/
static Int ext_vm_kfunc_spread_int(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs + f->spread(-1));
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with spread and float result
*/
static double ext_vm_kfunc_spread_float(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs + f->spread(-1));
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with lvalue spread
*/
static void ext_vm_kfunc_spread_lval(Frame *f, uint16_t lval, uint16_t n,
int nargs)
{
try {
f->kfunc(n, nargs + f->spread(lval));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function
*/
static void ext_vm_dfunc(Frame *f, uint16_t inherit, uint8_t n, int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n, nargs);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with int result
*/
static Int ext_vm_dfunc_int(Frame *f, uint16_t inherit, uint8_t n, int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n, nargs);
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with float result
*/
static double ext_vm_dfunc_float(Frame *f, uint16_t inherit, uint8_t n,
int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n, nargs);
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with spread
*/
static void ext_vm_dfunc_spread(Frame *f, uint16_t inherit, uint8_t n,
int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n,
nargs + f->spread(-1));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with spread and int result
*/
static Int ext_vm_dfunc_spread_int(Frame *f, uint16_t inherit, uint8_t n,
int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n,
nargs + f->spread(-1));
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function wit spread and float result
*/
static double ext_vm_dfunc_spread_float(Frame *f, uint16_t inherit,
uint8_t n, int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n,
nargs + f->spread(-1));
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call virtual function
*/
static void ext_vm_func(Frame *f, uint16_t index, int nargs)
{
try {
f->vfunc(index, nargs);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call virtual function with spread
*/
static void ext_vm_func_spread(Frame *f, uint16_t index, int nargs)
{
try {
f->vfunc(index, nargs + f->spread(-1));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* pop value from stack
*/
static void ext_vm_pop(Frame *f)
{
(f->sp++)->del();
}
/*
* pop value and return boolean result
*/
static bool ext_vm_pop_bool(Frame *f)
{
bool flag;
flag = VAL_TRUE(f->sp);
(f->sp++)->del();
return flag;
}
/*
* pop value and return int result
*/
static Int ext_vm_pop_int(Frame *f)
{
return (f->sp++)->number;
}
/*
* pop value and return float result
*/
static double ext_vm_pop_float(Frame *f)
{
return ext_float_getval(f->sp++);
}
/*
* is there an int on the stack?
*/
static bool ext_vm_switch_int(Frame *f)
{
return (f->sp->type == T_INT);
}
/*
* perform a range switch
*/
static uint32_t ext_vm_switch_range(Int *table, uint32_t size, Int number)
{
uint32_t mid, low, high;
low = 0;
high = size;
while (low < high) {
mid = (low + high) & ~0x01;
if (number >= table[mid]) {
if (number <= table[mid + 1]) {
return mid >> 1;
}
high = mid >> 1;
} else {
low = (mid >> 1) + 1;
}
}
return size;
}
/*
* perform a string switch
*/
static uint32_t ext_vm_switch_string(Frame *f, uint16_t *table, uint32_t size)
{
String *str;
Control *ctrl;
uint32_t mid, low, high;
int cmp;
if (f->sp->type == T_STRING) {
str = f->sp->string;
ctrl = f->p_ctrl;
low = (table[0] == 0 && table[1] == 0xffff);
high = size;
while (low < high) {
mid = (low + high) & ~0x01;
cmp = str->cmp(ctrl->strconst(table[mid], table[mid + 1]));
if (cmp == 0) {
size = mid >> 1;
break;
}
if (cmp < 0) {
high = mid >> 1;
} else {
low = (mid >> 1) + 1;
}
}
} else if (f->sp->type == T_NIL && table[0] == 0 && table[1] == 0xffff) {
size = 0; /* case nil */
}
(f->sp++)->del();
return size;
}
/*
* start rlimits
*/
static void ext_vm_rlimits(Frame *f, bool privileged)
{
try {
f->rlimits(privileged);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* end rlimits
*/
static void ext_vm_rlimits_end(Frame *f)
{
f->setRlimits(f->rlim->next);
}
/*
* catch an error
*/
static jmp_buf *ext_vm_catch(Frame *f)
{
UNREFERENCED_PARAMETER(f);
return ErrorContext::push(Frame::runtimeError);
}
/*
* caught an error
*/
static void ext_vm_caught(Frame *f, bool push)
{
if (push) {
PUSH_STRVAL(f, ErrorContext::exception());
}
}
/*
* end catch
*/
static void ext_vm_catch_end(Frame *f, bool push)
{
ErrorContext::pop();
if (push) {
*--f->sp = Value::nil;
}
}
/*
* set current line
*/
static void ext_vm_line(Frame *f, uint16_t line)
{
f->source = line;
}
/*
* add ticks at end of loop
*/
static void ext_vm_loop_ticks(Frame *f)
{
try {
loop_ticks(f);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
static void (*mod_fdlist)(int*, int);
static void (*mod_finish)();
/*
* NAME: ext->spawn()
* DESCRIPTION: supply function to pass open descriptors to, after a
* subprocess has been spawned
*/
static void ext_spawn(void (*fdlist)(int*, int), void (*finish)())
{
/* close channels with other modules */
conf_mod_finish();
mod_fdlist = fdlist;
mod_finish = finish;
}
static int (*jit_init)(int, int, size_t, size_t, int, int, int, uint8_t*,
size_t, void**);
static void (*jit_finish)();
static void (*jit_compile)(uint64_t, uint64_t, int, uint8_t*, size_t, int,
uint8_t*, size_t, uint8_t*, size_t);
static int (*jit_execute)(uint64_t, uint64_t, int, int, void*);
static void (*jit_release)(uint64_t, uint64_t);
/*
* NAME: ext->jit()
* DESCRIPTION: initialize JIT extension
*/
static void ext_jit(int (*init)(int, int, size_t, size_t, int, int, int,
uint8_t*, size_t, void**),
void (*finish)(),
void (*compile)(uint64_t, uint64_t, int, uint8_t*, size_t,
int, uint8_t*, size_t, uint8_t*, size_t),
int (*execute)(uint64_t, uint64_t, int, int, void*),
void (*release)(uint64_t, uint64_t))
{
jit_init = init;
jit_finish = finish;
jit_compile = compile;
jit_execute = execute;
jit_release = release;
}
/*
* NAME: ext->kfuns()
* DESCRIPTION: pass kernel function prototypes to the JIT extension
*/
void ext_kfuns(char *protos, int size, int nkfun)
{
if (jit_compile != NULL) {
static voidf *vmtab[96];
vmtab[ 0] = (voidf *) &ext_vm_int;
vmtab[ 1] = (voidf *) &ext_vm_float;
vmtab[ 2] = (voidf *) &ext_vm_string;
vmtab[ 3] = (voidf *) &ext_vm_param;
vmtab[ 4] = (voidf *) &ext_vm_param_int;
vmtab[ 5] = (voidf *) &ext_vm_param_float;
vmtab[ 6] = (voidf *) &ext_vm_local;
vmtab[ 7] = (voidf *) &ext_vm_local_int;
vmtab[ 8] = (voidf *) &ext_vm_local_float;
vmtab[ 9] = (voidf *) &ext_vm_global;
vmtab[10] = (voidf *) &ext_vm_global_int;
vmtab[11] = (voidf *) &ext_vm_global_float;
vmtab[12] = (voidf *) &ext_vm_index;
vmtab[13] = (voidf *) &ext_vm_index_int;
vmtab[14] = (voidf *) &ext_vm_index2;
vmtab[15] = (voidf *) &ext_vm_index2_int;
vmtab[16] = (voidf *) &ext_vm_aggregate;
vmtab[17] = (voidf *) &ext_vm_map_aggregate;
vmtab[18] = (voidf *) &ext_vm_cast;
vmtab[19] = (voidf *) &ext_vm_cast_int;
vmtab[20] = (voidf *) &ext_vm_cast_float;
vmtab[21] = (voidf *) &ext_vm_instanceof;
vmtab[22] = (voidf *) &ext_vm_range;
vmtab[23] = (voidf *) &ext_vm_range_from;
vmtab[24] = (voidf *) &ext_vm_range_to;
vmtab[25] = (voidf *) &ext_vm_store_param;
vmtab[26] = (voidf *) &ext_vm_store_param_int;
vmtab[27] = (voidf *) &ext_vm_store_param_float;
vmtab[28] = (voidf *) &ext_vm_store_local;
vmtab[29] = (voidf *) &ext_vm_store_local_int;
vmtab[30] = (voidf *) &ext_vm_store_local_float;
vmtab[31] = (voidf *) &ext_vm_store_global;
vmtab[32] = (voidf *) &ext_vm_store_global_int;
vmtab[33] = (voidf *) &ext_vm_store_global_float;
vmtab[34] = (voidf *) &ext_vm_store_index;
vmtab[35] = (voidf *) &ext_vm_store_param_index;
vmtab[36] = (voidf *) &ext_vm_store_local_index;
vmtab[37] = (voidf *) &ext_vm_store_global_index;
vmtab[38] = (voidf *) &ext_vm_store_index_index;
vmtab[39] = (voidf *) &ext_vm_stores;
vmtab[40] = (voidf *) &ext_vm_stores_lval;
vmtab[41] = (voidf *) &ext_vm_stores_spread;
vmtab[42] = (voidf *) &ext_vm_stores_cast;
vmtab[43] = (voidf *) &ext_vm_stores_param;
vmtab[44] = (voidf *) &ext_vm_stores_param_int;
vmtab[45] = (voidf *) &ext_vm_stores_param_float;
vmtab[46] = (voidf *) &ext_vm_stores_local;
vmtab[47] = (voidf *) &ext_vm_stores_local_int;
vmtab[48] = (voidf *) &ext_vm_stores_local_float;
vmtab[49] = (voidf *) &ext_vm_stores_global;
vmtab[50] = (voidf *) &ext_vm_stores_index;
vmtab[51] = (voidf *) &ext_vm_stores_param_index;
vmtab[52] = (voidf *) &ext_vm_stores_local_index;
vmtab[53] = (voidf *) &ext_vm_stores_global_index;
vmtab[54] = (voidf *) &ext_vm_stores_index_index;
vmtab[55] = (voidf *) &ext_vm_div_int;
vmtab[56] = (voidf *) &ext_vm_lshift_int;
vmtab[57] = (voidf *) &ext_vm_mod_int;
vmtab[58] = (voidf *) &ext_vm_rshift_int;
vmtab[59] = (voidf *) &ext_vm_tofloat;
vmtab[60] = (voidf *) &ext_vm_toint;
vmtab[61] = (voidf *) &ext_vm_toint_float;
vmtab[62] = (voidf *) &ext_vm_nil;
vmtab[63] = (voidf *) &ext_vm_add_float;
vmtab[64] = (voidf *) &ext_vm_div_float;
vmtab[65] = (voidf *) &ext_vm_mult_float;
vmtab[66] = (voidf *) &ext_vm_sub_float;
vmtab[67] = (voidf *) &ext_vm_kfunc;
vmtab[68] = (voidf *) &ext_vm_kfunc_int;
vmtab[69] = (voidf *) &ext_vm_kfunc_float;
vmtab[70] = (voidf *) &ext_vm_kfunc_spread;
vmtab[71] = (voidf *) &ext_vm_kfunc_spread_int;
vmtab[72] = (voidf *) &ext_vm_kfunc_spread_float;
vmtab[73] = (voidf *) &ext_vm_kfunc_spread_lval;
vmtab[74] = (voidf *) &ext_vm_dfunc;
vmtab[75] = (voidf *) &ext_vm_dfunc_int;
vmtab[76] = (voidf *) &ext_vm_dfunc_float;
vmtab[77] = (voidf *) &ext_vm_dfunc_spread;
vmtab[78] = (voidf *) &ext_vm_dfunc_spread_int;
vmtab[79] = (voidf *) &ext_vm_dfunc_spread_float;
vmtab[80] = (voidf *) &ext_vm_func;
vmtab[81] = (voidf *) &ext_vm_func_spread;
vmtab[82] = (voidf *) &ext_vm_pop;
vmtab[83] = (voidf *) &ext_vm_pop_bool;
vmtab[84] = (voidf *) &ext_vm_pop_int;
vmtab[85] = (voidf *) &ext_vm_pop_float;
vmtab[86] = (voidf *) &ext_vm_switch_int;
vmtab[87] = (voidf *) &ext_vm_switch_range;
vmtab[88] = (voidf *) &ext_vm_switch_string;
vmtab[89] = (voidf *) &ext_vm_rlimits;
vmtab[90] = (voidf *) &ext_vm_rlimits_end;
vmtab[91] = (voidf *) &ext_vm_catch;
vmtab[92] = (voidf *) &ext_vm_caught;
vmtab[93] = (voidf *) &ext_vm_catch_end;
vmtab[94] = (voidf *) &ext_vm_line;
vmtab[95] = (voidf *) &ext_vm_loop_ticks;
if (!(*jit_init)(VERSION_VM_MAJOR, VERSION_VM_MINOR, sizeof(Int), 1,
conf_typechecking(), KF_BUILTINS, nkfun,
(uint8_t *) protos, size, (void **) vmtab)) {
jit_compile = NULL;
}
}
}
/*
* JIT compile program
*/
static void ext_compile(const Frame *f, Control *ctrl)
{
Object *obj;
int i, j, nftypes;
const Inherit *inh;
char *ft, *vt;
const FuncDef *fdef;
const VarDef *vdef;
/*
* compile new program
*/
obj = OBJ(ctrl->oindex);
if (obj->flags & O_COMPILED) {
return;
}
obj->flags |= O_COMPILED;
/* count function types & variable types */
nftypes = 0;
for (inh = ctrl->inherits, i = ctrl->ninherits; i > 0; inh++, --i) {
nftypes += OBJR(inh->oindex)->control()->nfuncdefs;
}
char *ftypes = ALLOCA(char, ctrl->ninherits + nftypes);
char *vtypes = ALLOCA(char, ctrl->ninherits + ctrl->nvariables);
/* collect function types & variable types */
ft = ftypes;
vt = vtypes;
for (inh = ctrl->inherits, i = ctrl->ninherits; i > 0; inh++, --i) {
ctrl = OBJR(inh->oindex)->ctrl;
ctrl->program();
*ft++ = ctrl->nfuncdefs;
for (fdef = ctrl->funcs(), j = ctrl->nfuncdefs; j > 0; fdef++, --j)
{
*ft++ = PROTO_FTYPE(ctrl->prog + fdef->offset);
}
*vt++ = ctrl->nvardefs;
for (vdef = ctrl->vars(), j = ctrl->nvardefs; j > 0; vdef++, --j) {
*vt++ = vdef->type;
}
}
/* start JIT compiler */
ctrl = f->p_ctrl;
(*jit_compile)(ctrl->oindex, ctrl->instance, ctrl->ninherits,
(uint8_t *) ctrl->prog, ctrl->progsize, ctrl->nfuncdefs,
(uint8_t *) ftypes, ctrl->ninherits + nftypes,
(uint8_t *) vtypes, ctrl->ninherits + ctrl->nvariables);
AFREE(ftypes);
AFREE(vtypes);
}
/*
* NAME: ext->execute()
* DESCRIPTION: JIT-compile and execute a function
*/
bool ext_execute(const Frame *f, int func)
{
Control *ctrl;
int result;
if (jit_compile == NULL) {
return FALSE;
}
ctrl = f->p_ctrl;
if (ctrl->instance == 0) {
return FALSE;
}
if (!setjmp(*ErrorContext::push())) {
result = (*jit_execute)(ctrl->oindex, ctrl->instance, ctrl->version,
func, (void *) f);
ErrorContext::pop();
} else {
error((char *) NULL);
}
if (result < 0) {
ext_compile(f, ctrl);
return FALSE;
} else {
return (bool) result;
}
}
/*
* remove JIT-compiled object
*/
void ext_release(uint64_t index, uint64_t instance)
{
if (jit_compile != NULL) {
(*jit_release)(index, instance);
}
}
/*
* NAME: ext->dgd()
* DESCRIPTION: initialize extension interface
*/
bool ext_dgd(char *module, char *config, void (**fdlist)(int*, int),
void (**finish)())
{
voidf *ext_ext[5];
voidf *ext_frame[4];
voidf *ext_data[2];
voidf *ext_value[4];
voidf *ext_int[2];
voidf *ext_float[2];
voidf *ext_string[5];
voidf *ext_object[6];
voidf *ext_array[6];
voidf *ext_mapping[7];
voidf *ext_runtime[4];
voidf **ftabs[11];
int sizes[11];
int (*init) (int, int, voidf**[], int[], const char*);
init = (int (*) (int, int, voidf**[], int[], const char*))
P_dload(module, "ext_init");
if (init == NULL) {
return FALSE;
}
mod_fdlist = NULL;
mod_finish = NULL;
ext_ext[0] = (voidf *) &kf_ext_kfun;
ext_ext[1] = (voidf *) NULL;
ext_ext[2] = (voidf *) &ext_spawn;
ext_ext[3] = (voidf *) &Connection::fdclose;
ext_ext[4] = (voidf *) &ext_jit;
ext_frame[0] = (voidf *) &ext_frame_object;
ext_frame[1] = (voidf *) &ext_frame_dataspace;
ext_frame[2] = (voidf *) &ext_frame_arg;
ext_frame[3] = (voidf *) &ext_frame_atomic;
ext_data[0] = (voidf *) &Dataspace::extra;
ext_data[1] = (voidf *) &Dataspace::setExtra;
ext_value[0] = (voidf *) &ext_value_type;
ext_value[1] = (voidf *) &ext_value_nil;
ext_value[2] = (voidf *) &ext_value_temp;
ext_value[3] = (voidf *) &ext_value_temp2;
ext_int[0] = (voidf *) &ext_int_getval;
ext_int[1] = (voidf *) &ext_int_putval;
# ifndef NOFLOAT
ext_float[0] = (voidf *) &ext_float_getval;
ext_float[1] = (voidf *) &ext_float_putval;
# else
ext_float[0] = (voidf *) NULL;
ext_float[1] = (voidf *) NULL;
# endif
ext_string[0] = (voidf *) &ext_string_getval;
ext_string[1] = (voidf *) &ext_string_putval;
ext_string[2] = (voidf *) &ext_string_new;
ext_string[3] = (voidf *) &ext_string_text;
ext_string[4] = (voidf *) &ext_string_length;
ext_object[0] = (voidf *) &ext_object_putval;
ext_object[1] = (voidf *) &ext_object_name;
ext_object[2] = (voidf *) &ext_object_isspecial;
ext_object[3] = (voidf *) &ext_object_ismarked;
ext_object[4] = (voidf *) &ext_object_mark;
ext_object[5] = (voidf *) &ext_object_unmark;
ext_array[0] = (voidf *) &ext_array_getval;
ext_array[1] = (voidf *) &ext_array_putval;
ext_array[2] = (voidf *) &ext_array_new;
ext_array[3] = (voidf *) &ext_array_index;
ext_array[4] = (voidf *) &ext_array_assign;
ext_array[5] = (voidf *) &ext_array_size;
ext_mapping[0] = (voidf *) &ext_array_getval;
ext_mapping[1] = (voidf *) &ext_mapping_putval;
ext_mapping[2] = (voidf *) &ext_mapping_new;
ext_mapping[3] = (voidf *) &ext_mapping_index;
ext_mapping[4] = (voidf *) &ext_mapping_assign;
ext_mapping[5] = (voidf *) &ext_mapping_enum;
ext_mapping[6] = (voidf *) &ext_mapping_size;
ext_runtime[0] = (voidf *) &ext_runtime_error;
ext_runtime[1] = (voidf *) hash_md5_start;
ext_runtime[2] = (voidf *) hash_md5_block;
ext_runtime[3] = (voidf *) hash_md5_end;
ftabs[ 0] = ext_ext; sizes[ 0] = 5;
ftabs[ 1] = ext_frame; sizes[ 1] = 4;
ftabs[ 2] = ext_data; sizes[ 2] = 2;
ftabs[ 3] = ext_value; sizes[ 3] = 4;
ftabs[ 4] = ext_int; sizes[ 4] = 2;
ftabs[ 5] = ext_float; sizes[ 5] = 2;
ftabs[ 6] = ext_string; sizes[ 6] = 5;
ftabs[ 7] = ext_object; sizes[ 7] = 6;
ftabs[ 8] = ext_array; sizes[ 8] = 6;
ftabs[ 9] = ext_mapping; sizes[ 9] = 7;
ftabs[10] = ext_runtime; sizes[10] = 4;
if (!init(EXTENSION_MAJOR, EXTENSION_MINOR, ftabs, sizes, config)) {
fatal("incompatible runtime extension");
}
*fdlist = mod_fdlist;
*finish = mod_finish;
return TRUE;
}
/*
* NAME: ext->finish()
* DESCRIPTION: finish JIT compiler interface
*/
void ext_finish()
{
if (jit_compile != NULL) {
(*jit_finish)();
}
}
Update extension interface with tick accounting.
/*
* This file is part of DGD, https://github.com/dworkin/dgd
* Copyright (C) 1993-2010 Dworkin B.V.
* Copyright (C) 2010-2019 DGD Authors (see the commit log for details)
*
* This program 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.
*
* 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 "dgd.h"
# include "str.h"
# include "array.h"
# include "object.h"
# include "xfloat.h"
# include "data.h"
# include "control.h"
# include "interpret.h"
# include "comm.h"
# include "table.h"
# include <float.h>
# include <math.h>
# define EXTENSION_MAJOR 1
# define EXTENSION_MINOR 1
/*
* NAME: ext->frame_object()
* DESCRIPTION: return the current object
*/
static Object *ext_frame_object(Frame *f)
{
return (f->lwobj == NULL) ? OBJW(f->oindex) : NULL;
}
/*
* NAME: ext->frame_dataspace()
* DESCRIPTION: return the current dataspace
*/
static Dataspace *ext_frame_dataspace(Frame *f)
{
return f->data;
}
/*
* NAME: ext->frame_arg()
* DESCRIPTION: return the given argument
*/
static Value *ext_frame_arg(Frame *f, int nargs, int arg)
{
return f->sp + nargs - arg - 1;
}
/*
* NAME: ext->frame_atomic()
* DESCRIPTION: running atomically?
*/
static int ext_frame_atomic(Frame *f)
{
return (f->level != 0);
}
/*
* NAME: ext->value_type()
* DESCRIPTION: return the type of a value
*/
static int ext_value_type(Value *val)
{
return val->type;
}
/*
* NAME: ext->value_nil()
* DESCRIPTION: return nil
*/
static Value *ext_value_nil()
{
return &Value::nil;
}
/*
* NAME: ext->value_temp()
* DESCRIPTION: return a scratch value
*/
Value *ext_value_temp(Dataspace *data)
{
static Value temp;
UNREFERENCED_PARAMETER(data);
return &temp;
}
/*
* NAME: ext->value_temp2()
* DESCRIPTION: return another scratch value
*/
static Value *ext_value_temp2(Dataspace *data)
{
static Value temp2;
UNREFERENCED_PARAMETER(data);
return &temp2;
}
/*
* NAME: ext->int_getval()
* DESCRIPTION: retrieve an int from a value
*/
static Int ext_int_getval(Value *val)
{
return val->number;
}
/*
* NAME: ext->int_putval()
* DESCRIPTION: store an int in a value
*/
static void ext_int_putval(Value *val, Int i)
{
PUT_INTVAL(val, i);
}
# ifndef NOFLOAT
/*
* NAME: ext->float_getval()
* DESCRIPTION: retrieve a float from a value
*/
static long double ext_float_getval(Value *val)
{
Float flt;
double d;
GET_FLT(val, flt);
if ((flt.high | flt.low) == 0) {
return 0.0;
} else {
d = ldexp((double) (0x10 | (flt.high & 0xf)), 32);
d = ldexp(d + flt.low, ((flt.high >> 4) & 0x7ff) - 1023 - 36);
return (long double) ((flt.high >> 15) ? -d : d);
}
}
/*
* NAME: ext->float_putval()
* DESCRIPTION: store a float in a value
*/
static int ext_float_putval(Value *val, long double ld)
{
double d;
Float flt;
unsigned short sign;
int e;
Uuint m;
d = (double) ld;
if (d == 0.0) {
flt.high = 0;
flt.low = 0;
} else {
sign = (d < 0.0);
d = frexp(fabs(d), &e);
# if (DBL_MANT_DIG > 37)
d += (double) (1 << (DBL_MANT_DIG - 38));
d -= (double) (1 << (DBL_MANT_DIG - 38));
if (d >= 1.0) {
if (++e > 1023) {
return FALSE;
}
d = ldexp(d, -1);
}
# endif
if (e <= -1023) {
flt.high = 0;
flt.low = 0;
} else {
m = (Uuint) ldexp(d, 37);
flt.high = (sign << 15) | ((e - 1 + 1023) << 4) |
((unsigned short) (m >> 32) & 0xf);
flt.low = (Uuint) m;
}
}
PUT_FLTVAL(val, flt);
return TRUE;
}
# endif
/*
* NAME: ext->string_getval()
* DESCRIPTION: retrieve a string from a value
*/
static String *ext_string_getval(Value *val)
{
return val->string;
}
/*
* NAME: ext->string_putval()
* DESCRIPTION: store a string in a value
*/
static void ext_string_putval(Value *val, String *str)
{
PUT_STRVAL_NOREF(val, str);
}
/*
* NAME: ext->string_new()
* DESCRIPTION: create a new string
*/
static String *ext_string_new(Dataspace *data, char *text, int len)
{
UNREFERENCED_PARAMETER(data);
try {
return String::create(text, len);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->string_text()
* DESCRIPTION: return string text
*/
static char *ext_string_text(String *str)
{
return str->text;
}
/*
* NAME: ext->string_length()
* DESCRIPTION: return string length
*/
static int ext_string_length(String *str)
{
return str->len;
}
/*
* NAME: ext->object_putval()
* DESCRIPTION: store an object in a value
*/
static void ext_object_putval(Value *val, Object *obj)
{
PUT_OBJVAL(val, obj);
}
/*
* NAME: ext->object_name()
* DESCRIPTION: store the name of an object
*/
static const char *ext_object_name(Frame *f, Object *obj, char *buf)
{
UNREFERENCED_PARAMETER(f);
return obj->objName(buf);
}
/*
* NAME: ext->object_isspecial()
* DESCRIPTION: return TRUE if the given object is special, FALSE otherwise
*/
static int ext_object_isspecial(Object *obj)
{
return ((obj->flags & O_SPECIAL) != 0);
}
/*
* NAME: ext->object_ismarked()
* DESCRIPTION: return TRUE if the given object is marked, FALSE otherwise
*/
static int ext_object_ismarked(Object *obj)
{
return ((obj->flags & O_SPECIAL) == O_SPECIAL);
}
/*
* NAME: ext->object_mark()
* DESCRIPTION: mark the given object
*/
static void ext_object_mark(Object *obj)
{
obj->flags |= O_SPECIAL;
}
/*
* NAME: ext->object_unmark()
* DESCRIPTION: unmark the given object
*/
static void ext_object_unmark(Object *obj)
{
obj->flags &= ~O_SPECIAL;
}
/*
* NAME: ext->array_getval()
* DESCRIPTION: retrieve an array from a value
*/
static Array *ext_array_getval(Value *val)
{
return val->array;
}
/*
* NAME: ext->array_putval()
* DESCRIPTION: store an array in a value
*/
static void ext_array_putval(Value *val, Array *a)
{
PUT_ARRVAL_NOREF(val, a);
}
/*
* NAME: ext->array_new()
* DESCRIPTION: create a new array
*/
static Array *ext_array_new(Dataspace *data, int size)
{
try {
return Array::createNil(data, size);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->array_index()
* DESCRIPTION: return an array element
*/
static Value *ext_array_index(Array *a, int i)
{
return &Dataspace::elts(a)[i];
}
/*
* NAME: ext->array_assign()
* DESCRIPTION: assign a value to an array element
*/
static void ext_array_assign(Dataspace *data, Array *a, int i, Value *val)
{
data->assignElt(a, &Dataspace::elts(a)[i], val);
}
/*
* NAME: ext->array_size()
* DESCRIPTION: return the size of an array
*/
static int ext_array_size(Array *a)
{
return a->size;
}
/*
* NAME: ext->mapping_putval()
* DESCRIPTION: store a mapping in a value
*/
static void ext_mapping_putval(Value *val, Array *m)
{
PUT_MAPVAL_NOREF(val, m);
}
/*
* NAME: ext->mapping_new()
* DESCRIPTION: create a new mapping
*/
static Array *ext_mapping_new(Dataspace *data)
{
return Array::mapCreate(data, 0);
}
/*
* NAME: ext->mapping_index()
* DESCRIPTION: return a value from a mapping
*/
static Value *ext_mapping_index(Array *m, Value *idx)
{
try {
return m->mapIndex(m->primary->data, idx, (Value *) NULL,
(Value *) NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->mapping_assign()
* DESCRIPTION: assign to a mapping value
*/
static void ext_mapping_assign(Dataspace *data, Array *m, Value *idx,
Value *val)
{
try {
m->mapIndex(data, idx, val, (Value *) NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->mapping_enum()
* DESCRIPTION: return the nth enumerated index
*/
static Value *ext_mapping_enum(Array *m, int i)
{
m->mapCompact(m->primary->data);
return &Dataspace::elts(m)[i];
}
/*
* NAME: ext->mapping_size()
* DESCRIPTION: return the size of a mapping
*/
static int ext_mapping_size(Array *m)
{
return m->mapSize(m->primary->data);
}
/*
* NAME: ext->runtime_error()
* DESCRIPTION: handle an error at runtime
*/
void ext_runtime_error(Frame *f, const char *mesg)
{
UNREFERENCED_PARAMETER(f);
try {
error(mesg);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* NAME: ext->runtime_ticks()
* DESCRIPTION: spend ticks
*/
void ext_runtime_ticks(Frame *f, int ticks)
{
i_add_ticks(f, ticks);
}
/*
* push int on the stack
*/
static void ext_vm_int(Frame *f, Int n)
{
PUSH_INTVAL(f, n);
}
/*
* push float on the stack
*/
static void ext_vm_float(Frame *f, double flt)
{
ext_float_putval(--f->sp, flt);
}
/*
* push string on the stack
*/
static void ext_vm_string(Frame *f, uint16_t inherit, uint16_t index)
{
PUSH_STRVAL(f, f->p_ctrl->strconst(inherit, index));
}
/*
* push parameter on the stack
*/
static void ext_vm_param(Frame *f, uint8_t param)
{
f->pushValue(f->argp + param);
}
/*
* get int parameter
*/
static Int ext_vm_param_int(Frame *f, uint8_t param)
{
return f->argp[param].number;
}
/*
* get float parameter
*/
static double ext_vm_param_float(Frame *f, uint8_t param)
{
return ext_float_getval(f->argp + param);
}
/*
* push local variable on the stack
*/
static void ext_vm_local(Frame *f, uint8_t local)
{
f->pushValue(f->fp - local);
}
/*
* get int local variable
*/
static Int ext_vm_local_int(Frame *f, uint8_t local)
{
return (f->fp - local)->number;
}
/*
* get float local variable
*/
static double ext_vm_local_float(Frame *f, uint8_t local)
{
return ext_float_getval(f->fp - local);
}
/*
* get global variable
*/
static void ext_vm_global(Frame *f, uint16_t inherit, uint8_t index)
{
f->pushValue(f->global(inherit, index));
}
/*
* get integer global variable
*/
static Int ext_vm_global_int(Frame *f, uint16_t inherit, uint8_t index)
{
return f->global(inherit, index)->number;
}
/*
* get float global variable
*/
static double ext_vm_global_float(Frame *f, uint16_t inherit, uint8_t index)
{
return ext_float_getval(f->global(inherit, index));
}
/*
* index value on the stack
*/
static void ext_vm_index(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, FALSE);
*++f->sp = val;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* index string
*/
static Int ext_vm_index_int(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, FALSE);
f->sp += 2;
return val.number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* index and keep
*/
static void ext_vm_index2(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, TRUE);
*--f->sp = val;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* index string and keep, and return int
*/
static Int ext_vm_index2_int(Frame *f)
{
try {
Value val;
f->index(f->sp + 1, f->sp, &val, TRUE);
return val.number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* array aggregate
*/
static void ext_vm_aggregate(Frame *f, uint16_t size)
{
try {
f->aggregate(size);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* mapping aggregate
*/
static void ext_vm_map_aggregate(Frame *f, uint16_t size)
{
try {
f->mapAggregate(size);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* cast value to a type
*/
static void ext_vm_cast(Frame *f, uint8_t type, uint16_t inherit,
uint16_t index)
{
try {
f->cast(f->sp, type, ((Uint) inherit << 16) + index);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* cast value to an int
*/
static Int ext_vm_cast_int(Frame *f)
{
if (f->sp->type != T_INT) {
ext_runtime_error(f, "Value is not an int");
}
return (f->sp++)->number;
}
/*
* cast value to a float
*/
static double ext_vm_cast_float(Frame *f)
{
if (f->sp->type != T_FLOAT) {
ext_runtime_error(f, "Value is not a float");
}
return ext_float_getval(f->sp++);
}
/*
* obj <= "/path/to/thing"
*/
static Int ext_vm_instanceof(Frame *f, uint16_t inherit, uint16_t index)
{
Int instance;
instance = f->instanceOf(((Uint) inherit << 16) + index);
f->sp++;
return instance;
}
/*
* check range
*/
static void ext_vm_range(Frame *f)
{
try {
kf_ckrangeft(f, 0, NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* check range from
*/
static void ext_vm_range_from(Frame *f)
{
try {
kf_ckrangef(f, 0, NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* check range to
*/
static void ext_vm_range_to(Frame *f)
{
try {
kf_ckranget(f, 0, NULL);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* store parameter
*/
static void ext_vm_store_param(Frame *f, uint8_t param)
{
f->storeParam(param, f->sp);
}
/*
* store int in parameter
*/
static void ext_vm_store_param_int(Frame *f, uint8_t param, Int number)
{
Value val;
PUT_INTVAL(&val, number);
f->storeParam(param, &val);
}
/*
* store float in parameter
*/
static void ext_vm_store_param_float(Frame *f, uint8_t param, double flt)
{
Value val;
ext_float_putval(&val, flt);
f->storeParam(param, &val);
}
/*
* store local variable
*/
static void ext_vm_store_local(Frame *f, uint8_t local)
{
f->storeLocal(local, f->sp);
}
/*
* store int in local variable
*/
static void ext_vm_store_local_int(Frame *f, uint8_t local, Int number)
{
Value val;
PUT_INTVAL(&val, number);
f->storeLocal(local, &val);
}
/*
* store float in local variable
*/
static void ext_vm_store_local_float(Frame *f, uint8_t local, double flt)
{
Value val;
ext_float_putval(&val, flt);
f->storeLocal(local, &val);
}
/*
* store global variable
*/
static void ext_vm_store_global(Frame *f, uint16_t inherit, uint8_t index)
{
f->storeGlobal(inherit, index, f->sp);
}
/*
* store int in global variable
*/
static void ext_vm_store_global_int(Frame *f, uint16_t inherit,
uint8_t index, Int number)
{
Value val;
PUT_INTVAL(&val, number);
f->storeGlobal(inherit, index, &val);
}
/*
* store float in global variable
*/
static void ext_vm_store_global_float(Frame *f, uint16_t inherit,
uint8_t index, double flt)
{
Value val;
ext_float_putval(&val, flt);
f->storeGlobal(inherit, index, &val);
}
/*
* indexed store
*/
static void ext_vm_store_index(Frame *f)
{
try {
f->storeIndex(f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in parameter
*/
static void ext_vm_store_param_index(Frame *f, uint8_t param)
{
try {
f->storeParamIndex(param, f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in local variable
*/
static void ext_vm_store_local_index(Frame *f, uint8_t local)
{
try {
f->storeLocalIndex(local, f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in global variable
*/
static void ext_vm_store_global_index(Frame *f, uint16_t inherit, uint8_t index)
{
try {
f->storeGlobalIndex(inherit, index, f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed indexed store
*/
static void ext_vm_store_index_index(Frame *f)
{
try {
f->storeIndexIndex(f->sp);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* prepare for a number of stores
*/
static void ext_vm_stores(Frame *f, uint8_t n)
{
if (f->sp->type != T_ARRAY) {
ext_runtime_error(f, "Value is not an array");
}
if (n > f->sp->array->size) {
ext_runtime_error(f, "Wrong number of lvalues");
}
Dataspace::elts(f->sp->array);
f->nStores = n;
}
/*
* prepare for a number of stores
*/
static void ext_vm_stores_lval(Frame *f, uint8_t n)
{
if (n < f->sp->array->size) {
ext_runtime_error(f, "Missing lvalue");
}
f->nStores = n;
}
/*
* prepare for a number of stores
*/
static void ext_vm_stores_spread(Frame *f, uint8_t n, uint8_t offset,
uint8_t type, uint16_t inherit, uint16_t index)
{
--n;
if (n < f->storesSpread(n, offset, type, ((Uint) inherit << 16) + index)) {
ext_runtime_error(f, "Missing lvalue");
}
f->nStores = n;
}
/*
* cast value to a type
*/
static void ext_vm_stores_cast(Frame *f, uint8_t type,
uint16_t inherit, uint16_t index)
{
try {
if (f->nStores <= f->sp->array->size) {
f->cast(&f->sp->array->elts[f->nStores - 1], type,
((Uint) inherit << 16) + index);
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* store value in parameter
*/
static void ext_vm_stores_param(Frame *f, uint8_t param)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeParam(param, &f->sp->array->elts[f->nStores]);
}
}
/*
* store int in parameter
*/
static Int ext_vm_stores_param_int(Frame *f, uint8_t param)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeParam(param, &f->sp->array->elts[f->nStores]);
}
return f->argp[param].number;
}
/*
* store float in parameter
*/
static double ext_vm_stores_param_float(Frame *f, uint8_t param)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeParam(param, &f->sp->array->elts[f->nStores]);
}
return ext_float_getval(f->argp + param);
}
/*
* store value in local variable
*/
static void ext_vm_stores_local(Frame *f, uint8_t local)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeLocal(local, &f->sp->array->elts[f->nStores]);
}
}
/*
* store int in local variable
*/
static Int ext_vm_stores_local_int(Frame *f, uint8_t local, Int n)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeLocal(local, &f->sp->array->elts[f->nStores]);
return (f->fp - local)->number;
}
return n;
}
/*
* store float in local variable
*/
static double ext_vm_stores_local_float(Frame *f, uint8_t local, double flt)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeLocal(local, &f->sp->array->elts[f->nStores]);
return ext_float_getval(f->fp - local);
}
return flt;
}
/*
* store value in global variable
*/
static void ext_vm_stores_global(Frame *f, uint16_t inherit, uint8_t index)
{
if (--(f->nStores) < f->sp->array->size) {
f->storeGlobal(inherit, index, &f->sp->array->elts[f->nStores]);
}
}
/*
* indexed store
*/
static void ext_vm_stores_index(Frame *f)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeIndex(&f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in parameter
*/
static void ext_vm_stores_param_index(Frame *f, uint8_t param)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeParamIndex(param, &f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in local variable
*/
static void ext_vm_stores_local_index(Frame *f, uint8_t local)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeLocalIndex(local, &f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed store in global variable
*/
static void ext_vm_stores_global_index(Frame *f, uint16_t inherit,
uint8_t index)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeGlobalIndex(inherit, index,
&f->sp->array->elts[f->nStores]);
} else {
f->storeSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* indexed indexed store
*/
static void ext_vm_stores_index_index(Frame *f)
{
try {
if (--(f->nStores) < f->sp->array->size) {
f->storeIndexIndex(&f->sp->array->elts[f->nStores]);
} else {
f->storeSkipSkip();
}
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer division
*/
static Int ext_vm_div_int(Frame *f, Int num, Int denom)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::div(num, denom);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer left shift
*/
static Int ext_vm_lshift_int(Frame *f, Int num, Int shift)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::lshift(num, shift);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer modulus
*/
static Int ext_vm_mod_int(Frame *f, Int num, Int denom)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::mod(num, denom);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* integer right shift
*/
static Int ext_vm_rshift_int(Frame *f, Int num, Int shift)
{
UNREFERENCED_PARAMETER(f);
try {
return Frame::rshift(num, shift);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* convert to float
*/
static double ext_vm_tofloat(Frame *f)
{
try {
Float flt;
Value val;
f->toFloat(&flt);
PUT_FLT(&val, flt);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* convert to int
*/
static Int ext_vm_toint(Frame *f)
{
try {
return f->toInt();
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* convert float to int
*/
static Int ext_vm_toint_float(Frame *f, double iflt)
{
UNREFERENCED_PARAMETER(f);
try {
Value val;
Float flt;
ext_float_putval(&val, iflt);
GET_FLT(&val, flt);
return flt.ftoi();
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* nil
*/
static void ext_vm_nil(Frame *f)
{
*--f->sp = Value::nil;
}
/*
* float addition
*/
static double ext_vm_add_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.add(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* float division
*/
static double ext_vm_div_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.div(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* float multiplication
*/
static double ext_vm_mult_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.mult(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* float subtraction
*/
static double ext_vm_sub_float(Frame *f, double flt1, double flt2)
{
try {
Value val;
Float f1, f2;
i_add_ticks(f, 1);
ext_float_putval(&val, flt1);
GET_FLT(&val, f1);
ext_float_putval(&val, flt2);
GET_FLT(&val, f2);
f1.sub(f2);
PUT_FLTVAL(&val, f1);
return ext_float_getval(&val);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kernel function
*/
static void ext_vm_kfunc(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kernel function with int result
*/
static Int ext_vm_kfunc_int(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs);
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with float result
*/
static double ext_vm_kfunc_float(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs);
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with spread
*/
static void ext_vm_kfunc_spread(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs + f->spread(-1));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with spread and int result
*/
static Int ext_vm_kfunc_spread_int(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs + f->spread(-1));
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with spread and float result
*/
static double ext_vm_kfunc_spread_float(Frame *f, uint16_t n, int nargs)
{
try {
f->kfunc(n, nargs + f->spread(-1));
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call kfun with lvalue spread
*/
static void ext_vm_kfunc_spread_lval(Frame *f, uint16_t lval, uint16_t n,
int nargs)
{
try {
f->kfunc(n, nargs + f->spread(lval));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function
*/
static void ext_vm_dfunc(Frame *f, uint16_t inherit, uint8_t n, int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n, nargs);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with int result
*/
static Int ext_vm_dfunc_int(Frame *f, uint16_t inherit, uint8_t n, int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n, nargs);
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with float result
*/
static double ext_vm_dfunc_float(Frame *f, uint16_t inherit, uint8_t n,
int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n, nargs);
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with spread
*/
static void ext_vm_dfunc_spread(Frame *f, uint16_t inherit, uint8_t n,
int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n,
nargs + f->spread(-1));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function with spread and int result
*/
static Int ext_vm_dfunc_spread_int(Frame *f, uint16_t inherit, uint8_t n,
int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n,
nargs + f->spread(-1));
return (f->sp++)->number;
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call direct function wit spread and float result
*/
static double ext_vm_dfunc_spread_float(Frame *f, uint16_t inherit,
uint8_t n, int nargs)
{
try {
f->funcall(NULL, NULL, f->ctrl->imap[f->p_index + inherit], n,
nargs + f->spread(-1));
return ext_float_getval(f->sp++);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call virtual function
*/
static void ext_vm_func(Frame *f, uint16_t index, int nargs)
{
try {
f->vfunc(index, nargs);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* call virtual function with spread
*/
static void ext_vm_func_spread(Frame *f, uint16_t index, int nargs)
{
try {
f->vfunc(index, nargs + f->spread(-1));
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* pop value from stack
*/
static void ext_vm_pop(Frame *f)
{
(f->sp++)->del();
}
/*
* pop value and return boolean result
*/
static bool ext_vm_pop_bool(Frame *f)
{
bool flag;
flag = VAL_TRUE(f->sp);
(f->sp++)->del();
return flag;
}
/*
* pop value and return int result
*/
static Int ext_vm_pop_int(Frame *f)
{
return (f->sp++)->number;
}
/*
* pop value and return float result
*/
static double ext_vm_pop_float(Frame *f)
{
return ext_float_getval(f->sp++);
}
/*
* is there an int on the stack?
*/
static bool ext_vm_switch_int(Frame *f)
{
return (f->sp->type == T_INT);
}
/*
* perform a range switch
*/
static uint32_t ext_vm_switch_range(Int *table, uint32_t size, Int number)
{
uint32_t mid, low, high;
low = 0;
high = size;
while (low < high) {
mid = (low + high) & ~0x01;
if (number >= table[mid]) {
if (number <= table[mid + 1]) {
return mid >> 1;
}
high = mid >> 1;
} else {
low = (mid >> 1) + 1;
}
}
return size;
}
/*
* perform a string switch
*/
static uint32_t ext_vm_switch_string(Frame *f, uint16_t *table, uint32_t size)
{
String *str;
Control *ctrl;
uint32_t mid, low, high;
int cmp;
if (f->sp->type == T_STRING) {
str = f->sp->string;
ctrl = f->p_ctrl;
low = (table[0] == 0 && table[1] == 0xffff);
high = size;
while (low < high) {
mid = (low + high) & ~0x01;
cmp = str->cmp(ctrl->strconst(table[mid], table[mid + 1]));
if (cmp == 0) {
size = mid >> 1;
break;
}
if (cmp < 0) {
high = mid >> 1;
} else {
low = (mid >> 1) + 1;
}
}
} else if (f->sp->type == T_NIL && table[0] == 0 && table[1] == 0xffff) {
size = 0; /* case nil */
}
(f->sp++)->del();
return size;
}
/*
* start rlimits
*/
static void ext_vm_rlimits(Frame *f, bool privileged)
{
try {
f->rlimits(privileged);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
/*
* end rlimits
*/
static void ext_vm_rlimits_end(Frame *f)
{
f->setRlimits(f->rlim->next);
}
/*
* catch an error
*/
static jmp_buf *ext_vm_catch(Frame *f)
{
UNREFERENCED_PARAMETER(f);
return ErrorContext::push(Frame::runtimeError);
}
/*
* caught an error
*/
static void ext_vm_caught(Frame *f, bool push)
{
if (push) {
PUSH_STRVAL(f, ErrorContext::exception());
}
}
/*
* end catch
*/
static void ext_vm_catch_end(Frame *f, bool push)
{
ErrorContext::pop();
if (push) {
*--f->sp = Value::nil;
}
}
/*
* set current line
*/
static void ext_vm_line(Frame *f, uint16_t line)
{
f->source = line;
}
/*
* add ticks at end of loop
*/
static void ext_vm_loop_ticks(Frame *f)
{
try {
loop_ticks(f);
} catch (...) {
longjmp(*ErrorContext::env, 1);
}
}
static void (*mod_fdlist)(int*, int);
static void (*mod_finish)();
/*
* NAME: ext->spawn()
* DESCRIPTION: supply function to pass open descriptors to, after a
* subprocess has been spawned
*/
static void ext_spawn(void (*fdlist)(int*, int), void (*finish)())
{
/* close channels with other modules */
conf_mod_finish();
mod_fdlist = fdlist;
mod_finish = finish;
}
static int (*jit_init)(int, int, size_t, size_t, int, int, int, uint8_t*,
size_t, void**);
static void (*jit_finish)();
static void (*jit_compile)(uint64_t, uint64_t, int, uint8_t*, size_t, int,
uint8_t*, size_t, uint8_t*, size_t);
static int (*jit_execute)(uint64_t, uint64_t, int, int, void*);
static void (*jit_release)(uint64_t, uint64_t);
/*
* NAME: ext->jit()
* DESCRIPTION: initialize JIT extension
*/
static void ext_jit(int (*init)(int, int, size_t, size_t, int, int, int,
uint8_t*, size_t, void**),
void (*finish)(),
void (*compile)(uint64_t, uint64_t, int, uint8_t*, size_t,
int, uint8_t*, size_t, uint8_t*, size_t),
int (*execute)(uint64_t, uint64_t, int, int, void*),
void (*release)(uint64_t, uint64_t),
int (*functions)(uint64_t, uint64_t, int, void*))
{
jit_init = init;
jit_finish = finish;
jit_compile = compile;
jit_execute = execute;
jit_release = release;
}
/*
* NAME: ext->kfuns()
* DESCRIPTION: pass kernel function prototypes to the JIT extension
*/
void ext_kfuns(char *protos, int size, int nkfun)
{
if (jit_compile != NULL) {
static voidf *vmtab[96];
vmtab[ 0] = (voidf *) &ext_vm_int;
vmtab[ 1] = (voidf *) &ext_vm_float;
vmtab[ 2] = (voidf *) &ext_vm_string;
vmtab[ 3] = (voidf *) &ext_vm_param;
vmtab[ 4] = (voidf *) &ext_vm_param_int;
vmtab[ 5] = (voidf *) &ext_vm_param_float;
vmtab[ 6] = (voidf *) &ext_vm_local;
vmtab[ 7] = (voidf *) &ext_vm_local_int;
vmtab[ 8] = (voidf *) &ext_vm_local_float;
vmtab[ 9] = (voidf *) &ext_vm_global;
vmtab[10] = (voidf *) &ext_vm_global_int;
vmtab[11] = (voidf *) &ext_vm_global_float;
vmtab[12] = (voidf *) &ext_vm_index;
vmtab[13] = (voidf *) &ext_vm_index_int;
vmtab[14] = (voidf *) &ext_vm_index2;
vmtab[15] = (voidf *) &ext_vm_index2_int;
vmtab[16] = (voidf *) &ext_vm_aggregate;
vmtab[17] = (voidf *) &ext_vm_map_aggregate;
vmtab[18] = (voidf *) &ext_vm_cast;
vmtab[19] = (voidf *) &ext_vm_cast_int;
vmtab[20] = (voidf *) &ext_vm_cast_float;
vmtab[21] = (voidf *) &ext_vm_instanceof;
vmtab[22] = (voidf *) &ext_vm_range;
vmtab[23] = (voidf *) &ext_vm_range_from;
vmtab[24] = (voidf *) &ext_vm_range_to;
vmtab[25] = (voidf *) &ext_vm_store_param;
vmtab[26] = (voidf *) &ext_vm_store_param_int;
vmtab[27] = (voidf *) &ext_vm_store_param_float;
vmtab[28] = (voidf *) &ext_vm_store_local;
vmtab[29] = (voidf *) &ext_vm_store_local_int;
vmtab[30] = (voidf *) &ext_vm_store_local_float;
vmtab[31] = (voidf *) &ext_vm_store_global;
vmtab[32] = (voidf *) &ext_vm_store_global_int;
vmtab[33] = (voidf *) &ext_vm_store_global_float;
vmtab[34] = (voidf *) &ext_vm_store_index;
vmtab[35] = (voidf *) &ext_vm_store_param_index;
vmtab[36] = (voidf *) &ext_vm_store_local_index;
vmtab[37] = (voidf *) &ext_vm_store_global_index;
vmtab[38] = (voidf *) &ext_vm_store_index_index;
vmtab[39] = (voidf *) &ext_vm_stores;
vmtab[40] = (voidf *) &ext_vm_stores_lval;
vmtab[41] = (voidf *) &ext_vm_stores_spread;
vmtab[42] = (voidf *) &ext_vm_stores_cast;
vmtab[43] = (voidf *) &ext_vm_stores_param;
vmtab[44] = (voidf *) &ext_vm_stores_param_int;
vmtab[45] = (voidf *) &ext_vm_stores_param_float;
vmtab[46] = (voidf *) &ext_vm_stores_local;
vmtab[47] = (voidf *) &ext_vm_stores_local_int;
vmtab[48] = (voidf *) &ext_vm_stores_local_float;
vmtab[49] = (voidf *) &ext_vm_stores_global;
vmtab[50] = (voidf *) &ext_vm_stores_index;
vmtab[51] = (voidf *) &ext_vm_stores_param_index;
vmtab[52] = (voidf *) &ext_vm_stores_local_index;
vmtab[53] = (voidf *) &ext_vm_stores_global_index;
vmtab[54] = (voidf *) &ext_vm_stores_index_index;
vmtab[55] = (voidf *) &ext_vm_div_int;
vmtab[56] = (voidf *) &ext_vm_lshift_int;
vmtab[57] = (voidf *) &ext_vm_mod_int;
vmtab[58] = (voidf *) &ext_vm_rshift_int;
vmtab[59] = (voidf *) &ext_vm_tofloat;
vmtab[60] = (voidf *) &ext_vm_toint;
vmtab[61] = (voidf *) &ext_vm_toint_float;
vmtab[62] = (voidf *) &ext_vm_nil;
vmtab[63] = (voidf *) &ext_vm_add_float;
vmtab[64] = (voidf *) &ext_vm_div_float;
vmtab[65] = (voidf *) &ext_vm_mult_float;
vmtab[66] = (voidf *) &ext_vm_sub_float;
vmtab[67] = (voidf *) &ext_vm_kfunc;
vmtab[68] = (voidf *) &ext_vm_kfunc_int;
vmtab[69] = (voidf *) &ext_vm_kfunc_float;
vmtab[70] = (voidf *) &ext_vm_kfunc_spread;
vmtab[71] = (voidf *) &ext_vm_kfunc_spread_int;
vmtab[72] = (voidf *) &ext_vm_kfunc_spread_float;
vmtab[73] = (voidf *) &ext_vm_kfunc_spread_lval;
vmtab[74] = (voidf *) &ext_vm_dfunc;
vmtab[75] = (voidf *) &ext_vm_dfunc_int;
vmtab[76] = (voidf *) &ext_vm_dfunc_float;
vmtab[77] = (voidf *) &ext_vm_dfunc_spread;
vmtab[78] = (voidf *) &ext_vm_dfunc_spread_int;
vmtab[79] = (voidf *) &ext_vm_dfunc_spread_float;
vmtab[80] = (voidf *) &ext_vm_func;
vmtab[81] = (voidf *) &ext_vm_func_spread;
vmtab[82] = (voidf *) &ext_vm_pop;
vmtab[83] = (voidf *) &ext_vm_pop_bool;
vmtab[84] = (voidf *) &ext_vm_pop_int;
vmtab[85] = (voidf *) &ext_vm_pop_float;
vmtab[86] = (voidf *) &ext_vm_switch_int;
vmtab[87] = (voidf *) &ext_vm_switch_range;
vmtab[88] = (voidf *) &ext_vm_switch_string;
vmtab[89] = (voidf *) &ext_vm_rlimits;
vmtab[90] = (voidf *) &ext_vm_rlimits_end;
vmtab[91] = (voidf *) &ext_vm_catch;
vmtab[92] = (voidf *) &ext_vm_caught;
vmtab[93] = (voidf *) &ext_vm_catch_end;
vmtab[94] = (voidf *) &ext_vm_line;
vmtab[95] = (voidf *) &ext_vm_loop_ticks;
if (!(*jit_init)(VERSION_VM_MAJOR, VERSION_VM_MINOR, sizeof(Int), 1,
conf_typechecking(), KF_BUILTINS, nkfun,
(uint8_t *) protos, size, (void **) vmtab)) {
jit_compile = NULL;
}
}
}
/*
* JIT compile program
*/
static void ext_compile(const Frame *f, Control *ctrl)
{
Object *obj;
int i, j, nftypes;
const Inherit *inh;
char *ft, *vt;
const FuncDef *fdef;
const VarDef *vdef;
/*
* compile new program
*/
obj = OBJ(ctrl->oindex);
if (obj->flags & O_COMPILED) {
return;
}
obj->flags |= O_COMPILED;
/* count function types & variable types */
nftypes = 0;
for (inh = ctrl->inherits, i = ctrl->ninherits; i > 0; inh++, --i) {
nftypes += OBJR(inh->oindex)->control()->nfuncdefs;
}
char *ftypes = ALLOCA(char, ctrl->ninherits + nftypes);
char *vtypes = ALLOCA(char, ctrl->ninherits + ctrl->nvariables);
/* collect function types & variable types */
ft = ftypes;
vt = vtypes;
for (inh = ctrl->inherits, i = ctrl->ninherits; i > 0; inh++, --i) {
ctrl = OBJR(inh->oindex)->ctrl;
ctrl->program();
*ft++ = ctrl->nfuncdefs;
for (fdef = ctrl->funcs(), j = ctrl->nfuncdefs; j > 0; fdef++, --j)
{
*ft++ = PROTO_FTYPE(ctrl->prog + fdef->offset);
}
*vt++ = ctrl->nvardefs;
for (vdef = ctrl->vars(), j = ctrl->nvardefs; j > 0; vdef++, --j) {
*vt++ = vdef->type;
}
}
/* start JIT compiler */
ctrl = f->p_ctrl;
(*jit_compile)(ctrl->oindex, ctrl->instance, ctrl->ninherits,
(uint8_t *) ctrl->prog, ctrl->progsize, ctrl->nfuncdefs,
(uint8_t *) ftypes, ctrl->ninherits + nftypes,
(uint8_t *) vtypes, ctrl->ninherits + ctrl->nvariables);
AFREE(ftypes);
AFREE(vtypes);
}
/*
* NAME: ext->execute()
* DESCRIPTION: JIT-compile and execute a function
*/
bool ext_execute(const Frame *f, int func)
{
Control *ctrl;
int result;
if (jit_compile == NULL) {
return FALSE;
}
ctrl = f->p_ctrl;
if (ctrl->instance == 0) {
return FALSE;
}
if (!setjmp(*ErrorContext::push())) {
result = (*jit_execute)(ctrl->oindex, ctrl->instance, ctrl->version,
func, (void *) f);
ErrorContext::pop();
} else {
error((char *) NULL);
}
if (result < 0) {
ext_compile(f, ctrl);
return FALSE;
} else {
return (bool) result;
}
}
/*
* remove JIT-compiled object
*/
void ext_release(uint64_t index, uint64_t instance)
{
if (jit_compile != NULL) {
(*jit_release)(index, instance);
}
}
/*
* NAME: ext->dgd()
* DESCRIPTION: initialize extension interface
*/
bool ext_dgd(char *module, char *config, void (**fdlist)(int*, int),
void (**finish)())
{
voidf *ext_ext[5];
voidf *ext_frame[4];
voidf *ext_data[2];
voidf *ext_value[4];
voidf *ext_int[2];
voidf *ext_float[2];
voidf *ext_string[5];
voidf *ext_object[6];
voidf *ext_array[6];
voidf *ext_mapping[7];
voidf *ext_runtime[5];
voidf **ftabs[11];
int sizes[11];
int (*init) (int, int, voidf**[], int[], const char*);
init = (int (*) (int, int, voidf**[], int[], const char*))
P_dload(module, "ext_init");
if (init == NULL) {
return FALSE;
}
mod_fdlist = NULL;
mod_finish = NULL;
ext_ext[0] = (voidf *) &kf_ext_kfun;
ext_ext[1] = (voidf *) NULL;
ext_ext[2] = (voidf *) &ext_spawn;
ext_ext[3] = (voidf *) &Connection::fdclose;
ext_ext[4] = (voidf *) &ext_jit;
ext_frame[0] = (voidf *) &ext_frame_object;
ext_frame[1] = (voidf *) &ext_frame_dataspace;
ext_frame[2] = (voidf *) &ext_frame_arg;
ext_frame[3] = (voidf *) &ext_frame_atomic;
ext_data[0] = (voidf *) &Dataspace::extra;
ext_data[1] = (voidf *) &Dataspace::setExtra;
ext_value[0] = (voidf *) &ext_value_type;
ext_value[1] = (voidf *) &ext_value_nil;
ext_value[2] = (voidf *) &ext_value_temp;
ext_value[3] = (voidf *) &ext_value_temp2;
ext_int[0] = (voidf *) &ext_int_getval;
ext_int[1] = (voidf *) &ext_int_putval;
# ifndef NOFLOAT
ext_float[0] = (voidf *) &ext_float_getval;
ext_float[1] = (voidf *) &ext_float_putval;
# else
ext_float[0] = (voidf *) NULL;
ext_float[1] = (voidf *) NULL;
# endif
ext_string[0] = (voidf *) &ext_string_getval;
ext_string[1] = (voidf *) &ext_string_putval;
ext_string[2] = (voidf *) &ext_string_new;
ext_string[3] = (voidf *) &ext_string_text;
ext_string[4] = (voidf *) &ext_string_length;
ext_object[0] = (voidf *) &ext_object_putval;
ext_object[1] = (voidf *) &ext_object_name;
ext_object[2] = (voidf *) &ext_object_isspecial;
ext_object[3] = (voidf *) &ext_object_ismarked;
ext_object[4] = (voidf *) &ext_object_mark;
ext_object[5] = (voidf *) &ext_object_unmark;
ext_array[0] = (voidf *) &ext_array_getval;
ext_array[1] = (voidf *) &ext_array_putval;
ext_array[2] = (voidf *) &ext_array_new;
ext_array[3] = (voidf *) &ext_array_index;
ext_array[4] = (voidf *) &ext_array_assign;
ext_array[5] = (voidf *) &ext_array_size;
ext_mapping[0] = (voidf *) &ext_array_getval;
ext_mapping[1] = (voidf *) &ext_mapping_putval;
ext_mapping[2] = (voidf *) &ext_mapping_new;
ext_mapping[3] = (voidf *) &ext_mapping_index;
ext_mapping[4] = (voidf *) &ext_mapping_assign;
ext_mapping[5] = (voidf *) &ext_mapping_enum;
ext_mapping[6] = (voidf *) &ext_mapping_size;
ext_runtime[0] = (voidf *) &ext_runtime_error;
ext_runtime[1] = (voidf *) &hash_md5_start;
ext_runtime[2] = (voidf *) &hash_md5_block;
ext_runtime[3] = (voidf *) &hash_md5_end;
ext_runtime[4] = (voidf *) &ext_runtime_ticks;
ftabs[ 0] = ext_ext; sizes[ 0] = 5;
ftabs[ 1] = ext_frame; sizes[ 1] = 4;
ftabs[ 2] = ext_data; sizes[ 2] = 2;
ftabs[ 3] = ext_value; sizes[ 3] = 4;
ftabs[ 4] = ext_int; sizes[ 4] = 2;
ftabs[ 5] = ext_float; sizes[ 5] = 2;
ftabs[ 6] = ext_string; sizes[ 6] = 5;
ftabs[ 7] = ext_object; sizes[ 7] = 6;
ftabs[ 8] = ext_array; sizes[ 8] = 6;
ftabs[ 9] = ext_mapping; sizes[ 9] = 7;
ftabs[10] = ext_runtime; sizes[10] = 5;
if (!init(EXTENSION_MAJOR, EXTENSION_MINOR, ftabs, sizes, config)) {
fatal("incompatible runtime extension");
}
*fdlist = mod_fdlist;
*finish = mod_finish;
return TRUE;
}
/*
* NAME: ext->finish()
* DESCRIPTION: finish JIT compiler interface
*/
void ext_finish()
{
if (jit_compile != NULL) {
(*jit_finish)();
}
}
|
// $Id: fe.C,v 1.40 2005-06-12 18:36:40 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 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
// Local includes
#include "dense_matrix.h"
#include "dense_vector.h"
#include "dof_map.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_gauss.h"
#include "elem.h"
#include "libmesh_logging.h"
#include "fe_macro.h"
// ------------------------------------------------------------
// FE class members
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_shape_functions () const
{
return FE<Dim,T>::n_dofs (elem_type, fe_type.order);
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::attach_quadrature_rule (QBase* q)
{
assert (q != NULL);
qrule = q;
// make sure we don't cache results from a previous quadrature rule
elem_type = INVALID_ELEM;
return;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_quadrature_points () const
{
assert (qrule != NULL);
return qrule->n_points();
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_side(const Elem* const elem,
const Order o,
unsigned int s,
std::vector<unsigned int>& di)
{
assert(elem != NULL);
assert(s < elem->n_sides());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
o, n);
if (elem->is_node_on_side(n, s))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_edge(const Elem* const elem,
const Order o,
unsigned int e,
std::vector<unsigned int>& di)
{
assert(elem != NULL);
assert(e < elem->n_edges());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
o, n);
if (elem->is_node_on_edge(n, e))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::reinit(const Elem* elem,
const std::vector<Point>* const pts)
{
assert (elem != NULL);
// Only need the quadrature rule if the user did not supply
// the evaluation points
if (pts == NULL)
{
assert (qrule != NULL);
qrule->init(elem->type());
}
// Initialize the shape functions at the user-specified
// points
if (pts != NULL)
{
// Set the element type
elem_type = elem->type();
// Initialize the shape functions
this->init_shape_functions (*pts, elem);
}
// update the type in accordance to the current cell
// and reinit if the cell type has changed or (as in
// the case of the hierarchics) the shape functions need
// reinit, since they depend on the particular element
else if ((this->get_type() != elem->type()) ||
this->shapes_need_reinit())
{
// Set the element type
elem_type = elem->type();
// Initialize the shape functions
this->init_shape_functions (qrule->get_points(), elem);
}
// Compute the map for this element. In the future we can specify
// different types of maps
if (pts != NULL)
{
std::vector<Real> dummy_weights (pts->size(), 1.);
this->compute_map (dummy_weights, elem);
}
else
{
this->compute_map (qrule->get_weights(), elem);
}
// Compute the shape functions and the derivatives at all of the
// quadrature points.
this->compute_shape_functions (elem);
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_shape_functions(const std::vector<Point>& qp,
const Elem* elem)
{
assert (elem != NULL);
// Start logging the shape function initialization
START_LOG("init_shape_functions()", "FE");
// The number of quadrature points.
const unsigned int n_qp = qp.size();
// The element type and order to use in
// the map
const Order mapping_order (elem->default_order());
const ElemType mapping_elem_type (elem->type());
// Number of shape functions in the finite element approximation
// space.
const unsigned int n_approx_shape_functions =
this->n_shape_functions(this->get_type(),
this->get_order());
// Number of shape functions used to construt the map
// (Lagrange shape functions are used for mapping)
const unsigned int n_mapping_shape_functions =
FE<Dim,LAGRANGE>::n_shape_functions (mapping_elem_type,
mapping_order);
// resize the vectors to hold current data
// Phi are the shape functions used for the FE approximation
// Phi_map are the shape functions used for the FE mapping
{
phi.resize (n_approx_shape_functions);
dphi.resize (n_approx_shape_functions);
dphidx.resize (n_approx_shape_functions);
dphidy.resize (n_approx_shape_functions);
dphidz.resize (n_approx_shape_functions);
dphidxi.resize (n_approx_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phi.resize (n_approx_shape_functions);
d2phidx2.resize (n_approx_shape_functions);
d2phidxdy.resize (n_approx_shape_functions);
d2phidxdz.resize (n_approx_shape_functions);
d2phidy2.resize (n_approx_shape_functions);
d2phidydz.resize (n_approx_shape_functions);
d2phidz2.resize (n_approx_shape_functions);
d2phidxi2.resize (n_approx_shape_functions);
if (Dim > 1)
{
d2phidxideta.resize (n_approx_shape_functions);
d2phideta2.resize (n_approx_shape_functions);
}
if (Dim > 2)
{
d2phidxidzeta.resize (n_approx_shape_functions);
d2phidetadzeta.resize (n_approx_shape_functions);
d2phidzeta2.resize (n_approx_shape_functions);
}
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
dphideta.resize (n_approx_shape_functions);
if (Dim == 3)
dphidzeta.resize (n_approx_shape_functions);
phi_map.resize (n_mapping_shape_functions);
dphidxi_map.resize (n_mapping_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map.resize (n_mapping_shape_functions);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
{
dphideta_map.resize (n_mapping_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxideta_map.resize (n_mapping_shape_functions);
d2phideta2_map.resize (n_mapping_shape_functions);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
if (Dim == 3)
{
dphidzeta_map.resize (n_mapping_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxidzeta_map.resize (n_mapping_shape_functions);
d2phidetadzeta_map.resize (n_mapping_shape_functions);
d2phidzeta2_map.resize (n_mapping_shape_functions);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
for (unsigned int i=0; i<n_approx_shape_functions; i++)
{
phi[i].resize (n_qp);
dphi[i].resize (n_qp);
dphidx[i].resize (n_qp);
dphidy[i].resize (n_qp);
dphidz[i].resize (n_qp);
dphidxi[i].resize (n_qp);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phi[i].resize (n_qp);
d2phidx2[i].resize (n_qp);
d2phidxdy[i].resize (n_qp);
d2phidxdz[i].resize (n_qp);
d2phidy2[i].resize (n_qp);
d2phidydz[i].resize (n_qp);
d2phidz2[i].resize (n_qp);
d2phidxi2[i].resize (n_qp);
if (Dim > 1)
{
d2phidxideta[i].resize (n_qp);
d2phideta2[i].resize (n_qp);
}
if (Dim > 2)
{
d2phidxidzeta[i].resize (n_qp);
d2phidetadzeta[i].resize (n_qp);
d2phidzeta2[i].resize (n_qp);
}
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
dphideta[i].resize (n_qp);
if (Dim == 3)
dphidzeta[i].resize (n_qp);
}
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
{
phi_map[i].resize (n_qp);
dphidxi_map[i].resize (n_qp);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i].resize (n_qp);
if (Dim > 1)
{
d2phidxideta_map[i].resize (n_qp);
d2phideta2_map[i].resize (n_qp);
}
if (Dim > 2)
{
d2phidxidzeta_map[i].resize (n_qp);
d2phidetadzeta_map[i].resize (n_qp);
d2phidzeta2_map[i].resize (n_qp);
}
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
dphideta_map[i].resize (n_qp);
if (Dim == 3)
dphidzeta_map[i].resize (n_qp);
}
}
#ifdef ENABLE_INFINITE_ELEMENTS
//------------------------------------------------------------
// Initialize the data fields, which should only be used for infinite
// elements, to some sensible values, so that using a FE with the
// variational formulation of an InfFE, correct element matrices are
// returned
{
weight.resize (n_qp);
dweight.resize (n_qp);
dphase.resize (n_qp);
for (unsigned int p=0; p<n_qp; p++)
{
weight[p] = 1.;
dweight[p].zero();
dphase[p].zero();
}
}
#endif // ifdef ENABLE_INFINITE_ELEMENTS
switch (Dim)
{
//------------------------------------------------------------
// 1D
case 1:
{
// Compute the value of the approximation shape function i at quadrature point p
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi[i][p] = FE<Dim,T>::shape (elem, this->get_order(), i, qp[p]);
dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 0, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 0, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
// Compute the value of the mapping shape function i at quadrature point p
// (Lagrange shape functions are used for mapping)
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
break;
}
//------------------------------------------------------------
// 2D
case 2:
{
// Compute the value of the approximation shape function i at quadrature point p
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi[i][p] = FE<Dim,T>::shape (elem, this->get_order(), i, qp[p]);
dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 0, qp[p]);
dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 1, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 0, qp[p]);
d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 1, qp[p]);
d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 2, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
// Compute the value of the mapping shape function i at quadrature point p
// (Lagrange shape functions are used for mapping)
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
dphideta_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
d2phidxideta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
d2phideta2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 2, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
break;
}
//------------------------------------------------------------
// 3D
case 3:
{
// Compute the value of the approximation shape function i at quadrature point p
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi[i][p] = FE<Dim,T>::shape (elem, this->get_order(), i, qp[p]);
dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 0, qp[p]);
dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 1, qp[p]);
dphidzeta[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 2, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 0, qp[p]);
d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 1, qp[p]);
d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 2, qp[p]);
d2phidxidzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 3, qp[p]);
d2phidetadzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 4, qp[p]);
d2phidzeta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 5, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
// Compute the value of the mapping shape function i at quadrature point p
// (Lagrange shape functions are used for mapping)
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
dphideta_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
dphidzeta_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 2, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
d2phidxideta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
d2phideta2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 2, qp[p]);
d2phidxideta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 3, qp[p]);
d2phidetadzeta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 4, qp[p]);
d2phidzeta2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 5, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
break;
}
default:
error();
}
// Stop logging the shape function initialization
STOP_LOG("init_shape_functions()", "FE");
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_proj_constraints (DofConstraints &constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
#ifdef ENABLE_AMR
// Only constrain elements in 2,3D.
if (Dim == 1)
return;
assert (elem != NULL);
const FEType& fe_type = dof_map.variable_type(variable_number);
AutoPtr<FEBase> my_fe (FEBase::build(Dim, fe_type));
const FEContinuity cont = my_fe->get_continuity();
if (cont == DISCONTINUOUS)
return;
assert (cont == C_ZERO || cont == C_ONE);
AutoPtr<FEBase> parent_fe (FEBase::build(Dim, fe_type));
QGauss my_qface(Dim-1, fe_type.default_quadrature_order());
my_fe->attach_quadrature_rule (&my_qface);
std::vector<Point> parent_qface;
const std::vector<Real>& JxW = my_fe->get_JxW();
const std::vector<Point>& q_point = my_fe->get_xyz();
const std::vector<std::vector<Real> >& phi = my_fe->get_phi();
const std::vector<std::vector<Real> >& parent_phi =
parent_fe->get_phi();
const std::vector<Point> *face_normals = NULL;
const std::vector<std::vector<RealGradient> > *dphi = NULL;
const std::vector<std::vector<RealGradient> > *parent_dphi = NULL;
std::vector<unsigned int> child_dof_indices, parent_dof_indices;
std::vector<unsigned int> my_side_dofs, parent_side_dofs;
if (cont != C_ZERO)
{
const std::vector<Point>& ref_face_normals =
my_fe->get_normals();
face_normals = &ref_face_normals;
const std::vector<std::vector<RealGradient> >& ref_dphi =
my_fe->get_dphi();
dphi = &ref_dphi;
const std::vector<std::vector<RealGradient> >& ref_parent_dphi =
parent_fe->get_dphi();
parent_dphi = &ref_parent_dphi;
}
DenseMatrix<Real> Ke;
DenseVector<Real> Fe;
std::vector<DenseVector<Real> > Ue;
// Look at the element faces. Check to see if we need to
// build constraints.
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) != NULL)
// constrain dofs shared between
// this element and ones coarser
// than this element.
if (elem->neighbor(s)->level() < elem->level())
{
// Get pointers to the elements of interest and its parent.
const Elem* parent = elem->parent();
unsigned int s_parent = s;
// This can't happen... Only level-0 elements have NULL
// parents, and no level-0 elements can be at a higher
// level than their neighbors!
assert (parent != NULL);
my_fe->reinit(elem, s);
dof_map.dof_indices (elem, child_dof_indices,
variable_number);
dof_map.dof_indices (parent, parent_dof_indices,
variable_number);
const unsigned int n_qp = my_qface.n_points();
FEInterface::inverse_map (Dim, fe_type, parent, q_point,
parent_qface);
parent_fe->reinit(parent, &parent_qface);
// We're only concerned with DOFs whose values (and/or first
// derivatives for C1 elements) are supported on side nodes
dofs_on_side(elem, fe_type.order, s, my_side_dofs);
dofs_on_side(parent, fe_type.order, s_parent, parent_side_dofs);
const unsigned int n_side_dofs = my_side_dofs.size();
assert(n_side_dofs == parent_side_dofs.size());
Ke.resize (n_side_dofs, n_side_dofs);
Ue.resize(n_side_dofs);
// Form the projection matrix, (inner product of fine basis
// functions against fine test functions)
for (unsigned int is = 0; is != n_side_dofs; ++is)
{
const unsigned int i = my_side_dofs[is];
for (unsigned int js = 0; js != n_side_dofs; ++js)
{
const unsigned int j = my_side_dofs[js];
for (unsigned int qp = 0; qp != n_qp; ++qp)
{
Ke(is,js) += JxW[qp] * (phi[i][qp] * phi[j][qp]);
if (cont != C_ZERO)
Ke(is,js) += JxW[qp] * (((*dphi)[i][qp] *
(*face_normals)[qp]) *
((*dphi)[j][qp] *
(*face_normals)[qp]));
}
}
}
// Form the right hand sides, (inner product of coarse basis
// functions against fine test functions)
for (unsigned int is = 0; is != n_side_dofs; ++is)
{
const unsigned int i = parent_side_dofs[is];
Fe.resize (n_side_dofs);
for (unsigned int js = 0; js != n_side_dofs; ++js)
{
const unsigned int j = my_side_dofs[js];
for (unsigned int qp = 0; qp != n_qp; ++qp)
{
Fe(js) += JxW[qp] * (parent_phi[i][qp] *
phi[j][qp]);
if (cont != C_ZERO)
Fe(js) += JxW[qp] * (((*parent_dphi)[i][qp] *
(*face_normals)[qp]) *
((*dphi)[j][qp] *
(*face_normals)[qp]));
}
}
Ke.cholesky_solve(Fe, Ue[is]);
}
for (unsigned int is = 0; is != n_side_dofs; ++is)
{
const unsigned int i = parent_side_dofs[is];
const unsigned int their_dof_g = parent_dof_indices[i];
for (unsigned int js = 0; js != n_side_dofs; ++js)
{
const unsigned int j = my_side_dofs[js];
const unsigned int my_dof_g = child_dof_indices[j];
const Real their_dof_value = Ue[is](js);
if (their_dof_g == my_dof_g)
{
assert(std::abs(their_dof_value-1.) < 1.e-5);
for (unsigned int k = 0; k != n_side_dofs; ++k)
assert(k == is || std::abs(Ue[k](is)) < 1.e-5);
continue;
}
if (std::abs(their_dof_value) < 1.e-5)
continue;
DofConstraintRow& constraint_row =
constraints[my_dof_g];
constraint_row.insert(std::make_pair(their_dof_g,
their_dof_value));
}
}
}
#endif
}
#ifdef ENABLE_INFINITE_ELEMENTS
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_base_shape_functions(const std::vector<Point>& qp,
const Elem* e)
{
elem_type = e->type();
init_shape_functions(qp, e);
}
#endif
//--------------------------------------------------------------
// Explicit instantiations using macro from fe_macro.h
INSTANTIATE_FE(1);
INSTANTIATE_FE(2);
INSTANTIATE_FE(3);
Attempting to optimize for affine map case
git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@1223 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
// $Id: fe.C,v 1.41 2005-06-29 20:44:09 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 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
// Local includes
#include "dense_matrix.h"
#include "dense_vector.h"
#include "dof_map.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_gauss.h"
#include "elem.h"
#include "libmesh_logging.h"
#include "fe_macro.h"
// ------------------------------------------------------------
// FE class members
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_shape_functions () const
{
return FE<Dim,T>::n_dofs (elem_type, fe_type.order);
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::attach_quadrature_rule (QBase* q)
{
assert (q != NULL);
qrule = q;
// make sure we don't cache results from a previous quadrature rule
elem_type = INVALID_ELEM;
return;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_quadrature_points () const
{
assert (qrule != NULL);
return qrule->n_points();
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_side(const Elem* const elem,
const Order o,
unsigned int s,
std::vector<unsigned int>& di)
{
assert(elem != NULL);
assert(s < elem->n_sides());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
o, n);
if (elem->is_node_on_side(n, s))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_edge(const Elem* const elem,
const Order o,
unsigned int e,
std::vector<unsigned int>& di)
{
assert(elem != NULL);
assert(e < elem->n_edges());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
o, n);
if (elem->is_node_on_edge(n, e))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::reinit(const Elem* elem,
const std::vector<Point>* const pts)
{
assert (elem != NULL);
// Only need the quadrature rule if the user did not supply
// the evaluation points
if (pts == NULL)
{
assert (qrule != NULL);
qrule->init(elem->type());
}
// Initialize the shape functions at the user-specified
// points
if (pts != NULL)
{
// Set the element type
elem_type = elem->type();
// Initialize the shape functions
this->init_shape_functions (*pts, elem);
}
// update the type in accordance to the current cell
// and reinit if the cell type has changed or (as in
// the case of the hierarchics) the shape functions need
// reinit, since they depend on the particular element
else if ((this->get_type() != elem->type()) ||
this->shapes_need_reinit())
{
// Set the element type
elem_type = elem->type();
// Initialize the shape functions
this->init_shape_functions (qrule->get_points(), elem);
}
// Compute the map for this element. In the future we can specify
// different types of maps
if (pts != NULL)
{
std::vector<Real> dummy_weights (pts->size(), 1.);
this->compute_map (dummy_weights, elem);
}
else
{
this->compute_map (qrule->get_weights(), elem);
}
// Compute the shape functions and the derivatives at all of the
// quadrature points.
this->compute_shape_functions (elem);
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_shape_functions(const std::vector<Point>& qp,
const Elem* elem)
{
assert (elem != NULL);
// Start logging the shape function initialization
START_LOG("init_shape_functions()", "FE");
// The number of quadrature points.
const unsigned int n_qp = qp.size();
// The element type and order to use in
// the map
const Order mapping_order (elem->default_order());
const ElemType mapping_elem_type (elem->type());
// Number of shape functions in the finite element approximation
// space.
const unsigned int n_approx_shape_functions =
this->n_shape_functions(this->get_type(),
this->get_order());
// Number of shape functions used to construt the map
// (Lagrange shape functions are used for mapping)
const unsigned int n_mapping_shape_functions =
FE<Dim,LAGRANGE>::n_shape_functions (mapping_elem_type,
mapping_order);
// resize the vectors to hold current data
// Phi are the shape functions used for the FE approximation
// Phi_map are the shape functions used for the FE mapping
{
phi.resize (n_approx_shape_functions);
dphi.resize (n_approx_shape_functions);
dphidx.resize (n_approx_shape_functions);
dphidy.resize (n_approx_shape_functions);
dphidz.resize (n_approx_shape_functions);
dphidxi.resize (n_approx_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phi.resize (n_approx_shape_functions);
d2phidx2.resize (n_approx_shape_functions);
d2phidxdy.resize (n_approx_shape_functions);
d2phidxdz.resize (n_approx_shape_functions);
d2phidy2.resize (n_approx_shape_functions);
d2phidydz.resize (n_approx_shape_functions);
d2phidz2.resize (n_approx_shape_functions);
d2phidxi2.resize (n_approx_shape_functions);
if (Dim > 1)
{
d2phidxideta.resize (n_approx_shape_functions);
d2phideta2.resize (n_approx_shape_functions);
}
if (Dim > 2)
{
d2phidxidzeta.resize (n_approx_shape_functions);
d2phidetadzeta.resize (n_approx_shape_functions);
d2phidzeta2.resize (n_approx_shape_functions);
}
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
dphideta.resize (n_approx_shape_functions);
if (Dim == 3)
dphidzeta.resize (n_approx_shape_functions);
phi_map.resize (n_mapping_shape_functions);
dphidxi_map.resize (n_mapping_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map.resize (n_mapping_shape_functions);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
{
dphideta_map.resize (n_mapping_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxideta_map.resize (n_mapping_shape_functions);
d2phideta2_map.resize (n_mapping_shape_functions);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
if (Dim == 3)
{
dphidzeta_map.resize (n_mapping_shape_functions);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxidzeta_map.resize (n_mapping_shape_functions);
d2phidetadzeta_map.resize (n_mapping_shape_functions);
d2phidzeta2_map.resize (n_mapping_shape_functions);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
for (unsigned int i=0; i<n_approx_shape_functions; i++)
{
phi[i].resize (n_qp);
dphi[i].resize (n_qp);
dphidx[i].resize (n_qp);
dphidy[i].resize (n_qp);
dphidz[i].resize (n_qp);
dphidxi[i].resize (n_qp);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phi[i].resize (n_qp);
d2phidx2[i].resize (n_qp);
d2phidxdy[i].resize (n_qp);
d2phidxdz[i].resize (n_qp);
d2phidy2[i].resize (n_qp);
d2phidydz[i].resize (n_qp);
d2phidz2[i].resize (n_qp);
d2phidxi2[i].resize (n_qp);
if (Dim > 1)
{
d2phidxideta[i].resize (n_qp);
d2phideta2[i].resize (n_qp);
}
if (Dim > 2)
{
d2phidxidzeta[i].resize (n_qp);
d2phidetadzeta[i].resize (n_qp);
d2phidzeta2[i].resize (n_qp);
}
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
dphideta[i].resize (n_qp);
if (Dim == 3)
dphidzeta[i].resize (n_qp);
}
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
{
phi_map[i].resize (n_qp);
dphidxi_map[i].resize (n_qp);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i].resize (n_qp);
if (Dim > 1)
{
d2phidxideta_map[i].resize (n_qp);
d2phideta2_map[i].resize (n_qp);
}
if (Dim > 2)
{
d2phidxidzeta_map[i].resize (n_qp);
d2phidetadzeta_map[i].resize (n_qp);
d2phidzeta2_map[i].resize (n_qp);
}
#endif // ifdef ENABLE_SECOND_DERIVATIVES
if (Dim > 1)
dphideta_map[i].resize (n_qp);
if (Dim == 3)
dphidzeta_map[i].resize (n_qp);
}
}
#ifdef ENABLE_INFINITE_ELEMENTS
//------------------------------------------------------------
// Initialize the data fields, which should only be used for infinite
// elements, to some sensible values, so that using a FE with the
// variational formulation of an InfFE, correct element matrices are
// returned
{
weight.resize (n_qp);
dweight.resize (n_qp);
dphase.resize (n_qp);
for (unsigned int p=0; p<n_qp; p++)
{
weight[p] = 1.;
dweight[p].zero();
dphase[p].zero();
}
}
#endif // ifdef ENABLE_INFINITE_ELEMENTS
// Optimize for the affine elements case:
bool has_affine_map = elem->has_affine_map();
switch (Dim)
{
//------------------------------------------------------------
// 1D
case 1:
{
// Compute the value of the approximation shape function i at quadrature point p
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi[i][p] = FE<Dim,T>::shape (elem, this->get_order(), i, qp[p]);
dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 0, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 0, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
// Compute the value of the mapping shape function i at quadrature point p
// (Lagrange shape functions are used for mapping)
if (has_affine_map)
{
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
{
phi_map[i][0] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[0]);
dphidxi_map[i][0] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[0]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[0]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
for (unsigned int p=1; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = dphidxi_map[i][0];
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = d2phidxi2_map[i][0];
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
}
}
else
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
break;
}
//------------------------------------------------------------
// 2D
case 2:
{
// Compute the value of the approximation shape function i at quadrature point p
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi[i][p] = FE<Dim,T>::shape (elem, this->get_order(), i, qp[p]);
dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 0, qp[p]);
dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 1, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 0, qp[p]);
d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 1, qp[p]);
d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 2, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
// Compute the value of the mapping shape function i at quadrature point p
// (Lagrange shape functions are used for mapping)
if (has_affine_map)
{
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
{
phi_map[i][0] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[0]);
dphidxi_map[i][0] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[0]);
dphideta_map[i][0] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, qp[0]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[0]);
d2phidxideta_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 1, qp[0]);
d2phideta2_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 2, qp[0]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
for (unsigned int p=1; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = dphidxi_map[i][0];
dphideta_map[i][p] = dphideta_map[i][0];
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = d2phidxi2_map[i][0];
d2phidxideta_map[i][p] = d2phidxideta_map[i][0];
d2phideta2_map[i][p] = d2phideta2_map[i][0];
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
}
}
else
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
dphideta_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
d2phidxideta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
d2phideta2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 2, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
break;
}
//------------------------------------------------------------
// 3D
case 3:
{
// Compute the value of the approximation shape function i at quadrature point p
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi[i][p] = FE<Dim,T>::shape (elem, this->get_order(), i, qp[p]);
dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 0, qp[p]);
dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 1, qp[p]);
dphidzeta[i][p] = FE<Dim,T>::shape_deriv (elem, this->get_order(), i, 2, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 0, qp[p]);
d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 1, qp[p]);
d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 2, qp[p]);
d2phidxidzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 3, qp[p]);
d2phidetadzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 4, qp[p]);
d2phidzeta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->get_order(), i, 5, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
// Compute the value of the mapping shape function i at quadrature point p
// (Lagrange shape functions are used for mapping)
if (has_affine_map)
{
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
{
phi_map[i][0] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[0]);
dphidxi_map[i][0] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[0]);
dphideta_map[i][0] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, qp[0]);
dphidzeta_map[i][0] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 2, qp[0]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[0]);
d2phidxideta_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 1, qp[0]);
d2phideta2_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 2, qp[0]);
d2phidxideta_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 3, qp[0]);
d2phidetadzeta_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 4, qp[0]);
d2phidzeta2_map[i][0] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 5, qp[0]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
for (unsigned int p=1; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = dphidxi_map[i][0];
dphideta_map[i][p] = dphideta_map[i][0];
dphidzeta_map[i][p] = dphidzeta_map[i][0];
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = d2phidxi2_map[i][0];
d2phidxideta_map[i][p] = d2phidxideta_map[i][0];
d2phideta2_map[i][p] = d2phideta2_map[i][0];
d2phidxideta_map[i][p] = d2phidxideta_map[i][0];
d2phidetadzeta_map[i][p] = d2phidetadzeta_map[i][0];
d2phidzeta2_map[i][p] = d2phidzeta2_map[i][0];
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
}
}
else
for (unsigned int i=0; i<n_mapping_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
phi_map[i][p] = FE<Dim,LAGRANGE>::shape (mapping_elem_type, mapping_order, i, qp[p]);
dphidxi_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
dphideta_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
dphidzeta_map[i][p] = FE<Dim,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 2, qp[p]);
#ifdef ENABLE_SECOND_DERIVATIVES
d2phidxi2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 0, qp[p]);
d2phidxideta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 1, qp[p]);
d2phideta2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 2, qp[p]);
d2phidxideta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 3, qp[p]);
d2phidetadzeta_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 4, qp[p]);
d2phidzeta2_map[i][p] = FE<Dim,LAGRANGE>::shape_second_deriv (mapping_elem_type, mapping_order, i, 5, qp[p]);
#endif // ifdef ENABLE_SECOND_DERIVATIVES
}
break;
}
default:
error();
}
// Stop logging the shape function initialization
STOP_LOG("init_shape_functions()", "FE");
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_proj_constraints (DofConstraints &constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
#ifdef ENABLE_AMR
// Only constrain elements in 2,3D.
if (Dim == 1)
return;
assert (elem != NULL);
const FEType& fe_type = dof_map.variable_type(variable_number);
AutoPtr<FEBase> my_fe (FEBase::build(Dim, fe_type));
const FEContinuity cont = my_fe->get_continuity();
if (cont == DISCONTINUOUS)
return;
assert (cont == C_ZERO || cont == C_ONE);
AutoPtr<FEBase> parent_fe (FEBase::build(Dim, fe_type));
QGauss my_qface(Dim-1, fe_type.default_quadrature_order());
my_fe->attach_quadrature_rule (&my_qface);
std::vector<Point> parent_qface;
const std::vector<Real>& JxW = my_fe->get_JxW();
const std::vector<Point>& q_point = my_fe->get_xyz();
const std::vector<std::vector<Real> >& phi = my_fe->get_phi();
const std::vector<std::vector<Real> >& parent_phi =
parent_fe->get_phi();
const std::vector<Point> *face_normals = NULL;
const std::vector<std::vector<RealGradient> > *dphi = NULL;
const std::vector<std::vector<RealGradient> > *parent_dphi = NULL;
std::vector<unsigned int> child_dof_indices, parent_dof_indices;
std::vector<unsigned int> my_side_dofs, parent_side_dofs;
if (cont != C_ZERO)
{
const std::vector<Point>& ref_face_normals =
my_fe->get_normals();
face_normals = &ref_face_normals;
const std::vector<std::vector<RealGradient> >& ref_dphi =
my_fe->get_dphi();
dphi = &ref_dphi;
const std::vector<std::vector<RealGradient> >& ref_parent_dphi =
parent_fe->get_dphi();
parent_dphi = &ref_parent_dphi;
}
DenseMatrix<Real> Ke;
DenseVector<Real> Fe;
std::vector<DenseVector<Real> > Ue;
// Look at the element faces. Check to see if we need to
// build constraints.
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) != NULL)
// constrain dofs shared between
// this element and ones coarser
// than this element.
if (elem->neighbor(s)->level() < elem->level())
{
// Get pointers to the elements of interest and its parent.
const Elem* parent = elem->parent();
unsigned int s_parent = s;
// This can't happen... Only level-0 elements have NULL
// parents, and no level-0 elements can be at a higher
// level than their neighbors!
assert (parent != NULL);
my_fe->reinit(elem, s);
dof_map.dof_indices (elem, child_dof_indices,
variable_number);
dof_map.dof_indices (parent, parent_dof_indices,
variable_number);
const unsigned int n_qp = my_qface.n_points();
FEInterface::inverse_map (Dim, fe_type, parent, q_point,
parent_qface);
parent_fe->reinit(parent, &parent_qface);
// We're only concerned with DOFs whose values (and/or first
// derivatives for C1 elements) are supported on side nodes
dofs_on_side(elem, fe_type.order, s, my_side_dofs);
dofs_on_side(parent, fe_type.order, s_parent, parent_side_dofs);
const unsigned int n_side_dofs = my_side_dofs.size();
assert(n_side_dofs == parent_side_dofs.size());
Ke.resize (n_side_dofs, n_side_dofs);
Ue.resize(n_side_dofs);
// Form the projection matrix, (inner product of fine basis
// functions against fine test functions)
for (unsigned int is = 0; is != n_side_dofs; ++is)
{
const unsigned int i = my_side_dofs[is];
for (unsigned int js = 0; js != n_side_dofs; ++js)
{
const unsigned int j = my_side_dofs[js];
for (unsigned int qp = 0; qp != n_qp; ++qp)
{
Ke(is,js) += JxW[qp] * (phi[i][qp] * phi[j][qp]);
if (cont != C_ZERO)
Ke(is,js) += JxW[qp] * (((*dphi)[i][qp] *
(*face_normals)[qp]) *
((*dphi)[j][qp] *
(*face_normals)[qp]));
}
}
}
// Form the right hand sides, (inner product of coarse basis
// functions against fine test functions)
for (unsigned int is = 0; is != n_side_dofs; ++is)
{
const unsigned int i = parent_side_dofs[is];
Fe.resize (n_side_dofs);
for (unsigned int js = 0; js != n_side_dofs; ++js)
{
const unsigned int j = my_side_dofs[js];
for (unsigned int qp = 0; qp != n_qp; ++qp)
{
Fe(js) += JxW[qp] * (parent_phi[i][qp] *
phi[j][qp]);
if (cont != C_ZERO)
Fe(js) += JxW[qp] * (((*parent_dphi)[i][qp] *
(*face_normals)[qp]) *
((*dphi)[j][qp] *
(*face_normals)[qp]));
}
}
Ke.cholesky_solve(Fe, Ue[is]);
}
for (unsigned int is = 0; is != n_side_dofs; ++is)
{
const unsigned int i = parent_side_dofs[is];
const unsigned int their_dof_g = parent_dof_indices[i];
for (unsigned int js = 0; js != n_side_dofs; ++js)
{
const unsigned int j = my_side_dofs[js];
const unsigned int my_dof_g = child_dof_indices[j];
const Real their_dof_value = Ue[is](js);
if (their_dof_g == my_dof_g)
{
assert(std::abs(their_dof_value-1.) < 1.e-5);
for (unsigned int k = 0; k != n_side_dofs; ++k)
assert(k == is || std::abs(Ue[k](is)) < 1.e-5);
continue;
}
if (std::abs(their_dof_value) < 1.e-5)
continue;
DofConstraintRow& constraint_row =
constraints[my_dof_g];
constraint_row.insert(std::make_pair(their_dof_g,
their_dof_value));
}
}
}
#endif
}
#ifdef ENABLE_INFINITE_ELEMENTS
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_base_shape_functions(const std::vector<Point>& qp,
const Elem* e)
{
elem_type = e->type();
init_shape_functions(qp, e);
}
#endif
//--------------------------------------------------------------
// Explicit instantiations using macro from fe_macro.h
INSTANTIATE_FE(1);
INSTANTIATE_FE(2);
INSTANTIATE_FE(3);
|
// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 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
// Local includes
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/fe_interface.h"
#include "libmesh/fe_macro.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/quadrature.h"
#include "libmesh/tensor_value.h"
namespace libMesh
{
// ------------------------------------------------------------
// FE class members
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_shape_functions () const
{
return FE<Dim,T>::n_dofs (this->elem_type,
static_cast<Order>(this->fe_type.order + this->_p_level));
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::attach_quadrature_rule (QBase* q)
{
libmesh_assert(q);
this->qrule = q;
// make sure we don't cache results from a previous quadrature rule
this->elem_type = INVALID_ELEM;
return;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_quadrature_points () const
{
libmesh_assert(this->qrule);
return this->qrule->n_points();
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_side(const Elem* const elem,
const Order o,
unsigned int s,
std::vector<unsigned int>& di)
{
libmesh_assert(elem);
libmesh_assert_less (s, elem->n_sides());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
static_cast<Order>(o + elem->p_level()), n);
if (elem->is_node_on_side(n, s))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_edge(const Elem* const elem,
const Order o,
unsigned int e,
std::vector<unsigned int>& di)
{
libmesh_assert(elem);
libmesh_assert_less (e, elem->n_edges());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
static_cast<Order>(o + elem->p_level()), n);
if (elem->is_node_on_edge(n, e))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::reinit(const Elem* elem,
const std::vector<Point>* pts,
const std::vector<Real>* const weights)
{
// We can be called with no element. If we're evaluating SCALAR
// dofs we'll still have work to do.
// libmesh_assert(elem);
// Try to avoid calling init_shape_functions
// even when shapes_need_reinit
bool cached_nodes_still_fit = false;
// Most of the hard work happens when we have an actual element
if (elem)
{
// Initialize the shape functions at the user-specified
// points
if (pts != NULL && elem)
{
// Set the type and p level for this element
this->elem_type = elem->type();
this->_p_level = elem->p_level();
// Initialize the shape functions
this->_fe_map->template init_reference_to_physical_map<Dim>
(*pts, elem);
this->init_shape_functions (*pts, elem);
// The shape functions do not correspond to the qrule
this->shapes_on_quadrature = false;
}
// If there are no user specified points, we use the
// quadrature rule
// update the type in accordance to the current cell
// and reinit if the cell type has changed or (as in
// the case of the hierarchics) the shape functions need
// reinit, since they depend on the particular element shape
else
{
libmesh_assert(this->qrule);
this->qrule->init(elem->type(), elem->p_level());
if(this->qrule->shapes_need_reinit())
this->shapes_on_quadrature = false;
if (this->elem_type != elem->type() ||
this->_p_level != elem->p_level() ||
!this->shapes_on_quadrature)
{
// Set the type and p level for this element
this->elem_type = elem->type();
this->_p_level = elem->p_level();
// Initialize the shape functions
this->_fe_map->template init_reference_to_physical_map<Dim>
(this->qrule->get_points(), elem);
this->init_shape_functions (this->qrule->get_points(), elem);
if (this->shapes_need_reinit())
{
cached_nodes.resize(elem->n_nodes());
for (unsigned int n = 0; n != elem->n_nodes(); ++n)
{
cached_nodes[n] = elem->point(n);
}
}
}
else
{
// libmesh_assert_greater (elem->n_nodes(), 1);
cached_nodes_still_fit = true;
if (cached_nodes.size() != elem->n_nodes())
cached_nodes_still_fit = false;
else
for (unsigned int n = 1; n < elem->n_nodes(); ++n)
{
if (!(elem->point(n) - elem->point(0)).relative_fuzzy_equals
((cached_nodes[n] - cached_nodes[0]), 1e-13))
{
cached_nodes_still_fit = false;
break;
}
}
if (this->shapes_need_reinit() && !cached_nodes_still_fit)
{
this->_fe_map->template init_reference_to_physical_map<Dim>
(this->qrule->get_points(), elem);
this->init_shape_functions (this->qrule->get_points(), elem);
cached_nodes.resize(elem->n_nodes());
for (unsigned int n = 0; n != elem->n_nodes(); ++n)
cached_nodes[n] = elem->point(n);
}
}
// The shape functions correspond to the qrule
this->shapes_on_quadrature = true;
}
// Compute the map for this element. In the future we can specify
// different types of maps
if (pts != NULL)
{
if (weights != NULL)
{
this->_fe_map->compute_map (this->dim,*weights, elem);
}
else
{
std::vector<Real> dummy_weights (pts->size(), 1.);
this->_fe_map->compute_map (this->dim,dummy_weights, elem);
}
}
else
{
this->_fe_map->compute_map (this->dim,this->qrule->get_weights(), elem);
}
}
else // With no defined elem, so mapping or caching to
// be done, and our "quadrature rule" is one point for nonlocal
// (SCALAR) variables and zero points for local variables.
{
this->elem_type = INVALID_ELEM;
this->_p_level = 0;
if (!pts)
{
if (T == SCALAR)
{
this->qrule->get_points() =
std::vector<Point>(1,Point(0));
this->qrule->get_weights() =
std::vector<Real>(1,1);
}
else
{
this->qrule->get_points().clear();
this->qrule->get_weights().clear();
}
this->init_shape_functions
(this->qrule->get_points(), elem);
}
else
this->init_shape_functions (*pts, elem);
}
// Compute the shape functions and the derivatives at all of the
// quadrature points.
if (!cached_nodes_still_fit)
{
if (pts != NULL)
this->compute_shape_functions (elem,*pts);
else
this->compute_shape_functions(elem,this->qrule->get_points());
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_shape_functions(const std::vector<Point>& qp,
const Elem* elem)
{
// We can be called with no element. If we're evaluating SCALAR
// dofs we'll still have work to do.
// libmesh_assert(elem);
this->calculations_started = true;
// If the user forgot to request anything, we'll be safe and
// calculate everything:
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (!this->calculate_phi && !this->calculate_dphi && !this->calculate_d2phi
&& !this->calculate_curl_phi && !this->calculate_div_phi)
{
this->calculate_phi = this->calculate_dphi = this->calculate_d2phi = this->calculate_dphiref = true;
if( FEInterface::field_type(T) == TYPE_VECTOR )
{
this->calculate_curl_phi = true;
this->calculate_div_phi = true;
}
}
#else
if (!this->calculate_phi && !this->calculate_dphi && !this->calculate_curl_phi && !this->calculate_div_phi)
{
this->calculate_phi = this->calculate_dphi = this->calculate_dphiref = true;
if( FEInterface::field_type(T) == TYPE_VECTOR )
{
this->calculate_curl_phi = true;
this->calculate_div_phi = true;
}
}
#endif // LIBMESH_ENABLE_SECOND_DERIVATIVES
// Start logging the shape function initialization
START_LOG("init_shape_functions()", "FE");
// The number of quadrature points.
const unsigned int n_qp = libmesh_cast_int<unsigned int>(qp.size());
// Number of shape functions in the finite element approximation
// space.
const unsigned int n_approx_shape_functions =
this->n_shape_functions(this->get_type(),
this->get_order());
// resize the vectors to hold current data
// Phi are the shape functions used for the FE approximation
// Phi_map are the shape functions used for the FE mapping
if (this->calculate_phi)
this->phi.resize (n_approx_shape_functions);
if (this->calculate_dphi)
{
this->dphi.resize (n_approx_shape_functions);
this->dphidx.resize (n_approx_shape_functions);
this->dphidy.resize (n_approx_shape_functions);
this->dphidz.resize (n_approx_shape_functions);
}
if(this->calculate_dphiref)
{
if (Dim > 0)
this->dphidxi.resize (n_approx_shape_functions);
if (Dim > 1)
this->dphideta.resize (n_approx_shape_functions);
if (Dim > 2)
this->dphidzeta.resize (n_approx_shape_functions);
}
if( this->calculate_curl_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->curl_phi.resize(n_approx_shape_functions);
if( this->calculate_div_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->div_phi.resize(n_approx_shape_functions);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
{
this->d2phi.resize (n_approx_shape_functions);
this->d2phidx2.resize (n_approx_shape_functions);
this->d2phidxdy.resize (n_approx_shape_functions);
this->d2phidxdz.resize (n_approx_shape_functions);
this->d2phidy2.resize (n_approx_shape_functions);
this->d2phidydz.resize (n_approx_shape_functions);
this->d2phidz2.resize (n_approx_shape_functions);
if (Dim > 0)
this->d2phidxi2.resize (n_approx_shape_functions);
if (Dim > 1)
{
this->d2phidxideta.resize (n_approx_shape_functions);
this->d2phideta2.resize (n_approx_shape_functions);
}
if (Dim > 2)
{
this->d2phidxidzeta.resize (n_approx_shape_functions);
this->d2phidetadzeta.resize (n_approx_shape_functions);
this->d2phidzeta2.resize (n_approx_shape_functions);
}
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
for (unsigned int i=0; i<n_approx_shape_functions; i++)
{
if (this->calculate_phi)
this->phi[i].resize (n_qp);
if (this->calculate_dphi)
{
this->dphi[i].resize (n_qp);
this->dphidx[i].resize (n_qp);
this->dphidy[i].resize (n_qp);
this->dphidz[i].resize (n_qp);
}
if(this->calculate_dphiref)
{
if (Dim > 0)
this->dphidxi[i].resize(n_qp);
if (Dim > 1)
this->dphideta[i].resize(n_qp);
if (Dim > 2)
this->dphidzeta[i].resize(n_qp);
}
if(this->calculate_curl_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->curl_phi[i].resize(n_qp);
if(this->calculate_div_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->div_phi[i].resize(n_qp);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
{
this->d2phi[i].resize (n_qp);
this->d2phidx2[i].resize (n_qp);
this->d2phidxdy[i].resize (n_qp);
this->d2phidxdz[i].resize (n_qp);
this->d2phidy2[i].resize (n_qp);
this->d2phidydz[i].resize (n_qp);
this->d2phidz2[i].resize (n_qp);
if (Dim > 0)
this->d2phidxi2[i].resize (n_qp);
if (Dim > 1)
{
this->d2phidxideta[i].resize (n_qp);
this->d2phideta2[i].resize (n_qp);
}
if (Dim > 2)
{
this->d2phidxidzeta[i].resize (n_qp);
this->d2phidetadzeta[i].resize (n_qp);
this->d2phidzeta2[i].resize (n_qp);
}
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
}
#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
//------------------------------------------------------------
// Initialize the data fields, which should only be used for infinite
// elements, to some sensible values, so that using a FE with the
// variational formulation of an InfFE, correct element matrices are
// returned
{
this->weight.resize (n_qp);
this->dweight.resize (n_qp);
this->dphase.resize (n_qp);
for (unsigned int p=0; p<n_qp; p++)
{
this->weight[p] = 1.;
this->dweight[p].zero();
this->dphase[p].zero();
}
}
#endif // ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
switch (Dim)
{
//------------------------------------------------------------
// 0D
case 0:
{
break;
}
//------------------------------------------------------------
// 1D
case 1:
{
// Compute the value of the approximation shape function i at quadrature point p
if (this->calculate_dphiref)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
this->dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 0, qp[p]);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
this->d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 0, qp[p]);
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
break;
}
//------------------------------------------------------------
// 2D
case 2:
{
// Compute the value of the approximation shape function i at quadrature point p
if (this->calculate_dphiref)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 1, qp[p]);
}
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 1, qp[p]);
this->d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 2, qp[p]);
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
break;
}
//------------------------------------------------------------
// 3D
case 3:
{
// Compute the value of the approximation shape function i at quadrature point p
if (this->calculate_dphiref)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 1, qp[p]);
this->dphidzeta[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 2, qp[p]);
}
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 1, qp[p]);
this->d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 2, qp[p]);
this->d2phidxidzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 3, qp[p]);
this->d2phidetadzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 4, qp[p]);
this->d2phidzeta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 5, qp[p]);
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
break;
}
default:
libmesh_error_msg("Invalid dimension Dim = " << Dim);
}
// Stop logging the shape function initialization
STOP_LOG("init_shape_functions()", "FE");
}
#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_base_shape_functions(const std::vector<Point>& qp,
const Elem* e)
{
// I don't understand infinite elements well enough to risk
// calculating too little. :-( RHS
this->calculate_phi = this->calculate_dphi = this->calculate_d2phi = true;
this->elem_type = e->type();
this->_fe_map->template init_reference_to_physical_map<Dim>(qp, e);
init_shape_functions(qp, e);
}
#endif // LIBMESH_ENABLE_INFINITE_ELEMENTS
//--------------------------------------------------------------
// Explicit instantiations using macro from fe_macro.h
INSTANTIATE_FE(0);
INSTANTIATE_FE(1);
INSTANTIATE_FE(2);
INSTANTIATE_FE(3);
INSTANTIATE_SUBDIVISION_FE;
} // namespace libMesh
Reapply const
The refactoring that required removing it got reverted.
// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 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
// Local includes
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/fe_interface.h"
#include "libmesh/fe_macro.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/quadrature.h"
#include "libmesh/tensor_value.h"
namespace libMesh
{
// ------------------------------------------------------------
// FE class members
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_shape_functions () const
{
return FE<Dim,T>::n_dofs (this->elem_type,
static_cast<Order>(this->fe_type.order + this->_p_level));
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::attach_quadrature_rule (QBase* q)
{
libmesh_assert(q);
this->qrule = q;
// make sure we don't cache results from a previous quadrature rule
this->elem_type = INVALID_ELEM;
return;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_quadrature_points () const
{
libmesh_assert(this->qrule);
return this->qrule->n_points();
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_side(const Elem* const elem,
const Order o,
unsigned int s,
std::vector<unsigned int>& di)
{
libmesh_assert(elem);
libmesh_assert_less (s, elem->n_sides());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
static_cast<Order>(o + elem->p_level()), n);
if (elem->is_node_on_side(n, s))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::dofs_on_edge(const Elem* const elem,
const Order o,
unsigned int e,
std::vector<unsigned int>& di)
{
libmesh_assert(elem);
libmesh_assert_less (e, elem->n_edges());
di.clear();
unsigned int nodenum = 0;
const unsigned int n_nodes = elem->n_nodes();
for (unsigned int n = 0; n != n_nodes; ++n)
{
const unsigned int n_dofs = n_dofs_at_node(elem->type(),
static_cast<Order>(o + elem->p_level()), n);
if (elem->is_node_on_edge(n, e))
for (unsigned int i = 0; i != n_dofs; ++i)
di.push_back(nodenum++);
else
nodenum += n_dofs;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::reinit(const Elem* elem,
const std::vector<Point>* const pts,
const std::vector<Real>* const weights)
{
// We can be called with no element. If we're evaluating SCALAR
// dofs we'll still have work to do.
// libmesh_assert(elem);
// Try to avoid calling init_shape_functions
// even when shapes_need_reinit
bool cached_nodes_still_fit = false;
// Most of the hard work happens when we have an actual element
if (elem)
{
// Initialize the shape functions at the user-specified
// points
if (pts != NULL && elem)
{
// Set the type and p level for this element
this->elem_type = elem->type();
this->_p_level = elem->p_level();
// Initialize the shape functions
this->_fe_map->template init_reference_to_physical_map<Dim>
(*pts, elem);
this->init_shape_functions (*pts, elem);
// The shape functions do not correspond to the qrule
this->shapes_on_quadrature = false;
}
// If there are no user specified points, we use the
// quadrature rule
// update the type in accordance to the current cell
// and reinit if the cell type has changed or (as in
// the case of the hierarchics) the shape functions need
// reinit, since they depend on the particular element shape
else
{
libmesh_assert(this->qrule);
this->qrule->init(elem->type(), elem->p_level());
if(this->qrule->shapes_need_reinit())
this->shapes_on_quadrature = false;
if (this->elem_type != elem->type() ||
this->_p_level != elem->p_level() ||
!this->shapes_on_quadrature)
{
// Set the type and p level for this element
this->elem_type = elem->type();
this->_p_level = elem->p_level();
// Initialize the shape functions
this->_fe_map->template init_reference_to_physical_map<Dim>
(this->qrule->get_points(), elem);
this->init_shape_functions (this->qrule->get_points(), elem);
if (this->shapes_need_reinit())
{
cached_nodes.resize(elem->n_nodes());
for (unsigned int n = 0; n != elem->n_nodes(); ++n)
{
cached_nodes[n] = elem->point(n);
}
}
}
else
{
// libmesh_assert_greater (elem->n_nodes(), 1);
cached_nodes_still_fit = true;
if (cached_nodes.size() != elem->n_nodes())
cached_nodes_still_fit = false;
else
for (unsigned int n = 1; n < elem->n_nodes(); ++n)
{
if (!(elem->point(n) - elem->point(0)).relative_fuzzy_equals
((cached_nodes[n] - cached_nodes[0]), 1e-13))
{
cached_nodes_still_fit = false;
break;
}
}
if (this->shapes_need_reinit() && !cached_nodes_still_fit)
{
this->_fe_map->template init_reference_to_physical_map<Dim>
(this->qrule->get_points(), elem);
this->init_shape_functions (this->qrule->get_points(), elem);
cached_nodes.resize(elem->n_nodes());
for (unsigned int n = 0; n != elem->n_nodes(); ++n)
cached_nodes[n] = elem->point(n);
}
}
// The shape functions correspond to the qrule
this->shapes_on_quadrature = true;
}
// Compute the map for this element. In the future we can specify
// different types of maps
if (pts != NULL)
{
if (weights != NULL)
{
this->_fe_map->compute_map (this->dim,*weights, elem);
}
else
{
std::vector<Real> dummy_weights (pts->size(), 1.);
this->_fe_map->compute_map (this->dim,dummy_weights, elem);
}
}
else
{
this->_fe_map->compute_map (this->dim,this->qrule->get_weights(), elem);
}
}
else // With no defined elem, so mapping or caching to
// be done, and our "quadrature rule" is one point for nonlocal
// (SCALAR) variables and zero points for local variables.
{
this->elem_type = INVALID_ELEM;
this->_p_level = 0;
if (!pts)
{
if (T == SCALAR)
{
this->qrule->get_points() =
std::vector<Point>(1,Point(0));
this->qrule->get_weights() =
std::vector<Real>(1,1);
}
else
{
this->qrule->get_points().clear();
this->qrule->get_weights().clear();
}
this->init_shape_functions
(this->qrule->get_points(), elem);
}
else
this->init_shape_functions (*pts, elem);
}
// Compute the shape functions and the derivatives at all of the
// quadrature points.
if (!cached_nodes_still_fit)
{
if (pts != NULL)
this->compute_shape_functions (elem,*pts);
else
this->compute_shape_functions(elem,this->qrule->get_points());
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_shape_functions(const std::vector<Point>& qp,
const Elem* elem)
{
// We can be called with no element. If we're evaluating SCALAR
// dofs we'll still have work to do.
// libmesh_assert(elem);
this->calculations_started = true;
// If the user forgot to request anything, we'll be safe and
// calculate everything:
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (!this->calculate_phi && !this->calculate_dphi && !this->calculate_d2phi
&& !this->calculate_curl_phi && !this->calculate_div_phi)
{
this->calculate_phi = this->calculate_dphi = this->calculate_d2phi = this->calculate_dphiref = true;
if( FEInterface::field_type(T) == TYPE_VECTOR )
{
this->calculate_curl_phi = true;
this->calculate_div_phi = true;
}
}
#else
if (!this->calculate_phi && !this->calculate_dphi && !this->calculate_curl_phi && !this->calculate_div_phi)
{
this->calculate_phi = this->calculate_dphi = this->calculate_dphiref = true;
if( FEInterface::field_type(T) == TYPE_VECTOR )
{
this->calculate_curl_phi = true;
this->calculate_div_phi = true;
}
}
#endif // LIBMESH_ENABLE_SECOND_DERIVATIVES
// Start logging the shape function initialization
START_LOG("init_shape_functions()", "FE");
// The number of quadrature points.
const unsigned int n_qp = libmesh_cast_int<unsigned int>(qp.size());
// Number of shape functions in the finite element approximation
// space.
const unsigned int n_approx_shape_functions =
this->n_shape_functions(this->get_type(),
this->get_order());
// resize the vectors to hold current data
// Phi are the shape functions used for the FE approximation
// Phi_map are the shape functions used for the FE mapping
if (this->calculate_phi)
this->phi.resize (n_approx_shape_functions);
if (this->calculate_dphi)
{
this->dphi.resize (n_approx_shape_functions);
this->dphidx.resize (n_approx_shape_functions);
this->dphidy.resize (n_approx_shape_functions);
this->dphidz.resize (n_approx_shape_functions);
}
if(this->calculate_dphiref)
{
if (Dim > 0)
this->dphidxi.resize (n_approx_shape_functions);
if (Dim > 1)
this->dphideta.resize (n_approx_shape_functions);
if (Dim > 2)
this->dphidzeta.resize (n_approx_shape_functions);
}
if( this->calculate_curl_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->curl_phi.resize(n_approx_shape_functions);
if( this->calculate_div_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->div_phi.resize(n_approx_shape_functions);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
{
this->d2phi.resize (n_approx_shape_functions);
this->d2phidx2.resize (n_approx_shape_functions);
this->d2phidxdy.resize (n_approx_shape_functions);
this->d2phidxdz.resize (n_approx_shape_functions);
this->d2phidy2.resize (n_approx_shape_functions);
this->d2phidydz.resize (n_approx_shape_functions);
this->d2phidz2.resize (n_approx_shape_functions);
if (Dim > 0)
this->d2phidxi2.resize (n_approx_shape_functions);
if (Dim > 1)
{
this->d2phidxideta.resize (n_approx_shape_functions);
this->d2phideta2.resize (n_approx_shape_functions);
}
if (Dim > 2)
{
this->d2phidxidzeta.resize (n_approx_shape_functions);
this->d2phidetadzeta.resize (n_approx_shape_functions);
this->d2phidzeta2.resize (n_approx_shape_functions);
}
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
for (unsigned int i=0; i<n_approx_shape_functions; i++)
{
if (this->calculate_phi)
this->phi[i].resize (n_qp);
if (this->calculate_dphi)
{
this->dphi[i].resize (n_qp);
this->dphidx[i].resize (n_qp);
this->dphidy[i].resize (n_qp);
this->dphidz[i].resize (n_qp);
}
if(this->calculate_dphiref)
{
if (Dim > 0)
this->dphidxi[i].resize(n_qp);
if (Dim > 1)
this->dphideta[i].resize(n_qp);
if (Dim > 2)
this->dphidzeta[i].resize(n_qp);
}
if(this->calculate_curl_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->curl_phi[i].resize(n_qp);
if(this->calculate_div_phi && (FEInterface::field_type(T) == TYPE_VECTOR) )
this->div_phi[i].resize(n_qp);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
{
this->d2phi[i].resize (n_qp);
this->d2phidx2[i].resize (n_qp);
this->d2phidxdy[i].resize (n_qp);
this->d2phidxdz[i].resize (n_qp);
this->d2phidy2[i].resize (n_qp);
this->d2phidydz[i].resize (n_qp);
this->d2phidz2[i].resize (n_qp);
if (Dim > 0)
this->d2phidxi2[i].resize (n_qp);
if (Dim > 1)
{
this->d2phidxideta[i].resize (n_qp);
this->d2phideta2[i].resize (n_qp);
}
if (Dim > 2)
{
this->d2phidxidzeta[i].resize (n_qp);
this->d2phidetadzeta[i].resize (n_qp);
this->d2phidzeta2[i].resize (n_qp);
}
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
}
#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
//------------------------------------------------------------
// Initialize the data fields, which should only be used for infinite
// elements, to some sensible values, so that using a FE with the
// variational formulation of an InfFE, correct element matrices are
// returned
{
this->weight.resize (n_qp);
this->dweight.resize (n_qp);
this->dphase.resize (n_qp);
for (unsigned int p=0; p<n_qp; p++)
{
this->weight[p] = 1.;
this->dweight[p].zero();
this->dphase[p].zero();
}
}
#endif // ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
switch (Dim)
{
//------------------------------------------------------------
// 0D
case 0:
{
break;
}
//------------------------------------------------------------
// 1D
case 1:
{
// Compute the value of the approximation shape function i at quadrature point p
if (this->calculate_dphiref)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
this->dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 0, qp[p]);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
this->d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 0, qp[p]);
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
break;
}
//------------------------------------------------------------
// 2D
case 2:
{
// Compute the value of the approximation shape function i at quadrature point p
if (this->calculate_dphiref)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 1, qp[p]);
}
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 1, qp[p]);
this->d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 2, qp[p]);
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
break;
}
//------------------------------------------------------------
// 3D
case 3:
{
// Compute the value of the approximation shape function i at quadrature point p
if (this->calculate_dphiref)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->dphidxi[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->dphideta[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 1, qp[p]);
this->dphidzeta[i][p] = FE<Dim,T>::shape_deriv (elem, this->fe_type.order, i, 2, qp[p]);
}
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
if (this->calculate_d2phi)
for (unsigned int i=0; i<n_approx_shape_functions; i++)
for (unsigned int p=0; p<n_qp; p++)
{
this->d2phidxi2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 0, qp[p]);
this->d2phidxideta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 1, qp[p]);
this->d2phideta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 2, qp[p]);
this->d2phidxidzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 3, qp[p]);
this->d2phidetadzeta[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 4, qp[p]);
this->d2phidzeta2[i][p] = FE<Dim,T>::shape_second_deriv (elem, this->fe_type.order, i, 5, qp[p]);
}
#endif // ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
break;
}
default:
libmesh_error_msg("Invalid dimension Dim = " << Dim);
}
// Stop logging the shape function initialization
STOP_LOG("init_shape_functions()", "FE");
}
#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::init_base_shape_functions(const std::vector<Point>& qp,
const Elem* e)
{
// I don't understand infinite elements well enough to risk
// calculating too little. :-( RHS
this->calculate_phi = this->calculate_dphi = this->calculate_d2phi = true;
this->elem_type = e->type();
this->_fe_map->template init_reference_to_physical_map<Dim>(qp, e);
init_shape_functions(qp, e);
}
#endif // LIBMESH_ENABLE_INFINITE_ELEMENTS
//--------------------------------------------------------------
// Explicit instantiations using macro from fe_macro.h
INSTANTIATE_FE(0);
INSTANTIATE_FE(1);
INSTANTIATE_FE(2);
INSTANTIATE_FE(3);
INSTANTIATE_SUBDIVISION_FE;
} // namespace libMesh
|
#include "nixexpr.hh"
#include "parser.hh"
#include "hash.hh"
#include "util.hh"
#include "nixexpr-ast.hh"
#include <cstdlib>
using namespace nix;
struct Env;
struct Value;
typedef std::map<string, Value> Bindings;
struct Env
{
Env * up;
Bindings bindings;
};
typedef enum {
tInt = 1,
tAttrs,
tThunk,
tLambda,
tCopy,
tBlackhole
} ValueType;
struct Value
{
ValueType type;
union
{
int integer;
Bindings * attrs;
struct {
Env * env;
Expr expr;
} thunk;
struct {
Env * env;
Pattern pat;
Expr body;
} lambda;
Value * val;
};
};
std::ostream & operator << (std::ostream & str, Value & v)
{
switch (v.type) {
case tInt:
str << v.integer;
break;
case tAttrs:
str << "{ ";
foreach (Bindings::iterator, i, *v.attrs)
str << i->first << " = " << i->second << "; ";
str << "}";
break;
case tThunk:
str << "<CODE>";
break;
case tLambda:
str << "<LAMBDA>";
break;
default:
abort();
}
return str;
}
static void eval(Env * env, Expr e, Value & v);
void forceValue(Value & v)
{
if (v.type == tThunk) {
v.type = tBlackhole;
eval(v.thunk.env, v.thunk.expr, v);
}
else if (v.type == tCopy) {
forceValue(*v.val);
v = *v.val;
}
else if (v.type == tBlackhole)
throw EvalError("infinite recursion encountered");
}
Value * lookupVar(Env * env, const string & name)
{
for ( ; env; env = env->up) {
Bindings::iterator i = env->bindings.find(name);
if (i != env->bindings.end()) return &i->second;
}
throw Error("undefined variable");
}
unsigned long nrValues = 0;
unsigned long nrEnvs = 0;
Env * allocEnv()
{
nrEnvs++;
return new Env;
}
static void eval(Env * env, Expr e, Value & v)
{
printMsg(lvlError, format("eval: %1%") % e);
ATerm name;
if (matchVar(e, name)) {
Value * v2 = lookupVar(env, aterm2String(name));
forceValue(*v2);
v = *v2;
return;
}
int n;
if (matchInt(e, n)) {
v.type = tInt;
v.integer = n;
return;
}
ATermList es;
if (matchAttrs(e, es)) {
v.type = tAttrs;
v.attrs = new Bindings;
ATerm e2, pos;
for (ATermIterator i(es); i; ++i) {
if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
Value & v2 = (*v.attrs)[aterm2String(name)];
nrValues++;
v2.type = tThunk;
v2.thunk.env = env;
v2.thunk.expr = e2;
}
return;
}
ATermList rbnds, nrbnds;
if (matchRec(e, rbnds, nrbnds)) {
Env * env2 = allocEnv();
env2->up = env;
v.type = tAttrs;
v.attrs = &env2->bindings;
ATerm name, e2, pos;
for (ATermIterator i(rbnds); i; ++i) {
if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
Value & v2 = env2->bindings[aterm2String(name)];
nrValues++;
v2.type = tThunk;
v2.thunk.env = env2;
v2.thunk.expr = e2;
}
return;
}
Expr e2;
if (matchSelect(e, e2, name)) {
eval(env, e2, v);
if (v.type != tAttrs) throw TypeError("expected attribute set");
Bindings::iterator i = v.attrs->find(aterm2String(name));
if (i == v.attrs->end()) throw TypeError("attribute not found");
forceValue(i->second);
v = i->second;
return;
}
Pattern pat; Expr body; Pos pos;
if (matchFunction(e, pat, body, pos)) {
v.type = tLambda;
v.lambda.env = env;
v.lambda.pat = pat;
v.lambda.body = body;
return;
}
Expr fun, arg;
if (matchCall(e, fun, arg)) {
eval(env, fun, v);
if (v.type != tLambda) throw TypeError("expected function");
Env * env2 = allocEnv();
env2->up = env;
ATermList formals; ATerm ellipsis;
if (matchVarPat(v.lambda.pat, name)) {
Value & vArg = env2->bindings[aterm2String(name)];
vArg.type = tThunk;
vArg.thunk.env = env;
vArg.thunk.expr = arg;
}
else if (matchAttrsPat(v.lambda.pat, formals, ellipsis, name)) {
Value * vArg;
Value vArg_;
if (name == sNoAlias)
vArg = &vArg_;
else
vArg = &env2->bindings[aterm2String(name)];
eval(env, arg, *vArg);
if (vArg->type != tAttrs) throw TypeError("expected attribute set");
/* For each formal argument, get the actual argument. If
there is no matching actual argument but the formal
argument has a default, use the default. */
unsigned int attrsUsed = 0;
for (ATermIterator i(formals); i; ++i) {
Expr name, def;
DefaultValue def2;
if (!matchFormal(*i, name, def2)) abort(); /* can't happen */
Bindings::iterator j = vArg->attrs->find(aterm2String(name));
Value & v = env2->bindings[aterm2String(name)];
if (j == vArg->attrs->end()) {
if (!matchDefaultValue(def2, def)) def = 0;
if (def == 0) throw TypeError(format("the argument named `%1%' required by the function is missing")
% aterm2String(name));
v.type = tThunk;
v.thunk.env = env2;
v.thunk.expr = def;
} else {
attrsUsed++;
v.type = tCopy;
v.val = &j->second;
}
}
/* Check that each actual argument is listed as a formal
argument (unless the attribute match specifies a
`...'). TODO: show the names of the
expected/unexpected arguments. */
if (ellipsis == eFalse && attrsUsed != vArg->attrs->size())
throw TypeError("function called with unexpected argument");
}
else abort();
eval(env2, v.lambda.body, v);
return;
}
abort();
}
void doTest(string s)
{
EvalState state;
Expr e = parseExprFromString(state, s, "/");
printMsg(lvlError, format(">>>>> %1%") % e);
Value v;
eval(0, e, v);
printMsg(lvlError, format("result: %1%") % v);
}
void run(Strings args)
{
printMsg(lvlError, format("size of value: %1% bytes") % sizeof(Value));
doTest("123");
doTest("{ x = 1; y = 2; }");
doTest("{ x = 1; y = 2; }.y");
doTest("rec { x = 1; y = x; }.y");
doTest("(x: x) 1");
doTest("(x: y: y) 1 2");
doTest("x: x");
doTest("({x, y}: x) { x = 1; y = 2; }");
doTest("({x, y}@args: args.x) { x = 1; y = 2; }");
doTest("(args@{x, y}: args.x) { x = 1; y = 2; }");
doTest("({x ? 1}: x) { }");
doTest("({x ? 1, y ? x}: y) { x = 2; }");
doTest("({x, y, ...}: x) { x = 1; y = 2; z = 3; }");
doTest("({x, y, ...}@args: args.z) { x = 1; y = 2; z = 3; }");
//doTest("({x ? y, y ? x}: y) { }");
printMsg(lvlError, format("alloced %1% values") % nrValues);
printMsg(lvlError, format("alloced %1% environments") % nrEnvs);
}
void printHelp()
{
}
string programId = "eval-test";
* Don't convert variable names to strings.
#include "nixexpr.hh"
#include "parser.hh"
#include "hash.hh"
#include "util.hh"
#include "nixexpr-ast.hh"
#include <cstdlib>
using namespace nix;
struct Env;
struct Value;
typedef ATerm Sym;
typedef std::map<Sym, Value> Bindings;
struct Env
{
Env * up;
Bindings bindings;
};
typedef enum {
tInt = 1,
tAttrs,
tThunk,
tLambda,
tCopy,
tBlackhole
} ValueType;
struct Value
{
ValueType type;
union
{
int integer;
Bindings * attrs;
struct {
Env * env;
Expr expr;
} thunk;
struct {
Env * env;
Pattern pat;
Expr body;
} lambda;
Value * val;
};
};
std::ostream & operator << (std::ostream & str, Value & v)
{
switch (v.type) {
case tInt:
str << v.integer;
break;
case tAttrs:
str << "{ ";
foreach (Bindings::iterator, i, *v.attrs)
str << i->first << " = " << i->second << "; ";
str << "}";
break;
case tThunk:
str << "<CODE>";
break;
case tLambda:
str << "<LAMBDA>";
break;
default:
abort();
}
return str;
}
static void eval(Env * env, Expr e, Value & v);
void forceValue(Value & v)
{
if (v.type == tThunk) {
v.type = tBlackhole;
eval(v.thunk.env, v.thunk.expr, v);
}
else if (v.type == tCopy) {
forceValue(*v.val);
v = *v.val;
}
else if (v.type == tBlackhole)
throw EvalError("infinite recursion encountered");
}
Value * lookupVar(Env * env, Sym name)
{
for ( ; env; env = env->up) {
Bindings::iterator i = env->bindings.find(name);
if (i != env->bindings.end()) return &i->second;
}
throw Error("undefined variable");
}
unsigned long nrValues = 0;
unsigned long nrEnvs = 0;
Env * allocEnv()
{
nrEnvs++;
return new Env;
}
static void eval(Env * env, Expr e, Value & v)
{
printMsg(lvlError, format("eval: %1%") % e);
Sym name;
if (matchVar(e, name)) {
Value * v2 = lookupVar(env, name);
forceValue(*v2);
v = *v2;
return;
}
int n;
if (matchInt(e, n)) {
v.type = tInt;
v.integer = n;
return;
}
ATermList es;
if (matchAttrs(e, es)) {
v.type = tAttrs;
v.attrs = new Bindings;
ATerm e2, pos;
for (ATermIterator i(es); i; ++i) {
if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
Value & v2 = (*v.attrs)[name];
nrValues++;
v2.type = tThunk;
v2.thunk.env = env;
v2.thunk.expr = e2;
}
return;
}
ATermList rbnds, nrbnds;
if (matchRec(e, rbnds, nrbnds)) {
Env * env2 = allocEnv();
env2->up = env;
v.type = tAttrs;
v.attrs = &env2->bindings;
ATerm name, e2, pos;
for (ATermIterator i(rbnds); i; ++i) {
if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
Value & v2 = env2->bindings[name];
nrValues++;
v2.type = tThunk;
v2.thunk.env = env2;
v2.thunk.expr = e2;
}
return;
}
Expr e2;
if (matchSelect(e, e2, name)) {
eval(env, e2, v);
if (v.type != tAttrs) throw TypeError("expected attribute set");
Bindings::iterator i = v.attrs->find(name);
if (i == v.attrs->end()) throw TypeError("attribute not found");
forceValue(i->second);
v = i->second;
return;
}
Pattern pat; Expr body; Pos pos;
if (matchFunction(e, pat, body, pos)) {
v.type = tLambda;
v.lambda.env = env;
v.lambda.pat = pat;
v.lambda.body = body;
return;
}
Expr fun, arg;
if (matchCall(e, fun, arg)) {
eval(env, fun, v);
if (v.type != tLambda) throw TypeError("expected function");
Env * env2 = allocEnv();
env2->up = env;
ATermList formals; ATerm ellipsis;
if (matchVarPat(v.lambda.pat, name)) {
Value & vArg = env2->bindings[name];
vArg.type = tThunk;
vArg.thunk.env = env;
vArg.thunk.expr = arg;
}
else if (matchAttrsPat(v.lambda.pat, formals, ellipsis, name)) {
Value * vArg;
Value vArg_;
if (name == sNoAlias)
vArg = &vArg_;
else
vArg = &env2->bindings[name];
eval(env, arg, *vArg);
if (vArg->type != tAttrs) throw TypeError("expected attribute set");
/* For each formal argument, get the actual argument. If
there is no matching actual argument but the formal
argument has a default, use the default. */
unsigned int attrsUsed = 0;
for (ATermIterator i(formals); i; ++i) {
Expr def; Sym name;
DefaultValue def2;
if (!matchFormal(*i, name, def2)) abort(); /* can't happen */
Bindings::iterator j = vArg->attrs->find(name);
Value & v = env2->bindings[name];
if (j == vArg->attrs->end()) {
if (!matchDefaultValue(def2, def)) def = 0;
if (def == 0) throw TypeError(format("the argument named `%1%' required by the function is missing")
% aterm2String(name));
v.type = tThunk;
v.thunk.env = env2;
v.thunk.expr = def;
} else {
attrsUsed++;
v.type = tCopy;
v.val = &j->second;
}
}
/* Check that each actual argument is listed as a formal
argument (unless the attribute match specifies a
`...'). TODO: show the names of the
expected/unexpected arguments. */
if (ellipsis == eFalse && attrsUsed != vArg->attrs->size())
throw TypeError("function called with unexpected argument");
}
else abort();
eval(env2, v.lambda.body, v);
return;
}
abort();
}
void doTest(string s)
{
EvalState state;
Expr e = parseExprFromString(state, s, "/");
printMsg(lvlError, format(">>>>> %1%") % e);
Value v;
eval(0, e, v);
printMsg(lvlError, format("result: %1%") % v);
}
void run(Strings args)
{
printMsg(lvlError, format("size of value: %1% bytes") % sizeof(Value));
doTest("123");
doTest("{ x = 1; y = 2; }");
doTest("{ x = 1; y = 2; }.y");
doTest("rec { x = 1; y = x; }.y");
doTest("(x: x) 1");
doTest("(x: y: y) 1 2");
doTest("x: x");
doTest("({x, y}: x) { x = 1; y = 2; }");
doTest("({x, y}@args: args.x) { x = 1; y = 2; }");
doTest("(args@{x, y}: args.x) { x = 1; y = 2; }");
doTest("({x ? 1}: x) { }");
doTest("({x ? 1, y ? x}: y) { x = 2; }");
doTest("({x, y, ...}: x) { x = 1; y = 2; z = 3; }");
doTest("({x, y, ...}@args: args.z) { x = 1; y = 2; z = 3; }");
//doTest("({x ? y, y ? x}: y) { }");
doTest("let x = 1; in x");
printMsg(lvlError, format("alloced %1% values") % nrValues);
printMsg(lvlError, format("alloced %1% environments") % nrEnvs);
}
void printHelp()
{
}
string programId = "eval-test";
|
#include "download.hh"
#include "util.hh"
#include "globals.hh"
#include "hash.hh"
#include "store-api.hh"
#include "archive.hh"
#include "s3.hh"
#include "compression.hh"
#include "pathlocks.hh"
#include "finally.hh"
#ifdef ENABLE_S3
#include <aws/core/client/ClientConfiguration.h>
#endif
#include <unistd.h>
#include <fcntl.h>
#include <curl/curl.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <queue>
#include <random>
#include <thread>
using namespace std::string_literals;
namespace nix {
void DownloadError::anchor() {}
void SubstituteGone::anchor() {}
DownloadSettings downloadSettings;
static GlobalConfig::Register r1(&downloadSettings);
CachedDownloadRequest::CachedDownloadRequest(const std::string & uri)
: uri(uri), ttl(settings.tarballTtl)
{ }
std::string resolveUri(const std::string & uri)
{
if (uri.compare(0, 8, "channel:") == 0)
return "https://nixos.org/channels/" + std::string(uri, 8) + "/nixexprs.tar.xz";
else
return uri;
}
struct CurlDownloader : public Downloader
{
CURLM * curlm = 0;
std::random_device rd;
std::mt19937 mt19937;
struct DownloadItem : public std::enable_shared_from_this<DownloadItem>
{
CurlDownloader & downloader;
DownloadRequest request;
DownloadResult result;
Activity act;
bool done = false; // whether either the success or failure function has been called
Callback<DownloadResult> callback;
CURL * req = 0;
bool active = false; // whether the handle has been added to the multi object
std::string status;
unsigned int attempt = 0;
/* Don't start this download until the specified time point
has been reached. */
std::chrono::steady_clock::time_point embargo;
struct curl_slist * requestHeaders = 0;
std::string encoding;
bool acceptRanges = false;
curl_off_t writtenToSink = 0;
DownloadItem(CurlDownloader & downloader,
const DownloadRequest & request,
Callback<DownloadResult> && callback)
: downloader(downloader)
, request(request)
, act(*logger, lvlTalkative, actDownload,
fmt(request.data ? "uploading '%s'" : "downloading '%s'", request.uri),
{request.uri}, request.parentAct)
, callback(std::move(callback))
, finalSink([this](const unsigned char * data, size_t len) {
if (this->request.dataCallback) {
long httpStatus = 0;
curl_easy_getinfo(req, CURLINFO_RESPONSE_CODE, &httpStatus);
/* Only write data to the sink if this is a
successful response. */
if (httpStatus == 0 || httpStatus == 200 || httpStatus == 201 || httpStatus == 206) {
writtenToSink += len;
this->request.dataCallback((char *) data, len);
}
} else
this->result.data->append((char *) data, len);
})
{
if (!request.expectedETag.empty())
requestHeaders = curl_slist_append(requestHeaders, ("If-None-Match: " + request.expectedETag).c_str());
if (!request.mimeType.empty())
requestHeaders = curl_slist_append(requestHeaders, ("Content-Type: " + request.mimeType).c_str());
}
~DownloadItem()
{
if (req) {
if (active)
curl_multi_remove_handle(downloader.curlm, req);
curl_easy_cleanup(req);
}
if (requestHeaders) curl_slist_free_all(requestHeaders);
try {
if (!done)
fail(DownloadError(Interrupted, format("download of '%s' was interrupted") % request.uri));
} catch (...) {
ignoreException();
}
}
void failEx(std::exception_ptr ex)
{
assert(!done);
done = true;
callback.rethrow(ex);
}
template<class T>
void fail(const T & e)
{
failEx(std::make_exception_ptr(e));
}
LambdaSink finalSink;
std::shared_ptr<CompressionSink> decompressionSink;
std::exception_ptr writeException;
size_t writeCallback(void * contents, size_t size, size_t nmemb)
{
try {
size_t realSize = size * nmemb;
result.bodySize += realSize;
if (!decompressionSink)
decompressionSink = makeDecompressionSink(encoding, finalSink);
(*decompressionSink)((unsigned char *) contents, realSize);
return realSize;
} catch (...) {
writeException = std::current_exception();
return 0;
}
}
static size_t writeCallbackWrapper(void * contents, size_t size, size_t nmemb, void * userp)
{
return ((DownloadItem *) userp)->writeCallback(contents, size, nmemb);
}
size_t headerCallback(void * contents, size_t size, size_t nmemb)
{
size_t realSize = size * nmemb;
std::string line((char *) contents, realSize);
printMsg(lvlVomit, format("got header for '%s': %s") % request.uri % trim(line));
if (line.compare(0, 5, "HTTP/") == 0) { // new response starts
result.etag = "";
auto ss = tokenizeString<vector<string>>(line, " ");
status = ss.size() >= 2 ? ss[1] : "";
result.data = std::make_shared<std::string>();
result.bodySize = 0;
acceptRanges = false;
encoding = "";
} else {
auto i = line.find(':');
if (i != string::npos) {
string name = toLower(trim(string(line, 0, i)));
if (name == "etag") {
result.etag = trim(string(line, i + 1));
/* Hack to work around a GitHub bug: it sends
ETags, but ignores If-None-Match. So if we get
the expected ETag on a 200 response, then shut
down the connection because we already have the
data. */
if (result.etag == request.expectedETag && status == "200") {
debug(format("shutting down on 200 HTTP response with expected ETag"));
return 0;
}
} else if (name == "content-encoding")
encoding = trim(string(line, i + 1));
else if (name == "accept-ranges" && toLower(trim(std::string(line, i + 1))) == "bytes")
acceptRanges = true;
}
}
return realSize;
}
static size_t headerCallbackWrapper(void * contents, size_t size, size_t nmemb, void * userp)
{
return ((DownloadItem *) userp)->headerCallback(contents, size, nmemb);
}
int progressCallback(double dltotal, double dlnow)
{
try {
act.progress(dlnow, dltotal);
} catch (nix::Interrupted &) {
assert(_isInterrupted);
}
return _isInterrupted;
}
static int progressCallbackWrapper(void * userp, double dltotal, double dlnow, double ultotal, double ulnow)
{
return ((DownloadItem *) userp)->progressCallback(dltotal, dlnow);
}
static int debugCallback(CURL * handle, curl_infotype type, char * data, size_t size, void * userptr)
{
if (type == CURLINFO_TEXT)
vomit("curl: %s", chomp(std::string(data, size)));
return 0;
}
size_t readOffset = 0;
size_t readCallback(char *buffer, size_t size, size_t nitems)
{
if (readOffset == request.data->length())
return 0;
auto count = std::min(size * nitems, request.data->length() - readOffset);
assert(count);
memcpy(buffer, request.data->data() + readOffset, count);
readOffset += count;
return count;
}
static size_t readCallbackWrapper(char *buffer, size_t size, size_t nitems, void * userp)
{
return ((DownloadItem *) userp)->readCallback(buffer, size, nitems);
}
void init()
{
if (!req) req = curl_easy_init();
curl_easy_reset(req);
if (verbosity >= lvlVomit) {
curl_easy_setopt(req, CURLOPT_VERBOSE, 1);
curl_easy_setopt(req, CURLOPT_DEBUGFUNCTION, DownloadItem::debugCallback);
}
curl_easy_setopt(req, CURLOPT_URL, request.uri.c_str());
curl_easy_setopt(req, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(req, CURLOPT_MAXREDIRS, 10);
curl_easy_setopt(req, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(req, CURLOPT_USERAGENT,
("curl/" LIBCURL_VERSION " Nix/" + nixVersion +
(downloadSettings.userAgentSuffix != "" ? " " + downloadSettings.userAgentSuffix.get() : "")).c_str());
#if LIBCURL_VERSION_NUM >= 0x072b00
curl_easy_setopt(req, CURLOPT_PIPEWAIT, 1);
#endif
#if LIBCURL_VERSION_NUM >= 0x072f00
if (downloadSettings.enableHttp2)
curl_easy_setopt(req, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
else
curl_easy_setopt(req, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
#endif
curl_easy_setopt(req, CURLOPT_WRITEFUNCTION, DownloadItem::writeCallbackWrapper);
curl_easy_setopt(req, CURLOPT_WRITEDATA, this);
curl_easy_setopt(req, CURLOPT_HEADERFUNCTION, DownloadItem::headerCallbackWrapper);
curl_easy_setopt(req, CURLOPT_HEADERDATA, this);
curl_easy_setopt(req, CURLOPT_PROGRESSFUNCTION, progressCallbackWrapper);
curl_easy_setopt(req, CURLOPT_PROGRESSDATA, this);
curl_easy_setopt(req, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(req, CURLOPT_HTTPHEADER, requestHeaders);
if (request.head)
curl_easy_setopt(req, CURLOPT_NOBODY, 1);
if (request.data) {
curl_easy_setopt(req, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(req, CURLOPT_READFUNCTION, readCallbackWrapper);
curl_easy_setopt(req, CURLOPT_READDATA, this);
curl_easy_setopt(req, CURLOPT_INFILESIZE_LARGE, (curl_off_t) request.data->length());
}
if (request.verifyTLS) {
debug("verify TLS: Nix CA file = '%s'", settings.caFile);
if (settings.caFile != "")
curl_easy_setopt(req, CURLOPT_CAINFO, settings.caFile.c_str());
} else {
curl_easy_setopt(req, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(req, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_easy_setopt(req, CURLOPT_CONNECTTIMEOUT, downloadSettings.connectTimeout.get());
curl_easy_setopt(req, CURLOPT_LOW_SPEED_LIMIT, 1L);
curl_easy_setopt(req, CURLOPT_LOW_SPEED_TIME, downloadSettings.stalledDownloadTimeout.get());
/* If no file exist in the specified path, curl continues to work
anyway as if netrc support was disabled. */
curl_easy_setopt(req, CURLOPT_NETRC_FILE, settings.netrcFile.get().c_str());
curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
if (writtenToSink)
curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink);
result.data = std::make_shared<std::string>();
result.bodySize = 0;
}
void finish(CURLcode code)
{
long httpStatus = 0;
curl_easy_getinfo(req, CURLINFO_RESPONSE_CODE, &httpStatus);
char * effectiveUriCStr;
curl_easy_getinfo(req, CURLINFO_EFFECTIVE_URL, &effectiveUriCStr);
if (effectiveUriCStr)
result.effectiveUri = effectiveUriCStr;
debug("finished %s of '%s'; curl status = %d, HTTP status = %d, body = %d bytes",
request.verb(), request.uri, code, httpStatus, result.bodySize);
if (decompressionSink) {
try {
decompressionSink->finish();
} catch (...) {
writeException = std::current_exception();
}
}
if (code == CURLE_WRITE_ERROR && result.etag == request.expectedETag) {
code = CURLE_OK;
httpStatus = 304;
}
if (writeException)
failEx(writeException);
else if (code == CURLE_OK &&
(httpStatus == 200 || httpStatus == 201 || httpStatus == 204 || httpStatus == 206 || httpStatus == 304 || httpStatus == 226 /* FTP */ || httpStatus == 0 /* other protocol */))
{
result.cached = httpStatus == 304;
act.progress(result.bodySize, result.bodySize);
done = true;
callback(std::move(result));
}
else {
// We treat most errors as transient, but won't retry when hopeless
Error err = Transient;
if (httpStatus == 404 || httpStatus == 410 || code == CURLE_FILE_COULDNT_READ_FILE) {
// The file is definitely not there
err = NotFound;
} else if (httpStatus == 401 || httpStatus == 403 || httpStatus == 407) {
// Don't retry on authentication/authorization failures
err = Forbidden;
} else if (httpStatus >= 400 && httpStatus < 500 && httpStatus != 408 && httpStatus != 429) {
// Most 4xx errors are client errors and are probably not worth retrying:
// * 408 means the server timed out waiting for us, so we try again
// * 429 means too many requests, so we retry (with a delay)
err = Misc;
} else if (httpStatus == 501 || httpStatus == 505 || httpStatus == 511) {
// Let's treat most 5xx (server) errors as transient, except for a handful:
// * 501 not implemented
// * 505 http version not supported
// * 511 we're behind a captive portal
err = Misc;
} else {
// Don't bother retrying on certain cURL errors either
switch (code) {
case CURLE_FAILED_INIT:
case CURLE_URL_MALFORMAT:
case CURLE_NOT_BUILT_IN:
case CURLE_REMOTE_ACCESS_DENIED:
case CURLE_FILE_COULDNT_READ_FILE:
case CURLE_FUNCTION_NOT_FOUND:
case CURLE_ABORTED_BY_CALLBACK:
case CURLE_BAD_FUNCTION_ARGUMENT:
case CURLE_INTERFACE_FAILED:
case CURLE_UNKNOWN_OPTION:
case CURLE_SSL_CACERT_BADFILE:
case CURLE_TOO_MANY_REDIRECTS:
case CURLE_WRITE_ERROR:
err = Misc;
break;
default: // Shut up warnings
break;
}
}
attempt++;
auto exc =
code == CURLE_ABORTED_BY_CALLBACK && _isInterrupted
? DownloadError(Interrupted, fmt("%s of '%s' was interrupted", request.verb(), request.uri))
: httpStatus != 0
? DownloadError(err,
fmt("unable to %s '%s': HTTP error %d",
request.verb(), request.uri, httpStatus)
+ (code == CURLE_OK ? "" : fmt(" (curl error: %s)", curl_easy_strerror(code)))
)
: DownloadError(err,
fmt("unable to %s '%s': %s (%d)",
request.verb(), request.uri, curl_easy_strerror(code), code));
/* If this is a transient error, then maybe retry the
download after a while. If we're writing to a
sink, we can only retry if the server supports
ranged requests. */
if (err == Transient
&& attempt < request.tries
&& (!this->request.dataCallback
|| writtenToSink == 0
|| (acceptRanges && encoding.empty())))
{
int ms = request.baseRetryTimeMs * std::pow(2.0f, attempt - 1 + std::uniform_real_distribution<>(0.0, 0.5)(downloader.mt19937));
if (writtenToSink)
warn("%s; retrying from offset %d in %d ms", exc.what(), writtenToSink, ms);
else
warn("%s; retrying in %d ms", exc.what(), ms);
embargo = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
downloader.enqueueItem(shared_from_this());
}
else
fail(exc);
}
}
};
struct State
{
struct EmbargoComparator {
bool operator() (const std::shared_ptr<DownloadItem> & i1, const std::shared_ptr<DownloadItem> & i2) {
return i1->embargo > i2->embargo;
}
};
bool quit = false;
std::priority_queue<std::shared_ptr<DownloadItem>, std::vector<std::shared_ptr<DownloadItem>>, EmbargoComparator> incoming;
};
Sync<State> state_;
/* We can't use a std::condition_variable to wake up the curl
thread, because it only monitors file descriptors. So use a
pipe instead. */
Pipe wakeupPipe;
std::thread workerThread;
CurlDownloader()
: mt19937(rd())
{
static std::once_flag globalInit;
std::call_once(globalInit, curl_global_init, CURL_GLOBAL_ALL);
curlm = curl_multi_init();
#if LIBCURL_VERSION_NUM >= 0x072b00 // Multiplex requires >= 7.43.0
curl_multi_setopt(curlm, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
#endif
#if LIBCURL_VERSION_NUM >= 0x071e00 // Max connections requires >= 7.30.0
curl_multi_setopt(curlm, CURLMOPT_MAX_TOTAL_CONNECTIONS,
downloadSettings.httpConnections.get());
#endif
wakeupPipe.create();
fcntl(wakeupPipe.readSide.get(), F_SETFL, O_NONBLOCK);
workerThread = std::thread([&]() { workerThreadEntry(); });
}
~CurlDownloader()
{
stopWorkerThread();
workerThread.join();
if (curlm) curl_multi_cleanup(curlm);
}
void stopWorkerThread()
{
/* Signal the worker thread to exit. */
{
auto state(state_.lock());
state->quit = true;
}
writeFull(wakeupPipe.writeSide.get(), " ", false);
}
void workerThreadMain()
{
/* Cause this thread to be notified on SIGINT. */
auto callback = createInterruptCallback([&]() {
stopWorkerThread();
});
std::map<CURL *, std::shared_ptr<DownloadItem>> items;
bool quit = false;
std::chrono::steady_clock::time_point nextWakeup;
while (!quit) {
checkInterrupt();
/* Let curl do its thing. */
int running;
CURLMcode mc = curl_multi_perform(curlm, &running);
if (mc != CURLM_OK)
throw nix::Error(format("unexpected error from curl_multi_perform(): %s") % curl_multi_strerror(mc));
/* Set the promises of any finished requests. */
CURLMsg * msg;
int left;
while ((msg = curl_multi_info_read(curlm, &left))) {
if (msg->msg == CURLMSG_DONE) {
auto i = items.find(msg->easy_handle);
assert(i != items.end());
i->second->finish(msg->data.result);
curl_multi_remove_handle(curlm, i->second->req);
i->second->active = false;
items.erase(i);
}
}
/* Wait for activity, including wakeup events. */
int numfds = 0;
struct curl_waitfd extraFDs[1];
extraFDs[0].fd = wakeupPipe.readSide.get();
extraFDs[0].events = CURL_WAIT_POLLIN;
extraFDs[0].revents = 0;
long maxSleepTimeMs = items.empty() ? 10000 : 100;
auto sleepTimeMs =
nextWakeup != std::chrono::steady_clock::time_point()
? std::max(0, (int) std::chrono::duration_cast<std::chrono::milliseconds>(nextWakeup - std::chrono::steady_clock::now()).count())
: maxSleepTimeMs;
vomit("download thread waiting for %d ms", sleepTimeMs);
mc = curl_multi_wait(curlm, extraFDs, 1, sleepTimeMs, &numfds);
if (mc != CURLM_OK)
throw nix::Error(format("unexpected error from curl_multi_wait(): %s") % curl_multi_strerror(mc));
nextWakeup = std::chrono::steady_clock::time_point();
/* Add new curl requests from the incoming requests queue,
except for requests that are embargoed (waiting for a
retry timeout to expire). */
if (extraFDs[0].revents & CURL_WAIT_POLLIN) {
char buf[1024];
auto res = read(extraFDs[0].fd, buf, sizeof(buf));
if (res == -1 && errno != EINTR)
throw SysError("reading curl wakeup socket");
}
std::vector<std::shared_ptr<DownloadItem>> incoming;
auto now = std::chrono::steady_clock::now();
{
auto state(state_.lock());
while (!state->incoming.empty()) {
auto item = state->incoming.top();
if (item->embargo <= now) {
incoming.push_back(item);
state->incoming.pop();
} else {
if (nextWakeup == std::chrono::steady_clock::time_point()
|| item->embargo < nextWakeup)
nextWakeup = item->embargo;
break;
}
}
quit = state->quit;
}
for (auto & item : incoming) {
debug("starting %s of %s", item->request.verb(), item->request.uri);
item->init();
curl_multi_add_handle(curlm, item->req);
item->active = true;
items[item->req] = item;
}
}
debug("download thread shutting down");
}
void workerThreadEntry()
{
try {
workerThreadMain();
} catch (nix::Interrupted & e) {
} catch (std::exception & e) {
printError("unexpected error in download thread: %s", e.what());
}
{
auto state(state_.lock());
while (!state->incoming.empty()) state->incoming.pop();
state->quit = true;
}
}
void enqueueItem(std::shared_ptr<DownloadItem> item)
{
if (item->request.data
&& !hasPrefix(item->request.uri, "http://")
&& !hasPrefix(item->request.uri, "https://"))
throw nix::Error("uploading to '%s' is not supported", item->request.uri);
{
auto state(state_.lock());
if (state->quit)
throw nix::Error("cannot enqueue download request because the download thread is shutting down");
state->incoming.push(item);
}
writeFull(wakeupPipe.writeSide.get(), " ");
}
#ifdef ENABLE_S3
std::tuple<std::string, std::string, Store::Params> parseS3Uri(std::string uri)
{
auto [path, params] = splitUriAndParams(uri);
auto slash = path.find('/', 5); // 5 is the length of "s3://" prefix
if (slash == std::string::npos)
throw nix::Error("bad S3 URI '%s'", path);
std::string bucketName(path, 5, slash - 5);
std::string key(path, slash + 1);
return {bucketName, key, params};
}
#endif
void enqueueDownload(const DownloadRequest & request,
Callback<DownloadResult> callback) override
{
/* Ugly hack to support s3:// URIs. */
if (hasPrefix(request.uri, "s3://")) {
// FIXME: do this on a worker thread
try {
#ifdef ENABLE_S3
auto [bucketName, key, params] = parseS3Uri(request.uri);
std::string profile = get(params, "profile", "");
std::string region = get(params, "region", Aws::Region::US_EAST_1);
std::string scheme = get(params, "scheme", "");
std::string endpoint = get(params, "endpoint", "");
S3Helper s3Helper(profile, region, scheme, endpoint);
// FIXME: implement ETag
auto s3Res = s3Helper.getObject(bucketName, key);
DownloadResult res;
if (!s3Res.data)
throw DownloadError(NotFound, fmt("S3 object '%s' does not exist", request.uri));
res.data = s3Res.data;
callback(std::move(res));
#else
throw nix::Error("cannot download '%s' because Nix is not built with S3 support", request.uri);
#endif
} catch (...) { callback.rethrow(); }
return;
}
enqueueItem(std::make_shared<DownloadItem>(*this, request, std::move(callback)));
}
};
ref<Downloader> getDownloader()
{
static ref<Downloader> downloader = makeDownloader();
return downloader;
}
ref<Downloader> makeDownloader()
{
return make_ref<CurlDownloader>();
}
std::future<DownloadResult> Downloader::enqueueDownload(const DownloadRequest & request)
{
auto promise = std::make_shared<std::promise<DownloadResult>>();
enqueueDownload(request,
{[promise](std::future<DownloadResult> fut) {
try {
promise->set_value(fut.get());
} catch (...) {
promise->set_exception(std::current_exception());
}
}});
return promise->get_future();
}
DownloadResult Downloader::download(const DownloadRequest & request)
{
return enqueueDownload(request).get();
}
void Downloader::download(DownloadRequest && request, Sink & sink)
{
/* Note: we can't call 'sink' via request.dataCallback, because
that would cause the sink to execute on the downloader
thread. If 'sink' is a coroutine, this will fail. Also, if the
sink is expensive (e.g. one that does decompression and writing
to the Nix store), it would stall the download thread too much.
Therefore we use a buffer to communicate data between the
download thread and the calling thread. */
struct State {
bool quit = false;
std::exception_ptr exc;
std::string data;
std::condition_variable avail, request;
};
auto _state = std::make_shared<Sync<State>>();
/* In case of an exception, wake up the download thread. FIXME:
abort the download request. */
Finally finally([&]() {
auto state(_state->lock());
state->quit = true;
state->request.notify_one();
});
request.dataCallback = [_state](char * buf, size_t len) {
auto state(_state->lock());
if (state->quit) return;
/* If the buffer is full, then go to sleep until the calling
thread wakes us up (i.e. when it has removed data from the
buffer). We don't wait forever to prevent stalling the
download thread. (Hopefully sleeping will throttle the
sender.) */
if (state->data.size() > 1024 * 1024) {
debug("download buffer is full; going to sleep");
state.wait_for(state->request, std::chrono::seconds(10));
}
/* Append data to the buffer and wake up the calling
thread. */
state->data.append(buf, len);
state->avail.notify_one();
};
enqueueDownload(request,
{[_state](std::future<DownloadResult> fut) {
auto state(_state->lock());
state->quit = true;
try {
fut.get();
} catch (...) {
state->exc = std::current_exception();
}
state->avail.notify_one();
state->request.notify_one();
}});
while (true) {
checkInterrupt();
std::string chunk;
/* Grab data if available, otherwise wait for the download
thread to wake us up. */
{
auto state(_state->lock());
while (state->data.empty()) {
if (state->quit) {
if (state->exc) std::rethrow_exception(state->exc);
return;
}
state.wait(state->avail);
}
std::swap(chunk, state->data);
state->request.notify_one();
}
/* Flush the data to the sink and wake up the download thread
if it's blocked on a full buffer. We don't hold the state
lock while doing this to prevent blocking the download
thread if sink() takes a long time. */
sink((unsigned char *) chunk.data(), chunk.size());
}
}
CachedDownloadResult Downloader::downloadCached(
ref<Store> store, const CachedDownloadRequest & request)
{
auto url = resolveUri(request.uri);
auto name = request.name;
if (name == "") {
auto p = url.rfind('/');
if (p != string::npos) name = string(url, p + 1);
}
Path expectedStorePath;
if (request.expectedHash) {
expectedStorePath = store->makeFixedOutputPath(request.unpack, request.expectedHash, name);
if (store->isValidPath(expectedStorePath)) {
CachedDownloadResult result;
result.storePath = expectedStorePath;
result.path = store->toRealPath(expectedStorePath);
return result;
}
}
Path cacheDir = getCacheDir() + "/nix/tarballs";
createDirs(cacheDir);
string urlHash = hashString(htSHA256, name + std::string("\0"s) + url).to_string(Base32, false);
Path dataFile = cacheDir + "/" + urlHash + ".info";
Path fileLink = cacheDir + "/" + urlHash + "-file";
PathLocks lock({fileLink}, fmt("waiting for lock on '%1%'...", fileLink));
Path storePath;
string expectedETag;
bool skip = false;
CachedDownloadResult result;
if (pathExists(fileLink) && pathExists(dataFile)) {
storePath = readLink(fileLink);
store->addTempRoot(storePath);
if (store->isValidPath(storePath)) {
auto ss = tokenizeString<vector<string>>(readFile(dataFile), "\n");
if (ss.size() >= 3 && ss[0] == url) {
time_t lastChecked;
if (string2Int(ss[2], lastChecked) && (uint64_t) lastChecked + request.ttl >= (uint64_t) time(0)) {
skip = true;
result.effectiveUri = request.uri;
result.etag = ss[1];
} else if (!ss[1].empty()) {
debug(format("verifying previous ETag '%1%'") % ss[1]);
expectedETag = ss[1];
}
}
} else
storePath = "";
}
if (!skip) {
try {
DownloadRequest request2(url);
request2.expectedETag = expectedETag;
auto res = download(request2);
result.effectiveUri = res.effectiveUri;
result.etag = res.etag;
if (!res.cached) {
ValidPathInfo info;
StringSink sink;
dumpString(*res.data, sink);
Hash hash = hashString(request.expectedHash ? request.expectedHash.type : htSHA256, *res.data);
info.path = store->makeFixedOutputPath(false, hash, name);
info.narHash = hashString(htSHA256, *sink.s);
info.narSize = sink.s->size();
info.ca = makeFixedOutputCA(false, hash);
store->addToStore(info, sink.s, NoRepair, NoCheckSigs);
storePath = info.path;
}
assert(!storePath.empty());
replaceSymlink(storePath, fileLink);
writeFile(dataFile, url + "\n" + res.etag + "\n" + std::to_string(time(0)) + "\n");
} catch (DownloadError & e) {
if (storePath.empty()) throw;
warn("warning: %s; using cached result", e.msg());
result.etag = expectedETag;
}
}
if (request.unpack) {
Path unpackedLink = cacheDir + "/" + baseNameOf(storePath) + "-unpacked";
PathLocks lock2({unpackedLink}, fmt("waiting for lock on '%1%'...", unpackedLink));
Path unpackedStorePath;
if (pathExists(unpackedLink)) {
unpackedStorePath = readLink(unpackedLink);
store->addTempRoot(unpackedStorePath);
if (!store->isValidPath(unpackedStorePath))
unpackedStorePath = "";
}
if (unpackedStorePath.empty()) {
printInfo(format("unpacking '%1%'...") % url);
Path tmpDir = createTempDir();
AutoDelete autoDelete(tmpDir, true);
// FIXME: this requires GNU tar for decompression.
runProgram("tar", true, {"xf", store->toRealPath(storePath), "-C", tmpDir, "--strip-components", "1"});
unpackedStorePath = store->addToStore(name, tmpDir, true, htSHA256, defaultPathFilter, NoRepair);
}
replaceSymlink(unpackedStorePath, unpackedLink);
storePath = unpackedStorePath;
}
if (expectedStorePath != "" && storePath != expectedStorePath) {
unsigned int statusCode = 102;
Hash gotHash = request.unpack
? hashPath(request.expectedHash.type, store->toRealPath(storePath)).first
: hashFile(request.expectedHash.type, store->toRealPath(storePath));
throw nix::Error(statusCode, "hash mismatch in file downloaded from '%s':\n wanted: %s\n got: %s",
url, request.expectedHash.to_string(), gotHash.to_string());
}
result.storePath = storePath;
result.path = store->toRealPath(storePath);
return result;
}
bool isUri(const string & s)
{
if (s.compare(0, 8, "channel:") == 0) return true;
size_t pos = s.find("://");
if (pos == string::npos) return false;
string scheme(s, 0, pos);
return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh";
}
}
Don't retry on "unsupported protocol" error
When encountering an unsupported protocol, there's no need to retry.
Chances are, it won't suddenly be supported between retry attempts;
error instead. Otherwise, you see something like the following:
$ nix-env -i -f git://git@github.com/foo/bar
warning: unable to download 'git://git@github.com/foo/bar': Unsupported protocol (1); retrying in 335 ms
warning: unable to download 'git://git@github.com/foo/bar': Unsupported protocol (1); retrying in 604 ms
warning: unable to download 'git://git@github.com/foo/bar': Unsupported protocol (1); retrying in 1340 ms
warning: unable to download 'git://git@github.com/foo/bar': Unsupported protocol (1); retrying in 2685 ms
With this change, you now see:
$ nix-env -i -f git://git@github.com/foo/bar
error: unable to download 'git://git@github.com/foo/bar': Unsupported protocol (1)
(cherry picked from commit c976cb0b8ab5d0f2c4ab8c9826fc7db56e2f1b3e)
#include "download.hh"
#include "util.hh"
#include "globals.hh"
#include "hash.hh"
#include "store-api.hh"
#include "archive.hh"
#include "s3.hh"
#include "compression.hh"
#include "pathlocks.hh"
#include "finally.hh"
#ifdef ENABLE_S3
#include <aws/core/client/ClientConfiguration.h>
#endif
#include <unistd.h>
#include <fcntl.h>
#include <curl/curl.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <queue>
#include <random>
#include <thread>
using namespace std::string_literals;
namespace nix {
void DownloadError::anchor() {}
void SubstituteGone::anchor() {}
DownloadSettings downloadSettings;
static GlobalConfig::Register r1(&downloadSettings);
CachedDownloadRequest::CachedDownloadRequest(const std::string & uri)
: uri(uri), ttl(settings.tarballTtl)
{ }
std::string resolveUri(const std::string & uri)
{
if (uri.compare(0, 8, "channel:") == 0)
return "https://nixos.org/channels/" + std::string(uri, 8) + "/nixexprs.tar.xz";
else
return uri;
}
struct CurlDownloader : public Downloader
{
CURLM * curlm = 0;
std::random_device rd;
std::mt19937 mt19937;
struct DownloadItem : public std::enable_shared_from_this<DownloadItem>
{
CurlDownloader & downloader;
DownloadRequest request;
DownloadResult result;
Activity act;
bool done = false; // whether either the success or failure function has been called
Callback<DownloadResult> callback;
CURL * req = 0;
bool active = false; // whether the handle has been added to the multi object
std::string status;
unsigned int attempt = 0;
/* Don't start this download until the specified time point
has been reached. */
std::chrono::steady_clock::time_point embargo;
struct curl_slist * requestHeaders = 0;
std::string encoding;
bool acceptRanges = false;
curl_off_t writtenToSink = 0;
DownloadItem(CurlDownloader & downloader,
const DownloadRequest & request,
Callback<DownloadResult> && callback)
: downloader(downloader)
, request(request)
, act(*logger, lvlTalkative, actDownload,
fmt(request.data ? "uploading '%s'" : "downloading '%s'", request.uri),
{request.uri}, request.parentAct)
, callback(std::move(callback))
, finalSink([this](const unsigned char * data, size_t len) {
if (this->request.dataCallback) {
long httpStatus = 0;
curl_easy_getinfo(req, CURLINFO_RESPONSE_CODE, &httpStatus);
/* Only write data to the sink if this is a
successful response. */
if (httpStatus == 0 || httpStatus == 200 || httpStatus == 201 || httpStatus == 206) {
writtenToSink += len;
this->request.dataCallback((char *) data, len);
}
} else
this->result.data->append((char *) data, len);
})
{
if (!request.expectedETag.empty())
requestHeaders = curl_slist_append(requestHeaders, ("If-None-Match: " + request.expectedETag).c_str());
if (!request.mimeType.empty())
requestHeaders = curl_slist_append(requestHeaders, ("Content-Type: " + request.mimeType).c_str());
}
~DownloadItem()
{
if (req) {
if (active)
curl_multi_remove_handle(downloader.curlm, req);
curl_easy_cleanup(req);
}
if (requestHeaders) curl_slist_free_all(requestHeaders);
try {
if (!done)
fail(DownloadError(Interrupted, format("download of '%s' was interrupted") % request.uri));
} catch (...) {
ignoreException();
}
}
void failEx(std::exception_ptr ex)
{
assert(!done);
done = true;
callback.rethrow(ex);
}
template<class T>
void fail(const T & e)
{
failEx(std::make_exception_ptr(e));
}
LambdaSink finalSink;
std::shared_ptr<CompressionSink> decompressionSink;
std::exception_ptr writeException;
size_t writeCallback(void * contents, size_t size, size_t nmemb)
{
try {
size_t realSize = size * nmemb;
result.bodySize += realSize;
if (!decompressionSink)
decompressionSink = makeDecompressionSink(encoding, finalSink);
(*decompressionSink)((unsigned char *) contents, realSize);
return realSize;
} catch (...) {
writeException = std::current_exception();
return 0;
}
}
static size_t writeCallbackWrapper(void * contents, size_t size, size_t nmemb, void * userp)
{
return ((DownloadItem *) userp)->writeCallback(contents, size, nmemb);
}
size_t headerCallback(void * contents, size_t size, size_t nmemb)
{
size_t realSize = size * nmemb;
std::string line((char *) contents, realSize);
printMsg(lvlVomit, format("got header for '%s': %s") % request.uri % trim(line));
if (line.compare(0, 5, "HTTP/") == 0) { // new response starts
result.etag = "";
auto ss = tokenizeString<vector<string>>(line, " ");
status = ss.size() >= 2 ? ss[1] : "";
result.data = std::make_shared<std::string>();
result.bodySize = 0;
acceptRanges = false;
encoding = "";
} else {
auto i = line.find(':');
if (i != string::npos) {
string name = toLower(trim(string(line, 0, i)));
if (name == "etag") {
result.etag = trim(string(line, i + 1));
/* Hack to work around a GitHub bug: it sends
ETags, but ignores If-None-Match. So if we get
the expected ETag on a 200 response, then shut
down the connection because we already have the
data. */
if (result.etag == request.expectedETag && status == "200") {
debug(format("shutting down on 200 HTTP response with expected ETag"));
return 0;
}
} else if (name == "content-encoding")
encoding = trim(string(line, i + 1));
else if (name == "accept-ranges" && toLower(trim(std::string(line, i + 1))) == "bytes")
acceptRanges = true;
}
}
return realSize;
}
static size_t headerCallbackWrapper(void * contents, size_t size, size_t nmemb, void * userp)
{
return ((DownloadItem *) userp)->headerCallback(contents, size, nmemb);
}
int progressCallback(double dltotal, double dlnow)
{
try {
act.progress(dlnow, dltotal);
} catch (nix::Interrupted &) {
assert(_isInterrupted);
}
return _isInterrupted;
}
static int progressCallbackWrapper(void * userp, double dltotal, double dlnow, double ultotal, double ulnow)
{
return ((DownloadItem *) userp)->progressCallback(dltotal, dlnow);
}
static int debugCallback(CURL * handle, curl_infotype type, char * data, size_t size, void * userptr)
{
if (type == CURLINFO_TEXT)
vomit("curl: %s", chomp(std::string(data, size)));
return 0;
}
size_t readOffset = 0;
size_t readCallback(char *buffer, size_t size, size_t nitems)
{
if (readOffset == request.data->length())
return 0;
auto count = std::min(size * nitems, request.data->length() - readOffset);
assert(count);
memcpy(buffer, request.data->data() + readOffset, count);
readOffset += count;
return count;
}
static size_t readCallbackWrapper(char *buffer, size_t size, size_t nitems, void * userp)
{
return ((DownloadItem *) userp)->readCallback(buffer, size, nitems);
}
void init()
{
if (!req) req = curl_easy_init();
curl_easy_reset(req);
if (verbosity >= lvlVomit) {
curl_easy_setopt(req, CURLOPT_VERBOSE, 1);
curl_easy_setopt(req, CURLOPT_DEBUGFUNCTION, DownloadItem::debugCallback);
}
curl_easy_setopt(req, CURLOPT_URL, request.uri.c_str());
curl_easy_setopt(req, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(req, CURLOPT_MAXREDIRS, 10);
curl_easy_setopt(req, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(req, CURLOPT_USERAGENT,
("curl/" LIBCURL_VERSION " Nix/" + nixVersion +
(downloadSettings.userAgentSuffix != "" ? " " + downloadSettings.userAgentSuffix.get() : "")).c_str());
#if LIBCURL_VERSION_NUM >= 0x072b00
curl_easy_setopt(req, CURLOPT_PIPEWAIT, 1);
#endif
#if LIBCURL_VERSION_NUM >= 0x072f00
if (downloadSettings.enableHttp2)
curl_easy_setopt(req, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
else
curl_easy_setopt(req, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
#endif
curl_easy_setopt(req, CURLOPT_WRITEFUNCTION, DownloadItem::writeCallbackWrapper);
curl_easy_setopt(req, CURLOPT_WRITEDATA, this);
curl_easy_setopt(req, CURLOPT_HEADERFUNCTION, DownloadItem::headerCallbackWrapper);
curl_easy_setopt(req, CURLOPT_HEADERDATA, this);
curl_easy_setopt(req, CURLOPT_PROGRESSFUNCTION, progressCallbackWrapper);
curl_easy_setopt(req, CURLOPT_PROGRESSDATA, this);
curl_easy_setopt(req, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(req, CURLOPT_HTTPHEADER, requestHeaders);
if (request.head)
curl_easy_setopt(req, CURLOPT_NOBODY, 1);
if (request.data) {
curl_easy_setopt(req, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(req, CURLOPT_READFUNCTION, readCallbackWrapper);
curl_easy_setopt(req, CURLOPT_READDATA, this);
curl_easy_setopt(req, CURLOPT_INFILESIZE_LARGE, (curl_off_t) request.data->length());
}
if (request.verifyTLS) {
debug("verify TLS: Nix CA file = '%s'", settings.caFile);
if (settings.caFile != "")
curl_easy_setopt(req, CURLOPT_CAINFO, settings.caFile.c_str());
} else {
curl_easy_setopt(req, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(req, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_easy_setopt(req, CURLOPT_CONNECTTIMEOUT, downloadSettings.connectTimeout.get());
curl_easy_setopt(req, CURLOPT_LOW_SPEED_LIMIT, 1L);
curl_easy_setopt(req, CURLOPT_LOW_SPEED_TIME, downloadSettings.stalledDownloadTimeout.get());
/* If no file exist in the specified path, curl continues to work
anyway as if netrc support was disabled. */
curl_easy_setopt(req, CURLOPT_NETRC_FILE, settings.netrcFile.get().c_str());
curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
if (writtenToSink)
curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink);
result.data = std::make_shared<std::string>();
result.bodySize = 0;
}
void finish(CURLcode code)
{
long httpStatus = 0;
curl_easy_getinfo(req, CURLINFO_RESPONSE_CODE, &httpStatus);
char * effectiveUriCStr;
curl_easy_getinfo(req, CURLINFO_EFFECTIVE_URL, &effectiveUriCStr);
if (effectiveUriCStr)
result.effectiveUri = effectiveUriCStr;
debug("finished %s of '%s'; curl status = %d, HTTP status = %d, body = %d bytes",
request.verb(), request.uri, code, httpStatus, result.bodySize);
if (decompressionSink) {
try {
decompressionSink->finish();
} catch (...) {
writeException = std::current_exception();
}
}
if (code == CURLE_WRITE_ERROR && result.etag == request.expectedETag) {
code = CURLE_OK;
httpStatus = 304;
}
if (writeException)
failEx(writeException);
else if (code == CURLE_OK &&
(httpStatus == 200 || httpStatus == 201 || httpStatus == 204 || httpStatus == 206 || httpStatus == 304 || httpStatus == 226 /* FTP */ || httpStatus == 0 /* other protocol */))
{
result.cached = httpStatus == 304;
act.progress(result.bodySize, result.bodySize);
done = true;
callback(std::move(result));
}
else {
// We treat most errors as transient, but won't retry when hopeless
Error err = Transient;
if (httpStatus == 404 || httpStatus == 410 || code == CURLE_FILE_COULDNT_READ_FILE) {
// The file is definitely not there
err = NotFound;
} else if (httpStatus == 401 || httpStatus == 403 || httpStatus == 407) {
// Don't retry on authentication/authorization failures
err = Forbidden;
} else if (httpStatus >= 400 && httpStatus < 500 && httpStatus != 408 && httpStatus != 429) {
// Most 4xx errors are client errors and are probably not worth retrying:
// * 408 means the server timed out waiting for us, so we try again
// * 429 means too many requests, so we retry (with a delay)
err = Misc;
} else if (httpStatus == 501 || httpStatus == 505 || httpStatus == 511) {
// Let's treat most 5xx (server) errors as transient, except for a handful:
// * 501 not implemented
// * 505 http version not supported
// * 511 we're behind a captive portal
err = Misc;
} else {
// Don't bother retrying on certain cURL errors either
switch (code) {
case CURLE_FAILED_INIT:
case CURLE_URL_MALFORMAT:
case CURLE_NOT_BUILT_IN:
case CURLE_REMOTE_ACCESS_DENIED:
case CURLE_FILE_COULDNT_READ_FILE:
case CURLE_FUNCTION_NOT_FOUND:
case CURLE_ABORTED_BY_CALLBACK:
case CURLE_BAD_FUNCTION_ARGUMENT:
case CURLE_INTERFACE_FAILED:
case CURLE_UNKNOWN_OPTION:
case CURLE_SSL_CACERT_BADFILE:
case CURLE_TOO_MANY_REDIRECTS:
case CURLE_WRITE_ERROR:
case CURLE_UNSUPPORTED_PROTOCOL:
err = Misc;
break;
default: // Shut up warnings
break;
}
}
attempt++;
auto exc =
code == CURLE_ABORTED_BY_CALLBACK && _isInterrupted
? DownloadError(Interrupted, fmt("%s of '%s' was interrupted", request.verb(), request.uri))
: httpStatus != 0
? DownloadError(err,
fmt("unable to %s '%s': HTTP error %d",
request.verb(), request.uri, httpStatus)
+ (code == CURLE_OK ? "" : fmt(" (curl error: %s)", curl_easy_strerror(code)))
)
: DownloadError(err,
fmt("unable to %s '%s': %s (%d)",
request.verb(), request.uri, curl_easy_strerror(code), code));
/* If this is a transient error, then maybe retry the
download after a while. If we're writing to a
sink, we can only retry if the server supports
ranged requests. */
if (err == Transient
&& attempt < request.tries
&& (!this->request.dataCallback
|| writtenToSink == 0
|| (acceptRanges && encoding.empty())))
{
int ms = request.baseRetryTimeMs * std::pow(2.0f, attempt - 1 + std::uniform_real_distribution<>(0.0, 0.5)(downloader.mt19937));
if (writtenToSink)
warn("%s; retrying from offset %d in %d ms", exc.what(), writtenToSink, ms);
else
warn("%s; retrying in %d ms", exc.what(), ms);
embargo = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
downloader.enqueueItem(shared_from_this());
}
else
fail(exc);
}
}
};
struct State
{
struct EmbargoComparator {
bool operator() (const std::shared_ptr<DownloadItem> & i1, const std::shared_ptr<DownloadItem> & i2) {
return i1->embargo > i2->embargo;
}
};
bool quit = false;
std::priority_queue<std::shared_ptr<DownloadItem>, std::vector<std::shared_ptr<DownloadItem>>, EmbargoComparator> incoming;
};
Sync<State> state_;
/* We can't use a std::condition_variable to wake up the curl
thread, because it only monitors file descriptors. So use a
pipe instead. */
Pipe wakeupPipe;
std::thread workerThread;
CurlDownloader()
: mt19937(rd())
{
static std::once_flag globalInit;
std::call_once(globalInit, curl_global_init, CURL_GLOBAL_ALL);
curlm = curl_multi_init();
#if LIBCURL_VERSION_NUM >= 0x072b00 // Multiplex requires >= 7.43.0
curl_multi_setopt(curlm, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
#endif
#if LIBCURL_VERSION_NUM >= 0x071e00 // Max connections requires >= 7.30.0
curl_multi_setopt(curlm, CURLMOPT_MAX_TOTAL_CONNECTIONS,
downloadSettings.httpConnections.get());
#endif
wakeupPipe.create();
fcntl(wakeupPipe.readSide.get(), F_SETFL, O_NONBLOCK);
workerThread = std::thread([&]() { workerThreadEntry(); });
}
~CurlDownloader()
{
stopWorkerThread();
workerThread.join();
if (curlm) curl_multi_cleanup(curlm);
}
void stopWorkerThread()
{
/* Signal the worker thread to exit. */
{
auto state(state_.lock());
state->quit = true;
}
writeFull(wakeupPipe.writeSide.get(), " ", false);
}
void workerThreadMain()
{
/* Cause this thread to be notified on SIGINT. */
auto callback = createInterruptCallback([&]() {
stopWorkerThread();
});
std::map<CURL *, std::shared_ptr<DownloadItem>> items;
bool quit = false;
std::chrono::steady_clock::time_point nextWakeup;
while (!quit) {
checkInterrupt();
/* Let curl do its thing. */
int running;
CURLMcode mc = curl_multi_perform(curlm, &running);
if (mc != CURLM_OK)
throw nix::Error(format("unexpected error from curl_multi_perform(): %s") % curl_multi_strerror(mc));
/* Set the promises of any finished requests. */
CURLMsg * msg;
int left;
while ((msg = curl_multi_info_read(curlm, &left))) {
if (msg->msg == CURLMSG_DONE) {
auto i = items.find(msg->easy_handle);
assert(i != items.end());
i->second->finish(msg->data.result);
curl_multi_remove_handle(curlm, i->second->req);
i->second->active = false;
items.erase(i);
}
}
/* Wait for activity, including wakeup events. */
int numfds = 0;
struct curl_waitfd extraFDs[1];
extraFDs[0].fd = wakeupPipe.readSide.get();
extraFDs[0].events = CURL_WAIT_POLLIN;
extraFDs[0].revents = 0;
long maxSleepTimeMs = items.empty() ? 10000 : 100;
auto sleepTimeMs =
nextWakeup != std::chrono::steady_clock::time_point()
? std::max(0, (int) std::chrono::duration_cast<std::chrono::milliseconds>(nextWakeup - std::chrono::steady_clock::now()).count())
: maxSleepTimeMs;
vomit("download thread waiting for %d ms", sleepTimeMs);
mc = curl_multi_wait(curlm, extraFDs, 1, sleepTimeMs, &numfds);
if (mc != CURLM_OK)
throw nix::Error(format("unexpected error from curl_multi_wait(): %s") % curl_multi_strerror(mc));
nextWakeup = std::chrono::steady_clock::time_point();
/* Add new curl requests from the incoming requests queue,
except for requests that are embargoed (waiting for a
retry timeout to expire). */
if (extraFDs[0].revents & CURL_WAIT_POLLIN) {
char buf[1024];
auto res = read(extraFDs[0].fd, buf, sizeof(buf));
if (res == -1 && errno != EINTR)
throw SysError("reading curl wakeup socket");
}
std::vector<std::shared_ptr<DownloadItem>> incoming;
auto now = std::chrono::steady_clock::now();
{
auto state(state_.lock());
while (!state->incoming.empty()) {
auto item = state->incoming.top();
if (item->embargo <= now) {
incoming.push_back(item);
state->incoming.pop();
} else {
if (nextWakeup == std::chrono::steady_clock::time_point()
|| item->embargo < nextWakeup)
nextWakeup = item->embargo;
break;
}
}
quit = state->quit;
}
for (auto & item : incoming) {
debug("starting %s of %s", item->request.verb(), item->request.uri);
item->init();
curl_multi_add_handle(curlm, item->req);
item->active = true;
items[item->req] = item;
}
}
debug("download thread shutting down");
}
void workerThreadEntry()
{
try {
workerThreadMain();
} catch (nix::Interrupted & e) {
} catch (std::exception & e) {
printError("unexpected error in download thread: %s", e.what());
}
{
auto state(state_.lock());
while (!state->incoming.empty()) state->incoming.pop();
state->quit = true;
}
}
void enqueueItem(std::shared_ptr<DownloadItem> item)
{
if (item->request.data
&& !hasPrefix(item->request.uri, "http://")
&& !hasPrefix(item->request.uri, "https://"))
throw nix::Error("uploading to '%s' is not supported", item->request.uri);
{
auto state(state_.lock());
if (state->quit)
throw nix::Error("cannot enqueue download request because the download thread is shutting down");
state->incoming.push(item);
}
writeFull(wakeupPipe.writeSide.get(), " ");
}
#ifdef ENABLE_S3
std::tuple<std::string, std::string, Store::Params> parseS3Uri(std::string uri)
{
auto [path, params] = splitUriAndParams(uri);
auto slash = path.find('/', 5); // 5 is the length of "s3://" prefix
if (slash == std::string::npos)
throw nix::Error("bad S3 URI '%s'", path);
std::string bucketName(path, 5, slash - 5);
std::string key(path, slash + 1);
return {bucketName, key, params};
}
#endif
void enqueueDownload(const DownloadRequest & request,
Callback<DownloadResult> callback) override
{
/* Ugly hack to support s3:// URIs. */
if (hasPrefix(request.uri, "s3://")) {
// FIXME: do this on a worker thread
try {
#ifdef ENABLE_S3
auto [bucketName, key, params] = parseS3Uri(request.uri);
std::string profile = get(params, "profile", "");
std::string region = get(params, "region", Aws::Region::US_EAST_1);
std::string scheme = get(params, "scheme", "");
std::string endpoint = get(params, "endpoint", "");
S3Helper s3Helper(profile, region, scheme, endpoint);
// FIXME: implement ETag
auto s3Res = s3Helper.getObject(bucketName, key);
DownloadResult res;
if (!s3Res.data)
throw DownloadError(NotFound, fmt("S3 object '%s' does not exist", request.uri));
res.data = s3Res.data;
callback(std::move(res));
#else
throw nix::Error("cannot download '%s' because Nix is not built with S3 support", request.uri);
#endif
} catch (...) { callback.rethrow(); }
return;
}
enqueueItem(std::make_shared<DownloadItem>(*this, request, std::move(callback)));
}
};
ref<Downloader> getDownloader()
{
static ref<Downloader> downloader = makeDownloader();
return downloader;
}
ref<Downloader> makeDownloader()
{
return make_ref<CurlDownloader>();
}
std::future<DownloadResult> Downloader::enqueueDownload(const DownloadRequest & request)
{
auto promise = std::make_shared<std::promise<DownloadResult>>();
enqueueDownload(request,
{[promise](std::future<DownloadResult> fut) {
try {
promise->set_value(fut.get());
} catch (...) {
promise->set_exception(std::current_exception());
}
}});
return promise->get_future();
}
DownloadResult Downloader::download(const DownloadRequest & request)
{
return enqueueDownload(request).get();
}
void Downloader::download(DownloadRequest && request, Sink & sink)
{
/* Note: we can't call 'sink' via request.dataCallback, because
that would cause the sink to execute on the downloader
thread. If 'sink' is a coroutine, this will fail. Also, if the
sink is expensive (e.g. one that does decompression and writing
to the Nix store), it would stall the download thread too much.
Therefore we use a buffer to communicate data between the
download thread and the calling thread. */
struct State {
bool quit = false;
std::exception_ptr exc;
std::string data;
std::condition_variable avail, request;
};
auto _state = std::make_shared<Sync<State>>();
/* In case of an exception, wake up the download thread. FIXME:
abort the download request. */
Finally finally([&]() {
auto state(_state->lock());
state->quit = true;
state->request.notify_one();
});
request.dataCallback = [_state](char * buf, size_t len) {
auto state(_state->lock());
if (state->quit) return;
/* If the buffer is full, then go to sleep until the calling
thread wakes us up (i.e. when it has removed data from the
buffer). We don't wait forever to prevent stalling the
download thread. (Hopefully sleeping will throttle the
sender.) */
if (state->data.size() > 1024 * 1024) {
debug("download buffer is full; going to sleep");
state.wait_for(state->request, std::chrono::seconds(10));
}
/* Append data to the buffer and wake up the calling
thread. */
state->data.append(buf, len);
state->avail.notify_one();
};
enqueueDownload(request,
{[_state](std::future<DownloadResult> fut) {
auto state(_state->lock());
state->quit = true;
try {
fut.get();
} catch (...) {
state->exc = std::current_exception();
}
state->avail.notify_one();
state->request.notify_one();
}});
while (true) {
checkInterrupt();
std::string chunk;
/* Grab data if available, otherwise wait for the download
thread to wake us up. */
{
auto state(_state->lock());
while (state->data.empty()) {
if (state->quit) {
if (state->exc) std::rethrow_exception(state->exc);
return;
}
state.wait(state->avail);
}
std::swap(chunk, state->data);
state->request.notify_one();
}
/* Flush the data to the sink and wake up the download thread
if it's blocked on a full buffer. We don't hold the state
lock while doing this to prevent blocking the download
thread if sink() takes a long time. */
sink((unsigned char *) chunk.data(), chunk.size());
}
}
CachedDownloadResult Downloader::downloadCached(
ref<Store> store, const CachedDownloadRequest & request)
{
auto url = resolveUri(request.uri);
auto name = request.name;
if (name == "") {
auto p = url.rfind('/');
if (p != string::npos) name = string(url, p + 1);
}
Path expectedStorePath;
if (request.expectedHash) {
expectedStorePath = store->makeFixedOutputPath(request.unpack, request.expectedHash, name);
if (store->isValidPath(expectedStorePath)) {
CachedDownloadResult result;
result.storePath = expectedStorePath;
result.path = store->toRealPath(expectedStorePath);
return result;
}
}
Path cacheDir = getCacheDir() + "/nix/tarballs";
createDirs(cacheDir);
string urlHash = hashString(htSHA256, name + std::string("\0"s) + url).to_string(Base32, false);
Path dataFile = cacheDir + "/" + urlHash + ".info";
Path fileLink = cacheDir + "/" + urlHash + "-file";
PathLocks lock({fileLink}, fmt("waiting for lock on '%1%'...", fileLink));
Path storePath;
string expectedETag;
bool skip = false;
CachedDownloadResult result;
if (pathExists(fileLink) && pathExists(dataFile)) {
storePath = readLink(fileLink);
store->addTempRoot(storePath);
if (store->isValidPath(storePath)) {
auto ss = tokenizeString<vector<string>>(readFile(dataFile), "\n");
if (ss.size() >= 3 && ss[0] == url) {
time_t lastChecked;
if (string2Int(ss[2], lastChecked) && (uint64_t) lastChecked + request.ttl >= (uint64_t) time(0)) {
skip = true;
result.effectiveUri = request.uri;
result.etag = ss[1];
} else if (!ss[1].empty()) {
debug(format("verifying previous ETag '%1%'") % ss[1]);
expectedETag = ss[1];
}
}
} else
storePath = "";
}
if (!skip) {
try {
DownloadRequest request2(url);
request2.expectedETag = expectedETag;
auto res = download(request2);
result.effectiveUri = res.effectiveUri;
result.etag = res.etag;
if (!res.cached) {
ValidPathInfo info;
StringSink sink;
dumpString(*res.data, sink);
Hash hash = hashString(request.expectedHash ? request.expectedHash.type : htSHA256, *res.data);
info.path = store->makeFixedOutputPath(false, hash, name);
info.narHash = hashString(htSHA256, *sink.s);
info.narSize = sink.s->size();
info.ca = makeFixedOutputCA(false, hash);
store->addToStore(info, sink.s, NoRepair, NoCheckSigs);
storePath = info.path;
}
assert(!storePath.empty());
replaceSymlink(storePath, fileLink);
writeFile(dataFile, url + "\n" + res.etag + "\n" + std::to_string(time(0)) + "\n");
} catch (DownloadError & e) {
if (storePath.empty()) throw;
warn("warning: %s; using cached result", e.msg());
result.etag = expectedETag;
}
}
if (request.unpack) {
Path unpackedLink = cacheDir + "/" + baseNameOf(storePath) + "-unpacked";
PathLocks lock2({unpackedLink}, fmt("waiting for lock on '%1%'...", unpackedLink));
Path unpackedStorePath;
if (pathExists(unpackedLink)) {
unpackedStorePath = readLink(unpackedLink);
store->addTempRoot(unpackedStorePath);
if (!store->isValidPath(unpackedStorePath))
unpackedStorePath = "";
}
if (unpackedStorePath.empty()) {
printInfo(format("unpacking '%1%'...") % url);
Path tmpDir = createTempDir();
AutoDelete autoDelete(tmpDir, true);
// FIXME: this requires GNU tar for decompression.
runProgram("tar", true, {"xf", store->toRealPath(storePath), "-C", tmpDir, "--strip-components", "1"});
unpackedStorePath = store->addToStore(name, tmpDir, true, htSHA256, defaultPathFilter, NoRepair);
}
replaceSymlink(unpackedStorePath, unpackedLink);
storePath = unpackedStorePath;
}
if (expectedStorePath != "" && storePath != expectedStorePath) {
unsigned int statusCode = 102;
Hash gotHash = request.unpack
? hashPath(request.expectedHash.type, store->toRealPath(storePath)).first
: hashFile(request.expectedHash.type, store->toRealPath(storePath));
throw nix::Error(statusCode, "hash mismatch in file downloaded from '%s':\n wanted: %s\n got: %s",
url, request.expectedHash.to_string(), gotHash.to_string());
}
result.storePath = storePath;
result.path = store->toRealPath(storePath);
return result;
}
bool isUri(const string & s)
{
if (s.compare(0, 8, "channel:") == 0) return true;
size_t pos = s.find("://");
if (pos == string::npos) return false;
string scheme(s, 0, pos);
return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh";
}
}
|
/*
This program shows how to process BLAS LEVEL2 syr2
for i = 0 .. N
for j = 0 .. N
C[i,j] = A[i,j] + alpha * X[i]*Y[j] + alpha * X[j]*Y[i]
*/
#include <tiramisu/tiramisu.h>
#define NN 100
#define alpha 3
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("syr2");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant N("N", NN);
var i("i", 0, N), j("j", 0, N);
// Declare inputs : A(Matrix N*N) , X(Vector dim=N) , Y(Vector dim=N)
input A("A", {i, j}, p_uint8);
input x("B", {i}, p_uint8);
input y("C", {j}, p_uint8);
// Declare output which is result of computation
computation output("output", {i,j}, expr((uint8_t)alpha) * x(i) * y(j) + expr((uint8_t)alpha) * x(j) * y(i) + A(i, j) );
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
// Declare the buffers.
buffer b_A("b_A", {N,N}, p_uint8, a_input);
buffer b_x("b_x", {N}, p_uint8, a_input);
buffer b_y("b_y", {N}, p_uint8, a_input);
buffer b_output("b_output", {N,N}, p_uint8, a_output);
// Map the computations to a buffer.
A.store_in(&b_A);
x.store_in(&b_x);
y.store_in(&b_y);
output.store_in(&b_output,{i,j});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_A, &b_x, &b_y, &b_output}, "build/generated_syr2_2.o");
return 0;
}
Delete syr2_2_generator.cpp
|
//===--- swift-ide-test.cpp - IDE functionality testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "XMLValidator.h"
#include "swift/APINotes/APINotesReader.h"
#include "swift/APINotes/APINotesWriter.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/RawComment.h"
#include "swift/AST/USRGeneration.h"
#include "swift/Basic/DemangleWrappers.h"
#include "swift/Basic/DiagnosticConsumer.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Driver/FrontendUtil.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/IDE/CommentConversion.h"
#include "swift/IDE/ModuleInterfacePrinting.h"
#include "swift/IDE/REPLCodeCompletion.h"
#include "swift/IDE/SourceEntityWalker.h"
#include "swift/IDE/SyntaxModel.h"
#include "swift/IDE/Utils.h"
#include "swift/ReST/Parser.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <system_error>
#include <string>
using namespace swift;
using namespace ide;
enum class ActionType {
None,
CodeCompletion,
REPLCodeCompletion,
SyntaxColoring,
Structure,
Annotation,
TestInputCompleteness,
PrintASTNotTypeChecked,
PrintASTTypeChecked,
PrintModule,
PrintTypes,
PrintComments,
PrintModuleComments,
PrintModuleImports,
PrintUSRs,
ParseReST,
GenerateAPIAnnotation,
CheckAPIAnnotation,
TestCreateCompilerInvocation,
};
namespace options {
static llvm::cl::opt<ActionType>
Action(llvm::cl::desc("Mode:"), llvm::cl::init(ActionType::None),
llvm::cl::values(
clEnumValN(ActionType::CodeCompletion,
"code-completion", "Perform code completion"),
clEnumValN(ActionType::REPLCodeCompletion,
"repl-code-completion", "Perform REPL-style code completion"),
clEnumValN(ActionType::SyntaxColoring,
"syntax-coloring", "Perform syntax coloring"),
clEnumValN(ActionType::Structure,
"structure", "Perform document structure annotation"),
clEnumValN(ActionType::Annotation,
"annotate", "Perform semantic annotation"),
clEnumValN(ActionType::TestInputCompleteness,
"test-input-complete", "Check if input source is complete"),
clEnumValN(ActionType::PrintASTNotTypeChecked,
"print-ast-not-typechecked", "Print the non-typechecked AST"),
clEnumValN(ActionType::PrintASTTypeChecked,
"print-ast-typechecked", "Print the typechecked AST"),
clEnumValN(ActionType::PrintModule,
"print-module", "Print visible declarations in a module"),
clEnumValN(ActionType::PrintTypes,
"print-types", "Print types of all subexpressions and declarations in the AST"),
clEnumValN(ActionType::PrintComments,
"print-comments", "Print documentation comments attached to decls"),
clEnumValN(ActionType::PrintModuleComments,
"print-module-comments", "Given a module, print documentation comments attached to decls"),
clEnumValN(ActionType::PrintModuleImports,
"print-module-imports", "Recursively print all imports visible from a particular module"),
clEnumValN(ActionType::PrintUSRs,
"print-usrs", "Print USRs for all decls"),
clEnumValN(ActionType::ParseReST,
"parse-rest", "Parse a ReST file"),
clEnumValN(ActionType::GenerateAPIAnnotation,
"generate-api-annotation",
"Generate an API annotation file"),
clEnumValN(ActionType::CheckAPIAnnotation,
"check-api-annotation",
"Check an API annotation file"),
clEnumValN(ActionType::TestCreateCompilerInvocation,
"test-createCompilerInvocation",
"Test swift::driver::createCompilerInvocation using the "
"arguments passed to swift-ide-test (must be specified "
"before all other arguments)"),
clEnumValEnd));
static llvm::cl::opt<std::string>
SourceFilename("source-filename", llvm::cl::desc("Name of the source file"));
static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("[input files...]"),
llvm::cl::ZeroOrMore);
static llvm::cl::opt<std::string>
OutputFilename("o",
llvm::cl::desc("Output file name"));
static llvm::cl::list<std::string>
BuildConfigs("D", llvm::cl::desc("Build configurations"));
#ifndef SWIFT_MODULES_SDK
#define SWIFT_MODULES_SDK ""
#endif
static llvm::cl::opt<std::string>
SDK("sdk", llvm::cl::desc("path to the SDK to build against"),
llvm::cl::init(SWIFT_MODULES_SDK));
static llvm::cl::opt<std::string>
Triple("target", llvm::cl::desc("target triple"));
static llvm::cl::opt<std::string>
ModuleCachePath("module-cache-path", llvm::cl::desc("Clang module cache path"),
llvm::cl::init(SWIFT_MODULE_CACHE_PATH));
static llvm::cl::list<std::string>
ImportPaths("I", llvm::cl::desc("add a directory to the import search path"));
static llvm::cl::list<std::string>
FrameworkPaths("F", llvm::cl::desc("add a directory to the framework search path"));
static llvm::cl::opt<std::string>
ResourceDir("resource-dir",
llvm::cl::desc("The directory that holds the compiler resource files"));
static llvm::cl::opt<std::string>
ImportObjCHeader("import-objc-header", llvm::cl::desc("header to implicitly import"));
static llvm::cl::opt<bool>
EnableSourceImport("enable-source-import", llvm::cl::Hidden,
llvm::cl::init(false));
static llvm::cl::opt<bool>
SplitObjCSelectors("split-objc-selectors",
llvm::cl::desc("Split Objective-C selectors"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ImplicitProperties("enable-objc-implicit-properties",
llvm::cl::desc("Implicitly import Objective-C getter/setter pairs as properties"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
FactoryMethodsAsConstructors("enable-objc-factory-method-constructors",
llvm::cl::desc("Implicitly import Objective-C factory methods as initializers"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
PrintStats("print-stats",
llvm::cl::desc("Print statistics"),
llvm::cl::init(false));
// '-code-completion' options.
static llvm::cl::opt<std::string>
CodeCompletionToken("code-completion-token",
llvm::cl::desc("Code completion token name"));
static llvm::cl::opt<bool>
CodeCompletionDiagnostics("code-completion-diagnostics",
llvm::cl::desc("Print compiler diagnostics while "
"doing code completion"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
CodeCompletionKeywords("code-completion-keywords",
llvm::cl::desc("Include keywords in code completion results"),
llvm::cl::init(true));
// '-syntax-coloring' options.
static llvm::cl::opt<bool>
TerminalOutput("terminal",
llvm::cl::desc("Use terminal color for source annotations"));
static llvm::cl::opt<bool>
Typecheck("typecheck",
llvm::cl::desc("Type check the AST"),
llvm::cl::init(false));
// AST printing options.
static llvm::cl::opt<bool>
FunctionDefinitions("function-definitions",
llvm::cl::desc("Print function bodies"),
llvm::cl::init(true));
static llvm::cl::opt<bool>
PreferTypeRepr("prefer-type-repr",
llvm::cl::desc("When printing types, prefer printing TypeReprs"),
llvm::cl::init(true));
static llvm::cl::opt<bool>
FullyQualifiedTypes("fully-qualified-types",
llvm::cl::desc("Print fully qualified types"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ExplodePatternBindingDecls(
"explode-pattern-binding-decls",
llvm::cl::desc("Separate pattern binding decls into individual var decls"),
llvm::cl::init(false));
static llvm::cl::opt<std::string>
MangledNameToFind("find-mangled",
llvm::cl::desc("Print the entity with the given mangled name"));
// Module printing options.
static llvm::cl::list<std::string>
ModuleToPrint("module-to-print",
llvm::cl::desc("Name of the module to print"));
static llvm::cl::opt<bool>
ModulePrintSubmodules("module-print-submodules",
llvm::cl::desc("Recursively print submodules"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ModulePrintHidden("module-print-hidden",
llvm::cl::desc("Print non-exported imported or submodules"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ModulePrintSkipOverlay("module-print-skip-overlay",
llvm::cl::desc("Skip Swift overlay modules"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
FullyQualifiedTypesIfAmbiguous(
"fully-qualified-types-if-ambiguous",
llvm::cl::desc("Print types fully-qualified if they would be ambiguous "
"otherwise"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
SynthesizeSugarOnTypes(
"synthesize-sugar-on-types",
llvm::cl::desc("Always print Array and Optional with sugar"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
AnnotatePrint("annotate-print",
llvm::cl::desc("Annotate AST printing"),
llvm::cl::init(false));
// AST and module printing options.
static llvm::cl::opt<bool>
PrintImplicitAttrs("print-implicit-attrs",
llvm::cl::desc("Print implicit attributes"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
PrintAccessibility("print-accessibility",
llvm::cl::desc("Print accessibility for all values"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
SkipUnavailable("skip-unavailable",
llvm::cl::desc("Don't print unavailable declarations"),
llvm::cl::init(false));
static llvm::cl::opt<Accessibility>
AccessibilityFilter(
llvm::cl::desc("Accessibility filter:"),
llvm::cl::init(Accessibility::Private),
llvm::cl::values(
clEnumValN(Accessibility::Private, "accessibility-filter-private",
"Print all declarations"),
clEnumValN(Accessibility::Internal, "accessibility-filter-internal",
"Print internal and public declarations"),
clEnumValN(Accessibility::Public, "accessibility-filter-public",
"Print public declarations"),
clEnumValEnd));
static llvm::cl::opt<bool>
SkipPrivateStdlibDecls("skip-private-stdlib-decls",
llvm::cl::desc("Don't print declarations that start with '_'"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
PrintRegularComments("print-regular-comments",
llvm::cl::desc("Print regular comments from clang module headers"),
llvm::cl::init(false));
static llvm::cl::opt<std::string>
CommentsXMLSchema("comments-xml-schema",
llvm::cl::desc("Filename of the RelaxNG schema for documentation comments"));
} // namespace options
static std::unique_ptr<llvm::MemoryBuffer>
removeCodeCompletionTokens(llvm::MemoryBuffer *Input,
StringRef TokenName,
unsigned *CodeCompletionOffset) {
std::string CleanFile =
ide::removeCodeCompletionTokens(Input->getBuffer(),
TokenName,
CodeCompletionOffset);
return std::unique_ptr<llvm::MemoryBuffer>(
llvm::MemoryBuffer::getMemBufferCopy(CleanFile,
Input->getBufferIdentifier()));
}
static int doCodeCompletion(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
StringRef CodeCompletionToken,
bool CodeCompletionDiagnostics,
bool CodeCompletionKeywords) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
unsigned CodeCompletionOffset;
std::unique_ptr<llvm::MemoryBuffer> CleanFile(
removeCodeCompletionTokens(FileBufOrErr.get().get(), CodeCompletionToken,
&CodeCompletionOffset));
if (CodeCompletionOffset == ~0U) {
llvm::errs() << "could not find code completion token \""
<< CodeCompletionToken << "\"\n";
return 1;
}
llvm::outs() << "found code completion token " << CodeCompletionToken
<< " at offset " << CodeCompletionOffset << "\n";
llvm::errs() << "found code completion token " << CodeCompletionToken
<< " at offset " << CodeCompletionOffset << "\n";
CompilerInvocation Invocation(InitInvok);
Invocation.setCodeCompletionPoint(CleanFile.get(), CodeCompletionOffset);
ide::CodeCompletionCache CompletionCache;
ide::CodeCompletionContext CompletionContext(CompletionCache);
// Create a CodeCompletionConsumer.
std::unique_ptr<ide::CodeCompletionConsumer> Consumer(
new ide::PrintingCodeCompletionConsumer(
llvm::outs(), CodeCompletionKeywords));
// Cerate a factory for code completion callbacks that will feed the
// Consumer.
std::unique_ptr<CodeCompletionCallbacksFactory> CompletionCallbacksFactory(
ide::makeCodeCompletionCallbacksFactory(CompletionContext,
*Consumer.get()));
Invocation.setCodeCompletionFactory(CompletionCallbacksFactory.get());
CompilerInstance CI;
PrintingDiagnosticConsumer PrintDiags;
if (CodeCompletionDiagnostics) {
// Display diagnostics to stderr.
CI.addDiagnosticConsumer(&PrintDiags);
}
if (CI.setup(Invocation))
return 1;
CI.performSema();
return 0;
}
static int doREPLCodeCompletion(const CompilerInvocation &InitInvok,
StringRef SourceFilename) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
StringRef BufferText = FileBufOrErr.get()->getBuffer();
// Drop a single newline character from the buffer.
if (BufferText.endswith("\n"))
BufferText = BufferText.drop_back(1);
CompilerInvocation Invocation(InitInvok);
Invocation.setInputKind(SourceFileKind::REPL);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
SourceFile &SF = CI.getMainModule()->getMainSourceFile(SourceFileKind::REPL);
REPLCompletions REPLCompl;
REPLCompl.populate(SF, BufferText);
llvm::outs() << "Begin completions\n";
for (StringRef S : REPLCompl.getCompletionList()) {
llvm::outs() << S << "\n";
}
llvm::outs() << "End completions\n";
return 0;
}
//============================================================================//
// Syntax Coloring
//============================================================================//
namespace {
class PrintSyntaxColorWalker : public ide::SyntaxModelWalker {
SourceManager &SM;
unsigned BufferID;
llvm::raw_ostream &OS;
bool TerminalOutput;
const char *BufStart;
const char *BufEnd;
const char *CurrBufPtr;
public:
PrintSyntaxColorWalker(SourceManager &SM,
unsigned BufferID,
llvm::raw_ostream &OS,
bool TerminalOutput)
: SM(SM), BufferID(BufferID), OS(OS), TerminalOutput(TerminalOutput) {
CharSourceRange entireRange = SM.getRangeForBuffer(BufferID);
StringRef Buffer = SM.extractText(entireRange);
BufStart = Buffer.data();
BufEnd = Buffer.data() + Buffer.size();
CurrBufPtr = BufStart;
}
bool walkToNodePre(SyntaxNode Node) override {
if (shouldIgnore(Node))
return false;
const char *LocPtr = getPtr(Node.Range.getStart());
printSourceUntil(LocPtr);
wrap(Node.Kind, /*Begin=*/true);
return true;
}
bool walkToNodePost(SyntaxNode Node) override {
if (shouldIgnore(Node))
return true;
const char *LocPtr = getPtr(Node.Range.getStart());
unsigned Length = Node.Range.getByteLength();
if (Node.Kind == SyntaxNodeKind::CommentLine) {
if (LocPtr[Length-1] == '\n')
--Length; // Wrapping should be in the same line.
}
printSourceUntil(LocPtr + Length);
wrap(Node.Kind, /*Begin=*/false);
return true;
}
void wrap(SyntaxNodeKind Kind, bool Begin) {
if (TerminalOutput) {
wrapForTerminal(Kind, Begin);
} else {
wrapForTest(Kind, Begin);
}
}
bool shouldIgnore(SyntaxNode Node) const {
const char *LocPtr = getPtr(Node.Range.getStart());
if (Node.Kind == SyntaxNodeKind::CommentLine && !TerminalOutput) {
// Ignore CHECK lines.
if (StringRef(LocPtr, BufEnd - LocPtr).startswith("// CHECK"))
return true;
}
return false;
}
const char *getPtr(SourceLoc Loc) const {
return BufStart + SM.getLocOffsetInBuffer(Loc, BufferID);
}
void printSourceUntil(const char *Ptr) {
assert(Ptr >= CurrBufPtr && Ptr <= BufEnd);
StringRef Text = StringRef(CurrBufPtr, Ptr-CurrBufPtr);
// Skip all "// CHECK" lines.
while (true) {
size_t Idx = Text.find("// CHECK");
if (Idx == StringRef::npos)
break;
OS << Text.substr(0, Idx);
Idx = Text.find('\n', Idx);
Text = Idx == StringRef::npos ? StringRef() : Text.substr(Idx+1);
}
OS << Text;
CurrBufPtr = Ptr;
}
void wrapForTest(SyntaxNodeKind Kind, bool Begin) {
const char *Id = 0;
switch (Kind) {
case SyntaxNodeKind::Keyword: Id = "kw"; break;
// Skip identifier.
case SyntaxNodeKind::Identifier: return;
case SyntaxNodeKind::DollarIdent: Id = "dollar"; break;
case SyntaxNodeKind::Integer: Id = "int"; break;
case SyntaxNodeKind::Floating: Id = "float"; break;
case SyntaxNodeKind::String: Id = "str"; break;
case SyntaxNodeKind::Character: Id = "char"; break;
case SyntaxNodeKind::CommentLine: Id = "comment-line"; break;
case SyntaxNodeKind::CommentBlock: Id = "comment-block"; break;
case SyntaxNodeKind::CommentMarker: Id = "comment-marker"; break;
case SyntaxNodeKind::CommentURL: Id = "comment-url"; break;
case SyntaxNodeKind::TypeId: Id = "type"; break;
case SyntaxNodeKind::BuildConfigKeyword: Id = "#kw"; break;
case SyntaxNodeKind::BuildConfigId: Id = "#id"; break;
case SyntaxNodeKind::AttributeId: Id = "attr-id"; break;
case SyntaxNodeKind::AttributeBuiltin: Id = "attr-builtin"; break;
}
OS << (Begin ? "<" : "</") << Id << '>';
}
void wrapForTerminal(SyntaxNodeKind Kind, bool Begin) {
llvm::raw_ostream::Colors Col;
switch (Kind) {
case SyntaxNodeKind::Keyword: Col = llvm::raw_ostream::MAGENTA; break;
// Skip identifier.
case SyntaxNodeKind::Identifier: return;
case SyntaxNodeKind::DollarIdent: Col = llvm::raw_ostream::MAGENTA; break;
case SyntaxNodeKind::Integer: Col = llvm::raw_ostream::BLUE; break;
case SyntaxNodeKind::Floating: Col = llvm::raw_ostream::BLUE; break;
case SyntaxNodeKind::String: Col = llvm::raw_ostream::RED; break;
case SyntaxNodeKind::Character: Col = llvm::raw_ostream::BLUE; break;
case SyntaxNodeKind::CommentLine: Col = llvm::raw_ostream::GREEN; break;
case SyntaxNodeKind::CommentBlock: Col = llvm::raw_ostream::GREEN; break;
case SyntaxNodeKind::CommentMarker: Col = llvm::raw_ostream::MAGENTA; break;
case SyntaxNodeKind::CommentURL: Col = llvm::raw_ostream::RED; break;
case SyntaxNodeKind::TypeId: Col = llvm::raw_ostream::CYAN; break;
case SyntaxNodeKind::BuildConfigKeyword: Col = llvm::raw_ostream::YELLOW; break;
case SyntaxNodeKind::BuildConfigId: Col = llvm::raw_ostream::YELLOW; break;
case SyntaxNodeKind::AttributeId: Col = llvm::raw_ostream::CYAN; break;
case SyntaxNodeKind::AttributeBuiltin: Col = llvm::raw_ostream::MAGENTA; break;
}
if (Begin) {
if (const char *CStr =
llvm::sys::Process::OutputColor(Col, false, false)) {
OS << CStr;
}
} else {
OS << llvm::sys::Process::ResetColor();
}
}
void finished() {
OS << StringRef(CurrBufPtr, BufEnd-CurrBufPtr);
}
};
}
static int doSyntaxColoring(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool TerminalOutput,
bool RunTypeChecker) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
if (!RunTypeChecker)
CI.performParseOnly();
else
CI.performSema();
unsigned BufID = CI.getInputBufferIDs().back();
SourceFile *SF = nullptr;
for (auto Unit : CI.getMainModule()->getFiles()) {
SF = dyn_cast<SourceFile>(Unit);
if (SF)
break;
}
assert(SF && "no source file?");
ide::SyntaxModelContext ColorContext(*SF);
PrintSyntaxColorWalker ColorWalker(CI.getSourceMgr(), BufID, llvm::outs(),
TerminalOutput);
ColorContext.walk(ColorWalker);
ColorWalker.finished();
return 0;
}
//============================================================================//
// Structure Annotation
//============================================================================//
class PrintStructureWalker : public ide::SyntaxModelWalker {
SourceManager &SM;
llvm::raw_ostream &OS;
unsigned indentLevel = 0;
public:
PrintStructureWalker(SourceManager &SM,
llvm::raw_ostream &OS)
: SM(SM), OS(OS) {
}
bool walkToSubStructurePre(SyntaxStructureNode Node) override {
auto Start = SM.getLineAndColumn(Node.Range.getStart());
auto End = SM.getLineAndColumn(Node.Range.getEnd());
OS << std::string(indentLevel * 2, ' ');
switch (Node.Kind) {
case swift::ide::SyntaxStructureKind::Class:
OS << "Class ";
break;
case swift::ide::SyntaxStructureKind::Struct:
OS << "Struct ";
break;
case swift::ide::SyntaxStructureKind::Protocol:
OS << "Protocol ";
break;
case swift::ide::SyntaxStructureKind::Enum:
OS << "Enum ";
break;
case swift::ide::SyntaxStructureKind::Extension:
OS << "Extension ";
break;
case swift::ide::SyntaxStructureKind::FreeFunction:
case swift::ide::SyntaxStructureKind::InstanceFunction:
case swift::ide::SyntaxStructureKind::StaticFunction:
OS << "Func ";
break;
case swift::ide::SyntaxStructureKind::InstanceVariable:
OS << "Property ";
break;
case swift::ide::SyntaxStructureKind::Parameter:
OS << "Parameter ";
break;
case swift::ide::SyntaxStructureKind::BraceStatement:
OS << "Brace ";
break;
case swift::ide::SyntaxStructureKind::CallExpression:
OS << "Call ";
break;
}
OS << "at " << Start.first << ":" << Start.second << " - " <<
End.first << ":" << End.second;
if (Node.NameRange.isValid()) {
auto Start = SM.getLineAndColumn(Node.NameRange.getStart());
auto End = SM.getLineAndColumn(Node.NameRange.getEnd());
OS << ", name at " << Start.first << ":" << Start.second << " - " <<
End.first << ":" << End.second;
}
if (!Node.InheritedTypeRanges.empty()) {
OS << ", inherited types at";
for (auto &Range : Node.InheritedTypeRanges) {
auto Start = SM.getLineAndColumn(Range.getStart());
auto End = SM.getLineAndColumn(Range.getEnd());
OS << " " << Start.first << ":" << Start.second << " - " <<
End.first << ":" << End.second;
}
}
OS << "\n";
++indentLevel;
return true;
}
bool walkToSubStructurePost(SyntaxStructureNode Node) override {
assert(indentLevel > 0);
--indentLevel;
return true;
}
};
static int doStructureAnnotation(const CompilerInvocation &InitInvok,
StringRef SourceFilename) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performParseOnly();
ide::SyntaxModelContext StructureContext(
CI.getMainModule()->getMainSourceFile(SourceFileKind::Main));
PrintStructureWalker StructureWalker(CI.getSourceMgr(), llvm::outs());
StructureContext.walk(StructureWalker);
return 0;
}
//============================================================================//
// Semantic Annotation
//============================================================================//
namespace {
class AnnotationPrinter : public ide::SourceEntityWalker {
SourceManager &SM;
unsigned BufferID;
llvm::raw_ostream &OS;
bool TerminalOutput;
const char *BufStart;
const char *BufEnd;
const char *CurrBufPtr;
public:
AnnotationPrinter(SourceManager &SM,
unsigned BufferID,
llvm::raw_ostream &OS,
bool TerminalOutput)
: SM(SM), BufferID(BufferID), OS(OS), TerminalOutput(TerminalOutput) {
CharSourceRange entireRange = SM.getRangeForBuffer(BufferID);
StringRef Buffer = SM.extractText(entireRange);
BufStart = Buffer.data();
BufEnd = Buffer.data() + Buffer.size();
CurrBufPtr = BufStart;
}
void finished() {
OS << StringRef(CurrBufPtr, BufEnd-CurrBufPtr);
}
private:
struct SemanticSourceEntity {
CharSourceRange Range;
ValueDecl *Dcl = nullptr;
TypeDecl *CtorTyRef = nullptr;
ModuleEntity Mod;
bool IsRef = true;
SemanticSourceEntity(CharSourceRange Range,
ValueDecl *Dcl,
TypeDecl *CtorTyRef,
bool IsRef)
: Range(Range),
Dcl(Dcl),
CtorTyRef(CtorTyRef),
IsRef(IsRef) {}
SemanticSourceEntity(CharSourceRange Range,
ModuleEntity Mod)
: Range(Range),
Mod(Mod) {}
};
bool walkToDeclPre(Decl *D, CharSourceRange Range) override {
if (Range.getByteLength() == 0)
return true;
if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
annotateSourceEntity({ Range, VD, nullptr, /*IsRef=*/false});
return true;
}
bool visitDeclReference(ValueDecl *D, CharSourceRange Range,
TypeDecl *CtorTyRef) override {
annotateSourceEntity({ Range, D, CtorTyRef, /*IsRef=*/true });
return true;
}
bool visitCallArgName(Identifier Name, CharSourceRange Range,
ValueDecl *D) override {
annotateSourceEntity({ Range, D, nullptr, /*IsRef=*/true });
return true;
}
bool visitModuleReference(ModuleEntity Mod, CharSourceRange Range) override {
annotateSourceEntity({ Range, Mod });
return true;
}
void annotateSourceEntity(const SemanticSourceEntity &Entity) {
const char *LocPtr =
BufStart + SM.getLocOffsetInBuffer(Entity.Range.getStart(), BufferID);
unsigned Length = Entity.Range.getByteLength();
assert(LocPtr >= CurrBufPtr);
printSourceUntil(LocPtr);
StringRef NodeText = StringRef(LocPtr, Length);
if (TerminalOutput) {
if (!wrapForTerminal(Entity, NodeText))
OS << NodeText;
} else {
if (!wrapForTest(Entity, StringRef(LocPtr, Length)))
OS << NodeText;
}
CurrBufPtr = LocPtr + Length;
}
void printSourceUntil(const char *Ptr) {
StringRef Text = StringRef(CurrBufPtr, Ptr-CurrBufPtr);
// Skip all "// CHECK" lines.
while (true) {
size_t Idx = Text.find("// CHECK");
if (Idx == StringRef::npos)
break;
OS << Text.substr(0, Idx);
Idx = Text.find('\n', Idx);
Text = Idx == StringRef::npos ? StringRef() : Text.substr(Idx+1);
}
OS << Text;
}
void printLoc(SourceLoc Loc, raw_ostream &OS) {
OS << '@';
if (Loc.isValid()) {
auto LineCol = SM.getLineAndColumn(Loc, BufferID);
OS << LineCol.first << ':' << LineCol.second;
}
}
bool wrapForTest(const SemanticSourceEntity &Entity, StringRef Text) {
OS << '<';
bool IsInSystemModule = false;
ValueDecl *D = Entity.Dcl;
if (D) {
IsInSystemModule = D->getModuleContext()->isSystemModule();
if (IsInSystemModule)
OS << 'i';
if (isa<ConstructorDecl>(D) && Entity.IsRef) {
OS << "Ctor";
printLoc(D->getLoc(), OS);
if (Entity.CtorTyRef) {
OS << '-';
OS << Decl::getKindName(Entity.CtorTyRef->getKind());
printLoc(Entity.CtorTyRef->getLoc(), OS);
}
} else {
OS << Decl::getKindName(D->getKind());
if (Entity.IsRef)
printLoc(D->getLoc(), OS);
}
} else {
if (Entity.Mod.isSystemModule())
OS << 'i';
OS << "Mod";
}
OS << '>';
OS << Text;
OS << "</";
if (D) {
if (IsInSystemModule)
OS << 'i';
if (isa<ConstructorDecl>(D) && Entity.IsRef) {
OS << "Ctor";
} else {
OS << Decl::getKindName(D->getKind());
}
} else {
if (Entity.Mod.isSystemModule())
OS << 'i';
OS << "Mod";
}
OS << '>';
return true;
}
bool wrapForTerminal(const SemanticSourceEntity &Entity, StringRef Text) {
llvm::raw_ostream::Colors Col;
switch (Entity.Dcl->getKind()) {
default:
return false;
case DeclKind::Var:
Col = llvm::raw_ostream::GREEN;
break;
case DeclKind::Func:
case DeclKind::Constructor:
case DeclKind::Destructor:
Col = llvm::raw_ostream::MAGENTA;
break;
case DeclKind::Class:
Col = llvm::raw_ostream::RED;
break;
case DeclKind::Struct:
Col = llvm::raw_ostream::BLUE;
break;
case DeclKind::Protocol:
Col = llvm::raw_ostream::YELLOW;
break;
case DeclKind::TypeAlias:
case DeclKind::AssociatedType:
case DeclKind::GenericTypeParam:
Col = llvm::raw_ostream::CYAN; break;
}
if (const char *CStr =
llvm::sys::Process::OutputColor(Col, false, false)) {
OS << CStr;
}
OS << Text;
OS << llvm::sys::Process::ResetColor();
return true;
}
};
} // unnamed namespace
static int doSemanticAnnotation(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool TerminalOutput) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
unsigned BufID = CI.getInputBufferIDs().back();
AnnotationPrinter AnnotPrinter(CI.getSourceMgr(), BufID, llvm::outs(),
TerminalOutput);
AnnotPrinter.walk(*CI.getMainModule());
AnnotPrinter.finished();
return 0;
}
static int doInputCompletenessTest(StringRef SourceFilename) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
llvm::raw_ostream &OS = llvm::outs();
OS << SourceFilename << ": ";
if (isSourceInputComplete(std::move(FileBufOrErr.get())).IsComplete) {
OS << "IS_COMPLETE\n";
} else {
OS << "IS_INCOMPLETE\n";
}
return 0;
}
//============================================================================//
// AST printing
//============================================================================//
static Module *getModuleByFullName(ASTContext &Context, StringRef ModuleName) {
SmallVector<std::pair<Identifier, SourceLoc>, 4>
AccessPath;
while (!ModuleName.empty()) {
StringRef SubModuleName;
std::tie(SubModuleName, ModuleName) = ModuleName.split('.');
AccessPath.push_back(
{ Context.getIdentifier(SubModuleName), SourceLoc() });
}
return Context.getModule(AccessPath);
}
static Module *getModuleByFullName(ASTContext &Context, Identifier ModuleName) {
return Context.getModule(std::make_pair(ModuleName, SourceLoc()));
}
static int doPrintAST(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool RunTypeChecker,
bool FunctionDefinitions,
bool PreferTypeRepr,
bool ExplodePatternBindingDecls,
bool PrintImplicitAttrs,
bool PrintAccessibility,
bool PrintUnavailableDecls,
Accessibility AccessibilityFilter) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
if (!RunTypeChecker)
CI.performParseOnly();
else
CI.performSema();
PrintOptions Options = PrintOptions::printEverything();
Options.FunctionDefinitions = FunctionDefinitions;
Options.PreferTypeRepr = PreferTypeRepr;
Options.ExplodePatternBindingDecls = ExplodePatternBindingDecls;
Options.PrintImplicitAttrs = PrintImplicitAttrs;
Options.PrintAccessibility = PrintAccessibility;
Options.AccessibilityFilter = AccessibilityFilter;
Options.SkipUnavailable = !PrintUnavailableDecls;
if (options::MangledNameToFind.empty()) {
Module *M = CI.getMainModule();
M->getMainSourceFile(Invocation.getInputKind()).print(llvm::outs(),
Options);
return EXIT_SUCCESS;
}
// If we were given a mangled name, do a very simple form of LLDB's logic to
// look up a type based on that name.
Demangle::NodePointer node =
demangle_wrappers::demangleSymbolAsNode(options::MangledNameToFind);
using NodeKind = Demangle::Node::Kind;
if (node->getKind() != NodeKind::Global) {
llvm::errs() << "Unable to demangle name.\n";
return EXIT_FAILURE;
}
node = node->getFirstChild();
// FIXME: Look up things other than types.
if (node->getKind() != NodeKind::Type) {
llvm::errs() << "Name does not refer to a type.\n";
return EXIT_FAILURE;
}
node = node->getFirstChild();
switch (node->getKind()) {
case NodeKind::Class:
case NodeKind::Enum:
case NodeKind::Protocol:
case NodeKind::Structure:
break;
default:
llvm::errs() << "Name does not refer to a nominal type.\n";
return EXIT_FAILURE;
}
ASTContext &ctx = CI.getASTContext();
LookupName lookupName;
auto nameNode = node->getChild(1);
switch (nameNode->getKind()) {
case NodeKind::Identifier:
lookupName.Name = ctx.getIdentifier(nameNode->getText());
break;
case NodeKind::PrivateDeclName:
lookupName.PrivateDiscriminator =
ctx.getIdentifier(nameNode->getChild(0)->getText());
lookupName.Name = ctx.getIdentifier(nameNode->getChild(1)->getText());
break;
default:
llvm::errs() << "Unsupported name kind.\n";
return EXIT_FAILURE;
}
auto contextNode = node->getFirstChild();
// FIXME: Handle nested contexts.
if (contextNode->getKind() != NodeKind::Module) {
llvm::errs() << "Name does not refer to a top-level declaration.\n";
return EXIT_FAILURE;
}
const Module *M = getModuleByFullName(ctx, contextNode->getText());
SmallVector<ValueDecl *, 4> results;
M->lookupValue({}, lookupName.Name, NLKind::QualifiedLookup, results);
if (!lookupName.PrivateDiscriminator.empty()) {
auto newEnd = std::remove_if(results.begin(), results.end(),
[=](ValueDecl *VD) {
auto enclosingFile =
cast<FileUnit>(VD->getDeclContext()->getModuleScopeContext());
auto discriminator = enclosingFile->getDiscriminatorForPrivateValue(VD);
return discriminator != lookupName.PrivateDiscriminator;
});
results.erase(newEnd, results.end());
}
if (results.empty()) {
llvm::errs() << "No matching declarations found.\n";
return EXIT_FAILURE;
}
for (auto *VD : results)
VD->print(llvm::outs(), Options);
return EXIT_SUCCESS;
}
namespace {
class AnnotatingPrinter : public StreamPrinter {
public:
using StreamPrinter::StreamPrinter;
void printDeclPre(const Decl *D) override {
OS << "<decl:" << Decl::getKindName(D->getKind()) << '>';
}
void printDeclLoc(const Decl *D) override {
OS << "<loc>";
}
void printDeclNameEndLoc(const Decl *D) override {
OS << "</loc>";
}
void printDeclPost(const Decl *D) override {
OS << "</decl>";
}
void printTypeRef(const TypeDecl *TD, Identifier Name) override {
OS << "<ref:" << Decl::getKindName(TD->getKind()) << '>';
StreamPrinter::printTypeRef(TD, Name);
OS << "</ref>";
}
void printModuleRef(const Module *Mod, Identifier Name) override {
OS << "<ref:module>";
StreamPrinter::printModuleRef(Mod, Name);
OS << "</ref>";
}
};
}
static int doPrintModules(const CompilerInvocation &InitInvok,
const std::vector<std::string> ModulesToPrint,
ide::ModuleTraversalOptions TraversalOptions,
bool FullyQualifiedTypesIfAmbiguous,
bool SynthesizeSugarOnTypes,
bool AnnotatePrint,
bool PrintImplicitAttrs,
bool PrintAccessibility,
bool PrintUnavailableDecls,
bool PrintRegularComments,
Accessibility AccessibilityFilter,
bool PrintPrivateStdlibDecls) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
auto &Context = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Context, Context.StdlibModuleName);
if (!Stdlib)
return 1;
int ExitCode = 0;
PrintOptions Options = PrintOptions::printEverything();
Options.FullyQualifiedTypesIfAmbiguous = FullyQualifiedTypesIfAmbiguous;
Options.SynthesizeSugarOnTypes = SynthesizeSugarOnTypes;
Options.PrintImplicitAttrs = PrintImplicitAttrs;
Options.PrintAccessibility = PrintAccessibility;
Options.AccessibilityFilter = AccessibilityFilter;
Options.PrintRegularClangComments = PrintRegularComments;
Options.SkipPrivateStdlibDecls = !PrintPrivateStdlibDecls;
Options.SkipUnavailable = !PrintUnavailableDecls;
std::unique_ptr<ASTPrinter> Printer;
if (AnnotatePrint)
Printer.reset(new AnnotatingPrinter(llvm::outs()));
else
Printer.reset(new StreamPrinter(llvm::outs()));
for (StringRef ModuleToPrint : ModulesToPrint) {
if (ModuleToPrint.empty()) {
ExitCode = 1;
continue;
}
// Get the (sub)module to print.
auto *M = getModuleByFullName(Context, ModuleToPrint);
if (!M) {
ExitCode = 1;
continue;
}
// Split the module path.
std::vector<StringRef> ModuleName;
while (!ModuleToPrint.empty()) {
StringRef SubModuleName;
std::tie(SubModuleName, ModuleToPrint) = ModuleToPrint.split('.');
ModuleName.push_back(SubModuleName);
}
assert(!ModuleName.empty());
// FIXME: If ModuleToPrint is a submodule, get its top-level module, which
// will be the DeclContext for all of its Decls since we don't have first-
// class submodules.
if (ModuleName.size() > 1) {
M = getModuleByFullName(Context, ModuleName[0]);
if (!M) {
ExitCode = 1;
continue;
}
}
printSubmoduleInterface(M, ModuleName, TraversalOptions, *Printer, Options);
}
return ExitCode;
}
namespace {
class ASTTypePrinter : public ASTWalker {
raw_ostream &OS;
SourceManager &SM;
const PrintOptions &Options;
unsigned IndentLevel = 0;
public:
ASTTypePrinter(SourceManager &SM, const PrintOptions &Options)
: OS(llvm::outs()), SM(SM), Options(Options) {}
bool walkToDeclPre(Decl *D) override {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
OS.indent(IndentLevel * 2);
OS << Decl::getKindName(VD->getKind()) << "Decl '''"
<< VD->getName().str() << "''' ";
VD->getType().print(OS, Options);
OS << "\n";
}
IndentLevel++;
return true;
}
bool walkToDeclPost(Decl *D) override {
IndentLevel--;
return true;
}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
StringRef SourceCode{ "<unknown>" };
unsigned Line = ~0U;
SourceRange SR = E->getSourceRange();
if (SR.isValid()) {
unsigned BufferID = SM.findBufferContainingLoc(SR.Start);
SourceLoc EndCharLoc = Lexer::getLocForEndOfToken(SM, SR.End);
SourceCode = SM.extractText({ SR.Start,
SM.getByteDistance(SR.Start, EndCharLoc) });
unsigned Column;
std::tie(Line, Column) = SM.getLineAndColumn(SR.Start, BufferID);
}
OS.indent(IndentLevel * 2);
OS << Expr::getKindName(E->getKind()) << "Expr";
if (Line != ~0U)
OS << ":" << Line;
OS << " '''" << SourceCode << "''' ";
E->getType().print(OS, Options);
OS << "\n";
IndentLevel++;
return { true, E };
}
Expr *walkToExprPost(Expr *E) override {
IndentLevel--;
return E;
}
};
} // unnamed namespace
static int doPrintTypes(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool FullyQualifiedTypes) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
PrintOptions Options = PrintOptions::printEverything();
Options.FullyQualifiedTypes = FullyQualifiedTypes;
ASTTypePrinter Printer(CI.getSourceMgr(), Options);
CI.getMainModule()->walk(Printer);
return 0;
}
namespace {
class ASTCommentPrinter : public ASTWalker {
raw_ostream &OS;
SourceManager &SM;
XMLValidator &TheXMLValidator;
public:
ASTCommentPrinter(SourceManager &SM, XMLValidator &TheXMLValidator)
: OS(llvm::outs()), SM(SM), TheXMLValidator(TheXMLValidator) {}
StringRef getBufferIdentifier(SourceLoc Loc) {
unsigned BufferID = SM.findBufferContainingLoc(Loc);
return SM.getIdentifierForBuffer(BufferID);
}
void printWithEscaping(StringRef Str) {
for (char C : Str) {
switch (C) {
case '\n': OS << "\\n"; break;
case '\r': OS << "\\r"; break;
case '\t': OS << "\\t"; break;
case '\v': OS << "\\v"; break;
case '\f': OS << "\\f"; break;
default: OS << C; break;
}
}
}
void printDeclName(const ValueDecl *VD) {
if (auto *NTD = dyn_cast<NominalTypeDecl>(VD->getDeclContext())) {
Identifier Id = NTD->getName();
if (!Id.empty())
OS << Id.str() << ".";
}
Identifier Id = VD->getName();
if (!Id.empty()) {
OS << Id.str();
return;
}
if (auto FD = dyn_cast<FuncDecl>(VD)) {
if (auto *ASD = FD->getAccessorStorageDecl()) {
switch (FD->getAccessorKind()) {
case AccessorKind::NotAccessor:
llvm_unreachable("is not an accessor?");
case AccessorKind::IsGetter:
OS << "<getter for ";
break;
case AccessorKind::IsSetter:
OS << "<setter for ";
break;
case AccessorKind::IsWillSet:
OS << "<willSet for ";
break;
case AccessorKind::IsDidSet:
OS << "<didSet for ";
break;
}
printDeclName(ASD);
OS << ">";
return;
}
}
OS << "<anonymous>";
}
void printRawComment(const RawComment &RC) {
OS << "RawComment=";
if (RC.isEmpty()) {
OS << "none";
return;
}
OS << "[";
for (auto &SRC : RC.Comments)
printWithEscaping(SRC.RawText);
OS << "]";
}
void printBriefComment(StringRef Brief) {
OS << "BriefComment=";
if (Brief.empty()) {
OS << "none";
return;
}
OS << "[";
printWithEscaping(Brief);
OS << "]";
}
void printFullComment(const Decl *D) {
std::string XML;
{
llvm::raw_string_ostream OS(XML);
getDocumentationCommentAsXML(D, OS);
}
OS << "FullCommentAsXML=";
if (XML.empty()) {
OS << "none";
return;
}
OS << "[";
printWithEscaping(XML);
OS << "]";
auto Status = TheXMLValidator.validate(XML);
switch (Status.Code) {
case XMLValidator::ErrorCode::Valid:
OS << " CommentXMLValid";
break;
case XMLValidator::ErrorCode::NotCompiledIn:
OS << " ValidationSkipped=[libxml is missing]";
break;
case XMLValidator::ErrorCode::NoSchema:
OS << " ValidationSkipped=[schema is not set]";
break;
case XMLValidator::ErrorCode::BadSchema:
OS << " CommentXMLInvalid=[bad schema file]";
break;
case XMLValidator::ErrorCode::NotWellFormed:
OS << " CommentXMLInvalid=[not well-formed XML: " << Status.Message
<< "]";
break;
case XMLValidator::ErrorCode::NotValid:
OS << " CommentXMLInvalid=[not valid XML: " << Status.Message << "]";
break;
case XMLValidator::ErrorCode::InternalError:
OS << " CommentXMLInvalid=[libxml error]";
break;
}
}
bool walkToDeclPre(Decl *D) override {
if (D->isImplicit())
return true;
if (auto *VD = dyn_cast<ValueDecl>(D)) {
SourceLoc Loc = D->getLoc();
if (Loc.isValid()) {
auto LineAndColumn = SM.getLineAndColumn(Loc);
OS << getBufferIdentifier(VD->getLoc())
<< ":" << LineAndColumn.first << ":" << LineAndColumn.second << ": ";
}
OS << Decl::getKindName(VD->getKind()) << "/";
printDeclName(VD);
OS << " ";
printRawComment(D->getRawComment());
OS << " ";
printBriefComment(D->getBriefComment());
OS << " ";
printFullComment(D);
OS << "\n";
}
return true;
}
};
} // unnamed namespace
static int doPrintComments(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
StringRef CommentsXMLSchema) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
Invocation.getLangOptions().AttachCommentsToDecls = true;
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
XMLValidator TheXMLValidator;
TheXMLValidator.setSchema(CommentsXMLSchema);
ASTCommentPrinter Printer(CI.getSourceMgr(), TheXMLValidator);
CI.getMainModule()->walk(Printer);
return 0;
}
static int doPrintModuleComments(const CompilerInvocation &InitInvok,
const std::vector<std::string> ModulesToPrint,
StringRef CommentsXMLSchema) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
auto &Context = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Context, Context.StdlibModuleName);
if (!Stdlib)
return 1;
XMLValidator TheXMLValidator;
TheXMLValidator.setSchema(CommentsXMLSchema);
ASTCommentPrinter Printer(CI.getSourceMgr(), TheXMLValidator);
int ExitCode = 0;
for (StringRef ModuleToPrint : ModulesToPrint) {
auto *M = getModuleByFullName(Context, ModuleToPrint);
if (!M) {
ExitCode = -1;
continue;
}
M->walk(Printer);
}
return ExitCode;
}
static int doPrintModuleImports(const CompilerInvocation &InitInvok,
const std::vector<std::string> ModulesToPrint) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
auto &Context = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Context, Context.StdlibModuleName);
if (!Stdlib)
return 1;
int ExitCode = 0;
for (StringRef ModuleToPrint : ModulesToPrint) {
auto *M = getModuleByFullName(Context, ModuleToPrint);
if (!M) {
ExitCode = -1;
continue;
}
auto isClangModule = [](const Module *M) -> bool {
if (!M->getFiles().empty())
if (M->getFiles().front()->getKind() == FileUnitKind::ClangModule)
return true;
return false;
};
SmallVector<Module::ImportedModule, 16> scratch;
M->forAllVisibleModules({}, [&](const Module::ImportedModule &next) {
llvm::outs() << next.second->Name;
if (isClangModule(next.second))
llvm::outs() << " (Clang)";
llvm::outs() << ":\n";
scratch.clear();
next.second->getImportedModules(scratch, Module::ImportFilter::Public);
for (auto &import : scratch) {
llvm::outs() << "\t" << import.second->Name;
for (auto accessPathPiece : import.first) {
llvm::outs() << "." << accessPathPiece.first;
}
if (isClangModule(import.second))
llvm::outs() << " (Clang)";
llvm::outs() << "\n";
}
});
}
return ExitCode;
}
//============================================================================//
// Print USRs
//============================================================================//
namespace {
class USRPrinter : public ide::SourceEntityWalker {
SourceManager &SM;
unsigned BufferID;
llvm::raw_ostream &OS;
public:
USRPrinter(SourceManager &SM, unsigned BufferID, llvm::raw_ostream &OS)
: SM(SM), BufferID(BufferID), OS(OS) { }
private:
bool walkToDeclPre(Decl *D, CharSourceRange Range) override {
if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
printUSR(VD, Range.getStart());
return true;
}
bool walkToExprPre(Expr *E) override {
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
printUSR(DRE->getDecl(), E->getLoc());
return true;
}
void printUSR(const ValueDecl *VD, SourceLoc Loc) {
printLoc(Loc);
OS << ' ';
if (ide::printDeclUSR(VD, OS))
OS << "ERROR:no-usr";
OS << '\n';
}
void printLoc(SourceLoc Loc) {
if (Loc.isValid()) {
auto LineCol = SM.getLineAndColumn(Loc, BufferID);
OS << LineCol.first << ':' << LineCol.second;
}
}
};
} // unnamed namespace
static int doPrintUSRs(const CompilerInvocation &InitInvok,
StringRef SourceFilename) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
// FIXME: Arggh, we need to get rid of this thing.
Invocation.getClangImporterOptions().ExtraArgs = {
"-detailed-preprocessing-record"
};
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
unsigned BufID = CI.getInputBufferIDs().back();
USRPrinter Printer(CI.getSourceMgr(), BufID, llvm::outs());
Printer.walk(*CI.getMainModule());
return 0;
}
static int doParseReST(StringRef SourceFilename) {
llvm::rest::ReSTContext Context;
llvm::rest::SourceManager<unsigned> SM;
llvm::SmallString<64> DocutilsXML;
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFileOrSTDIN(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
llvm::rest::LineList LL({});
{
SmallVector<StringRef, 16> Lines;
splitIntoLines(FileBufOrErr.get()->getBuffer(), Lines);
llvm::rest::LineListBuilder Builder;
for (auto S : Lines) {
Builder.addLine(S, SM.registerLine(S, 0));
}
LL = Builder.takeLineList(Context);
}
auto *TheDocument = parseDocument(Context, LL);
{
llvm::raw_svector_ostream OS(DocutilsXML);
convertToDocutilsXML(TheDocument, OS);
}
llvm::outs() << DocutilsXML.str();
return 0;
}
static int doTestCreateCompilerInvocation(ArrayRef<const char *> Args) {
PrintingDiagnosticConsumer PDC;
SourceManager SM;
DiagnosticEngine Diags(SM);
Diags.addConsumer(PDC);
std::unique_ptr<CompilerInvocation> CI =
driver::createCompilerInvocation(Args, Diags);
if (!CI) {
llvm::errs() << "error: unable to create a CompilerInvocation\n";
return 1;
}
return 0;
}
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// getMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement getMainExecutable
// without being given the address of a function in the main executable).
void anchorForGetMainExecutable() {}
namespace {
// Unavailable option.
struct Unavailable {
StringRef Msg;
Unavailable(StringRef Msg) : Msg(Msg) { }
};
// Signature has been audited with respect to optional types.
struct OptionalTypeAdjustment {
llvm::SmallVector<api_notes::NullableKind, 3> AdjustedTypes;
OptionalTypeAdjustment(unsigned numParams) {
assert(numParams == 0);
}
template<typename ...Ts>
OptionalTypeAdjustment(unsigned numParams, Ts ...kinds) {
if (numParams > 0 ) {
assert(sizeof...(Ts) == numParams);
api_notes::NullableKind actualKinds[] = { kinds... };
AdjustedTypes.append(actualKinds, actualKinds + numParams);
}
}
};
// DesignatedInit flag
enum DesignatedInitFlag { DesignatedInit };
// FactoryAsClassMethod flag
enum FactoryAsClassMethodFlag { FactoryAsClassMethod };
template<typename T>
T &&operator|(T &&known, Unavailable unavailable) {
known.Unavailable = true;
known.UnavailableMsg = unavailable.Msg;
return std::move(known);
}
api_notes::ObjCContextInfo &&operator|(api_notes::ObjCContextInfo &&known,
OptionalTypeAdjustment adjustment) {
assert(adjustment.AdjustedTypes.size() <= 1);
if (adjustment.AdjustedTypes.size() == 1) {
known.setDefaultNullability(adjustment.AdjustedTypes[0]);
}
return std::move(known);
}
api_notes::ObjCPropertyInfo &&operator|(api_notes::ObjCPropertyInfo &&known,
api_notes::NullableKind kind) {
known.setNullabilityAudited(kind);
return std::move(known);
}
api_notes::ObjCMethodInfo &&operator|(api_notes::ObjCMethodInfo &&known,
OptionalTypeAdjustment adjustment) {
known.NullabilityAudited = true;
known.NumAdjustedNullable = adjustment.AdjustedTypes.size();
for (unsigned i = 0; i < known.NumAdjustedNullable; ++i)
known.addTypeInfo(i, adjustment.AdjustedTypes[i]);
return std::move(known);
}
api_notes::ObjCMethodInfo &&operator|(api_notes::ObjCMethodInfo &&known,
DesignatedInitFlag) {
known.DesignatedInit = true;
return std::move(known);
}
api_notes::ObjCMethodInfo &&operator|(api_notes::ObjCMethodInfo &&known,
FactoryAsClassMethodFlag) {
known.setFactoryAsInitKind(api_notes::FactoryAsInitKind::AsClassMethod);
return std::move(known);
}
}
/// Generate an API annotation file from the known Objective-C methods
/// file.
///
/// FIXME: This is a horrible, horrible hack.
bool generateAPIAnnotation(StringRef moduleName, StringRef fileName) {
using namespace api_notes;
APINotesWriter writer(moduleName);
// Constants used to map from KnownObjCMethods.def.
const auto OTK_None = api_notes::NullableKind::NonNullable;
(void)OTK_None;
const auto OTK_Optional = api_notes::NullableKind::Nullable;
(void)OTK_Optional;
const auto OTK_ImplicitlyUnwrappedOptional
= api_notes::NullableKind::Unknown;
(void)OTK_ImplicitlyUnwrappedOptional;
StringRef currentModuleName;
#define START_MODULE(ModuleName) \
currentModuleName = #ModuleName;
#define MAKE_SELECTOR_REF(NumPieces, ...) \
ObjCSelectorRef{NumPieces, { __VA_ARGS__ } }
#define INSTANCE_METHOD(ClassName, Selector, Options) \
if (moduleName.equals(currentModuleName)) { \
auto contextID = writer.addObjCClass(#ClassName, \
ObjCContextInfo()); \
writer.addObjCMethod(contextID, MAKE_SELECTOR_REF Selector, \
/*isInstanceMethod=*/true, \
ObjCMethodInfo() | Options); \
}
#define PROTOCOL_INSTANCE_METHOD(ProtocolName, Selector, Options) \
if (moduleName.equals(currentModuleName)) { \
auto contextID = writer.addObjCProtocol(#ProtocolName, \
ObjCContextInfo()); \
writer.addObjCMethod(contextID, MAKE_SELECTOR_REF Selector, \
/*isInstanceMethod=*/true, \
ObjCMethodInfo() | Options); \
}
#define CLASS_METHOD(ClassName, Selector, Options) \
if (moduleName == currentModuleName) { \
auto contextID = writer.addObjCClass(#ClassName, \
ObjCContextInfo()); \
writer.addObjCMethod(contextID, MAKE_SELECTOR_REF Selector, \
/*isInstanceMethod=*/false, \
ObjCMethodInfo() | Options); \
}
#define OBJC_CLASS(ClassName, Options) \
if (moduleName == currentModuleName) { \
writer.addObjCClass(#ClassName, ObjCContextInfo() | Options); \
}
#define OBJC_PROTOCOL(ProtocolName, Options) \
if (moduleName == currentModuleName) { \
writer.addObjCProtocol(#ProtocolName, ObjCContextInfo() | Options); \
}
#define OBJC_PROPERTY(ContextName, PropertyName, OptionalTypeKind) \
if (moduleName == currentModuleName) { \
auto contextID = writer.addObjCClass(#ContextName, \
ObjCContextInfo()); \
writer.addObjCProperty(contextID, #PropertyName, \
ObjCPropertyInfo() | OptionalTypeKind); \
}
#define OBJC_PROTOCOL_PROPERTY(ContextName, PropertyName, OptionalTypeKind) \
if (moduleName == currentModuleName) { \
auto contextID = writer.addObjCProtocol(#ContextName, \
ObjCContextInfo()); \
writer.addObjCProperty(contextID, #PropertyName, \
ObjCPropertyInfo() | OptionalTypeKind); \
}
#include "KnownObjCMethods.def"
#undef MAKE_SELECTOR_REF
std::error_code EC;
llvm::raw_fd_ostream os(fileName.str(), EC, llvm::sys::fs::OpenFlags::F_None);
writer.writeToStream(os);
os.flush();
return os.has_error();
}
/// Generate an API annotation file from the known Objective-C methods
/// file.
///
/// FIXME: This is a horrible, horrible hack.
bool checkAPIAnnotation(StringRef moduleName, StringRef fileName) {
using namespace api_notes;
auto bufferOrError = llvm::MemoryBuffer::getFile(fileName);
if (!bufferOrError)
return true;
auto reader = APINotesReader::get(std::move(bufferOrError.get()));
if (!reader)
return true;
// Okay. Go look for the data we expect.
StringRef currentModuleName;
// Constants used to map from KnownObjCMethods.def.
const auto OTK_None = api_notes::NullableKind::NonNullable;
(void)OTK_None;
const auto OTK_Optional = api_notes::NullableKind::Nullable;
(void)OTK_Optional;
const auto OTK_ImplicitlyUnwrappedOptional
= api_notes::NullableKind::Unknown;
(void)OTK_ImplicitlyUnwrappedOptional;
#define START_MODULE(ModuleName) \
currentModuleName = #ModuleName;
#define MAKE_SELECTOR_REF(NumPieces, ...) \
ObjCSelectorRef{NumPieces, { __VA_ARGS__ } }
#define INSTANCE_METHOD(ClassName, Selector, Options) \
if (auto classInfo = reader->lookupObjCClass(#ClassName)) { \
if (auto info = reader->lookupObjCMethod( \
classInfo->first, \
MAKE_SELECTOR_REF Selector, true)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCMethodInfo() | Options; \
if (*info != expectedInfo) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define PROTOCOL_INSTANCE_METHOD(ProtocolName, Selector, Options) \
if (auto protocolInfo = reader->lookupObjCProtocol(#ProtocolName)) { \
if (auto info = reader->lookupObjCMethod( \
protocolInfo->first, \
MAKE_SELECTOR_REF Selector, true)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName << " method" \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCMethodInfo() | Options; \
if (*info != expectedInfo) { \
llvm::errs() << "Protocol " << #ProtocolName << " method" \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName << " method" \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName \
<< " not found in API notes file\n"; \
return true; \
}
#define CLASS_METHOD(ClassName, Selector, Options) \
if (auto classInfo = reader->lookupObjCClass(#ClassName)) { \
if (auto info = reader->lookupObjCMethod( \
classInfo->first, \
MAKE_SELECTOR_REF Selector, false)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCMethodInfo() | Options; \
if (*info != expectedInfo) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_CLASS(ClassName, Options) \
if (auto info = reader->lookupObjCClass(#ClassName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Class " << moduleName << "." << #ClassName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCContextInfo() | Options; \
if (info->second != expectedInfo) { \
llvm::errs() << "Class " << moduleName << "." << #ClassName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << moduleName << "." << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_PROTOCOL(ProtocolName, Options) \
if (auto info = reader->lookupObjCProtocol(#ProtocolName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Protocol " << moduleName << "." << #ProtocolName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCContextInfo() | Options; \
if (info->second != expectedInfo) { \
llvm::errs() << "Protocol " << moduleName << "." << #ProtocolName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << moduleName << "." << #ProtocolName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_PROPERTY(ClassName, PropertyName, OptionalTypeKind) \
if (auto classInfo = reader->lookupObjCClass(#ClassName)) { \
if (auto info = reader->lookupObjCProperty(classInfo->first, \
#PropertyName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Property " << #ClassName << "." << #PropertyName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCPropertyInfo() | OptionalTypeKind; \
if (*info != expectedInfo) { \
llvm::errs() << "Property " << #ClassName << "." << #PropertyName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Property " << #ClassName << "." << #PropertyName \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_PROTOCOL_PROPERTY(ProtocolName, PropertyName, OptionalTypeKind) \
if (auto protocolInfo = reader->lookupObjCProtocol(#ProtocolName)) { \
if (auto info = reader->lookupObjCProperty(protocolInfo->first, \
#PropertyName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Property " << #ProtocolName << "." << #PropertyName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCPropertyInfo() | OptionalTypeKind; \
if (*info != expectedInfo) { \
llvm::errs() << "Property " << #ProtocolName << "." << #PropertyName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Property " << #ProtocolName << "." << #PropertyName \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName \
<< " not found in API notes file\n"; \
return true; \
}
#include "KnownObjCMethods.def"
#undef MAKE_SELECTOR_REF
return false;
}
int main(int argc, char *argv[]) {
// Print a stack trace if we signal out.
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
if (argc > 1) {
// Handle integrated test tools which do not use
// llvm::cl::ParseCommandLineOptions.
StringRef FirstArg(argv[1]);
if (FirstArg == "-test-createCompilerInvocation") {
ArrayRef<const char *> Args(argv + 2, argc - 2);
return doTestCreateCompilerInvocation(Args);
}
}
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift IDE Test\n");
if (options::Action == ActionType::None) {
llvm::errs() << "action required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (options::Action == ActionType::GenerateAPIAnnotation) {
if (options::OutputFilename.empty()) {
llvm::errs() << "output file required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (options::InputFilenames.size() != 1) {
llvm::errs() << "single input module required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (generateAPIAnnotation(options::InputFilenames[0],
options::OutputFilename)) {
llvm::errs() << "could not generate " << options::OutputFilename << "\n";
return 1;
}
return 0;
}
if (options::Action == ActionType::CheckAPIAnnotation) {
if (options::InputFilenames.size() != 2) {
llvm::errs() << "input file and module required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (checkAPIAnnotation(options::InputFilenames[0],
options::InputFilenames[1])) {
llvm::errs() << "could not read " << options::InputFilenames[0] << "\n";
return 1;
}
return 0;
}
if (options::Action == ActionType::TestCreateCompilerInvocation) {
llvm::errs() << "-test-createCompilerInvocation must be specified before "
"all other arguments\n";
return 1;
}
if (options::SourceFilename.empty()) {
llvm::errs() << "source file required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
// If no SDK was specified via -sdk, check environment variable SDKROOT.
if (options::SDK.getNumOccurrences() == 0) {
const char *SDKROOT = getenv("SDKROOT");
if (SDKROOT)
options::SDK = SDKROOT;
}
if (options::PrintStats)
llvm::EnableStatistics();
CompilerInvocation InitInvok;
for (auto &File : options::InputFilenames)
InitInvok.addInputFilename(File);
if (!options::InputFilenames.empty())
InitInvok.setInputKind(SourceFileKind::Library);
InitInvok.setMainExecutablePath(
llvm::sys::fs::getMainExecutable(argv[0],
reinterpret_cast<void *>(&anchorForGetMainExecutable)));
InitInvok.setModuleName("swift_ide_test");
InitInvok.setSDKPath(options::SDK);
if (!options::Triple.empty())
InitInvok.setTargetTriple(options::Triple);
InitInvok.getClangImporterOptions().ModuleCachePath =
options::ModuleCachePath;
InitInvok.setImportSearchPaths(options::ImportPaths);
InitInvok.setFrameworkSearchPaths(options::FrameworkPaths);
InitInvok.getFrontendOptions().EnableSourceImport =
options::EnableSourceImport;
InitInvok.getFrontendOptions().ImplicitObjCHeaderPath =
options::ImportObjCHeader;
InitInvok.getLangOptions().SplitPrepositions = options::SplitObjCSelectors;
InitInvok.getClangImporterOptions().InferImplicitProperties =
options::ImplicitProperties;
if (!options::ResourceDir.empty()) {
InitInvok.setRuntimeResourcePath(options::ResourceDir);
}
// Force these options, which are factored out for staging purposes.
InitInvok.getLangOptions().UsePrivateDiscriminators = true;
Mangle::Mangler::UsePrivateDiscriminators = true;
for (auto ConfigName : options::BuildConfigs)
InitInvok.getLangOptions().addBuildConfigOption(ConfigName);
int ExitCode;
switch (options::Action) {
case ActionType::None:
case ActionType::GenerateAPIAnnotation:
case ActionType::CheckAPIAnnotation:
case ActionType::TestCreateCompilerInvocation:
llvm_unreachable("should be handled above");
case ActionType::CodeCompletion:
if (options::CodeCompletionToken.empty()) {
llvm::errs() << "code completion token name required\n";
return 1;
}
ExitCode = doCodeCompletion(InitInvok,
options::SourceFilename,
options::CodeCompletionToken,
options::CodeCompletionDiagnostics,
options::CodeCompletionKeywords);
break;
case ActionType::REPLCodeCompletion:
ExitCode = doREPLCodeCompletion(InitInvok, options::SourceFilename);
break;
case ActionType::SyntaxColoring:
ExitCode = doSyntaxColoring(InitInvok,
options::SourceFilename,
options::TerminalOutput,
options::Typecheck);
break;
case ActionType::Structure:
ExitCode = doStructureAnnotation(InitInvok, options::SourceFilename);
break;
case ActionType::Annotation:
ExitCode = doSemanticAnnotation(InitInvok,
options::SourceFilename,
options::TerminalOutput);
break;
case ActionType::TestInputCompleteness:
ExitCode = doInputCompletenessTest(options::SourceFilename);
break;
case ActionType::PrintASTNotTypeChecked:
ExitCode = doPrintAST(InitInvok,
options::SourceFilename,
/*RunTypeChecker=*/false,
/*FunctionDefinitions=*/options::FunctionDefinitions,
/*PreferTypeRepr=*/options::PreferTypeRepr,
options::ExplodePatternBindingDecls,
options::PrintImplicitAttrs,
options::PrintAccessibility,
!options::SkipUnavailable,
options::AccessibilityFilter);
break;
case ActionType::PrintASTTypeChecked:
ExitCode = doPrintAST(InitInvok,
options::SourceFilename,
/*RunTypeChecker=*/true,
/*FunctionDefinitions=*/options::FunctionDefinitions,
/*PreferTypeRepr=*/options::PreferTypeRepr,
options::ExplodePatternBindingDecls,
options::PrintImplicitAttrs,
options::PrintAccessibility,
!options::SkipUnavailable,
options::AccessibilityFilter);
break;
case ActionType::PrintModule: {
ide::ModuleTraversalOptions TraversalOptions;
if (options::ModulePrintSubmodules)
TraversalOptions |= ide::ModuleTraversal::VisitSubmodules;
if (options::ModulePrintHidden)
TraversalOptions |= ide::ModuleTraversal::VisitHidden;
if (options::ModulePrintSkipOverlay)
TraversalOptions |= ide::ModuleTraversal::SkipOverlay;
ExitCode = doPrintModules(
InitInvok, options::ModuleToPrint, TraversalOptions,
options::FullyQualifiedTypesIfAmbiguous,
options::SynthesizeSugarOnTypes,
options::AnnotatePrint,
options::PrintImplicitAttrs,
options::PrintAccessibility,
!options::SkipUnavailable,
options::PrintRegularComments,
options::AccessibilityFilter,
!options::SkipPrivateStdlibDecls);
break;
}
case ActionType::PrintTypes:
ExitCode = doPrintTypes(InitInvok, options::SourceFilename,
options::FullyQualifiedTypes);
break;
case ActionType::PrintComments:
ExitCode = doPrintComments(InitInvok, options::SourceFilename,
options::CommentsXMLSchema);
break;
case ActionType::PrintModuleComments:
ExitCode = doPrintModuleComments(InitInvok, options::ModuleToPrint,
options::CommentsXMLSchema);
break;
case ActionType::PrintModuleImports:
ExitCode = doPrintModuleImports(InitInvok, options::ModuleToPrint);
break;
case ActionType::PrintUSRs:
ExitCode = doPrintUSRs(InitInvok, options::SourceFilename);
break;
case ActionType::ParseReST:
ExitCode = doParseReST(options::SourceFilename);
break;
}
if (options::PrintStats)
llvm::PrintStatistics();
return ExitCode;
}
Make swift-ide-test's options respect the defaults.
Swift SVN r21705
//===--- swift-ide-test.cpp - IDE functionality testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "XMLValidator.h"
#include "swift/APINotes/APINotesReader.h"
#include "swift/APINotes/APINotesWriter.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/RawComment.h"
#include "swift/AST/USRGeneration.h"
#include "swift/Basic/DemangleWrappers.h"
#include "swift/Basic/DiagnosticConsumer.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Driver/FrontendUtil.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/IDE/CommentConversion.h"
#include "swift/IDE/ModuleInterfacePrinting.h"
#include "swift/IDE/REPLCodeCompletion.h"
#include "swift/IDE/SourceEntityWalker.h"
#include "swift/IDE/SyntaxModel.h"
#include "swift/IDE/Utils.h"
#include "swift/ReST/Parser.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <system_error>
#include <string>
using namespace swift;
using namespace ide;
enum class ActionType {
None,
CodeCompletion,
REPLCodeCompletion,
SyntaxColoring,
Structure,
Annotation,
TestInputCompleteness,
PrintASTNotTypeChecked,
PrintASTTypeChecked,
PrintModule,
PrintTypes,
PrintComments,
PrintModuleComments,
PrintModuleImports,
PrintUSRs,
ParseReST,
GenerateAPIAnnotation,
CheckAPIAnnotation,
TestCreateCompilerInvocation,
};
namespace options {
static llvm::cl::opt<ActionType>
Action(llvm::cl::desc("Mode:"), llvm::cl::init(ActionType::None),
llvm::cl::values(
clEnumValN(ActionType::CodeCompletion,
"code-completion", "Perform code completion"),
clEnumValN(ActionType::REPLCodeCompletion,
"repl-code-completion", "Perform REPL-style code completion"),
clEnumValN(ActionType::SyntaxColoring,
"syntax-coloring", "Perform syntax coloring"),
clEnumValN(ActionType::Structure,
"structure", "Perform document structure annotation"),
clEnumValN(ActionType::Annotation,
"annotate", "Perform semantic annotation"),
clEnumValN(ActionType::TestInputCompleteness,
"test-input-complete", "Check if input source is complete"),
clEnumValN(ActionType::PrintASTNotTypeChecked,
"print-ast-not-typechecked", "Print the non-typechecked AST"),
clEnumValN(ActionType::PrintASTTypeChecked,
"print-ast-typechecked", "Print the typechecked AST"),
clEnumValN(ActionType::PrintModule,
"print-module", "Print visible declarations in a module"),
clEnumValN(ActionType::PrintTypes,
"print-types", "Print types of all subexpressions and declarations in the AST"),
clEnumValN(ActionType::PrintComments,
"print-comments", "Print documentation comments attached to decls"),
clEnumValN(ActionType::PrintModuleComments,
"print-module-comments", "Given a module, print documentation comments attached to decls"),
clEnumValN(ActionType::PrintModuleImports,
"print-module-imports", "Recursively print all imports visible from a particular module"),
clEnumValN(ActionType::PrintUSRs,
"print-usrs", "Print USRs for all decls"),
clEnumValN(ActionType::ParseReST,
"parse-rest", "Parse a ReST file"),
clEnumValN(ActionType::GenerateAPIAnnotation,
"generate-api-annotation",
"Generate an API annotation file"),
clEnumValN(ActionType::CheckAPIAnnotation,
"check-api-annotation",
"Check an API annotation file"),
clEnumValN(ActionType::TestCreateCompilerInvocation,
"test-createCompilerInvocation",
"Test swift::driver::createCompilerInvocation using the "
"arguments passed to swift-ide-test (must be specified "
"before all other arguments)"),
clEnumValEnd));
static llvm::cl::opt<std::string>
SourceFilename("source-filename", llvm::cl::desc("Name of the source file"));
static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("[input files...]"),
llvm::cl::ZeroOrMore);
static llvm::cl::opt<std::string>
OutputFilename("o",
llvm::cl::desc("Output file name"));
static llvm::cl::list<std::string>
BuildConfigs("D", llvm::cl::desc("Build configurations"));
#ifndef SWIFT_MODULES_SDK
#define SWIFT_MODULES_SDK ""
#endif
static llvm::cl::opt<std::string>
SDK("sdk", llvm::cl::desc("path to the SDK to build against"),
llvm::cl::init(SWIFT_MODULES_SDK));
static llvm::cl::opt<std::string>
Triple("target", llvm::cl::desc("target triple"));
static llvm::cl::opt<std::string>
ModuleCachePath("module-cache-path", llvm::cl::desc("Clang module cache path"),
llvm::cl::init(SWIFT_MODULE_CACHE_PATH));
static llvm::cl::list<std::string>
ImportPaths("I", llvm::cl::desc("add a directory to the import search path"));
static llvm::cl::list<std::string>
FrameworkPaths("F", llvm::cl::desc("add a directory to the framework search path"));
static llvm::cl::opt<std::string>
ResourceDir("resource-dir",
llvm::cl::desc("The directory that holds the compiler resource files"));
static llvm::cl::opt<std::string>
ImportObjCHeader("import-objc-header", llvm::cl::desc("header to implicitly import"));
static llvm::cl::opt<bool>
EnableSourceImport("enable-source-import", llvm::cl::Hidden,
llvm::cl::init(false));
static llvm::cl::opt<bool>
SplitObjCSelectors("split-objc-selectors",
llvm::cl::desc("Split Objective-C selectors"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ImplicitProperties("enable-objc-implicit-properties",
llvm::cl::desc("Implicitly import Objective-C getter/setter pairs as properties"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
FactoryMethodsAsConstructors("enable-objc-factory-method-constructors",
llvm::cl::desc("Implicitly import Objective-C factory methods as initializers"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
PrintStats("print-stats",
llvm::cl::desc("Print statistics"),
llvm::cl::init(false));
// '-code-completion' options.
static llvm::cl::opt<std::string>
CodeCompletionToken("code-completion-token",
llvm::cl::desc("Code completion token name"));
static llvm::cl::opt<bool>
CodeCompletionDiagnostics("code-completion-diagnostics",
llvm::cl::desc("Print compiler diagnostics while "
"doing code completion"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
CodeCompletionKeywords("code-completion-keywords",
llvm::cl::desc("Include keywords in code completion results"),
llvm::cl::init(true));
// '-syntax-coloring' options.
static llvm::cl::opt<bool>
TerminalOutput("terminal",
llvm::cl::desc("Use terminal color for source annotations"));
static llvm::cl::opt<bool>
Typecheck("typecheck",
llvm::cl::desc("Type check the AST"),
llvm::cl::init(false));
// AST printing options.
static llvm::cl::opt<bool>
FunctionDefinitions("function-definitions",
llvm::cl::desc("Print function bodies"),
llvm::cl::init(true));
static llvm::cl::opt<bool>
PreferTypeRepr("prefer-type-repr",
llvm::cl::desc("When printing types, prefer printing TypeReprs"),
llvm::cl::init(true));
static llvm::cl::opt<bool>
FullyQualifiedTypes("fully-qualified-types",
llvm::cl::desc("Print fully qualified types"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ExplodePatternBindingDecls(
"explode-pattern-binding-decls",
llvm::cl::desc("Separate pattern binding decls into individual var decls"),
llvm::cl::init(false));
static llvm::cl::opt<std::string>
MangledNameToFind("find-mangled",
llvm::cl::desc("Print the entity with the given mangled name"));
// Module printing options.
static llvm::cl::list<std::string>
ModuleToPrint("module-to-print",
llvm::cl::desc("Name of the module to print"));
static llvm::cl::opt<bool>
ModulePrintSubmodules("module-print-submodules",
llvm::cl::desc("Recursively print submodules"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ModulePrintHidden("module-print-hidden",
llvm::cl::desc("Print non-exported imported or submodules"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
ModulePrintSkipOverlay("module-print-skip-overlay",
llvm::cl::desc("Skip Swift overlay modules"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
FullyQualifiedTypesIfAmbiguous(
"fully-qualified-types-if-ambiguous",
llvm::cl::desc("Print types fully-qualified if they would be ambiguous "
"otherwise"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
SynthesizeSugarOnTypes(
"synthesize-sugar-on-types",
llvm::cl::desc("Always print Array and Optional with sugar"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
AnnotatePrint("annotate-print",
llvm::cl::desc("Annotate AST printing"),
llvm::cl::init(false));
// AST and module printing options.
static llvm::cl::opt<bool>
PrintImplicitAttrs("print-implicit-attrs",
llvm::cl::desc("Print implicit attributes"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
PrintAccessibility("print-accessibility",
llvm::cl::desc("Print accessibility for all values"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
SkipUnavailable("skip-unavailable",
llvm::cl::desc("Don't print unavailable declarations"),
llvm::cl::init(false));
static llvm::cl::opt<Accessibility>
AccessibilityFilter(
llvm::cl::desc("Accessibility filter:"),
llvm::cl::init(Accessibility::Private),
llvm::cl::values(
clEnumValN(Accessibility::Private, "accessibility-filter-private",
"Print all declarations"),
clEnumValN(Accessibility::Internal, "accessibility-filter-internal",
"Print internal and public declarations"),
clEnumValN(Accessibility::Public, "accessibility-filter-public",
"Print public declarations"),
clEnumValEnd));
static llvm::cl::opt<bool>
SkipPrivateStdlibDecls("skip-private-stdlib-decls",
llvm::cl::desc("Don't print declarations that start with '_'"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
PrintRegularComments("print-regular-comments",
llvm::cl::desc("Print regular comments from clang module headers"),
llvm::cl::init(false));
static llvm::cl::opt<std::string>
CommentsXMLSchema("comments-xml-schema",
llvm::cl::desc("Filename of the RelaxNG schema for documentation comments"));
} // namespace options
static std::unique_ptr<llvm::MemoryBuffer>
removeCodeCompletionTokens(llvm::MemoryBuffer *Input,
StringRef TokenName,
unsigned *CodeCompletionOffset) {
std::string CleanFile =
ide::removeCodeCompletionTokens(Input->getBuffer(),
TokenName,
CodeCompletionOffset);
return std::unique_ptr<llvm::MemoryBuffer>(
llvm::MemoryBuffer::getMemBufferCopy(CleanFile,
Input->getBufferIdentifier()));
}
static int doCodeCompletion(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
StringRef CodeCompletionToken,
bool CodeCompletionDiagnostics,
bool CodeCompletionKeywords) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
unsigned CodeCompletionOffset;
std::unique_ptr<llvm::MemoryBuffer> CleanFile(
removeCodeCompletionTokens(FileBufOrErr.get().get(), CodeCompletionToken,
&CodeCompletionOffset));
if (CodeCompletionOffset == ~0U) {
llvm::errs() << "could not find code completion token \""
<< CodeCompletionToken << "\"\n";
return 1;
}
llvm::outs() << "found code completion token " << CodeCompletionToken
<< " at offset " << CodeCompletionOffset << "\n";
llvm::errs() << "found code completion token " << CodeCompletionToken
<< " at offset " << CodeCompletionOffset << "\n";
CompilerInvocation Invocation(InitInvok);
Invocation.setCodeCompletionPoint(CleanFile.get(), CodeCompletionOffset);
ide::CodeCompletionCache CompletionCache;
ide::CodeCompletionContext CompletionContext(CompletionCache);
// Create a CodeCompletionConsumer.
std::unique_ptr<ide::CodeCompletionConsumer> Consumer(
new ide::PrintingCodeCompletionConsumer(
llvm::outs(), CodeCompletionKeywords));
// Cerate a factory for code completion callbacks that will feed the
// Consumer.
std::unique_ptr<CodeCompletionCallbacksFactory> CompletionCallbacksFactory(
ide::makeCodeCompletionCallbacksFactory(CompletionContext,
*Consumer.get()));
Invocation.setCodeCompletionFactory(CompletionCallbacksFactory.get());
CompilerInstance CI;
PrintingDiagnosticConsumer PrintDiags;
if (CodeCompletionDiagnostics) {
// Display diagnostics to stderr.
CI.addDiagnosticConsumer(&PrintDiags);
}
if (CI.setup(Invocation))
return 1;
CI.performSema();
return 0;
}
static int doREPLCodeCompletion(const CompilerInvocation &InitInvok,
StringRef SourceFilename) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
StringRef BufferText = FileBufOrErr.get()->getBuffer();
// Drop a single newline character from the buffer.
if (BufferText.endswith("\n"))
BufferText = BufferText.drop_back(1);
CompilerInvocation Invocation(InitInvok);
Invocation.setInputKind(SourceFileKind::REPL);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
SourceFile &SF = CI.getMainModule()->getMainSourceFile(SourceFileKind::REPL);
REPLCompletions REPLCompl;
REPLCompl.populate(SF, BufferText);
llvm::outs() << "Begin completions\n";
for (StringRef S : REPLCompl.getCompletionList()) {
llvm::outs() << S << "\n";
}
llvm::outs() << "End completions\n";
return 0;
}
//============================================================================//
// Syntax Coloring
//============================================================================//
namespace {
class PrintSyntaxColorWalker : public ide::SyntaxModelWalker {
SourceManager &SM;
unsigned BufferID;
llvm::raw_ostream &OS;
bool TerminalOutput;
const char *BufStart;
const char *BufEnd;
const char *CurrBufPtr;
public:
PrintSyntaxColorWalker(SourceManager &SM,
unsigned BufferID,
llvm::raw_ostream &OS,
bool TerminalOutput)
: SM(SM), BufferID(BufferID), OS(OS), TerminalOutput(TerminalOutput) {
CharSourceRange entireRange = SM.getRangeForBuffer(BufferID);
StringRef Buffer = SM.extractText(entireRange);
BufStart = Buffer.data();
BufEnd = Buffer.data() + Buffer.size();
CurrBufPtr = BufStart;
}
bool walkToNodePre(SyntaxNode Node) override {
if (shouldIgnore(Node))
return false;
const char *LocPtr = getPtr(Node.Range.getStart());
printSourceUntil(LocPtr);
wrap(Node.Kind, /*Begin=*/true);
return true;
}
bool walkToNodePost(SyntaxNode Node) override {
if (shouldIgnore(Node))
return true;
const char *LocPtr = getPtr(Node.Range.getStart());
unsigned Length = Node.Range.getByteLength();
if (Node.Kind == SyntaxNodeKind::CommentLine) {
if (LocPtr[Length-1] == '\n')
--Length; // Wrapping should be in the same line.
}
printSourceUntil(LocPtr + Length);
wrap(Node.Kind, /*Begin=*/false);
return true;
}
void wrap(SyntaxNodeKind Kind, bool Begin) {
if (TerminalOutput) {
wrapForTerminal(Kind, Begin);
} else {
wrapForTest(Kind, Begin);
}
}
bool shouldIgnore(SyntaxNode Node) const {
const char *LocPtr = getPtr(Node.Range.getStart());
if (Node.Kind == SyntaxNodeKind::CommentLine && !TerminalOutput) {
// Ignore CHECK lines.
if (StringRef(LocPtr, BufEnd - LocPtr).startswith("// CHECK"))
return true;
}
return false;
}
const char *getPtr(SourceLoc Loc) const {
return BufStart + SM.getLocOffsetInBuffer(Loc, BufferID);
}
void printSourceUntil(const char *Ptr) {
assert(Ptr >= CurrBufPtr && Ptr <= BufEnd);
StringRef Text = StringRef(CurrBufPtr, Ptr-CurrBufPtr);
// Skip all "// CHECK" lines.
while (true) {
size_t Idx = Text.find("// CHECK");
if (Idx == StringRef::npos)
break;
OS << Text.substr(0, Idx);
Idx = Text.find('\n', Idx);
Text = Idx == StringRef::npos ? StringRef() : Text.substr(Idx+1);
}
OS << Text;
CurrBufPtr = Ptr;
}
void wrapForTest(SyntaxNodeKind Kind, bool Begin) {
const char *Id = 0;
switch (Kind) {
case SyntaxNodeKind::Keyword: Id = "kw"; break;
// Skip identifier.
case SyntaxNodeKind::Identifier: return;
case SyntaxNodeKind::DollarIdent: Id = "dollar"; break;
case SyntaxNodeKind::Integer: Id = "int"; break;
case SyntaxNodeKind::Floating: Id = "float"; break;
case SyntaxNodeKind::String: Id = "str"; break;
case SyntaxNodeKind::Character: Id = "char"; break;
case SyntaxNodeKind::CommentLine: Id = "comment-line"; break;
case SyntaxNodeKind::CommentBlock: Id = "comment-block"; break;
case SyntaxNodeKind::CommentMarker: Id = "comment-marker"; break;
case SyntaxNodeKind::CommentURL: Id = "comment-url"; break;
case SyntaxNodeKind::TypeId: Id = "type"; break;
case SyntaxNodeKind::BuildConfigKeyword: Id = "#kw"; break;
case SyntaxNodeKind::BuildConfigId: Id = "#id"; break;
case SyntaxNodeKind::AttributeId: Id = "attr-id"; break;
case SyntaxNodeKind::AttributeBuiltin: Id = "attr-builtin"; break;
}
OS << (Begin ? "<" : "</") << Id << '>';
}
void wrapForTerminal(SyntaxNodeKind Kind, bool Begin) {
llvm::raw_ostream::Colors Col;
switch (Kind) {
case SyntaxNodeKind::Keyword: Col = llvm::raw_ostream::MAGENTA; break;
// Skip identifier.
case SyntaxNodeKind::Identifier: return;
case SyntaxNodeKind::DollarIdent: Col = llvm::raw_ostream::MAGENTA; break;
case SyntaxNodeKind::Integer: Col = llvm::raw_ostream::BLUE; break;
case SyntaxNodeKind::Floating: Col = llvm::raw_ostream::BLUE; break;
case SyntaxNodeKind::String: Col = llvm::raw_ostream::RED; break;
case SyntaxNodeKind::Character: Col = llvm::raw_ostream::BLUE; break;
case SyntaxNodeKind::CommentLine: Col = llvm::raw_ostream::GREEN; break;
case SyntaxNodeKind::CommentBlock: Col = llvm::raw_ostream::GREEN; break;
case SyntaxNodeKind::CommentMarker: Col = llvm::raw_ostream::MAGENTA; break;
case SyntaxNodeKind::CommentURL: Col = llvm::raw_ostream::RED; break;
case SyntaxNodeKind::TypeId: Col = llvm::raw_ostream::CYAN; break;
case SyntaxNodeKind::BuildConfigKeyword: Col = llvm::raw_ostream::YELLOW; break;
case SyntaxNodeKind::BuildConfigId: Col = llvm::raw_ostream::YELLOW; break;
case SyntaxNodeKind::AttributeId: Col = llvm::raw_ostream::CYAN; break;
case SyntaxNodeKind::AttributeBuiltin: Col = llvm::raw_ostream::MAGENTA; break;
}
if (Begin) {
if (const char *CStr =
llvm::sys::Process::OutputColor(Col, false, false)) {
OS << CStr;
}
} else {
OS << llvm::sys::Process::ResetColor();
}
}
void finished() {
OS << StringRef(CurrBufPtr, BufEnd-CurrBufPtr);
}
};
}
static int doSyntaxColoring(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool TerminalOutput,
bool RunTypeChecker) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
if (!RunTypeChecker)
CI.performParseOnly();
else
CI.performSema();
unsigned BufID = CI.getInputBufferIDs().back();
SourceFile *SF = nullptr;
for (auto Unit : CI.getMainModule()->getFiles()) {
SF = dyn_cast<SourceFile>(Unit);
if (SF)
break;
}
assert(SF && "no source file?");
ide::SyntaxModelContext ColorContext(*SF);
PrintSyntaxColorWalker ColorWalker(CI.getSourceMgr(), BufID, llvm::outs(),
TerminalOutput);
ColorContext.walk(ColorWalker);
ColorWalker.finished();
return 0;
}
//============================================================================//
// Structure Annotation
//============================================================================//
class PrintStructureWalker : public ide::SyntaxModelWalker {
SourceManager &SM;
llvm::raw_ostream &OS;
unsigned indentLevel = 0;
public:
PrintStructureWalker(SourceManager &SM,
llvm::raw_ostream &OS)
: SM(SM), OS(OS) {
}
bool walkToSubStructurePre(SyntaxStructureNode Node) override {
auto Start = SM.getLineAndColumn(Node.Range.getStart());
auto End = SM.getLineAndColumn(Node.Range.getEnd());
OS << std::string(indentLevel * 2, ' ');
switch (Node.Kind) {
case swift::ide::SyntaxStructureKind::Class:
OS << "Class ";
break;
case swift::ide::SyntaxStructureKind::Struct:
OS << "Struct ";
break;
case swift::ide::SyntaxStructureKind::Protocol:
OS << "Protocol ";
break;
case swift::ide::SyntaxStructureKind::Enum:
OS << "Enum ";
break;
case swift::ide::SyntaxStructureKind::Extension:
OS << "Extension ";
break;
case swift::ide::SyntaxStructureKind::FreeFunction:
case swift::ide::SyntaxStructureKind::InstanceFunction:
case swift::ide::SyntaxStructureKind::StaticFunction:
OS << "Func ";
break;
case swift::ide::SyntaxStructureKind::InstanceVariable:
OS << "Property ";
break;
case swift::ide::SyntaxStructureKind::Parameter:
OS << "Parameter ";
break;
case swift::ide::SyntaxStructureKind::BraceStatement:
OS << "Brace ";
break;
case swift::ide::SyntaxStructureKind::CallExpression:
OS << "Call ";
break;
}
OS << "at " << Start.first << ":" << Start.second << " - " <<
End.first << ":" << End.second;
if (Node.NameRange.isValid()) {
auto Start = SM.getLineAndColumn(Node.NameRange.getStart());
auto End = SM.getLineAndColumn(Node.NameRange.getEnd());
OS << ", name at " << Start.first << ":" << Start.second << " - " <<
End.first << ":" << End.second;
}
if (!Node.InheritedTypeRanges.empty()) {
OS << ", inherited types at";
for (auto &Range : Node.InheritedTypeRanges) {
auto Start = SM.getLineAndColumn(Range.getStart());
auto End = SM.getLineAndColumn(Range.getEnd());
OS << " " << Start.first << ":" << Start.second << " - " <<
End.first << ":" << End.second;
}
}
OS << "\n";
++indentLevel;
return true;
}
bool walkToSubStructurePost(SyntaxStructureNode Node) override {
assert(indentLevel > 0);
--indentLevel;
return true;
}
};
static int doStructureAnnotation(const CompilerInvocation &InitInvok,
StringRef SourceFilename) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performParseOnly();
ide::SyntaxModelContext StructureContext(
CI.getMainModule()->getMainSourceFile(SourceFileKind::Main));
PrintStructureWalker StructureWalker(CI.getSourceMgr(), llvm::outs());
StructureContext.walk(StructureWalker);
return 0;
}
//============================================================================//
// Semantic Annotation
//============================================================================//
namespace {
class AnnotationPrinter : public ide::SourceEntityWalker {
SourceManager &SM;
unsigned BufferID;
llvm::raw_ostream &OS;
bool TerminalOutput;
const char *BufStart;
const char *BufEnd;
const char *CurrBufPtr;
public:
AnnotationPrinter(SourceManager &SM,
unsigned BufferID,
llvm::raw_ostream &OS,
bool TerminalOutput)
: SM(SM), BufferID(BufferID), OS(OS), TerminalOutput(TerminalOutput) {
CharSourceRange entireRange = SM.getRangeForBuffer(BufferID);
StringRef Buffer = SM.extractText(entireRange);
BufStart = Buffer.data();
BufEnd = Buffer.data() + Buffer.size();
CurrBufPtr = BufStart;
}
void finished() {
OS << StringRef(CurrBufPtr, BufEnd-CurrBufPtr);
}
private:
struct SemanticSourceEntity {
CharSourceRange Range;
ValueDecl *Dcl = nullptr;
TypeDecl *CtorTyRef = nullptr;
ModuleEntity Mod;
bool IsRef = true;
SemanticSourceEntity(CharSourceRange Range,
ValueDecl *Dcl,
TypeDecl *CtorTyRef,
bool IsRef)
: Range(Range),
Dcl(Dcl),
CtorTyRef(CtorTyRef),
IsRef(IsRef) {}
SemanticSourceEntity(CharSourceRange Range,
ModuleEntity Mod)
: Range(Range),
Mod(Mod) {}
};
bool walkToDeclPre(Decl *D, CharSourceRange Range) override {
if (Range.getByteLength() == 0)
return true;
if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
annotateSourceEntity({ Range, VD, nullptr, /*IsRef=*/false});
return true;
}
bool visitDeclReference(ValueDecl *D, CharSourceRange Range,
TypeDecl *CtorTyRef) override {
annotateSourceEntity({ Range, D, CtorTyRef, /*IsRef=*/true });
return true;
}
bool visitCallArgName(Identifier Name, CharSourceRange Range,
ValueDecl *D) override {
annotateSourceEntity({ Range, D, nullptr, /*IsRef=*/true });
return true;
}
bool visitModuleReference(ModuleEntity Mod, CharSourceRange Range) override {
annotateSourceEntity({ Range, Mod });
return true;
}
void annotateSourceEntity(const SemanticSourceEntity &Entity) {
const char *LocPtr =
BufStart + SM.getLocOffsetInBuffer(Entity.Range.getStart(), BufferID);
unsigned Length = Entity.Range.getByteLength();
assert(LocPtr >= CurrBufPtr);
printSourceUntil(LocPtr);
StringRef NodeText = StringRef(LocPtr, Length);
if (TerminalOutput) {
if (!wrapForTerminal(Entity, NodeText))
OS << NodeText;
} else {
if (!wrapForTest(Entity, StringRef(LocPtr, Length)))
OS << NodeText;
}
CurrBufPtr = LocPtr + Length;
}
void printSourceUntil(const char *Ptr) {
StringRef Text = StringRef(CurrBufPtr, Ptr-CurrBufPtr);
// Skip all "// CHECK" lines.
while (true) {
size_t Idx = Text.find("// CHECK");
if (Idx == StringRef::npos)
break;
OS << Text.substr(0, Idx);
Idx = Text.find('\n', Idx);
Text = Idx == StringRef::npos ? StringRef() : Text.substr(Idx+1);
}
OS << Text;
}
void printLoc(SourceLoc Loc, raw_ostream &OS) {
OS << '@';
if (Loc.isValid()) {
auto LineCol = SM.getLineAndColumn(Loc, BufferID);
OS << LineCol.first << ':' << LineCol.second;
}
}
bool wrapForTest(const SemanticSourceEntity &Entity, StringRef Text) {
OS << '<';
bool IsInSystemModule = false;
ValueDecl *D = Entity.Dcl;
if (D) {
IsInSystemModule = D->getModuleContext()->isSystemModule();
if (IsInSystemModule)
OS << 'i';
if (isa<ConstructorDecl>(D) && Entity.IsRef) {
OS << "Ctor";
printLoc(D->getLoc(), OS);
if (Entity.CtorTyRef) {
OS << '-';
OS << Decl::getKindName(Entity.CtorTyRef->getKind());
printLoc(Entity.CtorTyRef->getLoc(), OS);
}
} else {
OS << Decl::getKindName(D->getKind());
if (Entity.IsRef)
printLoc(D->getLoc(), OS);
}
} else {
if (Entity.Mod.isSystemModule())
OS << 'i';
OS << "Mod";
}
OS << '>';
OS << Text;
OS << "</";
if (D) {
if (IsInSystemModule)
OS << 'i';
if (isa<ConstructorDecl>(D) && Entity.IsRef) {
OS << "Ctor";
} else {
OS << Decl::getKindName(D->getKind());
}
} else {
if (Entity.Mod.isSystemModule())
OS << 'i';
OS << "Mod";
}
OS << '>';
return true;
}
bool wrapForTerminal(const SemanticSourceEntity &Entity, StringRef Text) {
llvm::raw_ostream::Colors Col;
switch (Entity.Dcl->getKind()) {
default:
return false;
case DeclKind::Var:
Col = llvm::raw_ostream::GREEN;
break;
case DeclKind::Func:
case DeclKind::Constructor:
case DeclKind::Destructor:
Col = llvm::raw_ostream::MAGENTA;
break;
case DeclKind::Class:
Col = llvm::raw_ostream::RED;
break;
case DeclKind::Struct:
Col = llvm::raw_ostream::BLUE;
break;
case DeclKind::Protocol:
Col = llvm::raw_ostream::YELLOW;
break;
case DeclKind::TypeAlias:
case DeclKind::AssociatedType:
case DeclKind::GenericTypeParam:
Col = llvm::raw_ostream::CYAN; break;
}
if (const char *CStr =
llvm::sys::Process::OutputColor(Col, false, false)) {
OS << CStr;
}
OS << Text;
OS << llvm::sys::Process::ResetColor();
return true;
}
};
} // unnamed namespace
static int doSemanticAnnotation(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool TerminalOutput) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
unsigned BufID = CI.getInputBufferIDs().back();
AnnotationPrinter AnnotPrinter(CI.getSourceMgr(), BufID, llvm::outs(),
TerminalOutput);
AnnotPrinter.walk(*CI.getMainModule());
AnnotPrinter.finished();
return 0;
}
static int doInputCompletenessTest(StringRef SourceFilename) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
llvm::raw_ostream &OS = llvm::outs();
OS << SourceFilename << ": ";
if (isSourceInputComplete(std::move(FileBufOrErr.get())).IsComplete) {
OS << "IS_COMPLETE\n";
} else {
OS << "IS_INCOMPLETE\n";
}
return 0;
}
//============================================================================//
// AST printing
//============================================================================//
static Module *getModuleByFullName(ASTContext &Context, StringRef ModuleName) {
SmallVector<std::pair<Identifier, SourceLoc>, 4>
AccessPath;
while (!ModuleName.empty()) {
StringRef SubModuleName;
std::tie(SubModuleName, ModuleName) = ModuleName.split('.');
AccessPath.push_back(
{ Context.getIdentifier(SubModuleName), SourceLoc() });
}
return Context.getModule(AccessPath);
}
static Module *getModuleByFullName(ASTContext &Context, Identifier ModuleName) {
return Context.getModule(std::make_pair(ModuleName, SourceLoc()));
}
static int doPrintAST(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool RunTypeChecker,
bool FunctionDefinitions,
bool PreferTypeRepr,
bool ExplodePatternBindingDecls,
bool PrintImplicitAttrs,
bool PrintAccessibility,
bool PrintUnavailableDecls,
Accessibility AccessibilityFilter) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
if (!RunTypeChecker)
CI.performParseOnly();
else
CI.performSema();
PrintOptions Options = PrintOptions::printEverything();
Options.FunctionDefinitions = FunctionDefinitions;
Options.PreferTypeRepr = PreferTypeRepr;
Options.ExplodePatternBindingDecls = ExplodePatternBindingDecls;
Options.PrintImplicitAttrs = PrintImplicitAttrs;
Options.PrintAccessibility = PrintAccessibility;
Options.AccessibilityFilter = AccessibilityFilter;
Options.SkipUnavailable = !PrintUnavailableDecls;
if (options::MangledNameToFind.empty()) {
Module *M = CI.getMainModule();
M->getMainSourceFile(Invocation.getInputKind()).print(llvm::outs(),
Options);
return EXIT_SUCCESS;
}
// If we were given a mangled name, do a very simple form of LLDB's logic to
// look up a type based on that name.
Demangle::NodePointer node =
demangle_wrappers::demangleSymbolAsNode(options::MangledNameToFind);
using NodeKind = Demangle::Node::Kind;
if (node->getKind() != NodeKind::Global) {
llvm::errs() << "Unable to demangle name.\n";
return EXIT_FAILURE;
}
node = node->getFirstChild();
// FIXME: Look up things other than types.
if (node->getKind() != NodeKind::Type) {
llvm::errs() << "Name does not refer to a type.\n";
return EXIT_FAILURE;
}
node = node->getFirstChild();
switch (node->getKind()) {
case NodeKind::Class:
case NodeKind::Enum:
case NodeKind::Protocol:
case NodeKind::Structure:
break;
default:
llvm::errs() << "Name does not refer to a nominal type.\n";
return EXIT_FAILURE;
}
ASTContext &ctx = CI.getASTContext();
LookupName lookupName;
auto nameNode = node->getChild(1);
switch (nameNode->getKind()) {
case NodeKind::Identifier:
lookupName.Name = ctx.getIdentifier(nameNode->getText());
break;
case NodeKind::PrivateDeclName:
lookupName.PrivateDiscriminator =
ctx.getIdentifier(nameNode->getChild(0)->getText());
lookupName.Name = ctx.getIdentifier(nameNode->getChild(1)->getText());
break;
default:
llvm::errs() << "Unsupported name kind.\n";
return EXIT_FAILURE;
}
auto contextNode = node->getFirstChild();
// FIXME: Handle nested contexts.
if (contextNode->getKind() != NodeKind::Module) {
llvm::errs() << "Name does not refer to a top-level declaration.\n";
return EXIT_FAILURE;
}
const Module *M = getModuleByFullName(ctx, contextNode->getText());
SmallVector<ValueDecl *, 4> results;
M->lookupValue({}, lookupName.Name, NLKind::QualifiedLookup, results);
if (!lookupName.PrivateDiscriminator.empty()) {
auto newEnd = std::remove_if(results.begin(), results.end(),
[=](ValueDecl *VD) {
auto enclosingFile =
cast<FileUnit>(VD->getDeclContext()->getModuleScopeContext());
auto discriminator = enclosingFile->getDiscriminatorForPrivateValue(VD);
return discriminator != lookupName.PrivateDiscriminator;
});
results.erase(newEnd, results.end());
}
if (results.empty()) {
llvm::errs() << "No matching declarations found.\n";
return EXIT_FAILURE;
}
for (auto *VD : results)
VD->print(llvm::outs(), Options);
return EXIT_SUCCESS;
}
namespace {
class AnnotatingPrinter : public StreamPrinter {
public:
using StreamPrinter::StreamPrinter;
void printDeclPre(const Decl *D) override {
OS << "<decl:" << Decl::getKindName(D->getKind()) << '>';
}
void printDeclLoc(const Decl *D) override {
OS << "<loc>";
}
void printDeclNameEndLoc(const Decl *D) override {
OS << "</loc>";
}
void printDeclPost(const Decl *D) override {
OS << "</decl>";
}
void printTypeRef(const TypeDecl *TD, Identifier Name) override {
OS << "<ref:" << Decl::getKindName(TD->getKind()) << '>';
StreamPrinter::printTypeRef(TD, Name);
OS << "</ref>";
}
void printModuleRef(const Module *Mod, Identifier Name) override {
OS << "<ref:module>";
StreamPrinter::printModuleRef(Mod, Name);
OS << "</ref>";
}
};
}
static int doPrintModules(const CompilerInvocation &InitInvok,
const std::vector<std::string> ModulesToPrint,
ide::ModuleTraversalOptions TraversalOptions,
bool FullyQualifiedTypesIfAmbiguous,
bool SynthesizeSugarOnTypes,
bool AnnotatePrint,
bool PrintImplicitAttrs,
bool PrintAccessibility,
bool PrintUnavailableDecls,
bool PrintRegularComments,
Accessibility AccessibilityFilter,
bool PrintPrivateStdlibDecls) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
auto &Context = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Context, Context.StdlibModuleName);
if (!Stdlib)
return 1;
int ExitCode = 0;
PrintOptions Options = PrintOptions::printEverything();
Options.FullyQualifiedTypesIfAmbiguous = FullyQualifiedTypesIfAmbiguous;
Options.SynthesizeSugarOnTypes = SynthesizeSugarOnTypes;
Options.PrintImplicitAttrs = PrintImplicitAttrs;
Options.PrintAccessibility = PrintAccessibility;
Options.AccessibilityFilter = AccessibilityFilter;
Options.PrintRegularClangComments = PrintRegularComments;
Options.SkipPrivateStdlibDecls = !PrintPrivateStdlibDecls;
Options.SkipUnavailable = !PrintUnavailableDecls;
std::unique_ptr<ASTPrinter> Printer;
if (AnnotatePrint)
Printer.reset(new AnnotatingPrinter(llvm::outs()));
else
Printer.reset(new StreamPrinter(llvm::outs()));
for (StringRef ModuleToPrint : ModulesToPrint) {
if (ModuleToPrint.empty()) {
ExitCode = 1;
continue;
}
// Get the (sub)module to print.
auto *M = getModuleByFullName(Context, ModuleToPrint);
if (!M) {
ExitCode = 1;
continue;
}
// Split the module path.
std::vector<StringRef> ModuleName;
while (!ModuleToPrint.empty()) {
StringRef SubModuleName;
std::tie(SubModuleName, ModuleToPrint) = ModuleToPrint.split('.');
ModuleName.push_back(SubModuleName);
}
assert(!ModuleName.empty());
// FIXME: If ModuleToPrint is a submodule, get its top-level module, which
// will be the DeclContext for all of its Decls since we don't have first-
// class submodules.
if (ModuleName.size() > 1) {
M = getModuleByFullName(Context, ModuleName[0]);
if (!M) {
ExitCode = 1;
continue;
}
}
printSubmoduleInterface(M, ModuleName, TraversalOptions, *Printer, Options);
}
return ExitCode;
}
namespace {
class ASTTypePrinter : public ASTWalker {
raw_ostream &OS;
SourceManager &SM;
const PrintOptions &Options;
unsigned IndentLevel = 0;
public:
ASTTypePrinter(SourceManager &SM, const PrintOptions &Options)
: OS(llvm::outs()), SM(SM), Options(Options) {}
bool walkToDeclPre(Decl *D) override {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
OS.indent(IndentLevel * 2);
OS << Decl::getKindName(VD->getKind()) << "Decl '''"
<< VD->getName().str() << "''' ";
VD->getType().print(OS, Options);
OS << "\n";
}
IndentLevel++;
return true;
}
bool walkToDeclPost(Decl *D) override {
IndentLevel--;
return true;
}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
StringRef SourceCode{ "<unknown>" };
unsigned Line = ~0U;
SourceRange SR = E->getSourceRange();
if (SR.isValid()) {
unsigned BufferID = SM.findBufferContainingLoc(SR.Start);
SourceLoc EndCharLoc = Lexer::getLocForEndOfToken(SM, SR.End);
SourceCode = SM.extractText({ SR.Start,
SM.getByteDistance(SR.Start, EndCharLoc) });
unsigned Column;
std::tie(Line, Column) = SM.getLineAndColumn(SR.Start, BufferID);
}
OS.indent(IndentLevel * 2);
OS << Expr::getKindName(E->getKind()) << "Expr";
if (Line != ~0U)
OS << ":" << Line;
OS << " '''" << SourceCode << "''' ";
E->getType().print(OS, Options);
OS << "\n";
IndentLevel++;
return { true, E };
}
Expr *walkToExprPost(Expr *E) override {
IndentLevel--;
return E;
}
};
} // unnamed namespace
static int doPrintTypes(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
bool FullyQualifiedTypes) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
PrintOptions Options = PrintOptions::printEverything();
Options.FullyQualifiedTypes = FullyQualifiedTypes;
ASTTypePrinter Printer(CI.getSourceMgr(), Options);
CI.getMainModule()->walk(Printer);
return 0;
}
namespace {
class ASTCommentPrinter : public ASTWalker {
raw_ostream &OS;
SourceManager &SM;
XMLValidator &TheXMLValidator;
public:
ASTCommentPrinter(SourceManager &SM, XMLValidator &TheXMLValidator)
: OS(llvm::outs()), SM(SM), TheXMLValidator(TheXMLValidator) {}
StringRef getBufferIdentifier(SourceLoc Loc) {
unsigned BufferID = SM.findBufferContainingLoc(Loc);
return SM.getIdentifierForBuffer(BufferID);
}
void printWithEscaping(StringRef Str) {
for (char C : Str) {
switch (C) {
case '\n': OS << "\\n"; break;
case '\r': OS << "\\r"; break;
case '\t': OS << "\\t"; break;
case '\v': OS << "\\v"; break;
case '\f': OS << "\\f"; break;
default: OS << C; break;
}
}
}
void printDeclName(const ValueDecl *VD) {
if (auto *NTD = dyn_cast<NominalTypeDecl>(VD->getDeclContext())) {
Identifier Id = NTD->getName();
if (!Id.empty())
OS << Id.str() << ".";
}
Identifier Id = VD->getName();
if (!Id.empty()) {
OS << Id.str();
return;
}
if (auto FD = dyn_cast<FuncDecl>(VD)) {
if (auto *ASD = FD->getAccessorStorageDecl()) {
switch (FD->getAccessorKind()) {
case AccessorKind::NotAccessor:
llvm_unreachable("is not an accessor?");
case AccessorKind::IsGetter:
OS << "<getter for ";
break;
case AccessorKind::IsSetter:
OS << "<setter for ";
break;
case AccessorKind::IsWillSet:
OS << "<willSet for ";
break;
case AccessorKind::IsDidSet:
OS << "<didSet for ";
break;
}
printDeclName(ASD);
OS << ">";
return;
}
}
OS << "<anonymous>";
}
void printRawComment(const RawComment &RC) {
OS << "RawComment=";
if (RC.isEmpty()) {
OS << "none";
return;
}
OS << "[";
for (auto &SRC : RC.Comments)
printWithEscaping(SRC.RawText);
OS << "]";
}
void printBriefComment(StringRef Brief) {
OS << "BriefComment=";
if (Brief.empty()) {
OS << "none";
return;
}
OS << "[";
printWithEscaping(Brief);
OS << "]";
}
void printFullComment(const Decl *D) {
std::string XML;
{
llvm::raw_string_ostream OS(XML);
getDocumentationCommentAsXML(D, OS);
}
OS << "FullCommentAsXML=";
if (XML.empty()) {
OS << "none";
return;
}
OS << "[";
printWithEscaping(XML);
OS << "]";
auto Status = TheXMLValidator.validate(XML);
switch (Status.Code) {
case XMLValidator::ErrorCode::Valid:
OS << " CommentXMLValid";
break;
case XMLValidator::ErrorCode::NotCompiledIn:
OS << " ValidationSkipped=[libxml is missing]";
break;
case XMLValidator::ErrorCode::NoSchema:
OS << " ValidationSkipped=[schema is not set]";
break;
case XMLValidator::ErrorCode::BadSchema:
OS << " CommentXMLInvalid=[bad schema file]";
break;
case XMLValidator::ErrorCode::NotWellFormed:
OS << " CommentXMLInvalid=[not well-formed XML: " << Status.Message
<< "]";
break;
case XMLValidator::ErrorCode::NotValid:
OS << " CommentXMLInvalid=[not valid XML: " << Status.Message << "]";
break;
case XMLValidator::ErrorCode::InternalError:
OS << " CommentXMLInvalid=[libxml error]";
break;
}
}
bool walkToDeclPre(Decl *D) override {
if (D->isImplicit())
return true;
if (auto *VD = dyn_cast<ValueDecl>(D)) {
SourceLoc Loc = D->getLoc();
if (Loc.isValid()) {
auto LineAndColumn = SM.getLineAndColumn(Loc);
OS << getBufferIdentifier(VD->getLoc())
<< ":" << LineAndColumn.first << ":" << LineAndColumn.second << ": ";
}
OS << Decl::getKindName(VD->getKind()) << "/";
printDeclName(VD);
OS << " ";
printRawComment(D->getRawComment());
OS << " ";
printBriefComment(D->getBriefComment());
OS << " ";
printFullComment(D);
OS << "\n";
}
return true;
}
};
} // unnamed namespace
static int doPrintComments(const CompilerInvocation &InitInvok,
StringRef SourceFilename,
StringRef CommentsXMLSchema) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
Invocation.getLangOptions().AttachCommentsToDecls = true;
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
XMLValidator TheXMLValidator;
TheXMLValidator.setSchema(CommentsXMLSchema);
ASTCommentPrinter Printer(CI.getSourceMgr(), TheXMLValidator);
CI.getMainModule()->walk(Printer);
return 0;
}
static int doPrintModuleComments(const CompilerInvocation &InitInvok,
const std::vector<std::string> ModulesToPrint,
StringRef CommentsXMLSchema) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
auto &Context = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Context, Context.StdlibModuleName);
if (!Stdlib)
return 1;
XMLValidator TheXMLValidator;
TheXMLValidator.setSchema(CommentsXMLSchema);
ASTCommentPrinter Printer(CI.getSourceMgr(), TheXMLValidator);
int ExitCode = 0;
for (StringRef ModuleToPrint : ModulesToPrint) {
auto *M = getModuleByFullName(Context, ModuleToPrint);
if (!M) {
ExitCode = -1;
continue;
}
M->walk(Printer);
}
return ExitCode;
}
static int doPrintModuleImports(const CompilerInvocation &InitInvok,
const std::vector<std::string> ModulesToPrint) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
auto &Context = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Context, Context.StdlibModuleName);
if (!Stdlib)
return 1;
int ExitCode = 0;
for (StringRef ModuleToPrint : ModulesToPrint) {
auto *M = getModuleByFullName(Context, ModuleToPrint);
if (!M) {
ExitCode = -1;
continue;
}
auto isClangModule = [](const Module *M) -> bool {
if (!M->getFiles().empty())
if (M->getFiles().front()->getKind() == FileUnitKind::ClangModule)
return true;
return false;
};
SmallVector<Module::ImportedModule, 16> scratch;
M->forAllVisibleModules({}, [&](const Module::ImportedModule &next) {
llvm::outs() << next.second->Name;
if (isClangModule(next.second))
llvm::outs() << " (Clang)";
llvm::outs() << ":\n";
scratch.clear();
next.second->getImportedModules(scratch, Module::ImportFilter::Public);
for (auto &import : scratch) {
llvm::outs() << "\t" << import.second->Name;
for (auto accessPathPiece : import.first) {
llvm::outs() << "." << accessPathPiece.first;
}
if (isClangModule(import.second))
llvm::outs() << " (Clang)";
llvm::outs() << "\n";
}
});
}
return ExitCode;
}
//============================================================================//
// Print USRs
//============================================================================//
namespace {
class USRPrinter : public ide::SourceEntityWalker {
SourceManager &SM;
unsigned BufferID;
llvm::raw_ostream &OS;
public:
USRPrinter(SourceManager &SM, unsigned BufferID, llvm::raw_ostream &OS)
: SM(SM), BufferID(BufferID), OS(OS) { }
private:
bool walkToDeclPre(Decl *D, CharSourceRange Range) override {
if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
printUSR(VD, Range.getStart());
return true;
}
bool walkToExprPre(Expr *E) override {
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
printUSR(DRE->getDecl(), E->getLoc());
return true;
}
void printUSR(const ValueDecl *VD, SourceLoc Loc) {
printLoc(Loc);
OS << ' ';
if (ide::printDeclUSR(VD, OS))
OS << "ERROR:no-usr";
OS << '\n';
}
void printLoc(SourceLoc Loc) {
if (Loc.isValid()) {
auto LineCol = SM.getLineAndColumn(Loc, BufferID);
OS << LineCol.first << ':' << LineCol.second;
}
}
};
} // unnamed namespace
static int doPrintUSRs(const CompilerInvocation &InitInvok,
StringRef SourceFilename) {
CompilerInvocation Invocation(InitInvok);
Invocation.addInputFilename(SourceFilename);
// FIXME: Arggh, we need to get rid of this thing.
Invocation.getClangImporterOptions().ExtraArgs = {
"-detailed-preprocessing-record"
};
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation))
return 1;
CI.performSema();
unsigned BufID = CI.getInputBufferIDs().back();
USRPrinter Printer(CI.getSourceMgr(), BufID, llvm::outs());
Printer.walk(*CI.getMainModule());
return 0;
}
static int doParseReST(StringRef SourceFilename) {
llvm::rest::ReSTContext Context;
llvm::rest::SourceManager<unsigned> SM;
llvm::SmallString<64> DocutilsXML;
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFileOrSTDIN(SourceFilename);
if (!FileBufOrErr) {
llvm::errs() << "error opening input file: "
<< FileBufOrErr.getError().message() << '\n';
return 1;
}
llvm::rest::LineList LL({});
{
SmallVector<StringRef, 16> Lines;
splitIntoLines(FileBufOrErr.get()->getBuffer(), Lines);
llvm::rest::LineListBuilder Builder;
for (auto S : Lines) {
Builder.addLine(S, SM.registerLine(S, 0));
}
LL = Builder.takeLineList(Context);
}
auto *TheDocument = parseDocument(Context, LL);
{
llvm::raw_svector_ostream OS(DocutilsXML);
convertToDocutilsXML(TheDocument, OS);
}
llvm::outs() << DocutilsXML.str();
return 0;
}
static int doTestCreateCompilerInvocation(ArrayRef<const char *> Args) {
PrintingDiagnosticConsumer PDC;
SourceManager SM;
DiagnosticEngine Diags(SM);
Diags.addConsumer(PDC);
std::unique_ptr<CompilerInvocation> CI =
driver::createCompilerInvocation(Args, Diags);
if (!CI) {
llvm::errs() << "error: unable to create a CompilerInvocation\n";
return 1;
}
return 0;
}
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// getMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement getMainExecutable
// without being given the address of a function in the main executable).
void anchorForGetMainExecutable() {}
namespace {
// Unavailable option.
struct Unavailable {
StringRef Msg;
Unavailable(StringRef Msg) : Msg(Msg) { }
};
// Signature has been audited with respect to optional types.
struct OptionalTypeAdjustment {
llvm::SmallVector<api_notes::NullableKind, 3> AdjustedTypes;
OptionalTypeAdjustment(unsigned numParams) {
assert(numParams == 0);
}
template<typename ...Ts>
OptionalTypeAdjustment(unsigned numParams, Ts ...kinds) {
if (numParams > 0 ) {
assert(sizeof...(Ts) == numParams);
api_notes::NullableKind actualKinds[] = { kinds... };
AdjustedTypes.append(actualKinds, actualKinds + numParams);
}
}
};
// DesignatedInit flag
enum DesignatedInitFlag { DesignatedInit };
// FactoryAsClassMethod flag
enum FactoryAsClassMethodFlag { FactoryAsClassMethod };
template<typename T>
T &&operator|(T &&known, Unavailable unavailable) {
known.Unavailable = true;
known.UnavailableMsg = unavailable.Msg;
return std::move(known);
}
api_notes::ObjCContextInfo &&operator|(api_notes::ObjCContextInfo &&known,
OptionalTypeAdjustment adjustment) {
assert(adjustment.AdjustedTypes.size() <= 1);
if (adjustment.AdjustedTypes.size() == 1) {
known.setDefaultNullability(adjustment.AdjustedTypes[0]);
}
return std::move(known);
}
api_notes::ObjCPropertyInfo &&operator|(api_notes::ObjCPropertyInfo &&known,
api_notes::NullableKind kind) {
known.setNullabilityAudited(kind);
return std::move(known);
}
api_notes::ObjCMethodInfo &&operator|(api_notes::ObjCMethodInfo &&known,
OptionalTypeAdjustment adjustment) {
known.NullabilityAudited = true;
known.NumAdjustedNullable = adjustment.AdjustedTypes.size();
for (unsigned i = 0; i < known.NumAdjustedNullable; ++i)
known.addTypeInfo(i, adjustment.AdjustedTypes[i]);
return std::move(known);
}
api_notes::ObjCMethodInfo &&operator|(api_notes::ObjCMethodInfo &&known,
DesignatedInitFlag) {
known.DesignatedInit = true;
return std::move(known);
}
api_notes::ObjCMethodInfo &&operator|(api_notes::ObjCMethodInfo &&known,
FactoryAsClassMethodFlag) {
known.setFactoryAsInitKind(api_notes::FactoryAsInitKind::AsClassMethod);
return std::move(known);
}
}
/// Generate an API annotation file from the known Objective-C methods
/// file.
///
/// FIXME: This is a horrible, horrible hack.
bool generateAPIAnnotation(StringRef moduleName, StringRef fileName) {
using namespace api_notes;
APINotesWriter writer(moduleName);
// Constants used to map from KnownObjCMethods.def.
const auto OTK_None = api_notes::NullableKind::NonNullable;
(void)OTK_None;
const auto OTK_Optional = api_notes::NullableKind::Nullable;
(void)OTK_Optional;
const auto OTK_ImplicitlyUnwrappedOptional
= api_notes::NullableKind::Unknown;
(void)OTK_ImplicitlyUnwrappedOptional;
StringRef currentModuleName;
#define START_MODULE(ModuleName) \
currentModuleName = #ModuleName;
#define MAKE_SELECTOR_REF(NumPieces, ...) \
ObjCSelectorRef{NumPieces, { __VA_ARGS__ } }
#define INSTANCE_METHOD(ClassName, Selector, Options) \
if (moduleName.equals(currentModuleName)) { \
auto contextID = writer.addObjCClass(#ClassName, \
ObjCContextInfo()); \
writer.addObjCMethod(contextID, MAKE_SELECTOR_REF Selector, \
/*isInstanceMethod=*/true, \
ObjCMethodInfo() | Options); \
}
#define PROTOCOL_INSTANCE_METHOD(ProtocolName, Selector, Options) \
if (moduleName.equals(currentModuleName)) { \
auto contextID = writer.addObjCProtocol(#ProtocolName, \
ObjCContextInfo()); \
writer.addObjCMethod(contextID, MAKE_SELECTOR_REF Selector, \
/*isInstanceMethod=*/true, \
ObjCMethodInfo() | Options); \
}
#define CLASS_METHOD(ClassName, Selector, Options) \
if (moduleName == currentModuleName) { \
auto contextID = writer.addObjCClass(#ClassName, \
ObjCContextInfo()); \
writer.addObjCMethod(contextID, MAKE_SELECTOR_REF Selector, \
/*isInstanceMethod=*/false, \
ObjCMethodInfo() | Options); \
}
#define OBJC_CLASS(ClassName, Options) \
if (moduleName == currentModuleName) { \
writer.addObjCClass(#ClassName, ObjCContextInfo() | Options); \
}
#define OBJC_PROTOCOL(ProtocolName, Options) \
if (moduleName == currentModuleName) { \
writer.addObjCProtocol(#ProtocolName, ObjCContextInfo() | Options); \
}
#define OBJC_PROPERTY(ContextName, PropertyName, OptionalTypeKind) \
if (moduleName == currentModuleName) { \
auto contextID = writer.addObjCClass(#ContextName, \
ObjCContextInfo()); \
writer.addObjCProperty(contextID, #PropertyName, \
ObjCPropertyInfo() | OptionalTypeKind); \
}
#define OBJC_PROTOCOL_PROPERTY(ContextName, PropertyName, OptionalTypeKind) \
if (moduleName == currentModuleName) { \
auto contextID = writer.addObjCProtocol(#ContextName, \
ObjCContextInfo()); \
writer.addObjCProperty(contextID, #PropertyName, \
ObjCPropertyInfo() | OptionalTypeKind); \
}
#include "KnownObjCMethods.def"
#undef MAKE_SELECTOR_REF
std::error_code EC;
llvm::raw_fd_ostream os(fileName.str(), EC, llvm::sys::fs::OpenFlags::F_None);
writer.writeToStream(os);
os.flush();
return os.has_error();
}
/// Generate an API annotation file from the known Objective-C methods
/// file.
///
/// FIXME: This is a horrible, horrible hack.
bool checkAPIAnnotation(StringRef moduleName, StringRef fileName) {
using namespace api_notes;
auto bufferOrError = llvm::MemoryBuffer::getFile(fileName);
if (!bufferOrError)
return true;
auto reader = APINotesReader::get(std::move(bufferOrError.get()));
if (!reader)
return true;
// Okay. Go look for the data we expect.
StringRef currentModuleName;
// Constants used to map from KnownObjCMethods.def.
const auto OTK_None = api_notes::NullableKind::NonNullable;
(void)OTK_None;
const auto OTK_Optional = api_notes::NullableKind::Nullable;
(void)OTK_Optional;
const auto OTK_ImplicitlyUnwrappedOptional
= api_notes::NullableKind::Unknown;
(void)OTK_ImplicitlyUnwrappedOptional;
#define START_MODULE(ModuleName) \
currentModuleName = #ModuleName;
#define MAKE_SELECTOR_REF(NumPieces, ...) \
ObjCSelectorRef{NumPieces, { __VA_ARGS__ } }
#define INSTANCE_METHOD(ClassName, Selector, Options) \
if (auto classInfo = reader->lookupObjCClass(#ClassName)) { \
if (auto info = reader->lookupObjCMethod( \
classInfo->first, \
MAKE_SELECTOR_REF Selector, true)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCMethodInfo() | Options; \
if (*info != expectedInfo) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define PROTOCOL_INSTANCE_METHOD(ProtocolName, Selector, Options) \
if (auto protocolInfo = reader->lookupObjCProtocol(#ProtocolName)) { \
if (auto info = reader->lookupObjCMethod( \
protocolInfo->first, \
MAKE_SELECTOR_REF Selector, true)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName << " method" \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCMethodInfo() | Options; \
if (*info != expectedInfo) { \
llvm::errs() << "Protocol " << #ProtocolName << " method" \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName << " method" \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName \
<< " not found in API notes file\n"; \
return true; \
}
#define CLASS_METHOD(ClassName, Selector, Options) \
if (auto classInfo = reader->lookupObjCClass(#ClassName)) { \
if (auto info = reader->lookupObjCMethod( \
classInfo->first, \
MAKE_SELECTOR_REF Selector, false)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCMethodInfo() | Options; \
if (*info != expectedInfo) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName << " method" \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_CLASS(ClassName, Options) \
if (auto info = reader->lookupObjCClass(#ClassName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Class " << moduleName << "." << #ClassName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCContextInfo() | Options; \
if (info->second != expectedInfo) { \
llvm::errs() << "Class " << moduleName << "." << #ClassName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << moduleName << "." << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_PROTOCOL(ProtocolName, Options) \
if (auto info = reader->lookupObjCProtocol(#ProtocolName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Protocol " << moduleName << "." << #ProtocolName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCContextInfo() | Options; \
if (info->second != expectedInfo) { \
llvm::errs() << "Protocol " << moduleName << "." << #ProtocolName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << moduleName << "." << #ProtocolName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_PROPERTY(ClassName, PropertyName, OptionalTypeKind) \
if (auto classInfo = reader->lookupObjCClass(#ClassName)) { \
if (auto info = reader->lookupObjCProperty(classInfo->first, \
#PropertyName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Property " << #ClassName << "." << #PropertyName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCPropertyInfo() | OptionalTypeKind; \
if (*info != expectedInfo) { \
llvm::errs() << "Property " << #ClassName << "." << #PropertyName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Property " << #ClassName << "." << #PropertyName \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Class " << #ClassName \
<< " not found in API notes file\n"; \
return true; \
}
#define OBJC_PROTOCOL_PROPERTY(ProtocolName, PropertyName, OptionalTypeKind) \
if (auto protocolInfo = reader->lookupObjCProtocol(#ProtocolName)) { \
if (auto info = reader->lookupObjCProperty(protocolInfo->first, \
#PropertyName)) { \
if (moduleName != currentModuleName) { \
llvm::errs() << "Property " << #ProtocolName << "." << #PropertyName \
<< " should not have been found\n"; \
return true; \
} \
auto expectedInfo = ObjCPropertyInfo() | OptionalTypeKind; \
if (*info != expectedInfo) { \
llvm::errs() << "Property " << #ProtocolName << "." << #PropertyName \
<< " has incorrect information\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Property " << #ProtocolName << "." << #PropertyName \
<< " not found in API notes file\n"; \
return true; \
} \
} else if (moduleName == currentModuleName) { \
llvm::errs() << "Protocol " << #ProtocolName \
<< " not found in API notes file\n"; \
return true; \
}
#include "KnownObjCMethods.def"
#undef MAKE_SELECTOR_REF
return false;
}
int main(int argc, char *argv[]) {
// Print a stack trace if we signal out.
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
if (argc > 1) {
// Handle integrated test tools which do not use
// llvm::cl::ParseCommandLineOptions.
StringRef FirstArg(argv[1]);
if (FirstArg == "-test-createCompilerInvocation") {
ArrayRef<const char *> Args(argv + 2, argc - 2);
return doTestCreateCompilerInvocation(Args);
}
}
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift IDE Test\n");
if (options::Action == ActionType::None) {
llvm::errs() << "action required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (options::Action == ActionType::GenerateAPIAnnotation) {
if (options::OutputFilename.empty()) {
llvm::errs() << "output file required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (options::InputFilenames.size() != 1) {
llvm::errs() << "single input module required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (generateAPIAnnotation(options::InputFilenames[0],
options::OutputFilename)) {
llvm::errs() << "could not generate " << options::OutputFilename << "\n";
return 1;
}
return 0;
}
if (options::Action == ActionType::CheckAPIAnnotation) {
if (options::InputFilenames.size() != 2) {
llvm::errs() << "input file and module required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
if (checkAPIAnnotation(options::InputFilenames[0],
options::InputFilenames[1])) {
llvm::errs() << "could not read " << options::InputFilenames[0] << "\n";
return 1;
}
return 0;
}
if (options::Action == ActionType::TestCreateCompilerInvocation) {
llvm::errs() << "-test-createCompilerInvocation must be specified before "
"all other arguments\n";
return 1;
}
if (options::SourceFilename.empty()) {
llvm::errs() << "source file required\n";
llvm::cl::PrintHelpMessage();
return 1;
}
// If no SDK was specified via -sdk, check environment variable SDKROOT.
if (options::SDK.getNumOccurrences() == 0) {
const char *SDKROOT = getenv("SDKROOT");
if (SDKROOT)
options::SDK = SDKROOT;
}
if (options::PrintStats)
llvm::EnableStatistics();
CompilerInvocation InitInvok;
for (auto &File : options::InputFilenames)
InitInvok.addInputFilename(File);
if (!options::InputFilenames.empty())
InitInvok.setInputKind(SourceFileKind::Library);
InitInvok.setMainExecutablePath(
llvm::sys::fs::getMainExecutable(argv[0],
reinterpret_cast<void *>(&anchorForGetMainExecutable)));
InitInvok.setModuleName("swift_ide_test");
InitInvok.setSDKPath(options::SDK);
if (!options::Triple.empty())
InitInvok.setTargetTriple(options::Triple);
InitInvok.getClangImporterOptions().ModuleCachePath =
options::ModuleCachePath;
InitInvok.setImportSearchPaths(options::ImportPaths);
InitInvok.setFrameworkSearchPaths(options::FrameworkPaths);
InitInvok.getFrontendOptions().EnableSourceImport |=
options::EnableSourceImport;
InitInvok.getFrontendOptions().ImplicitObjCHeaderPath =
options::ImportObjCHeader;
InitInvok.getLangOptions().SplitPrepositions |= options::SplitObjCSelectors;
InitInvok.getClangImporterOptions().InferImplicitProperties |=
options::ImplicitProperties;
if (!options::ResourceDir.empty()) {
InitInvok.setRuntimeResourcePath(options::ResourceDir);
}
// Force these options, which are factored out for staging purposes.
InitInvok.getLangOptions().UsePrivateDiscriminators = true;
Mangle::Mangler::UsePrivateDiscriminators = true;
for (auto ConfigName : options::BuildConfigs)
InitInvok.getLangOptions().addBuildConfigOption(ConfigName);
int ExitCode;
switch (options::Action) {
case ActionType::None:
case ActionType::GenerateAPIAnnotation:
case ActionType::CheckAPIAnnotation:
case ActionType::TestCreateCompilerInvocation:
llvm_unreachable("should be handled above");
case ActionType::CodeCompletion:
if (options::CodeCompletionToken.empty()) {
llvm::errs() << "code completion token name required\n";
return 1;
}
ExitCode = doCodeCompletion(InitInvok,
options::SourceFilename,
options::CodeCompletionToken,
options::CodeCompletionDiagnostics,
options::CodeCompletionKeywords);
break;
case ActionType::REPLCodeCompletion:
ExitCode = doREPLCodeCompletion(InitInvok, options::SourceFilename);
break;
case ActionType::SyntaxColoring:
ExitCode = doSyntaxColoring(InitInvok,
options::SourceFilename,
options::TerminalOutput,
options::Typecheck);
break;
case ActionType::Structure:
ExitCode = doStructureAnnotation(InitInvok, options::SourceFilename);
break;
case ActionType::Annotation:
ExitCode = doSemanticAnnotation(InitInvok,
options::SourceFilename,
options::TerminalOutput);
break;
case ActionType::TestInputCompleteness:
ExitCode = doInputCompletenessTest(options::SourceFilename);
break;
case ActionType::PrintASTNotTypeChecked:
ExitCode = doPrintAST(InitInvok,
options::SourceFilename,
/*RunTypeChecker=*/false,
/*FunctionDefinitions=*/options::FunctionDefinitions,
/*PreferTypeRepr=*/options::PreferTypeRepr,
options::ExplodePatternBindingDecls,
options::PrintImplicitAttrs,
options::PrintAccessibility,
!options::SkipUnavailable,
options::AccessibilityFilter);
break;
case ActionType::PrintASTTypeChecked:
ExitCode = doPrintAST(InitInvok,
options::SourceFilename,
/*RunTypeChecker=*/true,
/*FunctionDefinitions=*/options::FunctionDefinitions,
/*PreferTypeRepr=*/options::PreferTypeRepr,
options::ExplodePatternBindingDecls,
options::PrintImplicitAttrs,
options::PrintAccessibility,
!options::SkipUnavailable,
options::AccessibilityFilter);
break;
case ActionType::PrintModule: {
ide::ModuleTraversalOptions TraversalOptions;
if (options::ModulePrintSubmodules)
TraversalOptions |= ide::ModuleTraversal::VisitSubmodules;
if (options::ModulePrintHidden)
TraversalOptions |= ide::ModuleTraversal::VisitHidden;
if (options::ModulePrintSkipOverlay)
TraversalOptions |= ide::ModuleTraversal::SkipOverlay;
ExitCode = doPrintModules(
InitInvok, options::ModuleToPrint, TraversalOptions,
options::FullyQualifiedTypesIfAmbiguous,
options::SynthesizeSugarOnTypes,
options::AnnotatePrint,
options::PrintImplicitAttrs,
options::PrintAccessibility,
!options::SkipUnavailable,
options::PrintRegularComments,
options::AccessibilityFilter,
!options::SkipPrivateStdlibDecls);
break;
}
case ActionType::PrintTypes:
ExitCode = doPrintTypes(InitInvok, options::SourceFilename,
options::FullyQualifiedTypes);
break;
case ActionType::PrintComments:
ExitCode = doPrintComments(InitInvok, options::SourceFilename,
options::CommentsXMLSchema);
break;
case ActionType::PrintModuleComments:
ExitCode = doPrintModuleComments(InitInvok, options::ModuleToPrint,
options::CommentsXMLSchema);
break;
case ActionType::PrintModuleImports:
ExitCode = doPrintModuleImports(InitInvok, options::ModuleToPrint);
break;
case ActionType::PrintUSRs:
ExitCode = doPrintUSRs(InitInvok, options::SourceFilename);
break;
case ActionType::ParseReST:
ExitCode = doParseReST(options::SourceFilename);
break;
}
if (options::PrintStats)
llvm::PrintStatistics();
return ExitCode;
}
|
/*
* DiscoveryListener
* Aug 2014
* nathan lachenmyer
*/
#include <memory>
#include "DiscoveryListener.h"
#include "DeviceHeader.h"
using namespace ofxPixelPusher;
DiscoveryListener* DiscoveryListener::mDiscoveryService = NULL;
DiscoveryListener* DiscoveryListener::getInstance() {
if (mDiscoveryService == NULL) {
mDiscoveryService = new DiscoveryListener();
}
return mDiscoveryService;
}
void DiscoveryListener::freeInstance() {
delete mDiscoveryService;
mDiscoveryService = NULL;
}
int DiscoveryListener::getFrameLimit() {
return mFrameLimit;
}
std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getPushers() {
mUpdateMutex.lock();
std::vector<std::shared_ptr<PixelPusher> > pusherVector;
for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator it = mPusherMap.begin();
it != mPusherMap.end();
++it) {
pusherVector.push_back(it->second);
}
mUpdateMutex.unlock();
return pusherVector;
}
std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getGroup(long groupId) {
mUpdateMutex.lock();
std::vector<std::shared_ptr<PixelPusher> > pusherVector;
for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
it != mGroupMap.upper_bound(groupId);
++it) {
pusherVector.push_back(it->second);
}
mUpdateMutex.unlock();
return pusherVector;
}
std::shared_ptr<PixelPusher> DiscoveryListener::getController(long groupId, long controllerId) {
mUpdateMutex.lock();
for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
it != mGroupMap.upper_bound(groupId);
++it) {
if (it->second->getControllerId() == controllerId) {
mUpdateMutex.unlock();
return it->second;
}
}
//if no matching PixelPusher is found, return a nullPtr
std::shared_ptr<PixelPusher> nullPtr;
mUpdateMutex.unlock();
return nullPtr;
}
DiscoveryListener::DiscoveryListener() {
mDiscoveryServiceSocket.Create();
mDiscoveryServiceSocket.Bind(mPort);
mDiscoveryServiceSocket.SetNonBlocking(true);
std::printf("Starting Discovery Listener Service...\n");
mAutoThrottle = true;
mFrameLimit = 60;
mUpdateMapThread = std::thread(&DiscoveryListener::updatePusherMap, this);
}
DiscoveryListener::~DiscoveryListener() {
if (mUpdateMapThread.joinable()) {
mUpdateMapThread.join();
}
}
void DiscoveryListener::receive() {
char udpMessage[4096];
int bytesReceived = mDiscoveryServiceSocket.Receive(udpMessage, 4096);
if (bytesReceived > 0) {
DiscoveryListener::getInstance()->update(std::string(udpMessage));
}
}
void DiscoveryListener::update(std::string udpMessage) {
std::printf("Updating registry...\n");
mUpdateMutex.lock();
DeviceHeader* header;
header = new DeviceHeader(reinterpret_cast<const unsigned char*> (udpMessage.c_str()), udpMessage.length());
if (header->getDeviceType() != PIXELPUSHER) {
//if the device type isn't PixelPusher, end processing it right here.
return;
}
std::shared_ptr<PixelPusher> incomingDevice(new PixelPusher(header));
std::string macAddress = incomingDevice->getMacAddress();
std::string ipAddress = incomingDevice->getIpAddress();
mLastSeenMap[macAddress] = std::clock() / CLOCKS_PER_SEC;
if (mPusherMap.count(macAddress) == 0) {
//does not already exist in the map
addNewPusher(macAddress, incomingDevice);
std::printf("Adding new PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
}
else {
//already exists in the map
if (!mPusherMap[macAddress]->isEqual(incomingDevice)) {
//if the pushers are not equal, replace it with this one
updatePusher(macAddress, incomingDevice);
std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
}
else {
//if they're the same, then just update it
mPusherMap[macAddress]->updateVariables(incomingDevice);
std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
if (incomingDevice->getDeltaSequence() > 3) {
mPusherMap[macAddress]->increaseExtraDelay(5);
}
if (incomingDevice->getDeltaSequence() < 1) {
mPusherMap[macAddress]->decreaseExtraDelay(1);
}
}
}
mUpdateMutex.unlock();
}
void DiscoveryListener::addNewPusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
mPusherMap.insert(std::make_pair(macAddress, pusher));
mGroupMap.insert(std::make_pair(pusher->getGroupId(), pusher));
pusher->createCardThread();
}
void DiscoveryListener::updatePusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
mPusherMap[macAddress]->copyHeader(pusher);
}
void DiscoveryListener::updatePusherMap() {
mRunUpdateMapThread = true;
while (mRunUpdateMapThread) {
mUpdateMutex.lock();
for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator pusher = mPusherMap.begin(); pusher != mPusherMap.end();) {
//pusher->first is Mac Address, pusher->second is the shared pointer to the PixelPusher
if (!pusher->second->isAlive()) {
std::printf("DiscoveryListener removing PixelPusher %s from all maps.\n", pusher->first.c_str());
pusher->second->destroyCardThread();
//remove pusher from maps
mLastSeenMap.erase(pusher->first);
mPusherMap.erase(pusher++);
}
else {
++pusher;
}
}
mUpdateMutex.unlock();
this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
integrated with ofxNetwork, but ofxNetwork doesnt appear to handle broadcasts properly
/*
* DiscoveryListener
* Aug 2014
* nathan lachenmyer
*/
#include <memory>
#include "DiscoveryListener.h"
#include "DeviceHeader.h"
using namespace ofxPixelPusher;
DiscoveryListener* DiscoveryListener::mDiscoveryService = NULL;
DiscoveryListener* DiscoveryListener::getInstance() {
if (mDiscoveryService == NULL) {
mDiscoveryService = new DiscoveryListener();
}
return mDiscoveryService;
}
void DiscoveryListener::freeInstance() {
delete mDiscoveryService;
mDiscoveryService = NULL;
}
int DiscoveryListener::getFrameLimit() {
return mFrameLimit;
}
std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getPushers() {
mUpdateMutex.lock();
std::vector<std::shared_ptr<PixelPusher> > pusherVector;
for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator it = mPusherMap.begin();
it != mPusherMap.end();
++it) {
pusherVector.push_back(it->second);
}
mUpdateMutex.unlock();
return pusherVector;
}
std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getGroup(long groupId) {
mUpdateMutex.lock();
std::vector<std::shared_ptr<PixelPusher> > pusherVector;
for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
it != mGroupMap.upper_bound(groupId);
++it) {
pusherVector.push_back(it->second);
}
mUpdateMutex.unlock();
return pusherVector;
}
std::shared_ptr<PixelPusher> DiscoveryListener::getController(long groupId, long controllerId) {
mUpdateMutex.lock();
for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
it != mGroupMap.upper_bound(groupId);
++it) {
if (it->second->getControllerId() == controllerId) {
mUpdateMutex.unlock();
return it->second;
}
}
//if no matching PixelPusher is found, return a nullPtr
std::shared_ptr<PixelPusher> nullPtr;
mUpdateMutex.unlock();
return nullPtr;
}
DiscoveryListener::DiscoveryListener() {
mDiscoveryServiceSocket.Create();
mDiscoveryServiceSocket.BindMcast("0.0.0.0", mPort);
mDiscoveryServiceSocket.SetNonBlocking(true);
std::printf("Starting Discovery Listener Service...\n");
mAutoThrottle = true;
mFrameLimit = 60;
mUpdateMapThread = std::thread(&DiscoveryListener::updatePusherMap, this);
}
DiscoveryListener::~DiscoveryListener() {
if (mUpdateMapThread.joinable()) {
mUpdateMapThread.join();
}
}
void DiscoveryListener::receive() {
char udpMessage[4096];
int bytesReceived = mDiscoveryServiceSocket.Receive(udpMessage, 4096);
if (bytesReceived > 0) {
DiscoveryListener::getInstance()->update(std::string(udpMessage));
}
}
void DiscoveryListener::update(std::string udpMessage) {
std::printf("Updating registry...\n");
mUpdateMutex.lock();
DeviceHeader* header;
header = new DeviceHeader(reinterpret_cast<const unsigned char*> (udpMessage.c_str()), udpMessage.length());
if (header->getDeviceType() != PIXELPUSHER) {
//if the device type isn't PixelPusher, end processing it right here.
return;
}
std::shared_ptr<PixelPusher> incomingDevice(new PixelPusher(header));
std::string macAddress = incomingDevice->getMacAddress();
std::string ipAddress = incomingDevice->getIpAddress();
mLastSeenMap[macAddress] = std::clock() / CLOCKS_PER_SEC;
if (mPusherMap.count(macAddress) == 0) {
//does not already exist in the map
addNewPusher(macAddress, incomingDevice);
std::printf("Adding new PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
}
else {
//already exists in the map
if (!mPusherMap[macAddress]->isEqual(incomingDevice)) {
//if the pushers are not equal, replace it with this one
updatePusher(macAddress, incomingDevice);
std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
}
else {
//if they're the same, then just update it
mPusherMap[macAddress]->updateVariables(incomingDevice);
std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
if (incomingDevice->getDeltaSequence() > 3) {
mPusherMap[macAddress]->increaseExtraDelay(5);
}
if (incomingDevice->getDeltaSequence() < 1) {
mPusherMap[macAddress]->decreaseExtraDelay(1);
}
}
}
mUpdateMutex.unlock();
}
void DiscoveryListener::addNewPusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
mPusherMap.insert(std::make_pair(macAddress, pusher));
mGroupMap.insert(std::make_pair(pusher->getGroupId(), pusher));
pusher->createCardThread();
}
void DiscoveryListener::updatePusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
mPusherMap[macAddress]->copyHeader(pusher);
}
void DiscoveryListener::updatePusherMap() {
mRunUpdateMapThread = true;
while (mRunUpdateMapThread) {
mUpdateMutex.lock();
for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator pusher = mPusherMap.begin(); pusher != mPusherMap.end();) {
//pusher->first is Mac Address, pusher->second is the shared pointer to the PixelPusher
if (!pusher->second->isAlive()) {
std::printf("DiscoveryListener removing PixelPusher %s from all maps.\n", pusher->first.c_str());
pusher->second->destroyCardThread();
//remove pusher from maps
mLastSeenMap.erase(pusher->first);
mPusherMap.erase(pusher++);
}
else {
++pusher;
}
}
mUpdateMutex.unlock();
this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
|
#include <rang.hpp>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <date.h>
#include "Tools/Display/Terminal/Terminal.hpp"
#ifdef ENABLE_MPI
#include <mpi.h>
#endif
#include "Tools/general_utils.h"
#include "Tools/system_functions.h"
#include "Tools/Display/rang_format/rang_format.h"
#include "Tools/Exception/exception.hpp"
#include "Factory/Module/Source/Source.hpp"
#include "Factory/Module/CRC/CRC.hpp"
#include "Factory/Module/Encoder/Encoder.hpp"
#include "Factory/Module/Puncturer/Puncturer.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "Factory/Module/Modem/Modem.hpp"
#include "Factory/Module/Channel/Channel.hpp"
#include "Factory/Module/Quantizer/Quantizer.hpp"
#include "Factory/Module/Decoder/Decoder.hpp"
#include "Factory/Module/Monitor/Monitor.hpp"
#include "Factory/Tools/Display/Terminal/Terminal.hpp"
#include "Launcher.hpp"
using namespace aff3ct;
using namespace aff3ct::launcher;
Launcher::Launcher(const int argc, const char **argv, factory::Simulation::parameters ¶ms_common,
std::ostream &stream)
: simu(nullptr), ah(argc, argv), params_common(params_common), stream(stream)
{
cmd_line += std::string(argv[0]) + std::string(" ");
for (auto i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
cmd_line += std::string(argv[i]);
else
cmd_line += std::string("\"") + std::string(argv[i]) + std::string("\"");
cmd_line += std::string(" ");
}
}
Launcher::~Launcher()
{
}
void Launcher::get_description_args()
{
}
void Launcher::store_args()
{
}
int Launcher::read_arguments()
{
this->get_description_args();
std::vector<std::string> cmd_error;
this->arg_vals = ah.parse_arguments(this->args, this->cmd_warn, cmd_error);
try
{
this->store_args();
}
catch(const std::exception& e)
{
auto save = tools::exception::no_backtrace;
tools::exception::no_backtrace = true;
cmd_error.emplace_back(e.what());
tools::exception::no_backtrace = save;
}
if (params_common.display_help)
{
auto grps = factory::Factory::create_groups({¶ms_common});
ah.print_help(this->args, grps, params_common.display_adv_help);
}
// print usage
if (!cmd_error.empty() && !params_common.display_help)
ah.print_usage(this->args);
// print the errors
if (!cmd_error.empty()) std::cerr << std::endl;
for (unsigned e = 0; e < cmd_error.size(); e++)
std::cerr << rang::tag::error << cmd_error[e] << std::endl;
// print the help tags
if (!cmd_error.empty() && !params_common.display_help)
{
tools::Argument_tag help_tag = {"help", "h"};
std::string message = "For more information please display the help (\"";
message += tools::Argument_handler::print_tag(help_tag) += "\").";
std::cerr << std::endl << rang::tag::info << message << std::endl;
}
return (!cmd_error.empty() || params_common.display_help) ? EXIT_FAILURE : EXIT_SUCCESS;
}
void Launcher::print_header()
{
// display configuration and simulation parameters
stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
stream << rang::tag::comment << rang::style::bold << "---- A FAST FORWARD ERROR CORRECTION TOOLBOX >> ----" << std::endl;
stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
stream << rang::tag::comment << rang::style::bold << rang::style::underline << "Parameters :"<< rang::style::reset << std::endl;
factory::Header::print_parameters({¶ms_common}, false, this->stream);
this->stream << rang::tag::comment << std::endl;
}
int Launcher::launch()
{
int exit_code = EXIT_SUCCESS;
std::srand((unsigned)this->params_common.global_seed);
// in case of the user call launch multiple times
if (simu != nullptr)
{
delete simu;
simu = nullptr;
}
if (this->read_arguments() == EXIT_FAILURE)
{
// print the warnings
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
for (unsigned w = 0; w < this->cmd_warn.size(); w++)
std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;
return EXIT_FAILURE;
}
// write the command and he curve name in the PyBER format
#ifdef ENABLE_MPI
if (!this->params_common.pyber.empty() && this->params_common.mpi_rank == 0)
#else
if (!this->params_common.pyber.empty())
#endif
{
stream << "Run command:" << std::endl;
stream << cmd_line << std::endl;
stream << "Curve name:" << std::endl;
stream << this->params_common.pyber << std::endl;
}
if (this->params_common.display_legend)
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
this->print_header();
// print the warnings
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
for (unsigned w = 0; w < this->cmd_warn.size(); w++)
std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;
try
{
simu = this->build_simu();
}
catch(const std::exception& e)
{
rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
exit_code = EXIT_FAILURE;
}
if (simu != nullptr)
{
// launch the simulation
if (this->params_common.display_legend)
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
stream << rang::tag::comment << "The simulation is running..." << std::endl;
try
{
simu->launch();
if (simu->is_error())
exit_code = EXIT_FAILURE;
}
catch(const std::exception& e)
{
rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
exit_code = EXIT_FAILURE;
}
}
if (this->params_common.display_legend)
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
stream << rang::tag::comment << "End of the simulation." << std::endl;
if (simu != nullptr)
{
delete simu;
simu = nullptr;
}
return exit_code;
}
Put back 'Trace:' when --sim-pyber.
#include <rang.hpp>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <date.h>
#include "Tools/Display/Terminal/Terminal.hpp"
#ifdef ENABLE_MPI
#include <mpi.h>
#endif
#include "Tools/general_utils.h"
#include "Tools/system_functions.h"
#include "Tools/Display/rang_format/rang_format.h"
#include "Tools/Exception/exception.hpp"
#include "Factory/Module/Source/Source.hpp"
#include "Factory/Module/CRC/CRC.hpp"
#include "Factory/Module/Encoder/Encoder.hpp"
#include "Factory/Module/Puncturer/Puncturer.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "Factory/Module/Modem/Modem.hpp"
#include "Factory/Module/Channel/Channel.hpp"
#include "Factory/Module/Quantizer/Quantizer.hpp"
#include "Factory/Module/Decoder/Decoder.hpp"
#include "Factory/Module/Monitor/Monitor.hpp"
#include "Factory/Tools/Display/Terminal/Terminal.hpp"
#include "Launcher.hpp"
using namespace aff3ct;
using namespace aff3ct::launcher;
Launcher::Launcher(const int argc, const char **argv, factory::Simulation::parameters ¶ms_common,
std::ostream &stream)
: simu(nullptr), ah(argc, argv), params_common(params_common), stream(stream)
{
cmd_line += std::string(argv[0]) + std::string(" ");
for (auto i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
cmd_line += std::string(argv[i]);
else
cmd_line += std::string("\"") + std::string(argv[i]) + std::string("\"");
cmd_line += std::string(" ");
}
}
Launcher::~Launcher()
{
}
void Launcher::get_description_args()
{
}
void Launcher::store_args()
{
}
int Launcher::read_arguments()
{
this->get_description_args();
std::vector<std::string> cmd_error;
this->arg_vals = ah.parse_arguments(this->args, this->cmd_warn, cmd_error);
try
{
this->store_args();
}
catch(const std::exception& e)
{
auto save = tools::exception::no_backtrace;
tools::exception::no_backtrace = true;
cmd_error.emplace_back(e.what());
tools::exception::no_backtrace = save;
}
if (params_common.display_help)
{
auto grps = factory::Factory::create_groups({¶ms_common});
ah.print_help(this->args, grps, params_common.display_adv_help);
}
// print usage
if (!cmd_error.empty() && !params_common.display_help)
ah.print_usage(this->args);
// print the errors
if (!cmd_error.empty()) std::cerr << std::endl;
for (unsigned e = 0; e < cmd_error.size(); e++)
std::cerr << rang::tag::error << cmd_error[e] << std::endl;
// print the help tags
if (!cmd_error.empty() && !params_common.display_help)
{
tools::Argument_tag help_tag = {"help", "h"};
std::string message = "For more information please display the help (\"";
message += tools::Argument_handler::print_tag(help_tag) += "\").";
std::cerr << std::endl << rang::tag::info << message << std::endl;
}
return (!cmd_error.empty() || params_common.display_help) ? EXIT_FAILURE : EXIT_SUCCESS;
}
void Launcher::print_header()
{
// display configuration and simulation parameters
stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
stream << rang::tag::comment << rang::style::bold << "---- A FAST FORWARD ERROR CORRECTION TOOLBOX >> ----" << std::endl;
stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
stream << rang::tag::comment << rang::style::bold << rang::style::underline << "Parameters :"<< rang::style::reset << std::endl;
factory::Header::print_parameters({¶ms_common}, false, this->stream);
this->stream << rang::tag::comment << std::endl;
}
int Launcher::launch()
{
int exit_code = EXIT_SUCCESS;
std::srand((unsigned)this->params_common.global_seed);
// in case of the user call launch multiple times
if (simu != nullptr)
{
delete simu;
simu = nullptr;
}
if (this->read_arguments() == EXIT_FAILURE)
{
// print the warnings
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
for (unsigned w = 0; w < this->cmd_warn.size(); w++)
std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;
return EXIT_FAILURE;
}
// write the command and he curve name in the PyBER format
#ifdef ENABLE_MPI
if (!this->params_common.pyber.empty() && this->params_common.mpi_rank == 0)
#else
if (!this->params_common.pyber.empty())
#endif
{
stream << "Run command:" << std::endl;
stream << cmd_line << std::endl;
stream << "Curve name:" << std::endl;
stream << this->params_common.pyber << std::endl;
stream << "Trace:" << std::endl;
}
if (this->params_common.display_legend)
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
this->print_header();
// print the warnings
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
for (unsigned w = 0; w < this->cmd_warn.size(); w++)
std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;
try
{
simu = this->build_simu();
}
catch(const std::exception& e)
{
rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
exit_code = EXIT_FAILURE;
}
if (simu != nullptr)
{
// launch the simulation
if (this->params_common.display_legend)
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
stream << rang::tag::comment << "The simulation is running..." << std::endl;
try
{
simu->launch();
if (simu->is_error())
exit_code = EXIT_FAILURE;
}
catch(const std::exception& e)
{
rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
exit_code = EXIT_FAILURE;
}
}
if (this->params_common.display_legend)
#ifdef ENABLE_MPI
if (this->params_common.mpi_rank == 0)
#endif
stream << rang::tag::comment << "End of the simulation." << std::endl;
if (simu != nullptr)
{
delete simu;
simu = nullptr;
}
return exit_code;
}
|
// @(#)root/tree:$Name: $:$Id: TTreeCache.cxx,v 1.5 2006/08/11 20:17:26 brun Exp $
// Author: Rene Brun 04/06/2006
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TTreeCache //
// //
// A specialized TFileCacheRead object for a TTree //
// This class acts as a file cache, registering automatically the //
// baskets from the branches being processed (TTree::Draw or //
// TTree::Process and TSelectors) when in the learning phase. //
// The learning phase is by default 100 entries. //
// It can be changed via TTreeCache::SetLearnEntries. //
// //
// This cache speeds-up considerably the performance, in particular //
// when the Tree is accessed remotely via a high latency network. //
// //
// The default cache size (10 Mbytes) may be changed via the function //
// TTreeCache::SetCacheSize //
// //
// Only the baskets for the requested entry range are put in the cache //
// //
// For each Tree being processed a TTreeCache object is created. //
// This object is automatically deleted when the Tree is deleted or //
// when the file is deleted. //
// //
// -Special case of a TChain //
// Once the training is done on the first Tree, the list of branches //
// in the cache is kept for the following files. //
// //
// -Special case of a TEventlist //
// if the Tree or TChain has a TEventlist, only the buffers //
// referenced by the list are put in the cache. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TTreeCache.h"
#include "TChain.h"
#include "TBranch.h"
#include "TEventList.h"
#include "TObjString.h"
Int_t TTreeCache::fgLearnEntries = 100;
ClassImp(TTreeCache)
//______________________________________________________________________________
TTreeCache::TTreeCache() : TFileCacheRead(),
fEntryMin(0),
fEntryMax(1),
fEntryNext(1),
fZipBytes(0),
fNbranches(0),
fNReadOk(0),
fNReadMiss(0),
fNReadPref(0),
fBranches(0),
fBrNames(0),
fOwner(0),
fTree(0),
fIsLearning(kTRUE)
{
// Default Constructor.
}
//______________________________________________________________________________
TTreeCache::TTreeCache(TTree *tree, Int_t buffersize) : TFileCacheRead(tree->GetCurrentFile(),buffersize),
fEntryMin(0),
fEntryMax(tree->GetEntriesFast()),
fEntryNext(0),
fZipBytes(0),
fNbranches(0),
fNReadOk(0),
fNReadMiss(0),
fNReadPref(0),
fBranches(0),
fBrNames(new TList),
fOwner(tree),
fTree(0),
fIsLearning(kTRUE)
{
// Constructor.
fEntryNext = fEntryMin + fgLearnEntries;
Int_t nleaves = tree->GetListOfLeaves()->GetEntries();
fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain?
}
//______________________________________________________________________________
TTreeCache::TTreeCache(const TTreeCache &pf) : TFileCacheRead(pf)
{
// Copy Constructor.
}
//______________________________________________________________________________
TTreeCache::~TTreeCache()
{
// destructor. (in general called by the TFile destructor
delete [] fBranches;
if (fBrNames) {fBrNames->Delete(); delete fBrNames;}
}
//______________________________________________________________________________
TTreeCache& TTreeCache::operator=(const TTreeCache& pf)
{
// Assignment.
if (this != &pf) TFileCacheRead::operator=(pf);
return *this;
}
//_____________________________________________________________________________
void TTreeCache::AddBranch(TBranch *b)
{
//add a branch to the list of branches to be stored in the cache
//this function is called by TBranch::GetBasket
if (!fIsLearning) return;
//Is branch already in the cache?
Bool_t isNew = kTRUE;
for (int i=0;i<fNbranches;i++) {
if (fBranches[i] == b) {isNew = kFALSE; break;}
}
if (isNew) {
fTree = b->GetTree();
fBranches[fNbranches] = b;
fBrNames->Add(new TObjString(b->GetName()));
fZipBytes += b->GetZipBytes();
fNbranches++;
if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName());
}
}
//_____________________________________________________________________________
Bool_t TTreeCache::FillBuffer()
{
//Fill the cache buffer with the branches in the cache
if (fNbranches <= 0) return kFALSE;
TTree *tree = fBranches[0]->GetTree();
Long64_t entry = tree->GetReadEntry();
if (entry < fEntryNext) return kFALSE;
// estimate number of entries that can fit in the cache
// compare it to the original value of fBufferSize not
// to the real one
fEntryNext = entry + tree->GetEntries()*fBufferSizeMin/fZipBytes;
if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1;
//check if owner has a TEventList set. If yes we optimize for this special case
//reading only the baskets containing entries in the list
TEventList *elist = fOwner->GetEventList();
Long64_t chainOffset = 0;
if (elist) {
fEntryNext = fTree->GetEntries();
if (fOwner->IsA() ==TChain::Class()) {
TChain *chain = (TChain*)fOwner;
Int_t t = chain->GetTreeNumber();
chainOffset = chain->GetTreeOffset()[t];
}
}
//clear cache buffer
TFileCacheRead::Prefetch(0,0);
//store baskets
Bool_t mustBreak = kFALSE;
for (Int_t i=0;i<fNbranches;i++) {
if (mustBreak) break;
TBranch *b = fBranches[i];
Int_t nb = b->GetMaxBaskets();
Int_t *lbaskets = b->GetBasketBytes();
Long64_t *entries = b->GetBasketEntry();
if (!lbaskets || !entries) continue;
//we have found the branch. We now register all its baskets
//from the requested offset to the basket below fEntrymax
for (Int_t j=0;j<nb;j++) {
Long64_t pos = b->GetBasketSeek(j);
Int_t len = lbaskets[j];
if (pos <= 0 || len <= 0) continue;
if (entries[j] > fEntryNext) continue;
if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue;
if (elist) {
Long64_t emax = fEntryMax;
if (j<nb-1) emax = entries[j+1]-1;
if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue;
}
fNReadPref++;
TFileCacheRead::Prefetch(pos,len);
//we allow up to twice the default buffer size. When using eventlist in particular
//it may happen that the evaluation of fEntryNext is bad, hence this protection
if (fNtot > 2*fBufferSizeMin) {TFileCacheRead::Prefetch(0,0);mustBreak = kTRUE; break;}
}
if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot);
}
fIsLearning = kFALSE;
if (mustBreak) return kFALSE;
return kTRUE;
}
//_____________________________________________________________________________
Double_t TTreeCache::GetEfficiency()
{
// Give the total efficiency of the cache... defined as the ratio
// of blocks found in the cache vs. the number of blocks prefetched
// ( it could be more than 1 if we read the same block from the cache more
// than once )
// Note: This should eb used at the end of the processing or we will
// get uncomplete stats
if ( !fNReadPref )
return 0;
return ((Double_t)fNReadOk / (Double_t)fNReadPref);
}
//_____________________________________________________________________________
Double_t TTreeCache::GetEfficiencyRel()
{
// This will indicate a sort of relative efficiency... a ratio of the
// reads found in the cache to the number of reads so far
if ( !fNReadOk && !fNReadMiss )
return 0;
return ((Double_t)fNReadOk / (Double_t)(fNReadOk + fNReadMiss));
}
//_____________________________________________________________________________
Int_t TTreeCache::GetLearnEntries()
{
//static function returning the number of entries used to train the cache
//see SetLearnEntries
return fgLearnEntries;
}
//_____________________________________________________________________________
TTree *TTreeCache::GetTree() const
{
//return Tree in the cache
if (fNbranches <= 0) return 0;
return fBranches[0]->GetTree();
}
//_____________________________________________________________________________
Int_t TTreeCache::ReadBuffer(char *buf, Long64_t pos, Int_t len)
{
// Read buffer at position pos.
// If pos is in the list of prefetched blocks read from fBuffer,
// then try to fill the cache from the list of selected branches,
// otherwise normal read from file. Returns -1 in case of read
// failure, 0 in case not in cache and 1 in case read from cache.
// This function overloads TFileCacheRead::ReadBuffer.
//Is request already in the cache?
if (TFileCacheRead::ReadBuffer(buf,pos,len) == 1){
fNReadOk++;
return 1;
}
//not found in cache. Do we need to fill the cache?
Bool_t bufferFilled = FillBuffer();
if (bufferFilled) {
Int_t res = TFileCacheRead::ReadBuffer(buf,pos,len);
if (res == 1)
fNReadOk++;
else if (res == 0)
fNReadMiss++;
return res;
}
fNReadMiss++;
return 0;
}
//_____________________________________________________________________________
void TTreeCache::SetEntryRange(Long64_t emin, Long64_t emax)
{
// Set the minimum and maximum entry number to be processed
// this information helps to optimize the number of baskets to read
// when prefetching the branch buffers.
fEntryMin = emin;
fEntryMax = emax;
fEntryNext = fEntryMin + fgLearnEntries;
fIsLearning = kTRUE;
fNbranches = 0;
fZipBytes = 0;
if (fBrNames) fBrNames->Delete();
if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext);
}
//_____________________________________________________________________________
void TTreeCache::SetLearnEntries(Int_t n)
{
// Static function to set the number of entries to be used in learning mode
// The default value for n is 10. n must be >= 1
if (n < 1) n = 1;
fgLearnEntries = n;
}
//_____________________________________________________________________________
void TTreeCache::UpdateBranches(TTree *tree)
{
//update pointer to current Tree and recompute pointers to the branches in the cache
fTree = tree;
Prefetch(0,0);
fEntryMin = 0;
fEntryMax = fTree->GetEntries();
fEntryNext = fEntryMin + fgLearnEntries;
fZipBytes = 0;
fNbranches = 0;
TIter next(fBrNames);
TObjString *os;
while ((os = (TObjString*)next())) {
TBranch *b = fTree->GetBranch(os->GetName());
if (!b) continue;
fBranches[fNbranches] = b;
fZipBytes += b->GetZipBytes();
fNbranches++;
}
}
Fix coding conventions violation.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@16000 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/tree:$Name: $:$Id: TTreeCache.cxx,v 1.6 2006/08/14 08:55:30 brun Exp $
// Author: Rene Brun 04/06/2006
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TTreeCache //
// //
// A specialized TFileCacheRead object for a TTree //
// This class acts as a file cache, registering automatically the //
// baskets from the branches being processed (TTree::Draw or //
// TTree::Process and TSelectors) when in the learning phase. //
// The learning phase is by default 100 entries. //
// It can be changed via TTreeCache::SetLearnEntries. //
// //
// This cache speeds-up considerably the performance, in particular //
// when the Tree is accessed remotely via a high latency network. //
// //
// The default cache size (10 Mbytes) may be changed via the function //
// TTreeCache::SetCacheSize //
// //
// Only the baskets for the requested entry range are put in the cache //
// //
// For each Tree being processed a TTreeCache object is created. //
// This object is automatically deleted when the Tree is deleted or //
// when the file is deleted. //
// //
// -Special case of a TChain //
// Once the training is done on the first Tree, the list of branches //
// in the cache is kept for the following files. //
// //
// -Special case of a TEventlist //
// if the Tree or TChain has a TEventlist, only the buffers //
// referenced by the list are put in the cache. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TTreeCache.h"
#include "TChain.h"
#include "TBranch.h"
#include "TEventList.h"
#include "TObjString.h"
Int_t TTreeCache::fgLearnEntries = 100;
ClassImp(TTreeCache)
//______________________________________________________________________________
TTreeCache::TTreeCache() : TFileCacheRead(),
fEntryMin(0),
fEntryMax(1),
fEntryNext(1),
fZipBytes(0),
fNbranches(0),
fNReadOk(0),
fNReadMiss(0),
fNReadPref(0),
fBranches(0),
fBrNames(0),
fOwner(0),
fTree(0),
fIsLearning(kTRUE)
{
// Default Constructor.
}
//______________________________________________________________________________
TTreeCache::TTreeCache(TTree *tree, Int_t buffersize) : TFileCacheRead(tree->GetCurrentFile(),buffersize),
fEntryMin(0),
fEntryMax(tree->GetEntriesFast()),
fEntryNext(0),
fZipBytes(0),
fNbranches(0),
fNReadOk(0),
fNReadMiss(0),
fNReadPref(0),
fBranches(0),
fBrNames(new TList),
fOwner(tree),
fTree(0),
fIsLearning(kTRUE)
{
// Constructor.
fEntryNext = fEntryMin + fgLearnEntries;
Int_t nleaves = tree->GetListOfLeaves()->GetEntries();
fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain?
}
//______________________________________________________________________________
TTreeCache::TTreeCache(const TTreeCache &pf) : TFileCacheRead(pf)
{
// Copy Constructor.
}
//______________________________________________________________________________
TTreeCache::~TTreeCache()
{
// destructor. (in general called by the TFile destructor
delete [] fBranches;
if (fBrNames) {fBrNames->Delete(); delete fBrNames;}
}
//______________________________________________________________________________
TTreeCache& TTreeCache::operator=(const TTreeCache& pf)
{
// Assignment.
if (this != &pf) TFileCacheRead::operator=(pf);
return *this;
}
//_____________________________________________________________________________
void TTreeCache::AddBranch(TBranch *b)
{
//add a branch to the list of branches to be stored in the cache
//this function is called by TBranch::GetBasket
if (!fIsLearning) return;
//Is branch already in the cache?
Bool_t isNew = kTRUE;
for (int i=0;i<fNbranches;i++) {
if (fBranches[i] == b) {isNew = kFALSE; break;}
}
if (isNew) {
fTree = b->GetTree();
fBranches[fNbranches] = b;
fBrNames->Add(new TObjString(b->GetName()));
fZipBytes += b->GetZipBytes();
fNbranches++;
if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName());
}
}
//_____________________________________________________________________________
Bool_t TTreeCache::FillBuffer()
{
//Fill the cache buffer with the branches in the cache
if (fNbranches <= 0) return kFALSE;
TTree *tree = fBranches[0]->GetTree();
Long64_t entry = tree->GetReadEntry();
if (entry < fEntryNext) return kFALSE;
// estimate number of entries that can fit in the cache
// compare it to the original value of fBufferSize not
// to the real one
fEntryNext = entry + tree->GetEntries()*fBufferSizeMin/fZipBytes;
if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1;
//check if owner has a TEventList set. If yes we optimize for this special case
//reading only the baskets containing entries in the list
TEventList *elist = fOwner->GetEventList();
Long64_t chainOffset = 0;
if (elist) {
fEntryNext = fTree->GetEntries();
if (fOwner->IsA() ==TChain::Class()) {
TChain *chain = (TChain*)fOwner;
Int_t t = chain->GetTreeNumber();
chainOffset = chain->GetTreeOffset()[t];
}
}
//clear cache buffer
TFileCacheRead::Prefetch(0,0);
//store baskets
Bool_t mustBreak = kFALSE;
for (Int_t i=0;i<fNbranches;i++) {
if (mustBreak) break;
TBranch *b = fBranches[i];
Int_t nb = b->GetMaxBaskets();
Int_t *lbaskets = b->GetBasketBytes();
Long64_t *entries = b->GetBasketEntry();
if (!lbaskets || !entries) continue;
//we have found the branch. We now register all its baskets
//from the requested offset to the basket below fEntrymax
for (Int_t j=0;j<nb;j++) {
Long64_t pos = b->GetBasketSeek(j);
Int_t len = lbaskets[j];
if (pos <= 0 || len <= 0) continue;
if (entries[j] > fEntryNext) continue;
if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue;
if (elist) {
Long64_t emax = fEntryMax;
if (j<nb-1) emax = entries[j+1]-1;
if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue;
}
fNReadPref++;
TFileCacheRead::Prefetch(pos,len);
//we allow up to twice the default buffer size. When using eventlist in particular
//it may happen that the evaluation of fEntryNext is bad, hence this protection
if (fNtot > 2*fBufferSizeMin) {TFileCacheRead::Prefetch(0,0);mustBreak = kTRUE; break;}
}
if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot);
}
fIsLearning = kFALSE;
if (mustBreak) return kFALSE;
return kTRUE;
}
//_____________________________________________________________________________
Double_t TTreeCache::GetEfficiency()
{
// Give the total efficiency of the cache... defined as the ratio
// of blocks found in the cache vs. the number of blocks prefetched
// ( it could be more than 1 if we read the same block from the cache more
// than once )
// Note: This should eb used at the end of the processing or we will
// get uncomplete stats
if ( !fNReadPref )
return 0;
return ((Double_t)fNReadOk / (Double_t)fNReadPref);
}
//_____________________________________________________________________________
Double_t TTreeCache::GetEfficiencyRel()
{
// This will indicate a sort of relative efficiency... a ratio of the
// reads found in the cache to the number of reads so far
if ( !fNReadOk && !fNReadMiss )
return 0;
return ((Double_t)fNReadOk / (Double_t)(fNReadOk + fNReadMiss));
}
//_____________________________________________________________________________
Int_t TTreeCache::GetLearnEntries()
{
//static function returning the number of entries used to train the cache
//see SetLearnEntries
return fgLearnEntries;
}
//_____________________________________________________________________________
TTree *TTreeCache::GetTree() const
{
//return Tree in the cache
if (fNbranches <= 0) return 0;
return fBranches[0]->GetTree();
}
//_____________________________________________________________________________
Int_t TTreeCache::ReadBuffer(char *buf, Long64_t pos, Int_t len)
{
// Read buffer at position pos.
// If pos is in the list of prefetched blocks read from fBuffer,
// then try to fill the cache from the list of selected branches,
// otherwise normal read from file. Returns -1 in case of read
// failure, 0 in case not in cache and 1 in case read from cache.
// This function overloads TFileCacheRead::ReadBuffer.
//Is request already in the cache?
if (TFileCacheRead::ReadBuffer(buf,pos,len) == 1){
fNReadOk++;
return 1;
}
//not found in cache. Do we need to fill the cache?
Bool_t bufferFilled = FillBuffer();
if (bufferFilled) {
Int_t res = TFileCacheRead::ReadBuffer(buf,pos,len);
if (res == 1)
fNReadOk++;
else if (res == 0)
fNReadMiss++;
return res;
}
fNReadMiss++;
return 0;
}
//_____________________________________________________________________________
void TTreeCache::SetEntryRange(Long64_t emin, Long64_t emax)
{
// Set the minimum and maximum entry number to be processed
// this information helps to optimize the number of baskets to read
// when prefetching the branch buffers.
fEntryMin = emin;
fEntryMax = emax;
fEntryNext = fEntryMin + fgLearnEntries;
fIsLearning = kTRUE;
fNbranches = 0;
fZipBytes = 0;
if (fBrNames) fBrNames->Delete();
if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext);
}
//_____________________________________________________________________________
void TTreeCache::SetLearnEntries(Int_t n)
{
// Static function to set the number of entries to be used in learning mode
// The default value for n is 10. n must be >= 1
if (n < 1) n = 1;
fgLearnEntries = n;
}
//_____________________________________________________________________________
void TTreeCache::UpdateBranches(TTree *tree)
{
//update pointer to current Tree and recompute pointers to the branches in the cache
fTree = tree;
Prefetch(0,0);
fEntryMin = 0;
fEntryMax = fTree->GetEntries();
fEntryNext = fEntryMin + fgLearnEntries;
fZipBytes = 0;
fNbranches = 0;
TIter next(fBrNames);
TObjString *os;
while ((os = (TObjString*)next())) {
TBranch *b = fTree->GetBranch(os->GetName());
if (!b) continue;
fBranches[fNbranches] = b;
fZipBytes += b->GetZipBytes();
fNbranches++;
}
}
|
#pragma once
#include <sstream>
#include <mimosa/init.hh>
#include <mimosa/http/server.hh>
#include <mimosa/http/response-writer.hh>
#include <mimosa/http/request-reader.hh>
#include <silicon/symbols.hh>
#include <iod/json.hh>
namespace iod
{
namespace mh = mimosa::http;
using s::_Secure;
using s::_Path;
using s::_Http_only;
using s::_Expires;
struct request
{
request(mh::RequestReader& rr) : rr_(rr) {
int n;
char buf[1024];
while ((n = rr_.read(buf, 1024))) { body_string.append(buf, n); }
body_stream.str(body_string);
body_stream.seekg(0);
body_stream.clear();
}
auto get_body_string() const { return body_stream.str(); }
auto& get_body_stream() { return body_stream; }
auto& get_params_string() { return params_string; }
auto& get_tail_string() { return tail_string; }
bool get_cookie(const std::string& key, std::string& value)
{
auto it = rr_.cookies().find(key);
if (it != rr_.cookies().end())
{
value = it->second;
return true;
}
else return false;
}
void set_params_position(int pos) {
params_string.str = body_string.c_str() + pos;
params_string.len = body_string.size() - pos;
tail_string = params_string;
}
void set_tail_position(int pos) {
tail_string.str = params_string.data() + pos;
tail_string.len = params_string.size() - pos;
}
std::istringstream body_stream;
std::string body_string;
stringview params_string;
stringview tail_string;
mh::RequestReader& rr_;
};
struct response
{
response(mh::ResponseWriter& rw) : rw_(rw) {}
auto get_body_string() const { return body_stream_.str(); }
auto& get_body_stream() { return body_stream_; }
template <typename T>
auto operator<<(const T& t)
{
body_stream_ << t;
}
template <typename... T>
auto operator<<(const iod::sio<T...>& t)
{
json_encode(t, body_stream_);
}
void write(const char* str, int len) {
rw_.write(str, len);
}
void write_body() {
std::string s = body_stream_.str();
rw_.write(s.c_str(), s.size());
}
template <typename... O>
void set_cookie(const std::string& key, const std::string& value, O&&... _options)
{
auto options = D(_options...);
auto* cookie = new mimosa::http::Cookie;
cookie->setKey(key);
cookie->setValue(value);
cookie->setSecure(options.has(_Secure));
cookie->setHttpOnly(options.has(_Http_only));
if (options.has(_Expires)) cookie->setExpires(options.get(_Expires, ""));
cookie->setPath(options.get(_Path, "/"));
rw_.addCookie(cookie);
}
void set_header(const std::string& key, const std::string& value) { rw_.addHeader(key, value); }
void set_status(int s) { rw_.setStatus(s); }
std::ostringstream body_stream_;
mh::ResponseWriter& rw_;
};
template <typename F>
struct mimosa_handler : public mh::Handler
{
mimosa_handler(F f) : fun_(f) {}
bool handle(mh::RequestReader & request_,
mh::ResponseWriter & response_) const
{
request request(request_);
response response(response_);
// std::cout << "before" << std::endl;
// std::cout << &request_ << std::endl;
// std::cout << &response_ << std::endl;
fun_(request, response);
// std::cout << "after" << std::endl;
response.rw_.setContentLength(response.get_body_string().size());
// std::cout << response.get_body_string().size() << std::endl;
response.write_body();
return true;
}
F fun_;
};
struct mimosa_backend
{
mimosa_backend(int argc, char* argv[]) { mimosa::init(argc, argv); }
mimosa_backend() { mimosa::deinit(); }
template <typename F>
void serve(F f);
};
typedef mimosa_backend backend;
}
#include <silicon/mimosa_backend.hpp>
mimosa backend: Access to the location and take the port as argument.
#pragma once
#include <sstream>
#include <mimosa/init.hh>
#include <mimosa/http/server.hh>
#include <mimosa/http/response-writer.hh>
#include <mimosa/http/request-reader.hh>
#include <silicon/symbols.hh>
#include <iod/json.hh>
namespace iod
{
namespace mh = mimosa::http;
using s::_Secure;
using s::_Path;
using s::_Http_only;
using s::_Expires;
struct request
{
request(mh::RequestReader& rr) : rr_(rr) {
int n;
char buf[1024];
while ((n = rr_.read(buf, 1024))) { body_string.append(buf, n); }
body_stream.str(body_string);
body_stream.seekg(0);
body_stream.clear();
}
auto get_body_string() const { return body_stream.str(); }
auto& get_body_stream() { return body_stream; }
auto& get_params_string() { return params_string; }
auto& get_tail_string() { return tail_string; }
bool get_cookie(const std::string& key, std::string& value)
{
auto it = rr_.cookies().find(key);
if (it != rr_.cookies().end())
{
value = it->second;
return true;
}
else return false;
}
void set_params_position(int pos) {
params_string.str = body_string.c_str() + pos;
params_string.len = body_string.size() - pos;
tail_string = params_string;
}
void set_tail_position(int pos) {
tail_string.str = params_string.data() + pos;
tail_string.len = params_string.size() - pos;
}
const std::string& location() { return rr_.location(); }
std::istringstream body_stream;
std::string body_string;
stringview params_string;
stringview tail_string;
mh::RequestReader& rr_;
};
struct response
{
response(mh::ResponseWriter& rw) : rw_(rw) {}
auto get_body_string() const { return body_stream_.str(); }
auto& get_body_stream() { return body_stream_; }
template <typename T>
auto operator<<(const T& t)
{
body_stream_ << t;
}
template <typename... T>
auto operator<<(const iod::sio<T...>& t)
{
json_encode(t, body_stream_);
}
void write(const char* str, int len) {
rw_.write(str, len);
}
void write_body() {
std::string s = body_stream_.str();
rw_.write(s.c_str(), s.size());
}
template <typename... O>
void set_cookie(const std::string& key, const std::string& value, O&&... _options)
{
auto options = D(_options...);
auto* cookie = new mimosa::http::Cookie;
cookie->setKey(key);
cookie->setValue(value);
cookie->setSecure(options.has(_Secure));
cookie->setHttpOnly(options.has(_Http_only));
if (options.has(_Expires)) cookie->setExpires(options.get(_Expires, ""));
cookie->setPath(options.get(_Path, "/"));
rw_.addCookie(cookie);
}
void set_header(const std::string& key, const std::string& value) { rw_.addHeader(key, value); }
void set_status(int s) { rw_.setStatus(s); }
std::ostringstream body_stream_;
mh::ResponseWriter& rw_;
};
template <typename F>
struct mimosa_handler : public mh::Handler
{
mimosa_handler(F f) : fun_(f) {}
bool handle(mh::RequestReader & request_,
mh::ResponseWriter & response_) const
{
request request(request_);
response response(response_);
// std::cout << "before" << std::endl;
// std::cout << &request_ << std::endl;
// std::cout << &response_ << std::endl;
fun_(request, response);
// std::cout << "after" << std::endl;
response.rw_.setContentLength(response.get_body_string().size());
// std::cout << response.get_body_string().size() << std::endl;
response.write_body();
return true;
}
F fun_;
};
struct mimosa_backend
{
mimosa_backend(int argc, char* argv[]) { mimosa::init(argc, argv); }
mimosa_backend() { mimosa::deinit(); }
template <typename F>
void serve(int port, F f);
};
typedef mimosa_backend backend;
}
#include <silicon/mimosa_backend.hpp>
|
// serial.cxx -- Unix serial I/O support
//
// Written by Curtis Olson, started November 1998.
//
// Copyright (C) 1998 Curtis L. Olson - curt@flightgear.org
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library 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.
//
// $Id$
#include <simgear/compiler.h>
#include STL_IOSTREAM
#ifdef SG_HAVE_STD_INCLUDE
# include <cerrno>
#else
# include <errno.h>
#endif
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
// maybe include something???
#else
# include <termios.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
#endif
#include <simgear/debug/logstream.hxx>
#include "serial.hxx"
SGSerialPort::SGSerialPort()
: dev_open(false)
{
// empty
}
SGSerialPort::SGSerialPort(const string& device, int baud) {
open_port(device);
if ( dev_open ) {
set_baud(baud);
}
}
SGSerialPort::~SGSerialPort() {
// closing the port here screws us up because if we would even so
// much as make a copy of an SGSerialPort object and then delete it,
// the file descriptor gets closed. Doh!!!
}
bool SGSerialPort::open_port(const string& device) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
fd = CreateFile( device.c_str(),
GENERIC_READ | GENERIC_WRITE,
0, // dwShareMode
NULL, // lpSecurityAttributes
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL );
if ( fd == INVALID_HANDLE_VALUE )
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Error opening serial device \""
<< device << "\" " << (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return false;
}
dev_open = true;
return true;
#else
struct termios config;
fd = open(device.c_str(), O_RDWR | O_NONBLOCK);
SG_LOG( SG_EVENT, SG_DEBUG, "Serial fd created = " << fd);
if ( fd == -1 ) {
SG_LOG( SG_IO, SG_ALERT, "Cannot open " << device
<< " for serial I/O" );
return false;
} else {
dev_open = true;
}
// set required port parameters
if ( tcgetattr( fd, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" );
return false;
}
// cfmakeraw( &config );
// cout << "config.c_iflag = " << config.c_iflag << endl;
// software flow control on
config.c_iflag |= IXON;
// config.c_iflag |= IXOFF;
// config.c_cflag |= CLOCAL;
#if ! defined( sgi )
// disable hardware flow control
config.c_cflag &= ~(CRTSCTS);
#endif
// cout << "config.c_iflag = " << config.c_iflag << endl;
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" );
return false;
}
return true;
#endif
}
bool SGSerialPort::close_port() {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
CloseHandle( fd );
#else
close(fd);
#endif
dev_open = false;
return true;
}
bool SGSerialPort::set_baud(int baud) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
return true;
#else
struct termios config;
speed_t speed = B9600;
if ( tcgetattr( fd, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" );
return false;
}
if ( baud == 300 ) {
speed = B300;
} else if ( baud == 1200 ) {
speed = B1200;
} else if ( baud == 2400 ) {
speed = B2400;
} else if ( baud == 4800 ) {
speed = B4800;
} else if ( baud == 9600 ) {
speed = B9600;
} else if ( baud == 19200 ) {
speed = B19200;
} else if ( baud == 38400 ) {
speed = B38400;
} else if ( baud == 57600 ) {
speed = B57600;
} else if ( baud == 115200 ) {
speed = B115200;
#if defined( linux ) || defined( __FreeBSD__ )
} else if ( baud == 230400 ) {
speed = B230400;
#endif
} else {
SG_LOG( SG_IO, SG_ALERT, "Unsupported baud rate " << baud );
return false;
}
if ( cfsetispeed( &config, speed ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Problem setting input baud rate" );
return false;
}
if ( cfsetospeed( &config, speed ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Problem setting output baud rate" );
return false;
}
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" );
return false;
}
return true;
#endif
}
string SGSerialPort::read_port() {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
string result = "";
return result;
#else
const int max_count = 1024;
char buffer[max_count+1];
int count;
string result;
count = read(fd, buffer, max_count);
// cout << "read " << count << " bytes" << endl;
if ( count < 0 ) {
// error condition
if ( errno != EAGAIN ) {
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on read, error number = " << errno );
}
return "";
} else {
buffer[count] = '\0';
result = buffer;
return result;
}
#endif
}
int SGSerialPort::read_port(char *buf, int len) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
buf[0] = '\0';
return 0;
#else
string result;
int count = read(fd, buf, len);
// cout << "read " << count << " bytes" << endl;
if ( count < 0 ) {
// error condition
if ( errno != EAGAIN ) {
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on read, error number = " << errno );
}
buf[0] = '\0';
return 0;
} else {
buf[count] = '\0';
return count;
}
#endif
}
int SGSerialPort::write_port(const string& value) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
LPCVOID lpBuffer = value.c_str();
DWORD nNumberOfBytesToWrite = value.length();
DWORD lpNumberOfBytesWritten;
OVERLAPPED lpOverlapped;
if ( WriteFile( fd,
lpBuffer,
nNumberOfBytesToWrite,
&lpNumberOfBytesWritten,
&lpOverlapped ) == 0 )
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return int(lpNumberOfBytesWritten);
}
return int(lpNumberOfBytesWritten);
#else
static bool error = false;
int count;
if ( error ) {
SG_LOG( SG_IO, SG_ALERT, "attempting serial write error recovery" );
// attempt some sort of error recovery
count = write(fd, "\n", 1);
if ( count == 1 ) {
// cout << "Serial error recover successful!\n";
error = false;
} else {
return 0;
}
}
count = write(fd, value.c_str(), value.length());
// cout << "write '" << value << "' " << count << " bytes" << endl;
if ( (int)count == (int)value.length() ) {
error = false;
} else {
if ( errno == EAGAIN ) {
// ok ... in our context we don't really care if we can't
// write a string, we'll just get it the next time around
error = false;
} else {
error = true;
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on write, error number = " << errno );
}
}
return count;
#endif
}
int SGSerialPort::write_port(const char* buf, int len) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
LPCVOID lpBuffer = buf;
DWORD nNumberOfBytesToWrite = len;
DWORD lpNumberOfBytesWritten;
OVERLAPPED lpOverlapped;
if ( WriteFile( fd,
lpBuffer,
nNumberOfBytesToWrite,
&lpNumberOfBytesWritten,
&lpOverlapped ) == 0 )
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return int(lpNumberOfBytesWritten);
}
return int(lpNumberOfBytesWritten);
#else
static bool error = false;
int count;
if ( error ) {
// attempt some sort of error recovery
count = write(fd, "\n", 1);
if ( count == 1 ) {
// cout << "Serial error recover successful!\n";
error = false;
} else {
return 0;
}
}
count = write(fd, buf, len);
// cout << "write '" << buf << "' " << count << " bytes" << endl;
if ( (int)count == len ) {
error = false;
} else {
error = true;
if ( errno == EAGAIN ) {
// ok ... in our context we don't really care if we can't
// write a string, we'll just get it the next time around
} else {
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on write, error number = " << errno );
}
}
return count;
#endif
}
Frederic BOUVIER:
Win32 serial port communication fixes.
// serial.cxx -- Unix serial I/O support
//
// Written by Curtis Olson, started November 1998.
//
// Copyright (C) 1998 Curtis L. Olson - curt@flightgear.org
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library 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.
//
// $Id$
#include <simgear/compiler.h>
#include STL_IOSTREAM
#ifdef SG_HAVE_STD_INCLUDE
# include <cerrno>
#else
# include <errno.h>
#endif
#if !defined( WIN32 ) || defined( __CYGWIN__) || defined( __CYGWIN32__ )
# include <termios.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
#endif
#include <simgear/debug/logstream.hxx>
#include "serial.hxx"
SGSerialPort::SGSerialPort()
: dev_open(false)
{
// empty
}
SGSerialPort::SGSerialPort(const string& device, int baud) {
open_port(device);
if ( dev_open ) {
set_baud(baud);
}
}
SGSerialPort::~SGSerialPort() {
// closing the port here screws us up because if we would even so
// much as make a copy of an SGSerialPort object and then delete it,
// the file descriptor gets closed. Doh!!!
}
bool SGSerialPort::open_port(const string& device) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
fd = CreateFile( device.c_str(),
GENERIC_READ | GENERIC_WRITE,
0, // dwShareMode
NULL, // lpSecurityAttributes
OPEN_EXISTING,
0,
NULL );
if ( fd == INVALID_HANDLE_VALUE )
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Error opening serial device \""
<< device << "\" " << (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return false;
}
dev_open = true;
return true;
#else
struct termios config;
fd = open(device.c_str(), O_RDWR | O_NONBLOCK);
SG_LOG( SG_EVENT, SG_DEBUG, "Serial fd created = " << fd);
if ( fd == -1 ) {
SG_LOG( SG_IO, SG_ALERT, "Cannot open " << device
<< " for serial I/O" );
return false;
} else {
dev_open = true;
}
// set required port parameters
if ( tcgetattr( fd, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" );
return false;
}
// cfmakeraw( &config );
// cout << "config.c_iflag = " << config.c_iflag << endl;
// software flow control on
config.c_iflag |= IXON;
// config.c_iflag |= IXOFF;
// config.c_cflag |= CLOCAL;
#if ! defined( sgi )
// disable hardware flow control
config.c_cflag &= ~(CRTSCTS);
#endif
// cout << "config.c_iflag = " << config.c_iflag << endl;
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" );
return false;
}
return true;
#endif
}
bool SGSerialPort::close_port() {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
CloseHandle( fd );
#else
close(fd);
#endif
dev_open = false;
return true;
}
bool SGSerialPort::set_baud(int baud) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
DCB dcb;
if ( GetCommState( fd, &dcb ) ) {
dcb.BaudRate = baud;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fOutX = TRUE;
dcb.fInX = TRUE;
if ( !SetCommState( fd, &dcb ) ) {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return false;
}
} else {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return false;
}
return true;
#else
struct termios config;
speed_t speed = B9600;
if ( tcgetattr( fd, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" );
return false;
}
if ( baud == 300 ) {
speed = B300;
} else if ( baud == 1200 ) {
speed = B1200;
} else if ( baud == 2400 ) {
speed = B2400;
} else if ( baud == 4800 ) {
speed = B4800;
} else if ( baud == 9600 ) {
speed = B9600;
} else if ( baud == 19200 ) {
speed = B19200;
} else if ( baud == 38400 ) {
speed = B38400;
} else if ( baud == 57600 ) {
speed = B57600;
} else if ( baud == 115200 ) {
speed = B115200;
#if defined( linux ) || defined( __FreeBSD__ )
} else if ( baud == 230400 ) {
speed = B230400;
#endif
} else {
SG_LOG( SG_IO, SG_ALERT, "Unsupported baud rate " << baud );
return false;
}
if ( cfsetispeed( &config, speed ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Problem setting input baud rate" );
return false;
}
if ( cfsetospeed( &config, speed ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Problem setting output baud rate" );
return false;
}
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" );
return false;
}
return true;
#endif
}
string SGSerialPort::read_port() {
const int max_count = 1024;
char buffer[max_count+1];
string result;
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
DWORD count;
if ( ReadFile( fd, buffer, max_count, &count, 0 ) ) {
buffer[count] = '\0';
result = buffer;
} else {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Serial I/O read error: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
}
return result;
#else
int count = read(fd, buffer, max_count);
// cout << "read " << count << " bytes" << endl;
if ( count < 0 ) {
// error condition
if ( errno != EAGAIN ) {
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on read, error number = " << errno );
}
return "";
} else {
buffer[count] = '\0';
result = buffer;
return result;
}
#endif
}
int SGSerialPort::read_port(char *buf, int len) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
DWORD count;
if ( ReadFile( fd, buf, len, &count, 0 ) ) {
buf[count] = '\0';
return count;
} else {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Serial I/O read error: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
buf[0] = '\0';
return 0;
}
#else
string result;
int count = read(fd, buf, len);
// cout << "read " << count << " bytes" << endl;
if ( count < 0 ) {
// error condition
if ( errno != EAGAIN ) {
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on read, error number = " << errno );
}
buf[0] = '\0';
return 0;
} else {
buf[count] = '\0';
return count;
}
#endif
}
int SGSerialPort::write_port(const string& value) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
LPCVOID lpBuffer = value.data();
DWORD nNumberOfBytesToWrite = value.length();
DWORD lpNumberOfBytesWritten;
if ( WriteFile( fd,
lpBuffer,
nNumberOfBytesToWrite,
&lpNumberOfBytesWritten,
0 ) == 0 )
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return int(lpNumberOfBytesWritten);
}
return int(lpNumberOfBytesWritten);
#else
static bool error = false;
int count;
if ( error ) {
SG_LOG( SG_IO, SG_ALERT, "attempting serial write error recovery" );
// attempt some sort of error recovery
count = write(fd, "\n", 1);
if ( count == 1 ) {
// cout << "Serial error recover successful!\n";
error = false;
} else {
return 0;
}
}
count = write(fd, value.c_str(), value.length());
// cout << "write '" << value << "' " << count << " bytes" << endl;
if ( (int)count == (int)value.length() ) {
error = false;
} else {
if ( errno == EAGAIN ) {
// ok ... in our context we don't really care if we can't
// write a string, we'll just get it the next time around
error = false;
} else {
error = true;
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on write, error number = " << errno );
}
}
return count;
#endif
}
int SGSerialPort::write_port(const char* buf, int len) {
#if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ )
LPCVOID lpBuffer = buf;
DWORD nNumberOfBytesToWrite = len;
DWORD lpNumberOfBytesWritten;
if ( WriteFile( fd,
lpBuffer,
nNumberOfBytesToWrite,
&lpNumberOfBytesWritten,
0 ) == 0 )
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: "
<< (const char*) lpMsgBuf );
LocalFree( lpMsgBuf );
return int(lpNumberOfBytesWritten);
}
return int(lpNumberOfBytesWritten);
#else
static bool error = false;
int count;
if ( error ) {
// attempt some sort of error recovery
count = write(fd, "\n", 1);
if ( count == 1 ) {
// cout << "Serial error recover successful!\n";
error = false;
} else {
return 0;
}
}
count = write(fd, buf, len);
// cout << "write '" << buf << "' " << count << " bytes" << endl;
if ( (int)count == len ) {
error = false;
} else {
error = true;
if ( errno == EAGAIN ) {
// ok ... in our context we don't really care if we can't
// write a string, we'll just get it the next time around
} else {
SG_LOG( SG_IO, SG_ALERT,
"Serial I/O on write, error number = " << errno );
}
}
return count;
#endif
}
|
#include "renderwidget.h"
static const char vertex_shader[] = " \
attribute vec2 position; \
attribute vec2 tex_coord; \
\
varying vec2 texc; \
\
void main() \
{ \
texc = tex_coord; \
gl_Position = vec4(position, 0, 1); \
}";
static const char fragment_shader[] = " \
uniform sampler2D samp; \
uniform sampler2D samp2; \
\
varying vec2 texc; \
\
void main() \
{ \
vec3 current_color = texture2D(samp, texc).bgr; \
vec3 prev_color = texture2D(samp2, texc).bgr; \
\
gl_FragColor = vec4(mix(current_color, prev_color, 0.5), 1); \
}";
RenderWidget::RenderWidget(QWidget* parent) : QOpenGLWidget(parent)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000.0 / 60.0);
}
RenderWidget::~RenderWidget()
{
makeCurrent();
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
glDeleteTextures(2, textures);
doneCurrent();
}
void RenderWidget::update_frame(u32* new_frame)
{
makeCurrent();
current_texture = (current_texture + 1) % 2;
glBindTexture(GL_TEXTURE_2D, textures[current_texture]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 160, 144, GL_RGBA, /*GL_UNSIGNED_SHORT_1_5_5_5_REV*/ GL_UNSIGNED_INT_8_8_8_8_REV, new_frame);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[current_texture]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[(current_texture + 1) % 2]);
glBindTexture(GL_TEXTURE_2D, 0);
doneCurrent();
}
void RenderWidget::initializeGL()
{
initializeOpenGLFunctions();
makeCurrent();
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT);
shaders.addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader);
shaders.addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader);
shaders.link();
shaders.bind();
vertex_location = shaders.attributeLocation("position");
texc_location = shaders.attributeLocation("tex_coord");
int sampler_location1 = shaders.uniformLocation("samp");
int sampler_location2 = shaders.uniformLocation("samp2");
shaders.setUniformValue(sampler_location1, 0);
shaders.setUniformValue(sampler_location2, 1);
shaders.release();
float vbo_data[] = {
//vertex data
-1, 1, //top left
1, 1, //top right
1, -1, //bottom right
-1, -1, //bottom left
//texture coords data
0, 1, //tl
1, 1, //tr
1, 0, //br
0, 0 //bl
};
GLubyte indexes[] = {0,1,2, 0,2,3};
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vbo_data), vbo_data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexes), indexes, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//generate our "frame buffers"
glGenTextures(2, textures);
for (auto tex : textures)
{
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, /*GL_UNSIGNED_SHORT_1_5_5_5_REV*/ GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, 0);
//set up everything and leave on forever (we only change textures, so why even bother with state changes?)
shaders.bind();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
//load vertices
glEnableVertexAttribArray(vertex_location);
glVertexAttribPointer(vertex_location, 2, GL_FLOAT, GL_FALSE, 0, 0);
//load texture coords
glEnableVertexAttribArray(texc_location);
glVertexAttribPointer(texc_location, 2, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(8));
//enable indexing
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
doneCurrent();
}
void RenderWidget::resizeGL(int w, int h)
{
}
void RenderWidget::paintGL()
{
makeCurrent();
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);
doneCurrent();
}
fixed 2nd texture bug (it`s no longer black)
#include "renderwidget.h"
static const char vertex_shader[] = " \
attribute vec2 position; \
attribute vec2 tex_coord; \
\
varying vec2 texc; \
\
void main() \
{ \
texc = tex_coord; \
gl_Position = vec4(position, 0, 1); \
}";
static const char fragment_shader[] = " \
uniform sampler2D samp; \
uniform sampler2D samp2; \
\
varying vec2 texc; \
\
void main() \
{ \
vec3 current_color = texture2D(samp, texc).bgr; \
vec3 prev_color = texture2D(samp2, texc).bgr; \
\
gl_FragColor = vec4(mix(current_color, prev_color, 0.5), 1); \
}";
RenderWidget::RenderWidget(QWidget* parent) : QOpenGLWidget(parent)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000.0 / 60.0);
}
RenderWidget::~RenderWidget()
{
makeCurrent();
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
glDeleteTextures(2, textures);
doneCurrent();
}
void RenderWidget::update_frame(u32* new_frame)
{
makeCurrent();
current_texture = (current_texture + 1) % 2;
glBindTexture(GL_TEXTURE_2D, textures[current_texture]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 160, 144, GL_RGBA, /*GL_UNSIGNED_SHORT_1_5_5_5_REV*/ GL_UNSIGNED_INT_8_8_8_8_REV, new_frame);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[current_texture]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[(current_texture + 1) % 2]);
doneCurrent();
}
void RenderWidget::initializeGL()
{
initializeOpenGLFunctions();
makeCurrent();
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT);
shaders.addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader);
shaders.addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader);
shaders.link();
shaders.bind();
vertex_location = shaders.attributeLocation("position");
texc_location = shaders.attributeLocation("tex_coord");
int sampler_location1 = shaders.uniformLocation("samp");
int sampler_location2 = shaders.uniformLocation("samp2");
shaders.setUniformValue(sampler_location1, 0);
shaders.setUniformValue(sampler_location2, 1);
shaders.release();
float vbo_data[] = {
//vertex data
-1, 1, //top left
1, 1, //top right
1, -1, //bottom right
-1, -1, //bottom left
//texture coords data
0, 1, //tl
1, 1, //tr
1, 0, //br
0, 0 //bl
};
GLubyte indexes[] = {0,1,2, 0,2,3};
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vbo_data), vbo_data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexes), indexes, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//generate our "frame buffers"
glGenTextures(2, textures);
for (auto tex : textures)
{
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, /*GL_UNSIGNED_SHORT_1_5_5_5_REV*/ GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, 0);
//set up everything and leave on forever (we only change textures, so why even bother with state changes?)
shaders.bind();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
//load vertices
glEnableVertexAttribArray(vertex_location);
glVertexAttribPointer(vertex_location, 2, GL_FLOAT, GL_FALSE, 0, 0);
//load texture coords
glEnableVertexAttribArray(texc_location);
glVertexAttribPointer(texc_location, 2, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(8));
//enable indexing
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
doneCurrent();
}
void RenderWidget::resizeGL(int w, int h)
{
}
void RenderWidget::paintGL()
{
makeCurrent();
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);
doneCurrent();
}
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/modules/video_coding/main/source/generic_decoder.h"
#include "webrtc/modules/video_coding/main/source/internal_defines.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/logging.h"
namespace webrtc {
VCMDecodedFrameCallback::VCMDecodedFrameCallback(VCMTiming& timing,
Clock* clock)
:
_critSect(CriticalSectionWrapper::CreateCriticalSection()),
_clock(clock),
_receiveCallback(NULL),
_timing(timing),
_timestampMap(kDecoderFrameMemoryLength),
_lastReceivedPictureID(0)
{
}
VCMDecodedFrameCallback::~VCMDecodedFrameCallback()
{
delete _critSect;
}
void VCMDecodedFrameCallback::SetUserReceiveCallback(
VCMReceiveCallback* receiveCallback)
{
CriticalSectionScoped cs(_critSect);
_receiveCallback = receiveCallback;
}
VCMReceiveCallback* VCMDecodedFrameCallback::UserReceiveCallback()
{
CriticalSectionScoped cs(_critSect);
return _receiveCallback;
}
int32_t VCMDecodedFrameCallback::Decoded(I420VideoFrame& decodedImage)
{
// TODO(holmer): We should improve this so that we can handle multiple
// callbacks from one call to Decode().
VCMFrameInformation* frameInfo;
VCMReceiveCallback* callback;
{
CriticalSectionScoped cs(_critSect);
frameInfo = static_cast<VCMFrameInformation*>(
_timestampMap.Pop(decodedImage.timestamp()));
callback = _receiveCallback;
}
assert(frameInfo != NULL);
_timing.StopDecodeTimer(
decodedImage.timestamp(),
frameInfo->decodeStartTimeMs,
_clock->TimeInMilliseconds());
if (callback != NULL)
{
decodedImage.set_render_time_ms(frameInfo->renderTimeMs);
callback->FrameToRender(decodedImage);
}
return WEBRTC_VIDEO_CODEC_OK;
}
int32_t
VCMDecodedFrameCallback::ReceivedDecodedReferenceFrame(
const uint64_t pictureId)
{
CriticalSectionScoped cs(_critSect);
if (_receiveCallback != NULL)
{
return _receiveCallback->ReceivedDecodedReferenceFrame(pictureId);
}
return -1;
}
int32_t
VCMDecodedFrameCallback::ReceivedDecodedFrame(const uint64_t pictureId)
{
_lastReceivedPictureID = pictureId;
return 0;
}
uint64_t VCMDecodedFrameCallback::LastReceivedPictureID() const
{
return _lastReceivedPictureID;
}
int32_t VCMDecodedFrameCallback::Map(uint32_t timestamp, VCMFrameInformation* frameInfo)
{
CriticalSectionScoped cs(_critSect);
return _timestampMap.Add(timestamp, frameInfo);
}
int32_t VCMDecodedFrameCallback::Pop(uint32_t timestamp)
{
CriticalSectionScoped cs(_critSect);
if (_timestampMap.Pop(timestamp) == NULL)
{
return VCM_GENERAL_ERROR;
}
return VCM_OK;
}
VCMGenericDecoder::VCMGenericDecoder(VideoDecoder& decoder, bool isExternal)
:
_callback(NULL),
_frameInfos(),
_nextFrameInfoIdx(0),
_decoder(decoder),
_codecType(kVideoCodecUnknown),
_isExternal(isExternal),
_keyFrameDecoded(false)
{
}
VCMGenericDecoder::~VCMGenericDecoder()
{
}
int32_t VCMGenericDecoder::InitDecode(const VideoCodec* settings,
int32_t numberOfCores)
{
_codecType = settings->codecType;
return _decoder.InitDecode(settings, numberOfCores);
}
int32_t VCMGenericDecoder::Decode(const VCMEncodedFrame& frame,
int64_t nowMs)
{
_frameInfos[_nextFrameInfoIdx].decodeStartTimeMs = nowMs;
_frameInfos[_nextFrameInfoIdx].renderTimeMs = frame.RenderTimeMs();
_callback->Map(frame.TimeStamp(), &_frameInfos[_nextFrameInfoIdx]);
_nextFrameInfoIdx = (_nextFrameInfoIdx + 1) % kDecoderFrameMemoryLength;
int32_t ret = _decoder.Decode(frame.EncodedImage(),
frame.MissingFrame(),
frame.FragmentationHeader(),
frame.CodecSpecific(),
frame.RenderTimeMs());
if (ret < WEBRTC_VIDEO_CODEC_OK)
{
LOG(LS_WARNING) << "Failed to decode frame with timestamp "
<< frame.TimeStamp() << ", error code: " << ret;
_callback->Pop(frame.TimeStamp());
return ret;
}
else if (ret == WEBRTC_VIDEO_CODEC_NO_OUTPUT ||
ret == WEBRTC_VIDEO_CODEC_REQUEST_SLI)
{
// No output
_callback->Pop(frame.TimeStamp());
}
return ret;
}
int32_t
VCMGenericDecoder::Release()
{
return _decoder.Release();
}
int32_t VCMGenericDecoder::Reset()
{
return _decoder.Reset();
}
int32_t VCMGenericDecoder::SetCodecConfigParameters(const uint8_t* buffer, int32_t size)
{
return _decoder.SetCodecConfigParameters(buffer, size);
}
int32_t VCMGenericDecoder::RegisterDecodeCompleteCallback(VCMDecodedFrameCallback* callback)
{
_callback = callback;
return _decoder.RegisterDecodeCompleteCallback(callback);
}
bool VCMGenericDecoder::External() const
{
return _isExternal;
}
} // namespace
Don't crash if a frame returned from the decoder is too old.
BUG=crbug/371805
R=pbos@webrtc.org
Review URL: https://webrtc-codereview.appspot.com/16559004
git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@6187 4adac7df-926f-26a2-2b94-8c16560cd09d
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/modules/video_coding/main/source/generic_decoder.h"
#include "webrtc/modules/video_coding/main/source/internal_defines.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/logging.h"
namespace webrtc {
VCMDecodedFrameCallback::VCMDecodedFrameCallback(VCMTiming& timing,
Clock* clock)
:
_critSect(CriticalSectionWrapper::CreateCriticalSection()),
_clock(clock),
_receiveCallback(NULL),
_timing(timing),
_timestampMap(kDecoderFrameMemoryLength),
_lastReceivedPictureID(0)
{
}
VCMDecodedFrameCallback::~VCMDecodedFrameCallback()
{
delete _critSect;
}
void VCMDecodedFrameCallback::SetUserReceiveCallback(
VCMReceiveCallback* receiveCallback)
{
CriticalSectionScoped cs(_critSect);
_receiveCallback = receiveCallback;
}
VCMReceiveCallback* VCMDecodedFrameCallback::UserReceiveCallback()
{
CriticalSectionScoped cs(_critSect);
return _receiveCallback;
}
int32_t VCMDecodedFrameCallback::Decoded(I420VideoFrame& decodedImage)
{
// TODO(holmer): We should improve this so that we can handle multiple
// callbacks from one call to Decode().
VCMFrameInformation* frameInfo;
VCMReceiveCallback* callback;
{
CriticalSectionScoped cs(_critSect);
frameInfo = static_cast<VCMFrameInformation*>(
_timestampMap.Pop(decodedImage.timestamp()));
callback = _receiveCallback;
}
if (frameInfo == NULL) {
LOG(LS_WARNING) << "Too many frames backed up in the decoder, dropping "
"this one.";
return WEBRTC_VIDEO_CODEC_OK;
}
_timing.StopDecodeTimer(
decodedImage.timestamp(),
frameInfo->decodeStartTimeMs,
_clock->TimeInMilliseconds());
if (callback != NULL)
{
decodedImage.set_render_time_ms(frameInfo->renderTimeMs);
callback->FrameToRender(decodedImage);
}
return WEBRTC_VIDEO_CODEC_OK;
}
int32_t
VCMDecodedFrameCallback::ReceivedDecodedReferenceFrame(
const uint64_t pictureId)
{
CriticalSectionScoped cs(_critSect);
if (_receiveCallback != NULL)
{
return _receiveCallback->ReceivedDecodedReferenceFrame(pictureId);
}
return -1;
}
int32_t
VCMDecodedFrameCallback::ReceivedDecodedFrame(const uint64_t pictureId)
{
_lastReceivedPictureID = pictureId;
return 0;
}
uint64_t VCMDecodedFrameCallback::LastReceivedPictureID() const
{
return _lastReceivedPictureID;
}
int32_t VCMDecodedFrameCallback::Map(uint32_t timestamp, VCMFrameInformation* frameInfo)
{
CriticalSectionScoped cs(_critSect);
return _timestampMap.Add(timestamp, frameInfo);
}
int32_t VCMDecodedFrameCallback::Pop(uint32_t timestamp)
{
CriticalSectionScoped cs(_critSect);
if (_timestampMap.Pop(timestamp) == NULL)
{
return VCM_GENERAL_ERROR;
}
return VCM_OK;
}
VCMGenericDecoder::VCMGenericDecoder(VideoDecoder& decoder, bool isExternal)
:
_callback(NULL),
_frameInfos(),
_nextFrameInfoIdx(0),
_decoder(decoder),
_codecType(kVideoCodecUnknown),
_isExternal(isExternal),
_keyFrameDecoded(false)
{
}
VCMGenericDecoder::~VCMGenericDecoder()
{
}
int32_t VCMGenericDecoder::InitDecode(const VideoCodec* settings,
int32_t numberOfCores)
{
_codecType = settings->codecType;
return _decoder.InitDecode(settings, numberOfCores);
}
int32_t VCMGenericDecoder::Decode(const VCMEncodedFrame& frame,
int64_t nowMs)
{
_frameInfos[_nextFrameInfoIdx].decodeStartTimeMs = nowMs;
_frameInfos[_nextFrameInfoIdx].renderTimeMs = frame.RenderTimeMs();
_callback->Map(frame.TimeStamp(), &_frameInfos[_nextFrameInfoIdx]);
_nextFrameInfoIdx = (_nextFrameInfoIdx + 1) % kDecoderFrameMemoryLength;
int32_t ret = _decoder.Decode(frame.EncodedImage(),
frame.MissingFrame(),
frame.FragmentationHeader(),
frame.CodecSpecific(),
frame.RenderTimeMs());
if (ret < WEBRTC_VIDEO_CODEC_OK)
{
LOG(LS_WARNING) << "Failed to decode frame with timestamp "
<< frame.TimeStamp() << ", error code: " << ret;
_callback->Pop(frame.TimeStamp());
return ret;
}
else if (ret == WEBRTC_VIDEO_CODEC_NO_OUTPUT ||
ret == WEBRTC_VIDEO_CODEC_REQUEST_SLI)
{
// No output
_callback->Pop(frame.TimeStamp());
}
return ret;
}
int32_t
VCMGenericDecoder::Release()
{
return _decoder.Release();
}
int32_t VCMGenericDecoder::Reset()
{
return _decoder.Reset();
}
int32_t VCMGenericDecoder::SetCodecConfigParameters(const uint8_t* buffer, int32_t size)
{
return _decoder.SetCodecConfigParameters(buffer, size);
}
int32_t VCMGenericDecoder::RegisterDecodeCompleteCallback(VCMDecodedFrameCallback* callback)
{
_callback = callback;
return _decoder.RegisterDecodeCompleteCallback(callback);
}
bool VCMGenericDecoder::External() const
{
return _isExternal;
}
} // namespace
|
/*************************************************************************
* Copyright (C) 2011-2013 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet 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. *
* *
* TeapotNet 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 TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "tpn/addressbook.h"
#include "tpn/user.h"
#include "tpn/core.h"
#include "tpn/sha512.h"
#include "tpn/config.h"
#include "tpn/file.h"
#include "tpn/directory.h"
#include "tpn/html.h"
#include "tpn/yamlserializer.h"
#include "tpn/jsonserializer.h"
#include "tpn/byteserializer.h"
#include "tpn/portmapping.h"
#include "tpn/httptunnel.h"
#include "tpn/mime.h"
namespace tpn
{
const double AddressBook::UpdateInterval = 300.;
const double AddressBook::UpdateStep = 0.20;
const int AddressBook::MaxChecksumDistance = 1000;
AddressBook::AddressBook(User *user) :
mUser(user),
mUserName(user->name())
{
Assert(UpdateInterval > 0);
Assert(mUser != NULL);
mFileName = mUser->profilePath() + "contacts";
Interface::Instance->add("/"+mUser->name()+"/contacts", this);
if(File::Exist(mFileName))
{
try {
File file(mFileName, File::Read);
load(file);
file.close();
}
catch(const Exception &e)
{
LogError("AddressBook", String("Loading failed: ") + e.what());
}
}
}
AddressBook::~AddressBook(void)
{
Interface::Instance->remove("/"+mUser->name()+"/contacts");
clear();
}
User *AddressBook::user(void) const
{
return mUser;
}
String AddressBook::userName(void) const
{
Synchronize(this);
return mUserName;
}
Identifier AddressBook::addContact(String name, const String &secret)
{
Synchronize(this);
String tracker = name.cut('@');
if(tracker.empty()) tracker = Config::Get("tracker");
String uname = name;
unsigned i = 1;
while((mContactsByUniqueName.contains(uname) && !mContactsByUniqueName.get(uname)->isDeleted())
|| uname == userName()) // userName reserved for self
{
uname = name;
uname << ++i;
}
Contact *oldContact;
if(mContactsByUniqueName.get(uname, oldContact))
{
unregisterContact(oldContact);
delete oldContact;
}
Contact *contact = new Contact(this, uname, name, tracker, secret);
if(mContacts.get(contact->peering(), oldContact))
{
if(!oldContact->isDeleted())
{
LogWarn("AddressBook::addContact", "The contact already exists with this secret: " + name);
delete contact;
return oldContact->peering();
}
oldContact->copy(contact);
delete contact;
contact = oldContact;
}
registerContact(contact);
save();
return contact->peering();
}
void AddressBook::removeContact(const Identifier &peering)
{
Synchronize(this);
Contact *contact;
if(mContacts.get(peering, contact))
{
contact->setDeleted();
Core::Instance->unregisterPeering(contact->peering());
Interface::Instance->remove(contact->urlPrefix(), contact);
mScheduler.remove(contact);
save();
// Erase messages
mUser->messageQueue()->erase(contact->uniqueName());
}
}
AddressBook::Contact *AddressBook::getContact(const Identifier &peering)
{
Synchronize(this);
Contact *contact;
if(mContacts.get(peering, contact)) return contact;
else return NULL;
}
const AddressBook::Contact *AddressBook::getContact(const Identifier &peering) const
{
Synchronize(this);
Contact *contact = NULL;
if(mContacts.get(peering, contact)) return contact;
else return NULL;
}
AddressBook::Contact *AddressBook::getContactByUniqueName(const String &uname)
{
Synchronize(this);
Contact *contact = NULL;
if(mContactsByUniqueName.get(uname, contact)) return contact;
else return NULL;
}
const AddressBook::Contact *AddressBook::getContactByUniqueName(const String &uname) const
{
Synchronize(this);
Contact *contact = NULL;
if(mContactsByUniqueName.get(uname, contact)) return contact;
else return NULL;
}
void AddressBook::getContacts(Array<AddressBook::Contact *> &array)
{
Synchronize(this);
mContactsByUniqueName.getValues(array);
Contact *self = getSelf();
if(self) array.remove(self);
int i=0;
while(i<array.size())
{
if(array[i]->isDeleted()) array.erase(i);
else ++i;
}
}
Identifier AddressBook::setSelf(const String &secret)
{
Synchronize(this);
const String tracker = Config::Get("tracker");
Contact *self = new Contact(this, userName(), userName(), tracker, secret);
Contact *tmp;
if(mContacts.get(self->peering(), tmp))
if(tmp->uniqueName() != userName())
throw Exception("a contact with the same peering already exists");
Contact *oldSelf = getSelf();
if(oldSelf)
{
unregisterContact(oldSelf);
oldSelf->copy(self);
delete self;
self = oldSelf;
}
registerContact(self);
save();
return self->peering();
}
AddressBook::Contact *AddressBook::getSelf(void)
{
Synchronize(this);
Contact *contact;
if(mContactsByUniqueName.get(userName(), contact)) return contact;
else return NULL;
}
const AddressBook::Contact *AddressBook::getSelf(void) const
{
Synchronize(this);
Contact *contact;
if(mContactsByUniqueName.get(userName(), contact)) return contact;
else return NULL;
}
void AddressBook::clear(void)
{
Synchronize(this);
mScheduler.clear(); // we make sure no task is running
for(Map<Identifier, Contact*>::iterator it = mContacts.begin();
it != mContacts.end();
++it)
{
Contact *contact = it->second;
delete contact;
}
mContacts.clear();
mContactsByUniqueName.clear();
}
void AddressBook::load(Stream &stream)
{
Synchronize(this);
Contact *contact = new Contact(this);
int i = 0;
//YamlSerializer serializer(&stream);
//while(serializer.input(*contact))
while(true)
{
// Not really clean but it protects from parse errors propagation
YamlSerializer serializer(&stream);
if(!serializer.input(*contact)) break;
Contact *oldContact = NULL;
if(mContactsByUniqueName.get(contact->uniqueName(), oldContact))
{
if(oldContact->time() >= contact->time())
{
oldContact->addAddresses(contact->addresses());
continue;
}
unregisterContact(oldContact);
if(!oldContact->isDeleted() && contact->isDeleted())
{
// Erase messages
mUser->messageQueue()->erase(contact->uniqueName());
}
oldContact->copy(contact);
std::swap(oldContact, contact);
delete oldContact;
}
registerContact(contact, i);
contact = new Contact(this);
++i;
}
delete contact;
}
void AddressBook::save(Stream &stream) const
{
Synchronize(this);
YamlSerializer serializer(&stream);
for(Map<Identifier, Contact*>::const_iterator it = mContacts.begin();
it != mContacts.end();
++it)
{
const Contact *contact = it->second;
serializer.output(*contact);
}
}
void AddressBook::save(void) const
{
Synchronize(this);
String data;
save(data);
SafeWriteFile file(mFileName);
file.write(data);
file.close();
const Contact *self = getSelf();
if(self && self->isConnected())
{
try {
Desynchronize(this);
Notification notification(data);
notification.setParameter("type", "contacts");
notification.send(self->peering());
}
catch(Exception &e)
{
LogWarn("AddressBook::Save", String("Contacts synchronization failed: ") + e.what());
}
}
}
void AddressBook::update(void)
{
Synchronize(this);
Array<Identifier> keys;
mContacts.getKeys(keys);
std::random_shuffle(keys.begin(), keys.end());
for(int i=0; i<keys.size(); ++i)
{
Contact *contact = getContact(keys[i]);
if(contact) mScheduler.schedule(contact, UpdateStep*i + UpdateStep*uniform(0., UpdateStep));
}
}
bool AddressBook::send(const Notification ¬ification)
{
Array<Identifier> keys;
SynchronizeStatement(this, mContacts.getKeys(keys));
bool success = false;
for(int i=0; i<keys.size(); ++i)
{
Contact *contact = getContact(keys[i]);
if(contact) success|= contact->send(notification);
}
return success;
}
bool AddressBook::send(const Message &message)
{
// TODO: could be more efficient
// should convert the message and use send(notification)
Array<Identifier> keys;
SynchronizeStatement(this, mContacts.getKeys(keys));
bool success = false;
for(int i=0; i<keys.size(); ++i)
{
Contact *contact = getContact(keys[i]);
if(contact) success|= contact->send(message);
}
return success;
}
void AddressBook::http(const String &prefix, Http::Request &request)
{
user()->setOnline();
try {
if(request.url.empty() || request.url == "/")
{
if(request.method == "POST")
{
try {
if(!user()->checkToken(request.post["token"], "contact"))
throw 403;
String command = request.post["command"];
if(command == "delete")
{
Synchronize(this);
String uname = request.post["argument"];
removeContact(mContactsByUniqueName.get(uname)->peering());
}
else {
String name = request.post["name"];
String secret = request.post["secret"];
// TODO: check size
if(name.empty() || secret.empty()) throw 400;
if(request.post.contains("self")) setSelf(secret);
else addContact(name, secret);
}
}
catch(const Exception &e)
{
LogWarn("AddressBook::http", e.what());
throw 400;
}
Http::Response response(request, 303);
response.headers["Location"] = prefix + "/";
response.send();
return;
}
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
Array<Contact*> contacts;
getContacts(contacts);
Contact *self = getSelf();
if(self) contacts.append(self);
JsonSerializer json(response.sock);
json.outputMapBegin();
for(int i=0; i<contacts.size(); ++i)
{
Contact *contact = contacts[i];
if(contact->isDeleted()) continue;
String name = contact->name();
String tracker = contact->tracker();
String status = contact->status();
String strPrefix = contact->urlPrefix();
MessageQueue *messageQueue = user()->messageQueue();
ConstSerializableWrapper<int> messagesWrapper(messageQueue->selectPrivate(contact->uniqueName()).unreadCount());
ConstSerializableWrapper<bool> newMessagesWrapper(messageQueue->hasNew());
SerializableMap<String, Serializable*> map;
map["name"] = &name;
map["tracker"] = &tracker;
map["status"] = &status;
map["prefix"] = &strPrefix;
map["messages"] = &messagesWrapper;
map["newmessages"] = &newMessagesWrapper;
json.outputMapElement(contact->uniqueName(), map);
}
json.outputMapEnd();
return;
}
Http::Response response(request,200);
response.send();
Html page(response.sock);
page.header("Contacts");
String token = user()->generateToken("contact");
// Personnal secret
page.openForm(prefix+"/","post");
page.openFieldset("Personal secret");
page.input("hidden", "token", token);
page.input("hidden","name",userName());
page.input("hidden","self","true");
if(getSelf()) page.text("Your personal secret is already set, but you can change it here.");
else page.text("Set the same username and the same personal secret on multiple devices to enable automatic synchronization.");
page.br();
page.br();
page.label("secret","Secret"); page.input("text","secret","",true); page.br();
page.label("add"); page.button("add","Set secret");
page.closeFieldset();
page.closeForm();
// Parameters that are to be sent in friend request
const String centralizedFriendSystemUrl = RAPTUREURL;
int lengthUrl = centralizedFriendSystemUrl.length();
String postrequest = "postrequest.php";
String secretgen = "secretgen.php";
String laststep = "laststep.php";
String finalize = "finalize.php";
String gcontacts = "gcontacts.php";
String tpn_id = user()->name()+"@"+user()->tracker();
String nameProfile = user()->profile()->realName();
String mailProfile = user()->profile()->eMail();
page.open("div",".box");
page.open("h2");
page.text("Add Contacts / Send invitations");
page.close("h2");
page.open("div", ".howtorequests");
page.text("In this section, you can either add your friends or send invitations to them. These invitations contain a personalized code that enable them to reach you and ensure your communications are encrypted. You will have to confirm request by pasting a code in the 'Accept Request' section.");
page.close("div");
page.open("div","invitationmethods");
page.open("span",".invitationimg");
page.image("/spy.png","Classic way","spyimg");
page.close("span");
page.open("span",".invitationimg");
page.image("/mail.png","Mail","mailimg");
page.close("span");
page.open("span",".invitationimg");
//page.openForm(centralizedFriendSystemUrl+gcontacts,"post","gmailform");
// TODO : add parmeter target in class html ?
page.raw("<form name=\"gmailform\" action=\""+centralizedFriendSystemUrl+"gcontacts.php\" method=\"post\" enctype=\"application/x-www-form-urlencoded\" target=\"_newtab\">");
page.input("hidden", "tpn_id", tpn_id);
page.image("/gmail.png","GMail","gmailimg");
page.closeForm();
page.close("span");
page.open("span",".invitationimg");
page.image("/facebook_by_benstein.png","Facebook","fbimg");
page.close("span");
page.close("div");
page.open("div","howtotext");
page.close("div");
page.close("div");
// Js globals loaded from C++
page.javascript("var centralizedFriendSystemUrl = \""+centralizedFriendSystemUrl+"\"; \n\
var nameProfile = \""+nameProfile+"\";\n\
var mailProfile = \""+mailProfile+"\";\n\
var tpnIdCookie = 'tpnIdCookie'; \n\
setCookie(tpnIdCookie,'"+tpn_id+"',365); // Keep tpn_id in a cookie\n\
var postUrl1 = \""+centralizedFriendSystemUrl+"\"+\""+postrequest+"\";\n\
var tpn_id = \""+tpn_id+"\" \n\
var prefix = \""+prefix+"\" \n\
var token = \""+token+"\" \n\
");
page.openForm(prefix+"/","post","newcontact");
page.open("div","newcontactdiv.box");
page.open("h2");
page.text("Add contact");
page.close("h2");
//page.openFieldset("New contact");
page.input("hidden", "token", token);
page.label("name","TeapotNet ID"); page.input("text","name"); page.br();
page.label("secret","Secret"); page.input("text","secret","",true); page.br();
page.label("add"); //page.button("add","Add contact");
page.raw("<input type=\"button\" name=\"add\" value=\"Add contact\">"); // No way not to submit form with input --> TODO : change in html.cpp ?
//page.closeFieldset();
page.close("div");
page.closeForm();
// TODO : add dummy form ? (check on stackoverflow says it should work fine with input outside forms)
page.open("div","sendrequest.box");
page.open("h2");
page.text("Send friend request");
page.close("h2");
page.label("mail_sender","Your Mail"); page.input("text","mail_sender"); page.br();
page.label("mail_receiver","Your friend's Mail"); page.input("text","mail_receiver"); page.br();
page.label("sendinvitation"); page.button("sendinvitation","Send invitation");
page.close("div");
page.open("div","acceptrequest.box");
page.open("h2");
page.text("Accept request");
page.close("h2");
page.open("div", ".howtorequests");
page.text("If you've received from a friend a TeapotNet code, paste it here. Your friend will automatically be added to your contacts list");
page.close("div");
page.input("text","posturl");
page.button("postfriendrequest","Go !");
page.close("div");
//page.closeForm();
// load rapture.js
page.raw("<script type=\"text/javascript\" src=\"/rapture.js\"></script>");
Array<Contact*> contacts;
getContacts(contacts);
if(!contacts.empty())
{
page.open("div",".box");
page.open("h2");
page.text("Contacts");
page.close("h2");
page.open("table",".contacts");
for(int i=0; i<contacts.size(); ++i)
{
Contact *contact = contacts[i];
if(contact->isDeleted()) continue;
String contactUrl = prefix + '/' + contact->uniqueName() + '/';
page.open("tr");
page.open("td",".name");
page.link(contact->urlPrefix(), contact->name());
page.close("td");
page.open("td",".tracker");
page.text(String("@") + contact->tracker());
page.close("td");
page.open("td",".uname");
page.text(contact->uniqueName());
page.close("td");
page.open("td",".checksum");
page.text(String(" check: ")+String::hexa(contact->peeringChecksum(),8));
page.close("td");
page.open("td",".delete");
page.image("/delete.png", "Delete");
page.closeLink();
page.close("td");
page.close("tr");
}
page.close("table");
page.close("div");
page.openForm(prefix+"/", "post", "executeForm");
page.input("hidden", "command");
page.input("hidden", "argument");
page.input("hidden", "token", token);
page.closeForm();
page.javascript("function deleteContact(uname) {\n\
if(confirm('Do you really want to delete '+uname+' ? The corresponding messages will be deleted too.')) {\n\
document.executeForm.command.value = 'delete';\n\
document.executeForm.argument.value = uname;\n\
document.executeForm.submit();\n\
}\n\
}");
page.javascript("$('td.delete').css('cursor', 'pointer').click(function(event) {\n\
event.stopPropagation();\n\
var uname = $(this).closest('tr').find('td.uname').text();\n\
deleteContact(uname);\n\
});");
}
page.footer();
return;
}
}
catch(const Exception &e)
{
LogWarn("AddressBook::http",e.what());
throw 500; // Httpd handles integer exceptions
}
throw 404;
}
void AddressBook::registerContact(Contact *contact, int ordinal)
{
Synchronize(this);
mContacts.insert(contact->peering(), contact);
mContactsByUniqueName.insert(contact->uniqueName(), contact);
if(!contact->isDeleted())
{
if(contact->isSelf()) Interface::Instance->remove("/"+userName()+"/myself/files"); // overriding Store
Interface::Instance->add(contact->urlPrefix(), contact);
mScheduler.schedule(contact, UpdateStep*ordinal + uniform(0., UpdateStep));
mScheduler.repeat(contact, UpdateInterval);
}
}
void AddressBook::unregisterContact(Contact *contact)
{
Synchronize(this);
mContacts.erase(contact->peering());
mContactsByUniqueName.erase(contact->uniqueName());
Core::Instance->unregisterPeering(contact->peering());
Interface::Instance->remove(contact->urlPrefix(), contact);
mScheduler.remove(contact);
}
bool AddressBook::publish(const Identifier &remotePeering)
{
String tracker = Config::Get("tracker");
try {
String url("http://" + tracker + "/tracker?id=" + remotePeering.toString());
List<Address> list;
Config::GetExternalAddresses(list);
String addresses;
for( List<Address>::iterator it = list.begin();
it != list.end();
++it)
{
if(!addresses.empty()) addresses+= ',';
addresses+= it->toString();
}
StringMap post;
post["instance"] = Core::Instance->getName();
post["addresses"] = addresses;
String externalPort = Config::Get("external_port");
if(!externalPort.empty() && externalPort != "auto") post["port"] = externalPort;
else post["port"] = Config::Get("port");
if(!Core::Instance->isPublicConnectable())
{
list.clear();
Core::Instance->getKnownPublicAdresses(list);
String altAddresses;
for( List<Address>::iterator it = list.begin();
it != list.end();
++it)
{
if(!altAddresses.empty()) altAddresses+= ',';
altAddresses+= it->toString();
}
post["alternate"] = altAddresses;
}
if(Http::Post(url, post) == 200)
{
SynchronizeStatement(this, mBogusTrackers.erase(tracker));
return true;
}
}
catch(const Timeout &e)
{
LogDebug("AddressBook::publish", e.what());
}
catch(const NetException &e)
{
LogDebug("AddressBook::publish", e.what());
}
catch(const std::exception &e)
{
LogWarn("AddressBook::publish", e.what());
}
SynchronizeStatement(this, mBogusTrackers.insert(tracker));
return false;
}
bool AddressBook::query(const Identifier &peering, const String &tracker, AddressMap &output, bool alternate)
{
output.clear();
String host(tracker);
if(host.empty()) host = Config::Get("tracker");
try {
String url = "http://" + host + "/tracker?id=" + peering.toString();
if(alternate) url+= "&alternate=1";
String tmp;
if(Http::Get(url, &tmp) == 200)
{
SynchronizeStatement(this, mBogusTrackers.erase(tracker));
tmp.trim();
if(tmp.empty()) return false;
YamlSerializer serializer(&tmp);
typedef SerializableMap<String, SerializableArray<Address> > content_t;
content_t content;
serializer.input(content);
for(content_t::const_iterator it = content.begin();
it != content.end();
++it)
{
const String &instance = it->first;
const Array<Address> &addrs = it->second;
for(int i=0; i<addrs.size(); ++i)
output[instance].insert(addrs[i], Time::Now());
}
return !output.empty();
}
}
catch(const Timeout &e)
{
LogDebug("AddressBook::query", e.what());
}
catch(const NetException &e)
{
LogDebug("AddressBook::query", e.what());
}
catch(const std::exception &e)
{
LogWarn("AddressBook::query", e.what());
}
SynchronizeStatement(this, mBogusTrackers.insert(tracker));
return false;
}
AddressBook::Contact::Contact( AddressBook *addressBook,
const String &uname,
const String &name,
const String &tracker,
const String &secret) :
mAddressBook(addressBook),
mUniqueName(uname),
mName(name),
mTracker(tracker),
mDeleted(false),
mFound(false),
mFirstUpdateTime(0),
mProfile(NULL)
{
Assert(addressBook != NULL);
Assert(!uname.empty());
Assert(!name.empty());
Assert(!tracker.empty());
Assert(!secret.empty());
// The secret will be salted with a XOR of the two names, as this is symmetrical
ByteString xored;
const String &a = mName;
const String &b = mAddressBook->userName();
for(size_t i=0; i<std::max(a.size(), b.size()); ++i)
{
char c = 0;
if(i < a.size()) c^= a[i];
if(i < b.size()) c^= b[i];
xored.push_back(c);
}
ByteString salt;
ByteSerializer ssalt(&salt);
// Compute secret
salt.clear();
ssalt.output(xored);
Sha512::DerivateKey(secret, salt, mSecret, Sha512::CryptRounds);
// Only half the secret (256 bits) is used to compute peerings
ByteString halfSecret(mSecret, 0, mSecret.size()/2);
// Compute peering
salt.clear();
ssalt.output("TeapotNet");
ssalt.output(mAddressBook->userName());
ssalt.output(mName);
Sha512::DerivateKey(halfSecret, salt, mPeering, Sha512::CryptRounds);
// Compute remote peering
salt.clear();
ssalt.output("TeapotNet");
ssalt.output(mName);
ssalt.output(mAddressBook->userName());
Sha512::DerivateKey(halfSecret, salt, mRemotePeering, Sha512::CryptRounds);
createProfile();
}
AddressBook::Contact::Contact(AddressBook *addressBook) :
mAddressBook(addressBook),
mDeleted(false),
mFound(false),
mFirstUpdateTime(0),
mProfile(NULL)
{
}
AddressBook::Contact::~Contact(void)
{
Interface::Instance->remove(urlPrefix(), this);
delete mProfile;
}
String AddressBook::Contact::uniqueName(void) const
{
Synchronize(mAddressBook);
return mUniqueName;
}
String AddressBook::Contact::name(void) const
{
Synchronize(mAddressBook);
return mName;
}
String AddressBook::Contact::tracker(void) const
{
Synchronize(mAddressBook);
if(mProfile) return mProfile->tracker();
else return mTracker;
}
Identifier AddressBook::Contact::peering(void) const
{
Synchronize(mAddressBook);
return mPeering;
}
Identifier AddressBook::Contact::remotePeering(void) const
{
Synchronize(mAddressBook);
return mRemotePeering;
}
Time AddressBook::Contact::time(void) const
{
Synchronize(mAddressBook);
return mTime;
}
uint32_t AddressBook::Contact::peeringChecksum(void) const
{
Synchronize(mAddressBook);
return mPeering.getDigest().checksum32() + mRemotePeering.getDigest().checksum32();
}
String AddressBook::Contact::urlPrefix(void) const
{
Synchronize(mAddressBook);
if(mUniqueName.empty()) return "";
if(isSelf()) return String("/")+mAddressBook->userName()+"/myself";
return String("/")+mAddressBook->userName()+"/contacts/"+mUniqueName;
}
ByteString AddressBook::Contact::secret(void) const
{
Synchronize(mAddressBook);
return mSecret;
}
Profile *AddressBook::Contact::profile(void) const
{
Synchronize(mAddressBook);
if(isSelf()) return mAddressBook->user()->profile();
else {
Assert(mProfile);
return mProfile;
}
}
bool AddressBook::Contact::isSelf(void) const
{
return (mUniqueName == mAddressBook->userName());
}
bool AddressBook::Contact::isFound(void) const
{
return mFound;
}
bool AddressBook::Contact::isConnected(void) const
{
Synchronize(mAddressBook);
return Core::Instance->hasPeer(mPeering);
}
bool AddressBook::Contact::isConnected(const String &instance) const
{
Synchronize(mAddressBook);
if(isSelf() && instance == Core::Instance->getName()) return true;
return Core::Instance->hasPeer(Identifier(mPeering, instance));
}
bool AddressBook::Contact::isOnline(void) const
{
Synchronize(mAddressBook);
if(isSelf() && mAddressBook->user()->isOnline()) return true;
if(!isConnected()) return false;
return !mOnlineInstances.empty();
}
String AddressBook::Contact::status(void) const
{
Synchronize(mAddressBook);
if(isSelf()) return "myself";
if(isOnline()) return "online";
else if(isConnected()) return "connected";
else if(isFound()) return "found";
else return "disconnected";
}
AddressBook::AddressMap AddressBook::Contact::addresses(void) const
{
Synchronize(mAddressBook);
return mAddrs;
}
bool AddressBook::Contact::isDeleted(void) const
{
Synchronize(mAddressBook);
return mDeleted;
}
void AddressBook::Contact::setDeleted(void)
{
Synchronize(mAddressBook);
mDeleted = true;
mTime = Time::Now();
}
void AddressBook::Contact::getInstancesNames(Array<String> &array)
{
SynchronizeStatement(mAddressBook, mAddrs.getKeys(array));
Array<String> others;
Core::Instance->getInstancesNames(peering(), others);
for(int i=0; i<others.size(); ++i)
if(!array.contains(others[i]))
array.append(others[i]);
}
bool AddressBook::Contact::addAddresses(const AddressMap &map)
{
bool changed = false;
for(AddressMap::const_iterator it = map.begin();
it != map.end();
++it)
{
Synchronize(mAddressBook);
const String &instance = it->first;
const AddressBlock &block = it->second;
AddressBlock &target = mAddrs[instance];
for(AddressBlock::const_iterator jt = block.begin();
jt != block.end();
++jt)
{
const Address &addr = jt->first;
const Time &time = jt->second;
if(!target.contains(addr) || target[addr] < time)
{
target[addr] = time;
changed = true;
}
}
}
if(changed) mAddressBook->save();
return true;
}
bool AddressBook::Contact::connectAddress(const Address &addr, const String &instance, bool save)
{
// Warning: NOT synchronized !
if(addr.isNull()) return false;
if(instance == Core::Instance->getName()) return false;
LogDebug("AddressBook::Contact", "Connecting " + instance + " on " + addr.toString() + "...");
Identifier peering(this->peering(), instance);
ByteStream *bs = NULL;
if(!Config::Get("force_http_tunnel").toBool() || !addr.isPublic() || addr.port() == 443)
{
Socket *sock = NULL;
try {
sock = new Socket(addr, 4.);
}
catch(const Exception &e)
{
sock = NULL;
LogDebug("AddressBook::Contact::connectAddress", String("Direct connection failed: ") + e.what());
}
if(sock)
{
sock->setTimeout(milliseconds(Config::Get("tpot_read_timeout").toInt()));
bs = sock;
}
}
if(!bs && addr.isPublic() && addr.port() != 443)
{
try {
bs = new HttpTunnel::Client(addr, 4.);
}
catch(const Exception &e)
{
bs = NULL;
LogDebug("AddressBook::Contact::connectAddress", String("HTTP tunnel failed: ") + e.what());
}
}
if(!bs) return false;
if(Core::Instance->addPeer(bs, addr, peering))
{
if(save)
{
SynchronizeStatement(mAddressBook, mAddrs[instance][addr] = Time::Now());
mAddressBook->save();
}
return true;
}
else {
// A node is running at this address but the user does not exist
if(save && mAddrs.contains(instance))
{
Synchronize(mAddressBook);
mAddrs[instance].erase(addr);
if(mAddrs[instance].empty())
mAddrs.erase(instance);
mAddressBook->save();
}
return false;
}
}
bool AddressBook::Contact::connectAddresses(const AddressMap &map, bool save, bool shuffle)
{
// Warning: NOT synchronized !
bool success = false;
for(AddressMap::const_iterator it = map.begin();
it != map.end();
++it)
{
const String &instance = it->first;
const AddressBlock &block = it->second;
if(instance == Core::Instance->getName()
|| mExcludedInstances.contains(instance)) continue;
// TODO: look for a better address than the already connected one
if(isConnected(instance))
{
// TODO: update time for currenly connected address
success = true;
continue;
}
Array<Address> addrs;
block.getKeys(addrs);
if(shuffle) std::random_shuffle(addrs.begin(), addrs.end());
LogDebug("AddressBook::Contact", "Connecting instance " + instance + " for " + name() + " (" + String::number(addrs.size()) + " address(es))...");
for(Array<Address>::const_reverse_iterator jt = addrs.rbegin();
jt != addrs.rend();
++jt)
{
if(connectAddress(*jt, instance, save))
{
success = true;
break;
}
}
}
return success;
}
void AddressBook::Contact::update(bool alternate)
{
// Warning: NOT synchronized !
if(isDeleted()) return;
Core::Instance->registerPeering(peering(), remotePeering(), secret(), this);
LogDebug("AddressBook::Contact", "Looking for " + uniqueName());
if(peering() != remotePeering() && Core::Instance->hasRegisteredPeering(remotePeering())) // the user is local
{
Identifier identifier(peering(), Core::Instance->getName());
if(!Core::Instance->hasPeer(identifier))
{
LogDebug("AddressBook::Contact", uniqueName() + " found locally");
Address addr("127.0.0.1", Config::Get("port"));
try {
Socket *sock = new Socket(addr);
Core::Instance->addPeer(sock, identifier);
}
catch(...)
{
LogDebug("AddressBook::Contact", "Warning: Unable to connect the local core");
}
}
}
if(!alternate)
{
if(mAddressBook->publish(remotePeering()))
LogDebug("AddressBook::Contact", "Published to tracker " + tracker() + " for " + uniqueName());
}
AddressMap newAddrs;
if(mAddressBook->query(peering(), tracker(), newAddrs, alternate))
LogDebug("AddressBook::Contact", "Queried tracker " + tracker() + " for " + uniqueName());
if(!newAddrs.empty())
{
if(!alternate) LogDebug("AddressBook::Contact", "Contact " + name() + " found (" + String::number(newAddrs.size()) + " instance(s))");
else LogDebug("AddressBook::Contact", "Alternative addresses for " + name() + " found (" + String::number(newAddrs.size()) + " instance(s))");
mFound = true;
connectAddresses(newAddrs, !alternate, alternate);
}
else if(!alternate)
{
mFound = false;
connectAddresses(addresses(), true, false);
}
{
Synchronize(mAddressBook);
AddressMap::iterator it = mAddrs.begin();
while(it != mAddrs.end())
{
const String &instance = it->first;
AddressBlock &block = it->second;
AddressBlock::iterator jt = block.begin();
while(jt != block.end())
{
if(Time::Now() - jt->second >= 3600*24*8) // 8 days
block.erase(jt++);
else jt++;
}
if(block.empty())
mAddrs.erase(it++);
else it++;
}
}
}
void AddressBook::Contact::createProfile(void)
{
if(isSelf()) return;
if(!mProfile)
{
mProfile = new Profile(mAddressBook->user(), mUniqueName, mTracker);
try {
mProfile->load();
}
catch(const Exception &e)
{
LogWarn("AddressBook::Contact", String("Unable to load profile for ") + uniqueName() + ": " + e.what());
}
}
}
void AddressBook::Contact::run(void)
{
Synchronize(mAddressBook);
if(mFirstUpdateTime == Time(0))
mFirstUpdateTime = Time::Now();
DesynchronizeStatement(mAddressBook, update(false));
if((Time::Now() - mFirstUpdateTime)*1000 >= UpdateInterval)
DesynchronizeStatement(mAddressBook, update(true));
}
void AddressBook::Contact::connected(const Identifier &peering, bool incoming)
{
// Handle the special case of symmetric peerings
if(!isSelf() && mPeering == mRemotePeering)
{
Contact *self = mAddressBook->getSelf();
// If there is no self contact, the remote instance *should* not be one of ours anyway.
if(self)
{
Notification notification(self->peering().toString());
notification.setParameter("type", "checkself");
notification.send(peering);
}
}
// Send status and profile
if(mAddressBook->user()->isOnline()) mAddressBook->user()->sendStatus(peering);
mAddressBook->user()->profile()->send(peering);
// Send secret and contacts if self
if(isSelf())
{
mAddressBook->user()->sendSecret(peering);
String data;
mAddressBook->save(data);
Notification notification(data);
notification.setParameter("type", "contacts");
notification.send(peering);
}
if(incoming)
{
MessageQueue::Selection selection = selectMessages();
int total = selection.count();
if(total > MaxChecksumDistance)
{
Message base;
if(selection.getOffset(total - MaxChecksumDistance, base))
Assert(selection.setBaseStamp(base.stamp()));
}
sendMessagesChecksum(peering, selection, 0, selection.count(), true);
}
}
void AddressBook::Contact::disconnected(const Identifier &peering)
{
mAddressBook->mScheduler.schedule(this, 10.);
SynchronizeStatement(mAddressBook, mOnlineInstances.erase(peering.getName()));
}
bool AddressBook::Contact::notification(const Identifier &peering, Notification *notification)
{
if(isDeleted()) return false;
Assert(notification);
StringMap parameters = notification->parameters();
String type;
parameters.get("type", type);
LogDebug("AddressBook::Contact", "Incoming notification from "+uniqueName()+" (type='" + type + "')");
if(type.empty() || type == "message")
{
Message message;
Assert(message.recv(*notification));
if(!isSelf())
{
message.setIncoming(!message.checkSignature(mAddressBook->user()));
if(message.isPublic() && !message.isIncoming()) message.setContact("");
else {
if(message.isPublic() && !message.contact().empty()) message.setRelayed(true);
message.setContact(uniqueName());
}
}
mAddressBook->user()->messageQueue()->add(message);
}
else if(type == "read" || type == "ack")
{
String data = notification->content();
YamlSerializer serializer(&data);
StringArray stamps;
serializer.input(stamps);
// Mark messages as read
bool privateOnly = !isSelf(); // others may not mark public messages as read
MessageQueue::Selection selection = selectMessages(privateOnly);
for(int i=0; i<stamps.size(); ++i)
selection.markRead(stamps[i]);
}
else if(type == "unread")
{
String data = notification->content();
YamlSerializer serializer(&data);
StringSet recvStamps;
serializer.input(recvStamps);
// Mark messages as read
bool privateOnly = !isSelf(); // others may not mark public messages as read
MessageQueue::Selection selection = selectMessages(privateOnly);
Array<Message> unread;
selection.getUnread(unread);
// Mark not present stamps as read
for(int i=0; i<unread.size(); ++i)
{
String stamp = unread[i].stamp();
if(recvStamps.contains(stamp)) recvStamps.erase(stamp);
else selection.markRead(stamp);
}
// Ack left stamps
if(!recvStamps.empty())
{
StringArray ackedStamps;
ackedStamps.assign(recvStamps.begin(), recvStamps.end());
String tmp;
YamlSerializer outSerializer(&tmp);
outSerializer.output(ackedStamps);
Notification notification(tmp);
notification.setParameter("type", "read");
notification.send(peering);
}
}
else if(type == "checksum")
{
int offset = 0;
int count = 0;
int total = 0;
bool recursion = false;
String base;
try {
parameters["offset"] >> offset;
parameters["count"] >> count;
parameters["total"] >> total;
parameters["recursion"] >> recursion;
if(parameters.contains("base"))
parameters["base"] >> base;
Assert(offset >= 0);
Assert(count >= 0);
Assert(offset + count <= total);
}
catch(const Exception &e)
{
throw InvalidData("checksum notification parameters: " + String(e.what()));
}
ByteString checksum;
try {
notification->content().extract(checksum);
}
catch(...)
{
throw InvalidData("checksum notification content: " + notification->content());
}
LogDebug("AddressBook::Contact", "Synchronization: Received checksum: " + String::number(offset) + ", " + String::number(count) + " (recursion " + (recursion ? "enabled" : "disabled") + ")");
MessageQueue::Selection selection = selectMessages();
if(!base.empty())
{
if(!selection.setBaseStamp(base))
LogDebug("AddressBook::Contact", "Synchronization: Base message '"+base+"' does not exist");
}
int localTotal = selection.count();
bool isLastIteration = false;
if(offset + count <= localTotal)
{
ByteString result;
selection.checksum(offset, count, result);
if(result != checksum)
{
LogDebug("AddressBook::Contact", "Synchronization: No match: " + String::number(offset) + ", " + String::number(count));
if(count == 1) // TODO
{
sendMessages(peering, selection, offset, count);
if(recursion)
{
sendMessagesChecksum(peering, selection, offset, count, false);
isLastIteration = true;
}
}
else if(recursion)
{
sendMessagesChecksum(peering, selection, offset, count/2, true);
sendMessagesChecksum(peering, selection, offset + count/2, count - count/2, true);
}
if(!recursion)
isLastIteration = true;
}
else {
LogDebug("AddressBook::Contact", "Synchronization: Match: " + String::number(offset) + ", " + String::number(count));
isLastIteration = true;
}
}
else {
if(offset == 0)
{
LogDebug("AddressBook::Contact", "Synchronization: Remote has more messages");
sendMessagesChecksum(peering, selection, 0, localTotal, true);
}
}
if(isLastIteration && offset == 0)
{
// If messages are missing remotely
if(total < localTotal)
sendMessages(peering, selection, total, localTotal - total);
sendUnread(peering);
}
}
else if(type == "checkself")
{
Identifier checkself;
try {
notification->content().extract(checkself);
}
catch(...)
{
throw InvalidData("checkself notification content: " + notification->content());
}
Contact *self = mAddressBook->getSelf();
if(self && (isSelf() != (checkself == self->peering())))
{
LogDebug("AddressBook::Contact::notification", "Remote instance belongs to us on a symmetric peering, disconnecting");
mExcludedInstances.insert(peering.getName());
return false; // disconnect
}
}
else if(type == "status")
{
Synchronize(mAddressBook);
String status = notification->content().toLower().trimmed();
if(status == "online") mOnlineInstances.insert(peering.getName());
else mOnlineInstances.erase(peering.getName());
}
else if(type == "secret")
{
if(!isSelf())
{
LogWarn("AddressBook::Contact::notification", "Received secret update from other than self, dropping");
return true;
}
ByteString secret;
try {
notification->content().extract(secret);
}
catch(...)
{
throw InvalidData("secret notification content: " + notification->content());
}
if(!parameters.contains("time"))
{
LogWarn("AddressBook::Contact::notification", "Received secret update without time, dropping");
return true;
}
Time time;
parameters["time"] >> time;
mAddressBook->user()->setSecret(secret, time);
}
else if(type == "profile" || type == "profilediff")
{
String data = notification->content();
YamlSerializer serializer(&data);
Profile *p = profile();
Time time;
if(parameters.contains("time")) parameters["time"] >> time;
else if(type != "profilediff")
{
LogWarn("AddressBook::Contact::notification", "Received profile update without time, dropping");
return true;
}
if(time > p->time())
{
Synchronize(p);
if(type != "profilediff") p->clear();
p->deserialize(serializer);
p->save();
}
}
else if(type == "contacts")
{
if(!isSelf())
{
LogWarn("AddressBook::Contact::notification", "Received contacts update from other than self, dropping");
return true;
}
// DO NOT synchronize here, as the contact could disappear during load
String data = notification->content();
mAddressBook->load(data);
}
else if(type == "text")
{
LogDebug("AddressBook::Contact", "Got deprecated notification with type 'text'");
}
else LogDebug("AddressBook::Contact", "Unknown notification type '" + type + "'");
return true;
}
MessageQueue::Selection AddressBook::Contact::selectMessages(bool privateOnly) const
{
MessageQueue *messageQueue = mAddressBook->user()->messageQueue();
String uname;
if(!isSelf()) uname = uniqueName();
if(!privateOnly) return messageQueue->select(uname);
else return messageQueue->selectPrivate(uname);
}
void AddressBook::Contact::sendMessages(const Identifier &peering, const MessageQueue::Selection &selection, int offset, int count) const
{
if(!count) return;
LogDebug("AddressBook::Contact", "Synchronization: Sending messages: " + String::number(offset) + ", " + String::number(count));
Array<Message> messages;
selection.getRange(offset, count, messages);
for(int i=0; i<messages.size(); ++i)
messages[i].send(peering);
}
void AddressBook::Contact::sendMessagesChecksum(const Identifier &peering, const MessageQueue::Selection &selection, int offset, int count, bool recursion) const
{
int total = selection.count();
offset = bounds(offset, 0, total);
count = bounds(count, 0, total - offset);
LogDebug("AddressBook::Contact", "Synchronization: Sending checksum: " + String::number(offset) + ", " + String::number(count) + " (recursion " + (recursion ? "enabled" : "disabled") + ")");
ByteString result;
selection.checksum(offset, count, result);
StringMap parameters;
parameters["type"] << "checksum";
parameters["offset"] << offset;
parameters["count"] << count;
parameters["total"] << total;
parameters["recursion"] << recursion;
String base = selection.baseStamp();
if(!base.empty()) parameters["base"] << base;
Notification notification(result.toString());
notification.setParameters(parameters);
notification.send(peering);
}
void AddressBook::Contact::sendUnread(const Identifier &peering) const
{
bool privateOnly = !isSelf();
MessageQueue::Selection selection = selectMessages(privateOnly);
StringArray unreadStamps;
selection.getUnreadStamps(unreadStamps);
String tmp;
YamlSerializer serializer(&tmp);
serializer.output(unreadStamps);
Notification notification(tmp);
notification.setParameter("type", "unread");
notification.send(peering);
}
bool AddressBook::Contact::request(const Identifier &peering, Request *request)
{
Assert(request);
if(!mDeleted) request->execute(mAddressBook->user(), isSelf());
else request->executeDummy();
return true;
}
bool AddressBook::Contact::send(const Notification ¬ification)
{
return notification.send(peering());
}
bool AddressBook::Contact::send(const Message &message)
{
return message.send(peering());
}
void AddressBook::Contact::http(const String &prefix, Http::Request &request)
{
mAddressBook->user()->setOnline();
try {
if(request.url.empty() || request.url == "/")
{
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.sock);
String strName = name();
String strTracker = tracker();
String strStatus = status();
MessageQueue *messageQueue = mAddressBook->user()->messageQueue();
ConstSerializableWrapper<int> messagesWrapper(messageQueue->selectPrivate(uniqueName()).unreadCount());
ConstSerializableWrapper<bool> newMessagesWrapper(messageQueue->hasNew());
Array<String> instances;
getInstancesNames(instances);
StringMap instancesMap;
for(int i=0; i<instances.size(); ++i)
{
if(isConnected(instances[i])) instancesMap[instances[i]] = "connected";
else instancesMap[instances[i]] = "disconnected";
}
SerializableMap<String, Serializable*> map;
map["name"] = &strName;
map["tracker"] = &strTracker;
map["status"] = &strStatus;
map["messages"] = &messagesWrapper;
map["newmessages"] = &newMessagesWrapper;
map["instances"] = &instancesMap;
json.output(map);
return;
}
Http::Response response(request,200);
response.send();
Html page(response.sock);
if(isSelf()) page.header("Myself");
else {
page.header("Contact: "+name());
page.open("div", "topmenu");
page.span(status().capitalized(), "status.button");
page.close("div");
}
// TODO: insert here profile infos
page.open("div",".box");
page.open("table", ".menu");
page.open("tr");
page.open("td");
page.openLink(prefix + "/files/");
page.image("/icon_files.png", "Files", ".bigicon");
page.closeLink();
page.close("td");
page.open("td", ".title");
page.text("Files");
page.close("td");
page.close("tr");
page.open("tr");
page.open("td");
page.openLink(prefix + "/search/");
page.image("/icon_search.png", "Search", ".bigicon");
page.closeLink();
page.close("td");
page.open("td", ".title");
page.text("Search");
page.close("td");
page.close("tr");
page.open("tr");
page.open("td");
page.openLink(profile()->urlPrefix());
page.image("/icon_profile.png", "Profile", ".bigicon");
page.closeLink();
page.close("td");
page.open("td", ".title");
page.text("Profile");
page.close("td");
page.close("tr");
if(!isSelf())
{
page.open("tr");
page.open("td");
page.openLink(prefix + "/chat/");
page.image("/icon_chat.png", "Chat", ".bigicon");
page.closeLink();
page.close("td");
page.open("td",".title");
page.text("Chat");
page.span("", "messagescount.messagescount");
page.close("td");
page.close("tr");
}
page.close("table");
page.close("div");
page.open("div",".box");
page.open("h2");
page.text("Instances");
page.close("h2");
page.open("table", "instances");
page.close("table");
page.close("div");
unsigned refreshPeriod = 5000;
page.javascript("setCallback(\""+prefix+"/?json\", "+String::number(refreshPeriod)+", function(info) {\n\
transition($('#status'), info.status.capitalize());\n\
$('#status').removeClass().addClass('button').addClass(info.status);\n\
var msg = '';\n\
if(info.messages != 0) msg = ' ('+info.messages+')';\n\
transition($('#messagescount'), msg);\n\
$('#instances').empty();\n\
if($.isEmptyObject(info.instances)) $('#instances').text('No connected instance');\n\
else $.each(info.instances, function(instance, status) {\n\
$('#instances').append($('<tr>')\n\
.addClass(status)\n\
.append($('<td>').addClass('name').text(instance))\n\
.append($('<td>').addClass('status').text(status.capitalize())));\n\
});\n\
});");
// Recent files
page.open("div",".box");
page.open("h2");
page.text("Recent files");
page.close("h2");
page.div("", "recent");
page.close("div");
int maxAge = 60*60*24*7; // 7 days
int count = 20;
page.javascript("listDirectory('"+prefix+"/search?json&maxage="+String::number(maxAge)+"&count="+String::number(count)+"','#recent',false);");
page.footer();
return;
}
else {
String url = request.url;
String directory = url;
directory.ignore(); // remove first '/'
url = "/" + directory.cut('/');
if(directory.empty()) throw 404;
if(request.get.contains("play"))
{
String host;
if(!request.headers.get("Host", host))
host = String("localhost:") + Config::Get("interface_port");
Http::Response response(request, 200);
response.headers["Content-Disposition"] = "attachment; filename=\"stream.m3u\"";
response.headers["Content-Type"] = "audio/x-mpegurl";
response.send();
String link = "http://" + host + prefix + request.url + "?file=1";
String instance;
if(request.get.get("instance", instance))
link+= "&instance=" + instance;
response.sock->writeLine("#EXTM3U");
response.sock->writeLine(String("#EXTINF:-1, ") + APPNAME + " stream");
response.sock->writeLine(link);
return;
}
if(directory == "files")
{
String target(url);
Assert(!target.empty());
if(request.get.contains("json") || request.get.contains("playlist"))
{
// Query resources
Resource::Query query(mAddressBook->user()->store(), target);
query.setFromSelf(isSelf());
SerializableSet<Resource> resources;
bool success = query.submitRemote(resources, peering());
if(isSelf()) success|= query.submitLocal(resources);
if(!success) throw 404;
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.sock);
json.output(resources);
}
else {
Http::Response response(request, 200);
response.headers["Content-Disposition"] = "attachment; filename=\"playlist.m3u\"";
response.headers["Content-Type"] = "audio/x-mpegurl";
response.send();
String host;
request.headers.get("Host", host);
Resource::CreatePlaylist(resources, response.sock, host);
}
return;
}
// if it seems to be a file
if(target[target.size()-1] != '/')
{
String instance;
request.get.get("instance", instance);
Identifier instancePeering(peering());
if(!instancePeering.empty()) instancePeering.setName(instance);
Resource resource(instancePeering, url, mAddressBook->user()->store());
try {
resource.fetch(isSelf()); // we might find a better way to access it
}
catch(const Exception &e)
{
LogWarn("AddressBook::Contact::http", String("Resource lookup failed: ") + e.what());
throw 404;
}
// redirect if it's a directory
if(resource.isDirectory())
{
if(request.get.contains("download"))
throw 404;
Http::Response response(request, 301); // Moved permanently
response.headers["Location"] = prefix + request.url + '/';
response.send();
return;
}
// Get range
int64_t rangeBegin = 0;
int64_t rangeEnd = 0;
bool hasRange = request.extractRange(rangeBegin, rangeEnd, resource.size());
int64_t rangeSize = rangeEnd - rangeBegin;
// Get resource accessor
Resource::Accessor *accessor = resource.accessor();
if(!accessor) throw 404;
// Forge HTTP response header
Http::Response response(request, 200);
if(!hasRange) response.headers["Content-SHA512"] << resource.digest();
response.headers["Content-Length"] << rangeSize;
response.headers["Content-Name"] = resource.name();
response.headers["Last-Modified"] = resource.time().toHttpDate();
response.headers["Accept-Ranges"] = "bytes";
if(request.get.contains("download"))
{
response.headers["Content-Disposition"] = "attachment; filename=\"" + resource.name() + "\"";
response.headers["Content-Type"] = "application/octet-stream";
}
else {
response.headers["Content-Disposition"] = "inline; filename=\"" + resource.name() + "\"";
response.headers["Content-Type"] = Mime::GetType(resource.name());
}
response.send();
if(request.method == "HEAD") return;
try {
// Launch transfer
if(hasRange) accessor->seekRead(rangeBegin);
accessor->readBinary(*response.sock, rangeSize); // let's go !
}
catch(const NetException &e)
{
return; // nothing to do
}
catch(const Exception &e)
{
LogWarn("Interface::process", String("Error during file transfer: ") + e.what());
}
}
else {
Http::Response response(request, 200);
response.send();
Html page(response.sock);
if(target == "/") page.header(name()+": Browse files");
else page.header(name()+": "+target.substr(1));
page.open("div","topmenu");
if(!isSelf()) page.span(status().capitalized(), "status.button");
page.link(prefix+"/search/","Search files",".button");
page.link(prefix+request.url+"?playlist","Play all",".button");
page.close("div");
unsigned refreshPeriod = 5000;
page.javascript("setCallback(\""+prefix+"/?json\", "+String::number(refreshPeriod)+", function(info) {\n\
transition($('#status'), info.status.capitalize());\n\
$('#status').removeClass().addClass('button').addClass(info.status);\n\
if(info.newmessages) playMessageSound();\n\
});");
page.div("","list.box");
page.javascript("listDirectory('"+prefix+request.url+"?json','#list',true);");
page.footer();
}
return;
}
else if(directory == "search")
{
if(url != "/") throw 404;
String match;
if(!request.post.get("query", match))
request.get.get("query", match);
match.trim();
if(request.get.contains("json") || request.get.contains("playlist"))
{
String tmp;
int minAge = 0;
int maxAge = 0;
int count = 0;
if(request.get.get("minage", tmp)) tmp >> minAge;
if(request.get.get("maxage", tmp)) tmp >> maxAge;
if(request.get.get("count", tmp)) tmp >> count;
if(match.empty() && maxAge <= 0) throw 400;
Resource::Query query(mAddressBook->user()->store());
if(isSelf()) query.setFromSelf(isSelf());
if(!match.empty()) query.setMatch(match);
if(minAge > 0) query.setMinAge(minAge);
if(maxAge > 0) query.setMaxAge(maxAge);
if(count > 0) query.setLimit(count);
SerializableSet<Resource> resources;
bool success = query.submitRemote(resources, peering());
if(isSelf()) success|= query.submitLocal(resources);
if(!success) throw 404;
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.sock);
json.output(resources);
}
else {
Http::Response response(request, 200);
response.headers["Content-Disposition"] = "attachment; filename=\"playlist.m3u\"";
response.headers["Content-Type"] = "audio/x-mpegurl";
response.send();
String host;
request.headers.get("Host", host);
Resource::CreatePlaylist(resources, response.sock, host);
}
return;
}
Http::Response response(request, 200);
response.send();
Html page(response.sock);
if(match.empty()) page.header(name() + ": Search");
else page.header(name() + ": Searching " + match);
page.open("div","topmenu");
if(!isSelf()) page.span(status().capitalized(), "status.button");
page.openForm(prefix + "/search", "post", "searchForm");
page.input("text", "query", match);
page.button("search","Search");
page.closeForm();
page.javascript("$(document).ready(function() { document.searchForm.query.focus(); });");
if(!match.empty()) page.link(prefix+request.url+"?query="+match.urlEncode()+"&playlist","Play all",".button");
page.close("div");
unsigned refreshPeriod = 5000;
page.javascript("setCallback(\""+prefix+"/?json\", "+String::number(refreshPeriod)+", function(info) {\n\
transition($('#status'), info.status.capitalize());\n\
$('#status').removeClass().addClass('button').addClass(info.status);\n\
if(info.newmessages) playMessageSound();\n\
});");
if(!match.empty())
{
page.div("", "list.box");
page.javascript("listDirectory('"+prefix+request.url+"?query="+match.urlEncode()+"&json','#list');");
}
page.footer();
return;
}
else if(directory == "avatar")
{
Http::Response response(request, 303); // See other
response.headers["Location"] = profile()->avatarUrl();
response.send();
return;
}
else if(directory == "chat")
{
if(isSelf()) throw 404;
Http::Response response(request, 301); // Moved permanently
response.headers["Location"] = mAddressBook->user()->urlPrefix() + "/messages/" + uniqueName().urlEncode() + "/";
response.send();
return;
}
}
}
catch(const NetException &e)
{
throw;
}
catch(const Exception &e)
{
LogWarn("AddressBook::Contact::http", e.what());
throw 500;
}
throw 404;
}
void AddressBook::Contact::copy(const AddressBook::Contact *contact)
{
Synchronize(mAddressBook);
Assert(contact);
mUniqueName = contact->mUniqueName;
mName = contact->mName;
mTracker = contact->mTracker;
mSecret = contact->mSecret;
mPeering = contact->mPeering;
mRemotePeering = contact->mRemotePeering;
mTime = contact->mTime;
mDeleted = contact->mDeleted;
addAddresses(contact->addresses());
}
void AddressBook::Contact::serialize(Serializer &s) const
{
Synchronize(mAddressBook);
StringMap map;
map["uname"] << mUniqueName;
map["name"] << mName;
map["tracker"] << tracker();
map["secret"] << mSecret;
map["peering"] << mPeering;
map["remote"] << mRemotePeering;
map["time"] << mTime;
map["deleted"] << mDeleted;
s.outputMapBegin(2);
s.outputMapElement(String("info"),map);
s.outputMapElement(String("addrs"),mAddrs);
s.outputMapEnd();
}
bool AddressBook::Contact::deserialize(Serializer &s)
{
Synchronize(mAddressBook);
mUniqueName.clear();
mName.clear();
mTracker.clear();
mSecret.clear();
mPeering.clear();
mRemotePeering.clear();
mDeleted = false;
mTime = Time::Now();
StringMap map;
String key;
AssertIO(s.inputMapBegin());
AssertIO(s.inputMapElement(key, map) && key == "info");
AssertIO(s.inputMapElement(key, mAddrs) && key == "addrs");
map["uname"] >> mUniqueName;
map["name"] >> mName;
map["tracker"] >> mTracker;
map["secret"] >> mSecret;
map["peering"] >> mPeering;
map["remote"] >> mRemotePeering;
if(map.contains("time"))
{
map["time"] >> mTime;
mTime = std::min(mTime, Time::Now());
}
if(map.contains("deleted"))
{
map["deleted"] >> mDeleted;
}
// TODO: checks
mFound = false;
createProfile();
return true;
}
bool AddressBook::Contact::isInlineSerializable(void) const
{
return false;
}
}
Cosmetic modifications for contacts panel
/*************************************************************************
* Copyright (C) 2011-2013 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet 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. *
* *
* TeapotNet 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 TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "tpn/addressbook.h"
#include "tpn/user.h"
#include "tpn/core.h"
#include "tpn/sha512.h"
#include "tpn/config.h"
#include "tpn/file.h"
#include "tpn/directory.h"
#include "tpn/html.h"
#include "tpn/yamlserializer.h"
#include "tpn/jsonserializer.h"
#include "tpn/byteserializer.h"
#include "tpn/portmapping.h"
#include "tpn/httptunnel.h"
#include "tpn/mime.h"
namespace tpn
{
const double AddressBook::UpdateInterval = 300.;
const double AddressBook::UpdateStep = 0.20;
const int AddressBook::MaxChecksumDistance = 1000;
AddressBook::AddressBook(User *user) :
mUser(user),
mUserName(user->name())
{
Assert(UpdateInterval > 0);
Assert(mUser != NULL);
mFileName = mUser->profilePath() + "contacts";
Interface::Instance->add("/"+mUser->name()+"/contacts", this);
if(File::Exist(mFileName))
{
try {
File file(mFileName, File::Read);
load(file);
file.close();
}
catch(const Exception &e)
{
LogError("AddressBook", String("Loading failed: ") + e.what());
}
}
}
AddressBook::~AddressBook(void)
{
Interface::Instance->remove("/"+mUser->name()+"/contacts");
clear();
}
User *AddressBook::user(void) const
{
return mUser;
}
String AddressBook::userName(void) const
{
Synchronize(this);
return mUserName;
}
Identifier AddressBook::addContact(String name, const String &secret)
{
Synchronize(this);
String tracker = name.cut('@');
if(tracker.empty()) tracker = Config::Get("tracker");
String uname = name;
unsigned i = 1;
while((mContactsByUniqueName.contains(uname) && !mContactsByUniqueName.get(uname)->isDeleted())
|| uname == userName()) // userName reserved for self
{
uname = name;
uname << ++i;
}
Contact *oldContact;
if(mContactsByUniqueName.get(uname, oldContact))
{
unregisterContact(oldContact);
delete oldContact;
}
Contact *contact = new Contact(this, uname, name, tracker, secret);
if(mContacts.get(contact->peering(), oldContact))
{
if(!oldContact->isDeleted())
{
LogWarn("AddressBook::addContact", "The contact already exists with this secret: " + name);
delete contact;
return oldContact->peering();
}
oldContact->copy(contact);
delete contact;
contact = oldContact;
}
registerContact(contact);
save();
return contact->peering();
}
void AddressBook::removeContact(const Identifier &peering)
{
Synchronize(this);
Contact *contact;
if(mContacts.get(peering, contact))
{
contact->setDeleted();
Core::Instance->unregisterPeering(contact->peering());
Interface::Instance->remove(contact->urlPrefix(), contact);
mScheduler.remove(contact);
save();
// Erase messages
mUser->messageQueue()->erase(contact->uniqueName());
}
}
AddressBook::Contact *AddressBook::getContact(const Identifier &peering)
{
Synchronize(this);
Contact *contact;
if(mContacts.get(peering, contact)) return contact;
else return NULL;
}
const AddressBook::Contact *AddressBook::getContact(const Identifier &peering) const
{
Synchronize(this);
Contact *contact = NULL;
if(mContacts.get(peering, contact)) return contact;
else return NULL;
}
AddressBook::Contact *AddressBook::getContactByUniqueName(const String &uname)
{
Synchronize(this);
Contact *contact = NULL;
if(mContactsByUniqueName.get(uname, contact)) return contact;
else return NULL;
}
const AddressBook::Contact *AddressBook::getContactByUniqueName(const String &uname) const
{
Synchronize(this);
Contact *contact = NULL;
if(mContactsByUniqueName.get(uname, contact)) return contact;
else return NULL;
}
void AddressBook::getContacts(Array<AddressBook::Contact *> &array)
{
Synchronize(this);
mContactsByUniqueName.getValues(array);
Contact *self = getSelf();
if(self) array.remove(self);
int i=0;
while(i<array.size())
{
if(array[i]->isDeleted()) array.erase(i);
else ++i;
}
}
Identifier AddressBook::setSelf(const String &secret)
{
Synchronize(this);
const String tracker = Config::Get("tracker");
Contact *self = new Contact(this, userName(), userName(), tracker, secret);
Contact *tmp;
if(mContacts.get(self->peering(), tmp))
if(tmp->uniqueName() != userName())
throw Exception("a contact with the same peering already exists");
Contact *oldSelf = getSelf();
if(oldSelf)
{
unregisterContact(oldSelf);
oldSelf->copy(self);
delete self;
self = oldSelf;
}
registerContact(self);
save();
return self->peering();
}
AddressBook::Contact *AddressBook::getSelf(void)
{
Synchronize(this);
Contact *contact;
if(mContactsByUniqueName.get(userName(), contact)) return contact;
else return NULL;
}
const AddressBook::Contact *AddressBook::getSelf(void) const
{
Synchronize(this);
Contact *contact;
if(mContactsByUniqueName.get(userName(), contact)) return contact;
else return NULL;
}
void AddressBook::clear(void)
{
Synchronize(this);
mScheduler.clear(); // we make sure no task is running
for(Map<Identifier, Contact*>::iterator it = mContacts.begin();
it != mContacts.end();
++it)
{
Contact *contact = it->second;
delete contact;
}
mContacts.clear();
mContactsByUniqueName.clear();
}
void AddressBook::load(Stream &stream)
{
Synchronize(this);
Contact *contact = new Contact(this);
int i = 0;
//YamlSerializer serializer(&stream);
//while(serializer.input(*contact))
while(true)
{
// Not really clean but it protects from parse errors propagation
YamlSerializer serializer(&stream);
if(!serializer.input(*contact)) break;
Contact *oldContact = NULL;
if(mContactsByUniqueName.get(contact->uniqueName(), oldContact))
{
if(oldContact->time() >= contact->time())
{
oldContact->addAddresses(contact->addresses());
continue;
}
unregisterContact(oldContact);
if(!oldContact->isDeleted() && contact->isDeleted())
{
// Erase messages
mUser->messageQueue()->erase(contact->uniqueName());
}
oldContact->copy(contact);
std::swap(oldContact, contact);
delete oldContact;
}
registerContact(contact, i);
contact = new Contact(this);
++i;
}
delete contact;
}
void AddressBook::save(Stream &stream) const
{
Synchronize(this);
YamlSerializer serializer(&stream);
for(Map<Identifier, Contact*>::const_iterator it = mContacts.begin();
it != mContacts.end();
++it)
{
const Contact *contact = it->second;
serializer.output(*contact);
}
}
void AddressBook::save(void) const
{
Synchronize(this);
String data;
save(data);
SafeWriteFile file(mFileName);
file.write(data);
file.close();
const Contact *self = getSelf();
if(self && self->isConnected())
{
try {
Desynchronize(this);
Notification notification(data);
notification.setParameter("type", "contacts");
notification.send(self->peering());
}
catch(Exception &e)
{
LogWarn("AddressBook::Save", String("Contacts synchronization failed: ") + e.what());
}
}
}
void AddressBook::update(void)
{
Synchronize(this);
Array<Identifier> keys;
mContacts.getKeys(keys);
std::random_shuffle(keys.begin(), keys.end());
for(int i=0; i<keys.size(); ++i)
{
Contact *contact = getContact(keys[i]);
if(contact) mScheduler.schedule(contact, UpdateStep*i + UpdateStep*uniform(0., UpdateStep));
}
}
bool AddressBook::send(const Notification ¬ification)
{
Array<Identifier> keys;
SynchronizeStatement(this, mContacts.getKeys(keys));
bool success = false;
for(int i=0; i<keys.size(); ++i)
{
Contact *contact = getContact(keys[i]);
if(contact) success|= contact->send(notification);
}
return success;
}
bool AddressBook::send(const Message &message)
{
// TODO: could be more efficient
// should convert the message and use send(notification)
Array<Identifier> keys;
SynchronizeStatement(this, mContacts.getKeys(keys));
bool success = false;
for(int i=0; i<keys.size(); ++i)
{
Contact *contact = getContact(keys[i]);
if(contact) success|= contact->send(message);
}
return success;
}
void AddressBook::http(const String &prefix, Http::Request &request)
{
user()->setOnline();
try {
if(request.url.empty() || request.url == "/")
{
if(request.method == "POST")
{
try {
if(!user()->checkToken(request.post["token"], "contact"))
throw 403;
String command = request.post["command"];
if(command == "delete")
{
Synchronize(this);
String uname = request.post["argument"];
removeContact(mContactsByUniqueName.get(uname)->peering());
}
else {
String name = request.post["name"];
String secret = request.post["secret"];
// TODO: check size
if(name.empty() || secret.empty()) throw 400;
if(request.post.contains("self")) setSelf(secret);
else addContact(name, secret);
}
}
catch(const Exception &e)
{
LogWarn("AddressBook::http", e.what());
throw 400;
}
Http::Response response(request, 303);
response.headers["Location"] = prefix + "/";
response.send();
return;
}
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
Array<Contact*> contacts;
getContacts(contacts);
Contact *self = getSelf();
if(self) contacts.append(self);
JsonSerializer json(response.sock);
json.outputMapBegin();
for(int i=0; i<contacts.size(); ++i)
{
Contact *contact = contacts[i];
if(contact->isDeleted()) continue;
String name = contact->name();
String tracker = contact->tracker();
String status = contact->status();
String strPrefix = contact->urlPrefix();
MessageQueue *messageQueue = user()->messageQueue();
ConstSerializableWrapper<int> messagesWrapper(messageQueue->selectPrivate(contact->uniqueName()).unreadCount());
ConstSerializableWrapper<bool> newMessagesWrapper(messageQueue->hasNew());
SerializableMap<String, Serializable*> map;
map["name"] = &name;
map["tracker"] = &tracker;
map["status"] = &status;
map["prefix"] = &strPrefix;
map["messages"] = &messagesWrapper;
map["newmessages"] = &newMessagesWrapper;
json.outputMapElement(contact->uniqueName(), map);
}
json.outputMapEnd();
return;
}
Http::Response response(request,200);
response.send();
Html page(response.sock);
page.header("Contacts");
String token = user()->generateToken("contact");
// Personnal secret
page.openForm(prefix+"/","post");
page.openFieldset("Personal secret");
page.input("hidden", "token", token);
page.input("hidden","name",userName());
page.input("hidden","self","true");
if(getSelf()) page.text("Your personal secret is already set, but you can change it here.");
else page.text("Set the same username and the same personal secret on multiple devices to enable automatic synchronization. The longer the secret, the more secure it is.");
page.br();
page.br();
page.label("secret","Secret"); page.input("text","secret","",true); page.br();
page.label("add"); page.button("add","Set secret");
page.closeFieldset();
page.closeForm();
// Parameters that are to be sent in friend request
const String centralizedFriendSystemUrl = RAPTUREURL;
int lengthUrl = centralizedFriendSystemUrl.length();
String postrequest = "postrequest.php";
String secretgen = "secretgen.php";
String laststep = "laststep.php";
String finalize = "finalize.php";
String gcontacts = "gcontacts.php";
String tpn_id = user()->name()+"@"+user()->tracker();
String nameProfile = user()->profile()->realName();
String mailProfile = user()->profile()->eMail();
page.open("div",".box");
page.open("h2");
page.text("Add Contacts / Send invitations");
page.close("h2");
page.open("div", ".howtorequests");
page.text("In this section, you can either add your friends or send invitations to them. These invitations contain a personalized code that enable them to reach you and ensure your communications are encrypted. You will have to confirm request by pasting a code in the 'Accept Request' section.");
page.close("div");
page.open("div","invitationmethods");
page.open("span",".invitationimg");
page.image("/spy.png","Classic way","spyimg");
page.close("span");
page.open("span",".invitationimg");
page.image("/mail.png","Mail","mailimg");
page.close("span");
page.open("span",".invitationimg");
//page.openForm(centralizedFriendSystemUrl+gcontacts,"post","gmailform");
// TODO : add parmeter target in class html ?
page.raw("<form name=\"gmailform\" action=\""+centralizedFriendSystemUrl+"gcontacts.php\" method=\"post\" enctype=\"application/x-www-form-urlencoded\" target=\"_newtab\">");
page.input("hidden", "tpn_id", tpn_id);
page.image("/gmail.png","GMail","gmailimg");
page.closeForm();
page.close("span");
page.open("span",".invitationimg");
page.image("/facebook_by_benstein.png","Facebook","fbimg");
page.close("span");
page.close("div");
page.open("div","howtotext");
page.close("div");
page.close("div");
// Js globals loaded from C++
page.javascript("var centralizedFriendSystemUrl = \""+centralizedFriendSystemUrl+"\"; \n\
var nameProfile = \""+nameProfile+"\";\n\
var mailProfile = \""+mailProfile+"\";\n\
var tpnIdCookie = 'tpnIdCookie'; \n\
setCookie(tpnIdCookie,'"+tpn_id+"',365); // Keep tpn_id in a cookie\n\
var postUrl1 = \""+centralizedFriendSystemUrl+"\"+\""+postrequest+"\";\n\
var tpn_id = \""+tpn_id+"\" \n\
var prefix = \""+prefix+"\" \n\
var token = \""+token+"\" \n\
");
page.openForm(prefix+"/","post","newcontact");
page.open("div","newcontactdiv.box");
page.open("h2");
page.text("Add contact");
page.close("h2");
//page.openFieldset("New contact");
page.input("hidden", "token", token);
page.label("name","TeapotNet ID"); page.input("text","name"); page.br();
page.label("secret","Secret"); page.input("text","secret","",true); page.br();
page.label("add"); //page.button("add","Add contact");
page.raw("<input type=\"button\" name=\"add\" value=\"Add contact\">"); // No way not to submit form with input --> TODO : change in html.cpp ?
//page.closeFieldset();
page.close("div");
page.closeForm();
// TODO : add dummy form ? (check on stackoverflow says it should work fine with input outside forms)
page.open("div","sendrequest.box");
page.open("h2");
page.text("Send friend request");
page.close("h2");
page.label("mail_sender","Your Mail"); page.input("text","mail_sender"); page.br();
page.label("mail_receiver","Your friend's Mail"); page.input("text","mail_receiver"); page.br();
page.label("sendinvitation"); page.button("sendinvitation","Send invitation");
page.close("div");
page.open("div","acceptrequest.box");
page.open("h2");
page.text("Accept request");
page.close("h2");
page.open("div", ".howtorequests");
page.text("If you've received from a friend a TeapotNet code, paste it here. Your friend will automatically be added to your contacts list");
page.close("div");
page.input("text","posturl");
page.button("postfriendrequest","Go !");
page.close("div");
//page.closeForm();
// load rapture.js
page.raw("<script type=\"text/javascript\" src=\"/rapture.js\"></script>");
Array<Contact*> contacts;
getContacts(contacts);
if(!contacts.empty())
{
page.open("div",".box");
page.open("h2");
page.text("Contacts");
page.close("h2");
page.open("table",".contacts");
for(int i=0; i<contacts.size(); ++i)
{
Contact *contact = contacts[i];
if(contact->isDeleted()) continue;
String contactUrl = prefix + '/' + contact->uniqueName() + '/';
page.open("tr");
page.open("td",".name");
page.text(contact->name());
page.close("td");
page.open("td",".tracker");
page.text(String("@") + contact->tracker());
page.close("td");
page.open("td",".uname");
page.link(contact->urlPrefix(), contact->uniqueName());
page.close("td");
page.open("td",".checksum");
page.text(String(" check: ")+String::hexa(contact->peeringChecksum(),8));
page.close("td");
page.open("td",".delete");
page.image("/delete.png", "Delete");
page.closeLink();
page.close("td");
page.close("tr");
}
page.close("table");
page.close("div");
page.openForm(prefix+"/", "post", "executeForm");
page.input("hidden", "command");
page.input("hidden", "argument");
page.input("hidden", "token", token);
page.closeForm();
page.javascript("function deleteContact(uname) {\n\
if(confirm('Do you really want to delete '+uname+' ? The corresponding messages will be deleted too.')) {\n\
document.executeForm.command.value = 'delete';\n\
document.executeForm.argument.value = uname;\n\
document.executeForm.submit();\n\
}\n\
}");
page.javascript("$('td.delete').css('cursor', 'pointer').click(function(event) {\n\
event.stopPropagation();\n\
var uname = $(this).closest('tr').find('td.uname').text();\n\
deleteContact(uname);\n\
});");
}
page.footer();
return;
}
}
catch(const Exception &e)
{
LogWarn("AddressBook::http",e.what());
throw 500; // Httpd handles integer exceptions
}
throw 404;
}
void AddressBook::registerContact(Contact *contact, int ordinal)
{
Synchronize(this);
mContacts.insert(contact->peering(), contact);
mContactsByUniqueName.insert(contact->uniqueName(), contact);
if(!contact->isDeleted())
{
if(contact->isSelf()) Interface::Instance->remove("/"+userName()+"/myself/files"); // overriding Store
Interface::Instance->add(contact->urlPrefix(), contact);
mScheduler.schedule(contact, UpdateStep*ordinal + uniform(0., UpdateStep));
mScheduler.repeat(contact, UpdateInterval);
}
}
void AddressBook::unregisterContact(Contact *contact)
{
Synchronize(this);
mContacts.erase(contact->peering());
mContactsByUniqueName.erase(contact->uniqueName());
Core::Instance->unregisterPeering(contact->peering());
Interface::Instance->remove(contact->urlPrefix(), contact);
mScheduler.remove(contact);
}
bool AddressBook::publish(const Identifier &remotePeering)
{
String tracker = Config::Get("tracker");
try {
String url("http://" + tracker + "/tracker?id=" + remotePeering.toString());
List<Address> list;
Config::GetExternalAddresses(list);
String addresses;
for( List<Address>::iterator it = list.begin();
it != list.end();
++it)
{
if(!addresses.empty()) addresses+= ',';
addresses+= it->toString();
}
StringMap post;
post["instance"] = Core::Instance->getName();
post["addresses"] = addresses;
String externalPort = Config::Get("external_port");
if(!externalPort.empty() && externalPort != "auto") post["port"] = externalPort;
else post["port"] = Config::Get("port");
if(!Core::Instance->isPublicConnectable())
{
list.clear();
Core::Instance->getKnownPublicAdresses(list);
String altAddresses;
for( List<Address>::iterator it = list.begin();
it != list.end();
++it)
{
if(!altAddresses.empty()) altAddresses+= ',';
altAddresses+= it->toString();
}
post["alternate"] = altAddresses;
}
if(Http::Post(url, post) == 200)
{
SynchronizeStatement(this, mBogusTrackers.erase(tracker));
return true;
}
}
catch(const Timeout &e)
{
LogDebug("AddressBook::publish", e.what());
}
catch(const NetException &e)
{
LogDebug("AddressBook::publish", e.what());
}
catch(const std::exception &e)
{
LogWarn("AddressBook::publish", e.what());
}
SynchronizeStatement(this, mBogusTrackers.insert(tracker));
return false;
}
bool AddressBook::query(const Identifier &peering, const String &tracker, AddressMap &output, bool alternate)
{
output.clear();
String host(tracker);
if(host.empty()) host = Config::Get("tracker");
try {
String url = "http://" + host + "/tracker?id=" + peering.toString();
if(alternate) url+= "&alternate=1";
String tmp;
if(Http::Get(url, &tmp) == 200)
{
SynchronizeStatement(this, mBogusTrackers.erase(tracker));
tmp.trim();
if(tmp.empty()) return false;
YamlSerializer serializer(&tmp);
typedef SerializableMap<String, SerializableArray<Address> > content_t;
content_t content;
serializer.input(content);
for(content_t::const_iterator it = content.begin();
it != content.end();
++it)
{
const String &instance = it->first;
const Array<Address> &addrs = it->second;
for(int i=0; i<addrs.size(); ++i)
output[instance].insert(addrs[i], Time::Now());
}
return !output.empty();
}
}
catch(const Timeout &e)
{
LogDebug("AddressBook::query", e.what());
}
catch(const NetException &e)
{
LogDebug("AddressBook::query", e.what());
}
catch(const std::exception &e)
{
LogWarn("AddressBook::query", e.what());
}
SynchronizeStatement(this, mBogusTrackers.insert(tracker));
return false;
}
AddressBook::Contact::Contact( AddressBook *addressBook,
const String &uname,
const String &name,
const String &tracker,
const String &secret) :
mAddressBook(addressBook),
mUniqueName(uname),
mName(name),
mTracker(tracker),
mDeleted(false),
mFound(false),
mFirstUpdateTime(0),
mProfile(NULL)
{
Assert(addressBook != NULL);
Assert(!uname.empty());
Assert(!name.empty());
Assert(!tracker.empty());
Assert(!secret.empty());
// The secret will be salted with a XOR of the two names, as this is symmetrical
ByteString xored;
const String &a = mName;
const String &b = mAddressBook->userName();
for(size_t i=0; i<std::max(a.size(), b.size()); ++i)
{
char c = 0;
if(i < a.size()) c^= a[i];
if(i < b.size()) c^= b[i];
xored.push_back(c);
}
ByteString salt;
ByteSerializer ssalt(&salt);
// Compute secret
salt.clear();
ssalt.output(xored);
Sha512::DerivateKey(secret, salt, mSecret, Sha512::CryptRounds);
// Only half the secret (256 bits) is used to compute peerings
ByteString halfSecret(mSecret, 0, mSecret.size()/2);
// Compute peering
salt.clear();
ssalt.output("TeapotNet");
ssalt.output(mAddressBook->userName());
ssalt.output(mName);
Sha512::DerivateKey(halfSecret, salt, mPeering, Sha512::CryptRounds);
// Compute remote peering
salt.clear();
ssalt.output("TeapotNet");
ssalt.output(mName);
ssalt.output(mAddressBook->userName());
Sha512::DerivateKey(halfSecret, salt, mRemotePeering, Sha512::CryptRounds);
createProfile();
}
AddressBook::Contact::Contact(AddressBook *addressBook) :
mAddressBook(addressBook),
mDeleted(false),
mFound(false),
mFirstUpdateTime(0),
mProfile(NULL)
{
}
AddressBook::Contact::~Contact(void)
{
Interface::Instance->remove(urlPrefix(), this);
delete mProfile;
}
String AddressBook::Contact::uniqueName(void) const
{
Synchronize(mAddressBook);
return mUniqueName;
}
String AddressBook::Contact::name(void) const
{
Synchronize(mAddressBook);
return mName;
}
String AddressBook::Contact::tracker(void) const
{
Synchronize(mAddressBook);
if(mProfile) return mProfile->tracker();
else return mTracker;
}
Identifier AddressBook::Contact::peering(void) const
{
Synchronize(mAddressBook);
return mPeering;
}
Identifier AddressBook::Contact::remotePeering(void) const
{
Synchronize(mAddressBook);
return mRemotePeering;
}
Time AddressBook::Contact::time(void) const
{
Synchronize(mAddressBook);
return mTime;
}
uint32_t AddressBook::Contact::peeringChecksum(void) const
{
Synchronize(mAddressBook);
return mPeering.getDigest().checksum32() + mRemotePeering.getDigest().checksum32();
}
String AddressBook::Contact::urlPrefix(void) const
{
Synchronize(mAddressBook);
if(mUniqueName.empty()) return "";
if(isSelf()) return String("/")+mAddressBook->userName()+"/myself";
return String("/")+mAddressBook->userName()+"/contacts/"+mUniqueName;
}
ByteString AddressBook::Contact::secret(void) const
{
Synchronize(mAddressBook);
return mSecret;
}
Profile *AddressBook::Contact::profile(void) const
{
Synchronize(mAddressBook);
if(isSelf()) return mAddressBook->user()->profile();
else {
Assert(mProfile);
return mProfile;
}
}
bool AddressBook::Contact::isSelf(void) const
{
return (mUniqueName == mAddressBook->userName());
}
bool AddressBook::Contact::isFound(void) const
{
return mFound;
}
bool AddressBook::Contact::isConnected(void) const
{
Synchronize(mAddressBook);
return Core::Instance->hasPeer(mPeering);
}
bool AddressBook::Contact::isConnected(const String &instance) const
{
Synchronize(mAddressBook);
if(isSelf() && instance == Core::Instance->getName()) return true;
return Core::Instance->hasPeer(Identifier(mPeering, instance));
}
bool AddressBook::Contact::isOnline(void) const
{
Synchronize(mAddressBook);
if(isSelf() && mAddressBook->user()->isOnline()) return true;
if(!isConnected()) return false;
return !mOnlineInstances.empty();
}
String AddressBook::Contact::status(void) const
{
Synchronize(mAddressBook);
if(isSelf()) return "myself";
if(isOnline()) return "online";
else if(isConnected()) return "connected";
else if(isFound()) return "found";
else return "disconnected";
}
AddressBook::AddressMap AddressBook::Contact::addresses(void) const
{
Synchronize(mAddressBook);
return mAddrs;
}
bool AddressBook::Contact::isDeleted(void) const
{
Synchronize(mAddressBook);
return mDeleted;
}
void AddressBook::Contact::setDeleted(void)
{
Synchronize(mAddressBook);
mDeleted = true;
mTime = Time::Now();
}
void AddressBook::Contact::getInstancesNames(Array<String> &array)
{
SynchronizeStatement(mAddressBook, mAddrs.getKeys(array));
Array<String> others;
Core::Instance->getInstancesNames(peering(), others);
for(int i=0; i<others.size(); ++i)
if(!array.contains(others[i]))
array.append(others[i]);
}
bool AddressBook::Contact::addAddresses(const AddressMap &map)
{
bool changed = false;
for(AddressMap::const_iterator it = map.begin();
it != map.end();
++it)
{
Synchronize(mAddressBook);
const String &instance = it->first;
const AddressBlock &block = it->second;
AddressBlock &target = mAddrs[instance];
for(AddressBlock::const_iterator jt = block.begin();
jt != block.end();
++jt)
{
const Address &addr = jt->first;
const Time &time = jt->second;
if(!target.contains(addr) || target[addr] < time)
{
target[addr] = time;
changed = true;
}
}
}
if(changed) mAddressBook->save();
return true;
}
bool AddressBook::Contact::connectAddress(const Address &addr, const String &instance, bool save)
{
// Warning: NOT synchronized !
if(addr.isNull()) return false;
if(instance == Core::Instance->getName()) return false;
LogDebug("AddressBook::Contact", "Connecting " + instance + " on " + addr.toString() + "...");
Identifier peering(this->peering(), instance);
ByteStream *bs = NULL;
if(!Config::Get("force_http_tunnel").toBool() || !addr.isPublic() || addr.port() == 443)
{
Socket *sock = NULL;
try {
sock = new Socket(addr, 4.);
}
catch(const Exception &e)
{
sock = NULL;
LogDebug("AddressBook::Contact::connectAddress", String("Direct connection failed: ") + e.what());
}
if(sock)
{
sock->setTimeout(milliseconds(Config::Get("tpot_read_timeout").toInt()));
bs = sock;
}
}
if(!bs && addr.isPublic() && addr.port() != 443)
{
try {
bs = new HttpTunnel::Client(addr, 4.);
}
catch(const Exception &e)
{
bs = NULL;
LogDebug("AddressBook::Contact::connectAddress", String("HTTP tunnel failed: ") + e.what());
}
}
if(!bs) return false;
if(Core::Instance->addPeer(bs, addr, peering))
{
if(save)
{
SynchronizeStatement(mAddressBook, mAddrs[instance][addr] = Time::Now());
mAddressBook->save();
}
return true;
}
else {
// A node is running at this address but the user does not exist
if(save && mAddrs.contains(instance))
{
Synchronize(mAddressBook);
mAddrs[instance].erase(addr);
if(mAddrs[instance].empty())
mAddrs.erase(instance);
mAddressBook->save();
}
return false;
}
}
bool AddressBook::Contact::connectAddresses(const AddressMap &map, bool save, bool shuffle)
{
// Warning: NOT synchronized !
bool success = false;
for(AddressMap::const_iterator it = map.begin();
it != map.end();
++it)
{
const String &instance = it->first;
const AddressBlock &block = it->second;
if(instance == Core::Instance->getName()
|| mExcludedInstances.contains(instance)) continue;
// TODO: look for a better address than the already connected one
if(isConnected(instance))
{
// TODO: update time for currenly connected address
success = true;
continue;
}
Array<Address> addrs;
block.getKeys(addrs);
if(shuffle) std::random_shuffle(addrs.begin(), addrs.end());
LogDebug("AddressBook::Contact", "Connecting instance " + instance + " for " + name() + " (" + String::number(addrs.size()) + " address(es))...");
for(Array<Address>::const_reverse_iterator jt = addrs.rbegin();
jt != addrs.rend();
++jt)
{
if(connectAddress(*jt, instance, save))
{
success = true;
break;
}
}
}
return success;
}
void AddressBook::Contact::update(bool alternate)
{
// Warning: NOT synchronized !
if(isDeleted()) return;
Core::Instance->registerPeering(peering(), remotePeering(), secret(), this);
LogDebug("AddressBook::Contact", "Looking for " + uniqueName());
if(peering() != remotePeering() && Core::Instance->hasRegisteredPeering(remotePeering())) // the user is local
{
Identifier identifier(peering(), Core::Instance->getName());
if(!Core::Instance->hasPeer(identifier))
{
LogDebug("AddressBook::Contact", uniqueName() + " found locally");
Address addr("127.0.0.1", Config::Get("port"));
try {
Socket *sock = new Socket(addr);
Core::Instance->addPeer(sock, identifier);
}
catch(...)
{
LogDebug("AddressBook::Contact", "Warning: Unable to connect the local core");
}
}
}
if(!alternate)
{
if(mAddressBook->publish(remotePeering()))
LogDebug("AddressBook::Contact", "Published to tracker " + tracker() + " for " + uniqueName());
}
AddressMap newAddrs;
if(mAddressBook->query(peering(), tracker(), newAddrs, alternate))
LogDebug("AddressBook::Contact", "Queried tracker " + tracker() + " for " + uniqueName());
if(!newAddrs.empty())
{
if(!alternate) LogDebug("AddressBook::Contact", "Contact " + name() + " found (" + String::number(newAddrs.size()) + " instance(s))");
else LogDebug("AddressBook::Contact", "Alternative addresses for " + name() + " found (" + String::number(newAddrs.size()) + " instance(s))");
mFound = true;
connectAddresses(newAddrs, !alternate, alternate);
}
else if(!alternate)
{
mFound = false;
connectAddresses(addresses(), true, false);
}
{
Synchronize(mAddressBook);
AddressMap::iterator it = mAddrs.begin();
while(it != mAddrs.end())
{
const String &instance = it->first;
AddressBlock &block = it->second;
AddressBlock::iterator jt = block.begin();
while(jt != block.end())
{
if(Time::Now() - jt->second >= 3600*24*8) // 8 days
block.erase(jt++);
else jt++;
}
if(block.empty())
mAddrs.erase(it++);
else it++;
}
}
}
void AddressBook::Contact::createProfile(void)
{
if(isSelf()) return;
if(!mProfile)
{
mProfile = new Profile(mAddressBook->user(), mUniqueName, mTracker);
try {
mProfile->load();
}
catch(const Exception &e)
{
LogWarn("AddressBook::Contact", String("Unable to load profile for ") + uniqueName() + ": " + e.what());
}
}
}
void AddressBook::Contact::run(void)
{
Synchronize(mAddressBook);
if(mFirstUpdateTime == Time(0))
mFirstUpdateTime = Time::Now();
DesynchronizeStatement(mAddressBook, update(false));
if((Time::Now() - mFirstUpdateTime)*1000 >= UpdateInterval)
DesynchronizeStatement(mAddressBook, update(true));
}
void AddressBook::Contact::connected(const Identifier &peering, bool incoming)
{
// Handle the special case of symmetric peerings
if(!isSelf() && mPeering == mRemotePeering)
{
Contact *self = mAddressBook->getSelf();
// If there is no self contact, the remote instance *should* not be one of ours anyway.
if(self)
{
Notification notification(self->peering().toString());
notification.setParameter("type", "checkself");
notification.send(peering);
}
}
// Send status and profile
if(mAddressBook->user()->isOnline()) mAddressBook->user()->sendStatus(peering);
mAddressBook->user()->profile()->send(peering);
// Send secret and contacts if self
if(isSelf())
{
mAddressBook->user()->sendSecret(peering);
String data;
mAddressBook->save(data);
Notification notification(data);
notification.setParameter("type", "contacts");
notification.send(peering);
}
if(incoming)
{
MessageQueue::Selection selection = selectMessages();
int total = selection.count();
if(total > MaxChecksumDistance)
{
Message base;
if(selection.getOffset(total - MaxChecksumDistance, base))
Assert(selection.setBaseStamp(base.stamp()));
}
sendMessagesChecksum(peering, selection, 0, selection.count(), true);
}
}
void AddressBook::Contact::disconnected(const Identifier &peering)
{
mAddressBook->mScheduler.schedule(this, 10.);
SynchronizeStatement(mAddressBook, mOnlineInstances.erase(peering.getName()));
}
bool AddressBook::Contact::notification(const Identifier &peering, Notification *notification)
{
if(isDeleted()) return false;
Assert(notification);
StringMap parameters = notification->parameters();
String type;
parameters.get("type", type);
LogDebug("AddressBook::Contact", "Incoming notification from "+uniqueName()+" (type='" + type + "')");
if(type.empty() || type == "message")
{
Message message;
Assert(message.recv(*notification));
if(!isSelf())
{
message.setIncoming(!message.checkSignature(mAddressBook->user()));
if(message.isPublic() && !message.isIncoming()) message.setContact("");
else {
if(message.isPublic() && !message.contact().empty()) message.setRelayed(true);
message.setContact(uniqueName());
}
}
mAddressBook->user()->messageQueue()->add(message);
}
else if(type == "read" || type == "ack")
{
String data = notification->content();
YamlSerializer serializer(&data);
StringArray stamps;
serializer.input(stamps);
// Mark messages as read
bool privateOnly = !isSelf(); // others may not mark public messages as read
MessageQueue::Selection selection = selectMessages(privateOnly);
for(int i=0; i<stamps.size(); ++i)
selection.markRead(stamps[i]);
}
else if(type == "unread")
{
String data = notification->content();
YamlSerializer serializer(&data);
StringSet recvStamps;
serializer.input(recvStamps);
// Mark messages as read
bool privateOnly = !isSelf(); // others may not mark public messages as read
MessageQueue::Selection selection = selectMessages(privateOnly);
Array<Message> unread;
selection.getUnread(unread);
// Mark not present stamps as read
for(int i=0; i<unread.size(); ++i)
{
String stamp = unread[i].stamp();
if(recvStamps.contains(stamp)) recvStamps.erase(stamp);
else selection.markRead(stamp);
}
// Ack left stamps
if(!recvStamps.empty())
{
StringArray ackedStamps;
ackedStamps.assign(recvStamps.begin(), recvStamps.end());
String tmp;
YamlSerializer outSerializer(&tmp);
outSerializer.output(ackedStamps);
Notification notification(tmp);
notification.setParameter("type", "read");
notification.send(peering);
}
}
else if(type == "checksum")
{
int offset = 0;
int count = 0;
int total = 0;
bool recursion = false;
String base;
try {
parameters["offset"] >> offset;
parameters["count"] >> count;
parameters["total"] >> total;
parameters["recursion"] >> recursion;
if(parameters.contains("base"))
parameters["base"] >> base;
Assert(offset >= 0);
Assert(count >= 0);
Assert(offset + count <= total);
}
catch(const Exception &e)
{
throw InvalidData("checksum notification parameters: " + String(e.what()));
}
ByteString checksum;
try {
notification->content().extract(checksum);
}
catch(...)
{
throw InvalidData("checksum notification content: " + notification->content());
}
LogDebug("AddressBook::Contact", "Synchronization: Received checksum: " + String::number(offset) + ", " + String::number(count) + " (recursion " + (recursion ? "enabled" : "disabled") + ")");
MessageQueue::Selection selection = selectMessages();
if(!base.empty())
{
if(!selection.setBaseStamp(base))
LogDebug("AddressBook::Contact", "Synchronization: Base message '"+base+"' does not exist");
}
int localTotal = selection.count();
bool isLastIteration = false;
if(offset + count <= localTotal)
{
ByteString result;
selection.checksum(offset, count, result);
if(result != checksum)
{
LogDebug("AddressBook::Contact", "Synchronization: No match: " + String::number(offset) + ", " + String::number(count));
if(count == 1) // TODO
{
sendMessages(peering, selection, offset, count);
if(recursion)
{
sendMessagesChecksum(peering, selection, offset, count, false);
isLastIteration = true;
}
}
else if(recursion)
{
sendMessagesChecksum(peering, selection, offset, count/2, true);
sendMessagesChecksum(peering, selection, offset + count/2, count - count/2, true);
}
if(!recursion)
isLastIteration = true;
}
else {
LogDebug("AddressBook::Contact", "Synchronization: Match: " + String::number(offset) + ", " + String::number(count));
isLastIteration = true;
}
}
else {
if(offset == 0)
{
LogDebug("AddressBook::Contact", "Synchronization: Remote has more messages");
sendMessagesChecksum(peering, selection, 0, localTotal, true);
}
}
if(isLastIteration && offset == 0)
{
// If messages are missing remotely
if(total < localTotal)
sendMessages(peering, selection, total, localTotal - total);
sendUnread(peering);
}
}
else if(type == "checkself")
{
Identifier checkself;
try {
notification->content().extract(checkself);
}
catch(...)
{
throw InvalidData("checkself notification content: " + notification->content());
}
Contact *self = mAddressBook->getSelf();
if(self && (isSelf() != (checkself == self->peering())))
{
LogDebug("AddressBook::Contact::notification", "Remote instance belongs to us on a symmetric peering, disconnecting");
mExcludedInstances.insert(peering.getName());
return false; // disconnect
}
}
else if(type == "status")
{
Synchronize(mAddressBook);
String status = notification->content().toLower().trimmed();
if(status == "online") mOnlineInstances.insert(peering.getName());
else mOnlineInstances.erase(peering.getName());
}
else if(type == "secret")
{
if(!isSelf())
{
LogWarn("AddressBook::Contact::notification", "Received secret update from other than self, dropping");
return true;
}
ByteString secret;
try {
notification->content().extract(secret);
}
catch(...)
{
throw InvalidData("secret notification content: " + notification->content());
}
if(!parameters.contains("time"))
{
LogWarn("AddressBook::Contact::notification", "Received secret update without time, dropping");
return true;
}
Time time;
parameters["time"] >> time;
mAddressBook->user()->setSecret(secret, time);
}
else if(type == "profile" || type == "profilediff")
{
String data = notification->content();
YamlSerializer serializer(&data);
Profile *p = profile();
Time time;
if(parameters.contains("time")) parameters["time"] >> time;
else if(type != "profilediff")
{
LogWarn("AddressBook::Contact::notification", "Received profile update without time, dropping");
return true;
}
if(time > p->time())
{
Synchronize(p);
if(type != "profilediff") p->clear();
p->deserialize(serializer);
p->save();
}
}
else if(type == "contacts")
{
if(!isSelf())
{
LogWarn("AddressBook::Contact::notification", "Received contacts update from other than self, dropping");
return true;
}
// DO NOT synchronize here, as the contact could disappear during load
String data = notification->content();
mAddressBook->load(data);
}
else if(type == "text")
{
LogDebug("AddressBook::Contact", "Got deprecated notification with type 'text'");
}
else LogDebug("AddressBook::Contact", "Unknown notification type '" + type + "'");
return true;
}
MessageQueue::Selection AddressBook::Contact::selectMessages(bool privateOnly) const
{
MessageQueue *messageQueue = mAddressBook->user()->messageQueue();
String uname;
if(!isSelf()) uname = uniqueName();
if(!privateOnly) return messageQueue->select(uname);
else return messageQueue->selectPrivate(uname);
}
void AddressBook::Contact::sendMessages(const Identifier &peering, const MessageQueue::Selection &selection, int offset, int count) const
{
if(!count) return;
LogDebug("AddressBook::Contact", "Synchronization: Sending messages: " + String::number(offset) + ", " + String::number(count));
Array<Message> messages;
selection.getRange(offset, count, messages);
for(int i=0; i<messages.size(); ++i)
messages[i].send(peering);
}
void AddressBook::Contact::sendMessagesChecksum(const Identifier &peering, const MessageQueue::Selection &selection, int offset, int count, bool recursion) const
{
int total = selection.count();
offset = bounds(offset, 0, total);
count = bounds(count, 0, total - offset);
LogDebug("AddressBook::Contact", "Synchronization: Sending checksum: " + String::number(offset) + ", " + String::number(count) + " (recursion " + (recursion ? "enabled" : "disabled") + ")");
ByteString result;
selection.checksum(offset, count, result);
StringMap parameters;
parameters["type"] << "checksum";
parameters["offset"] << offset;
parameters["count"] << count;
parameters["total"] << total;
parameters["recursion"] << recursion;
String base = selection.baseStamp();
if(!base.empty()) parameters["base"] << base;
Notification notification(result.toString());
notification.setParameters(parameters);
notification.send(peering);
}
void AddressBook::Contact::sendUnread(const Identifier &peering) const
{
bool privateOnly = !isSelf();
MessageQueue::Selection selection = selectMessages(privateOnly);
StringArray unreadStamps;
selection.getUnreadStamps(unreadStamps);
String tmp;
YamlSerializer serializer(&tmp);
serializer.output(unreadStamps);
Notification notification(tmp);
notification.setParameter("type", "unread");
notification.send(peering);
}
bool AddressBook::Contact::request(const Identifier &peering, Request *request)
{
Assert(request);
if(!mDeleted) request->execute(mAddressBook->user(), isSelf());
else request->executeDummy();
return true;
}
bool AddressBook::Contact::send(const Notification ¬ification)
{
return notification.send(peering());
}
bool AddressBook::Contact::send(const Message &message)
{
return message.send(peering());
}
void AddressBook::Contact::http(const String &prefix, Http::Request &request)
{
mAddressBook->user()->setOnline();
try {
if(request.url.empty() || request.url == "/")
{
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.sock);
String strName = name();
String strTracker = tracker();
String strStatus = status();
MessageQueue *messageQueue = mAddressBook->user()->messageQueue();
ConstSerializableWrapper<int> messagesWrapper(messageQueue->selectPrivate(uniqueName()).unreadCount());
ConstSerializableWrapper<bool> newMessagesWrapper(messageQueue->hasNew());
Array<String> instances;
getInstancesNames(instances);
StringMap instancesMap;
for(int i=0; i<instances.size(); ++i)
{
if(isConnected(instances[i])) instancesMap[instances[i]] = "connected";
else instancesMap[instances[i]] = "disconnected";
}
SerializableMap<String, Serializable*> map;
map["name"] = &strName;
map["tracker"] = &strTracker;
map["status"] = &strStatus;
map["messages"] = &messagesWrapper;
map["newmessages"] = &newMessagesWrapper;
map["instances"] = &instancesMap;
json.output(map);
return;
}
Http::Response response(request,200);
response.send();
Html page(response.sock);
if(isSelf()) page.header("Myself");
else {
page.header("Contact: "+name());
page.open("div", "topmenu");
page.span(status().capitalized(), "status.button");
page.close("div");
}
// TODO: insert here profile infos
page.open("div",".box");
page.open("table", ".menu");
page.open("tr");
page.open("td");
page.openLink(prefix + "/files/");
page.image("/icon_files.png", "Files", ".bigicon");
page.closeLink();
page.close("td");
page.open("td", ".title");
page.text("Files");
page.close("td");
page.close("tr");
page.open("tr");
page.open("td");
page.openLink(prefix + "/search/");
page.image("/icon_search.png", "Search", ".bigicon");
page.closeLink();
page.close("td");
page.open("td", ".title");
page.text("Search");
page.close("td");
page.close("tr");
page.open("tr");
page.open("td");
page.openLink(profile()->urlPrefix());
page.image("/icon_profile.png", "Profile", ".bigicon");
page.closeLink();
page.close("td");
page.open("td", ".title");
page.text("Profile");
page.close("td");
page.close("tr");
if(!isSelf())
{
page.open("tr");
page.open("td");
page.openLink(prefix + "/chat/");
page.image("/icon_chat.png", "Chat", ".bigicon");
page.closeLink();
page.close("td");
page.open("td",".title");
page.text("Chat");
page.span("", "messagescount.messagescount");
page.close("td");
page.close("tr");
}
page.close("table");
page.close("div");
page.open("div",".box");
page.open("h2");
page.text("Instances");
page.close("h2");
page.open("table", "instances");
page.close("table");
page.close("div");
unsigned refreshPeriod = 5000;
page.javascript("setCallback(\""+prefix+"/?json\", "+String::number(refreshPeriod)+", function(info) {\n\
transition($('#status'), info.status.capitalize());\n\
$('#status').removeClass().addClass('button').addClass(info.status);\n\
var msg = '';\n\
if(info.messages != 0) msg = ' ('+info.messages+')';\n\
transition($('#messagescount'), msg);\n\
$('#instances').empty();\n\
if($.isEmptyObject(info.instances)) $('#instances').text('No connected instance');\n\
else $.each(info.instances, function(instance, status) {\n\
$('#instances').append($('<tr>')\n\
.addClass(status)\n\
.append($('<td>').addClass('name').text(instance))\n\
.append($('<td>').addClass('status').text(status.capitalize())));\n\
});\n\
});");
// Recent files
page.open("div",".box");
page.open("h2");
page.text("Recent files");
page.close("h2");
page.div("", "recent");
page.close("div");
int maxAge = 60*60*24*7; // 7 days
int count = 20;
page.javascript("listDirectory('"+prefix+"/search?json&maxage="+String::number(maxAge)+"&count="+String::number(count)+"','#recent',false);");
page.footer();
return;
}
else {
String url = request.url;
String directory = url;
directory.ignore(); // remove first '/'
url = "/" + directory.cut('/');
if(directory.empty()) throw 404;
if(request.get.contains("play"))
{
String host;
if(!request.headers.get("Host", host))
host = String("localhost:") + Config::Get("interface_port");
Http::Response response(request, 200);
response.headers["Content-Disposition"] = "attachment; filename=\"stream.m3u\"";
response.headers["Content-Type"] = "audio/x-mpegurl";
response.send();
String link = "http://" + host + prefix + request.url + "?file=1";
String instance;
if(request.get.get("instance", instance))
link+= "&instance=" + instance;
response.sock->writeLine("#EXTM3U");
response.sock->writeLine(String("#EXTINF:-1, ") + APPNAME + " stream");
response.sock->writeLine(link);
return;
}
if(directory == "files")
{
String target(url);
Assert(!target.empty());
if(request.get.contains("json") || request.get.contains("playlist"))
{
// Query resources
Resource::Query query(mAddressBook->user()->store(), target);
query.setFromSelf(isSelf());
SerializableSet<Resource> resources;
bool success = query.submitRemote(resources, peering());
if(isSelf()) success|= query.submitLocal(resources);
if(!success) throw 404;
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.sock);
json.output(resources);
}
else {
Http::Response response(request, 200);
response.headers["Content-Disposition"] = "attachment; filename=\"playlist.m3u\"";
response.headers["Content-Type"] = "audio/x-mpegurl";
response.send();
String host;
request.headers.get("Host", host);
Resource::CreatePlaylist(resources, response.sock, host);
}
return;
}
// if it seems to be a file
if(target[target.size()-1] != '/')
{
String instance;
request.get.get("instance", instance);
Identifier instancePeering(peering());
if(!instancePeering.empty()) instancePeering.setName(instance);
Resource resource(instancePeering, url, mAddressBook->user()->store());
try {
resource.fetch(isSelf()); // we might find a better way to access it
}
catch(const Exception &e)
{
LogWarn("AddressBook::Contact::http", String("Resource lookup failed: ") + e.what());
throw 404;
}
// redirect if it's a directory
if(resource.isDirectory())
{
if(request.get.contains("download"))
throw 404;
Http::Response response(request, 301); // Moved permanently
response.headers["Location"] = prefix + request.url + '/';
response.send();
return;
}
// Get range
int64_t rangeBegin = 0;
int64_t rangeEnd = 0;
bool hasRange = request.extractRange(rangeBegin, rangeEnd, resource.size());
int64_t rangeSize = rangeEnd - rangeBegin;
// Get resource accessor
Resource::Accessor *accessor = resource.accessor();
if(!accessor) throw 404;
// Forge HTTP response header
Http::Response response(request, 200);
if(!hasRange) response.headers["Content-SHA512"] << resource.digest();
response.headers["Content-Length"] << rangeSize;
response.headers["Content-Name"] = resource.name();
response.headers["Last-Modified"] = resource.time().toHttpDate();
response.headers["Accept-Ranges"] = "bytes";
if(request.get.contains("download"))
{
response.headers["Content-Disposition"] = "attachment; filename=\"" + resource.name() + "\"";
response.headers["Content-Type"] = "application/octet-stream";
}
else {
response.headers["Content-Disposition"] = "inline; filename=\"" + resource.name() + "\"";
response.headers["Content-Type"] = Mime::GetType(resource.name());
}
response.send();
if(request.method == "HEAD") return;
try {
// Launch transfer
if(hasRange) accessor->seekRead(rangeBegin);
accessor->readBinary(*response.sock, rangeSize); // let's go !
}
catch(const NetException &e)
{
return; // nothing to do
}
catch(const Exception &e)
{
LogWarn("Interface::process", String("Error during file transfer: ") + e.what());
}
}
else {
Http::Response response(request, 200);
response.send();
Html page(response.sock);
if(target == "/") page.header(name()+": Browse files");
else page.header(name()+": "+target.substr(1));
page.open("div","topmenu");
if(!isSelf()) page.span(status().capitalized(), "status.button");
page.link(prefix+"/search/","Search files",".button");
page.link(prefix+request.url+"?playlist","Play all",".button");
page.close("div");
unsigned refreshPeriod = 5000;
page.javascript("setCallback(\""+prefix+"/?json\", "+String::number(refreshPeriod)+", function(info) {\n\
transition($('#status'), info.status.capitalize());\n\
$('#status').removeClass().addClass('button').addClass(info.status);\n\
if(info.newmessages) playMessageSound();\n\
});");
page.div("","list.box");
page.javascript("listDirectory('"+prefix+request.url+"?json','#list',true);");
page.footer();
}
return;
}
else if(directory == "search")
{
if(url != "/") throw 404;
String match;
if(!request.post.get("query", match))
request.get.get("query", match);
match.trim();
if(request.get.contains("json") || request.get.contains("playlist"))
{
String tmp;
int minAge = 0;
int maxAge = 0;
int count = 0;
if(request.get.get("minage", tmp)) tmp >> minAge;
if(request.get.get("maxage", tmp)) tmp >> maxAge;
if(request.get.get("count", tmp)) tmp >> count;
if(match.empty() && maxAge <= 0) throw 400;
Resource::Query query(mAddressBook->user()->store());
if(isSelf()) query.setFromSelf(isSelf());
if(!match.empty()) query.setMatch(match);
if(minAge > 0) query.setMinAge(minAge);
if(maxAge > 0) query.setMaxAge(maxAge);
if(count > 0) query.setLimit(count);
SerializableSet<Resource> resources;
bool success = query.submitRemote(resources, peering());
if(isSelf()) success|= query.submitLocal(resources);
if(!success) throw 404;
if(request.get.contains("json"))
{
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.sock);
json.output(resources);
}
else {
Http::Response response(request, 200);
response.headers["Content-Disposition"] = "attachment; filename=\"playlist.m3u\"";
response.headers["Content-Type"] = "audio/x-mpegurl";
response.send();
String host;
request.headers.get("Host", host);
Resource::CreatePlaylist(resources, response.sock, host);
}
return;
}
Http::Response response(request, 200);
response.send();
Html page(response.sock);
if(match.empty()) page.header(name() + ": Search");
else page.header(name() + ": Searching " + match);
page.open("div","topmenu");
if(!isSelf()) page.span(status().capitalized(), "status.button");
page.openForm(prefix + "/search", "post", "searchForm");
page.input("text", "query", match);
page.button("search","Search");
page.closeForm();
page.javascript("$(document).ready(function() { document.searchForm.query.focus(); });");
if(!match.empty()) page.link(prefix+request.url+"?query="+match.urlEncode()+"&playlist","Play all",".button");
page.close("div");
unsigned refreshPeriod = 5000;
page.javascript("setCallback(\""+prefix+"/?json\", "+String::number(refreshPeriod)+", function(info) {\n\
transition($('#status'), info.status.capitalize());\n\
$('#status').removeClass().addClass('button').addClass(info.status);\n\
if(info.newmessages) playMessageSound();\n\
});");
if(!match.empty())
{
page.div("", "list.box");
page.javascript("listDirectory('"+prefix+request.url+"?query="+match.urlEncode()+"&json','#list');");
}
page.footer();
return;
}
else if(directory == "avatar")
{
Http::Response response(request, 303); // See other
response.headers["Location"] = profile()->avatarUrl();
response.send();
return;
}
else if(directory == "chat")
{
if(isSelf()) throw 404;
Http::Response response(request, 301); // Moved permanently
response.headers["Location"] = mAddressBook->user()->urlPrefix() + "/messages/" + uniqueName().urlEncode() + "/";
response.send();
return;
}
}
}
catch(const NetException &e)
{
throw;
}
catch(const Exception &e)
{
LogWarn("AddressBook::Contact::http", e.what());
throw 500;
}
throw 404;
}
void AddressBook::Contact::copy(const AddressBook::Contact *contact)
{
Synchronize(mAddressBook);
Assert(contact);
mUniqueName = contact->mUniqueName;
mName = contact->mName;
mTracker = contact->mTracker;
mSecret = contact->mSecret;
mPeering = contact->mPeering;
mRemotePeering = contact->mRemotePeering;
mTime = contact->mTime;
mDeleted = contact->mDeleted;
addAddresses(contact->addresses());
}
void AddressBook::Contact::serialize(Serializer &s) const
{
Synchronize(mAddressBook);
StringMap map;
map["uname"] << mUniqueName;
map["name"] << mName;
map["tracker"] << tracker();
map["secret"] << mSecret;
map["peering"] << mPeering;
map["remote"] << mRemotePeering;
map["time"] << mTime;
map["deleted"] << mDeleted;
s.outputMapBegin(2);
s.outputMapElement(String("info"),map);
s.outputMapElement(String("addrs"),mAddrs);
s.outputMapEnd();
}
bool AddressBook::Contact::deserialize(Serializer &s)
{
Synchronize(mAddressBook);
mUniqueName.clear();
mName.clear();
mTracker.clear();
mSecret.clear();
mPeering.clear();
mRemotePeering.clear();
mDeleted = false;
mTime = Time::Now();
StringMap map;
String key;
AssertIO(s.inputMapBegin());
AssertIO(s.inputMapElement(key, map) && key == "info");
AssertIO(s.inputMapElement(key, mAddrs) && key == "addrs");
map["uname"] >> mUniqueName;
map["name"] >> mName;
map["tracker"] >> mTracker;
map["secret"] >> mSecret;
map["peering"] >> mPeering;
map["remote"] >> mRemotePeering;
if(map.contains("time"))
{
map["time"] >> mTime;
mTime = std::min(mTime, Time::Now());
}
if(map.contains("deleted"))
{
map["deleted"] >> mDeleted;
}
// TODO: checks
mFound = false;
createProfile();
return true;
}
bool AddressBook::Contact::isInlineSerializable(void) const
{
return false;
}
}
|
// @(#)root/tree:$Id$
// Author: Rene Brun 12/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TTree //
// //
// A TTree object has a header with a name and a title.
// It consists of a list of independent branches (TBranch). Each branch
// has its own definition and list of buffers. Branch buffers may be
// automatically written to disk or kept in memory until the Tree attribute
// fMaxVirtualSize is reached. Variables of one branch are written to the
// same buffer. A branch buffer is automatically compressed if the file
// compression attribute is set (default).
//
// Branches may be written to different files (see TBranch::SetFile).
//
// The ROOT user can decide to make one single branch and serialize one
// object into one single I/O buffer or to make several branches.
// Making one single branch and one single buffer can be the right choice
// when one wants to process only a subset of all entries in the tree.
// (you know for example the list of entry numbers you want to process).
// Making several branches is particularly interesting in the data analysis
// phase, when one wants to histogram some attributes of an object (entry)
// without reading all the attributes.
//
// ==> TTree *tree = new TTree(name, title)
// Creates a Tree with name and title.
//
// Various kinds of branches can be added to a tree:
//
// ==> Case A
// ======
// TBranch *branch = tree->Branch(branchname, address, leaflist, bufsize)
// * address is the address of the first item of a structure
// * leaflist is the concatenation of all the variable names and types
// separated by a colon character :
// The variable name and the variable type are separated by a slash (/).
// The variable type may be 0,1 or 2 characters. If no type is given,
// the type of the variable is assumed to be the same as the previous
// variable. If the first variable does not have a type, it is assumed
// of type F by default. The list of currently supported types is given below:
// - C : a character string terminated by the 0 character
// - B : an 8 bit signed integer (Char_t)
// - b : an 8 bit unsigned integer (UChar_t)
// - S : a 16 bit signed integer (Short_t)
// - s : a 16 bit unsigned integer (UShort_t)
// - I : a 32 bit signed integer (Int_t)
// - i : a 32 bit unsigned integer (UInt_t)
// - F : a 32 bit floating point (Float_t)
// - D : a 64 bit floating point (Double_t)
// - L : a 64 bit signed integer (Long64_t)
// - l : a 64 bit unsigned integer (ULong64_t)
// - O : a boolean (Bool_t)
// * If the address points to a single numerical variable, the leaflist is optional:
// int value;
// tree->Branch(branchname, &value);
// * If the address points to more than one numerical variable, we strongly recommend
// that the variable be sorted in decreasing order of size. Any other order will
// result in a non-portable (even between CINT and compiled code on the platform)
// TTree (i.e. you will not be able to read it back on a platform with a different
// padding strategy).
//
// ==> Case B
// ======
// TBranch *branch = tree->Branch(branchname, &p_object, bufsize, splitlevel)/
// TBranch *branch = tree->Branch(branchname, className, &p_object, bufsize, splitlevel)
// * p_object is a pointer to an object.
// * If className is not specified, Branch uses the type of p_object to determine the
// type of the object.
// * If className is used to specify explicitly the object type, the className must
// be of a type related to the one pointed to by the pointer. It should be either
// a parent or derived class.
// * if splitlevel=0, the object is serialized in the branch buffer.
// * if splitlevel=1 (default), this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// the mechanism described in case C is applied to this array.
// * if splitlevel=2 ,this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// it is processed as a TObject*, only one branch.
//
// Note: The pointer whose address is passed to TTree::Branch must not
// be destroyed (i.e. go out of scope) until the TTree is deleted or
// TTree::ResetBranchAddress is called.
//
// Note: The pointer p_object must be initialized before calling TTree::Branch
// Do either:
// MyDataClass* p_object = 0;
// tree->Branch(branchname, &p_object);
// Or
// MyDataClass* p_object = new MyDataClass;
// tree->Branch(branchname, &p_object);
//
// ==> Case C
// ======
// MyClass object;
// TBranch *branch = tree->Branch(branchname, &object, bufsize, splitlevel)
//
// Note: The 2nd parameter must be the address of a valid object.
// The object must not be destroyed (i.e. be deleted) until the TTree
// is deleted or TTree::ResetBranchAddress is called.
//
// * if splitlevel=0, the object is serialized in the branch buffer.
// * if splitlevel=1 (default), this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// the mechanism described in case C is applied to this array.
// * if splitlevel=2 ,this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// it is processed as a TObject*, only one branch.
//
// ==> Case D
// ======
// TBranch *branch = tree->Branch(branchname,clonesarray, bufsize, splitlevel)
// clonesarray is the address of a pointer to a TClonesArray.
// The TClonesArray is a direct access list of objects of the same class.
// For example, if the TClonesArray is an array of TTrack objects,
// this function will create one subbranch for each data member of
// the object TTrack.
//
// ==> Case E
// ======
// TBranch *branch = tree->Branch( branchname, STLcollection, buffsize, splitlevel);
// STLcollection is the address of a pointer to std::vector, std::list,
// std::deque, std::set or std::multiset containing pointers to objects.
// If the splitlevel is a value bigger than 100 then the collection
// will be written in split mode. Ie. if it contains objects of any
// types deriving from TTrack this function will sort the objects
// basing on their type and store them in separate branches in split
// mode.
//
// ==> branch->SetAddress(Void *address)
// In case of dynamic structures changing with each entry for example, one must
// redefine the branch address before filling the branch again.
// This is done via the TBranch::SetAddress member function.
//
// ==> tree->Fill()
// loops on all defined branches and for each branch invokes the Fill function.
//
// See also the class TNtuple (a simple Tree with branches of floats)
//
// Adding a Branch to an Existing Tree
// ===================================
// You may want to add a branch to an existing tree. For example,
// if one variable in the tree was computed with a certain algorithm,
// you may want to try another algorithm and compare the results.
// One solution is to add a new branch, fill it, and save the tree.
// The code below adds a simple branch to an existing tree.
// Note the kOverwrite option in the Write method, it overwrites the
// existing tree. If it is not specified, two copies of the tree headers
// are saved.
//
// void tree3AddBranch(){
// TFile f("tree3.root", "update");
//
// Float_t new_v;
// TTree *t3 = (TTree*)f->Get("t3");
// TBranch *newBranch = t3->Branch("new_v", &new_v, "new_v/F");
//
// //read the number of entries in the t3
// Long64_t nentries = t3->GetEntries();
//
// for (Long64_t i = 0; i < nentries; i++){
// new_v= gRandom->Gaus(0, 1);
// newBranch->Fill();
// }
// // save only the new version of the tree
// t3->Write("", TObject::kOverwrite);
// }
// Adding a branch is often not possible because the tree is in a read-only
// file and you do not have permission to save the modified tree with the
// new branch. Even if you do have the permission, you risk losing the
// original tree with an unsuccessful attempt to save the modification.
// Since trees are usually large, adding a branch could extend it over the
// 2GB limit. In this case, the attempt to write the tree fails, and the
// original data is erased.
// In addition, adding a branch to a tree enlarges the tree and increases
// the amount of memory needed to read an entry, and therefore decreases
// the performance.
//
// For these reasons, ROOT offers the concept of friends for trees (and chains).
// We encourage you to use TTree::AddFriend rather than adding a branch manually.
//
//Begin_Html
/*
<img src="gif/tree_layout.gif">
*/
//End_Html
// =============================================================================
//______________________________________________________________________________
//*-*-*-*-*-*-*A simple example with histograms and a tree*-*-*-*-*-*-*-*-*-*
//*-* ===========================================
//
// This program creates :
// - a one dimensional histogram
// - a two dimensional histogram
// - a profile histogram
// - a tree
//
// These objects are filled with some random numbers and saved on a file.
//
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//
// #include "TFile.h"
// #include "TH1.h"
// #include "TH2.h"
// #include "TProfile.h"
// #include "TRandom.h"
// #include "TTree.h"
//
//
// //______________________________________________________________________________
// main(int argc, char **argv)
// {
// // Create a new ROOT binary machine independent file.
// // Note that this file may contain any kind of ROOT objects, histograms,trees
// // pictures, graphics objects, detector geometries, tracks, events, etc..
// // This file is now becoming the current directory.
// TFile hfile("htree.root","RECREATE","Demo ROOT file with histograms & trees");
//
// // Create some histograms and a profile histogram
// TH1F *hpx = new TH1F("hpx","This is the px distribution",100,-4,4);
// TH2F *hpxpy = new TH2F("hpxpy","py ps px",40,-4,4,40,-4,4);
// TProfile *hprof = new TProfile("hprof","Profile of pz versus px",100,-4,4,0,20);
//
// // Define some simple structures
// typedef struct {Float_t x,y,z;} POINT;
// typedef struct {
// Int_t ntrack,nseg,nvertex;
// UInt_t flag;
// Float_t temperature;
// } EVENTN;
// static POINT point;
// static EVENTN eventn;
//
// // Create a ROOT Tree
// TTree *tree = new TTree("T","An example of ROOT tree with a few branches");
// tree->Branch("point",&point,"x:y:z");
// tree->Branch("eventn",&eventn,"ntrack/I:nseg:nvertex:flag/i:temperature/F");
// tree->Branch("hpx","TH1F",&hpx,128000,0);
//
// Float_t px,py,pz;
// static Float_t p[3];
//
// //--------------------Here we start a loop on 1000 events
// for ( Int_t i=0; i<1000; i++) {
// gRandom->Rannor(px,py);
// pz = px*px + py*py;
// Float_t random = gRandom->::Rndm(1);
//
// // Fill histograms
// hpx->Fill(px);
// hpxpy->Fill(px,py,1);
// hprof->Fill(px,pz,1);
//
// // Fill structures
// p[0] = px;
// p[1] = py;
// p[2] = pz;
// point.x = 10*(random-1);;
// point.y = 5*random;
// point.z = 20*random;
// eventn.ntrack = Int_t(100*random);
// eventn.nseg = Int_t(2*eventn.ntrack);
// eventn.nvertex = 1;
// eventn.flag = Int_t(random+0.5);
// eventn.temperature = 20+random;
//
// // Fill the tree. For each event, save the 2 structures and 3 objects
// // In this simple example, the objects hpx, hprof and hpxpy are slightly
// // different from event to event. We expect a big compression factor!
// tree->Fill();
// }
// //--------------End of the loop
//
// tree->Print();
//
// // Save all objects in this file
// hfile.Write();
//
// // Close the file. Note that this is automatically done when you leave
// // the application.
// hfile.Close();
//
// return 0;
// }
// //
//////////////////////////////////////////////////////////////////////////
#include "RConfig.h"
#include "TTree.h"
#include "TArrayC.h"
#include "TBufferFile.h"
#include "TBaseClass.h"
#include "TBasket.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TBranchRef.h"
#include "TBrowser.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TClonesArray.h"
#include "TCut.h"
#include "TDataMember.h"
#include "TDataType.h"
#include "TDirectory.h"
#include "TError.h"
#include "TEntryList.h"
#include "TEventList.h"
#include "TFile.h"
#include "TFolder.h"
#include "TFriendElement.h"
#include "TInterpreter.h"
#include "TLeaf.h"
#include "TLeafB.h"
#include "TLeafC.h"
#include "TLeafD.h"
#include "TLeafElement.h"
#include "TLeafF.h"
#include "TLeafI.h"
#include "TLeafL.h"
#include "TLeafObject.h"
#include "TLeafS.h"
#include "TList.h"
#include "TMath.h"
#include "TROOT.h"
#include "TRealData.h"
#include "TRegexp.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
#include "TStyle.h"
#include "TSystem.h"
#include "TTreeCloner.h"
#include "TTreeCache.h"
#include "TTreeCacheUnzip.h"
#include "TVirtualCollectionProxy.h"
#include "TEmulatedCollectionProxy.h"
#include "TVirtualFitter.h"
#include "TVirtualIndex.h"
#include "TVirtualPad.h"
#include "TBranchSTL.h"
#include "TSchemaRuleSet.h"
#include <cstddef>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
Long64_t TTree::fgMaxTreeSize = 100000000000LL;
TTree* gTree;
ClassImp(TTree)
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
static char DataTypeToChar(EDataType datatype)
{
// Return the leaflist 'char' for a given datatype.
switch(datatype) {
case kChar_t: return 'B';
case kUChar_t: return 'b';
case kBool_t: return 'O';
case kShort_t: return 'S';
case kUShort_t: return 's';
case kCounter:
case kInt_t: return 'I';
case kUInt_t: return 'i';
case kDouble_t:
case kDouble32_t: return 'D';
case kFloat_t:
case kFloat16_t: return 'F';
case kLong_t: return 0; // unsupported
case kULong_t: return 0; // unsupported?
case kchar: return 0; // unsupported
case kLong64_t: return 'L';
case kULong64_t: return 'l';
case kCharStar: return 'C';
case kBits: return 0; //unsupported
case kOther_t:
case kNoType_t:
default:
return 0;
}
return 0;
}
//______________________________________________________________________________
// Helper class to prevent infinite recursion in the usage of TTree Friends.
//______________________________________________________________________________
TTree::TFriendLock::TFriendLock(TTree* tree, UInt_t methodbit)
: fTree(tree)
{
// Record in tree that it has been used while recursively looks through the friends.
// We could also add some code to acquire an actual
// lock to prevent multi-thread issues
fMethodBit = methodbit;
if (fTree) {
fPrevious = fTree->fFriendLockStatus & fMethodBit;
fTree->fFriendLockStatus |= fMethodBit;
} else {
fPrevious = 0;
}
}
//______________________________________________________________________________
TTree::TFriendLock::TFriendLock(const TFriendLock& tfl) :
fTree(tfl.fTree),
fMethodBit(tfl.fMethodBit),
fPrevious(tfl.fPrevious)
{
//copy constructor
}
//______________________________________________________________________________
TTree::TFriendLock& TTree::TFriendLock::operator=(const TTree::TFriendLock& tfl)
{
//assignement operator
if(this!=&tfl) {
fTree=tfl.fTree;
fMethodBit=tfl.fMethodBit;
fPrevious=tfl.fPrevious;
}
return *this;
}
//______________________________________________________________________________
TTree::TFriendLock::~TFriendLock()
{
// Restore the state of tree the same as before we set the lock.
if (fTree) {
if (!fPrevious) {
fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
}
}
}
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
//______________________________________________________________________________
TTree::TTree()
: TNamed()
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(0)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
{
// Default constructor and I/O constructor.
//
// Note: We do *not* insert ourself into the current directory.
//
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
}
//______________________________________________________________________________
TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */)
: TNamed(name, title)
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(0)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
{
// Normal tree constructor.
//
// The tree is created in the current directory.
// Use the various functions Branch below to add branches to this tree.
//
// If the first character of title is a "/", the function assumes a folder name.
// In this case, it creates automatically branches following the folder hierarchy.
// splitlevel may be used in this case to control the split level.
// TAttLine state.
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
// TAttFill state.
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
// TAttMarkerState.
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
// Insert ourself into the current directory.
// FIXME: This is very annoying behaviour, we should
// be able to choose to not do this like we
// can with a histogram.
fDirectory = gDirectory;
fDirectory->Append(this);
// We become the current tree.
gTree = this;
// If title starts with "/" and is a valid folder name, a superbranch
// is created.
// FIXME: Why?
if (strlen(title) > 2) {
if (title[0] == '/') {
Branch(title+1,32000,splitlevel);
}
}
}
//______________________________________________________________________________
TTree::~TTree()
{
// Destructor.
if (fDirectory) {
// We are in a directory, which may possibly be a file.
if (fDirectory->GetList()) {
// Remove us from the directory listing.
fDirectory->Remove(this);
}
//delete the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
if (file) {
TFileCacheRead *pf = file->GetCacheRead();
if (pf && pf->InheritsFrom(TTreeCache::Class())) {
TTreeCache *tpf = (TTreeCache*)pf;
if (tpf->GetOwner() == this) {
delete tpf;
tpf = 0;
file->SetCacheRead(0);
}
}
}
}
// We don't own the leaves in fLeaves, the branches do.
fLeaves.Clear();
// I'm ready to destroy any objects allocated by
// SetAddress() by my branches. If I have clones,
// tell them to zero their pointers to this shared
// memory.
if (fClones && fClones->GetEntries()) {
// I have clones.
// I am about to delete the objects created by
// SetAddress() which we are sharing, so tell
// the clones to release their pointers to them.
for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
TTree* clone = (TTree*) lnk->GetObject();
// clone->ResetBranchAddresses();
// Reset only the branch we have set the address of.
CopyAddresses(clone,kTRUE);
}
}
// Get rid of our branches, note that this will also release
// any memory allocated by TBranchElement::SetAddress().
fBranches.Delete();
// FIXME: We must consider what to do with the reset of these if we are a clone.
delete fPlayer;
fPlayer = 0;
if (fFriends) {
fFriends->Delete();
delete fFriends;
fFriends = 0;
}
if (fAliases) {
fAliases->Delete();
delete fAliases;
fAliases = 0;
}
if (fUserInfo) {
fUserInfo->Delete();
delete fUserInfo;
fUserInfo = 0;
}
if (fClones) {
// Clone trees should no longer be removed from fClones when they are deleted.
gROOT->GetListOfCleanups()->Remove(fClones);
// Note: fClones does not own its content.
delete fClones;
fClones = 0;
}
if (fEntryList) {
if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==0) {
// Delete the entry list if it is marked to be deleted and it is not also
// owned by a directory. (Otherwise we would need to make sure that a
// TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
delete fEntryList;
fEntryList=0;
}
}
delete fTreeIndex;
fTreeIndex = 0;
delete fBranchRef;
fBranchRef = 0;
// Must be done after the destruction of friends.
// Note: We do *not* own our directory.
fDirectory = 0;
}
//______________________________________________________________________________
void TTree::AddBranchToCache(const char*bname, Bool_t subbranches)
{
// Add branch with name bname to the Tree cache.
// If bname="*" all branches are added to the cache.
// if subbranches is true all the branches of the subbranches are
// also put to the cache.
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->AddBranch(bname,subbranches);
}
//______________________________________________________________________________
void TTree::AddBranchToCache(TBranch *b, Bool_t subbranches)
{
// Add branch b to the Tree cache.
// if subbranches is true all the branches of the subbranches are
// also put to the cache.
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->AddBranch(b,subbranches);
}
//______________________________________________________________________________
void TTree::AddClone(TTree* clone)
{
// Add a cloned tree to our list of trees to be notified whenever we change
// our branch addresses or when we are deleted.
if (!fClones) {
fClones = new TList();
fClones->SetOwner(false);
// So that the clones are automatically removed from the list when
// they are deleted.
gROOT->GetListOfCleanups()->Add(fClones);
}
if (!fClones->FindObject(clone)) {
fClones->Add(clone);
}
}
//______________________________________________________________________________
TFriendElement* TTree::AddFriend(const char* treename, const char* filename)
{
// Add a TFriendElement to the list of friends.
//
// This function:
// -opens a file if filename is specified
// -reads a Tree with name treename from the file (current directory)
// -adds the Tree to the list of friends
// see other AddFriend functions
//
// A TFriendElement TF describes a TTree object TF in a file.
// When a TFriendElement TF is added to the the list of friends of an
// existing TTree T, any variable from TF can be referenced in a query
// to T.
//
// A tree keeps a list of friends. In the context of a tree (or a chain),
// friendship means unrestricted access to the friends data. In this way
// it is much like adding another branch to the tree without taking the risk
// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
// method. The tree in the diagram below has two friends (friend_tree1 and
// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
//
//Begin_Html
/*
<img src="gif/tree_friend1.gif">
*/
//End_Html
//
// The AddFriend method has two parameters, the first is the tree name and the
// second is the name of the ROOT file where the friend tree is saved.
// AddFriend automatically opens the friend file. If no file name is given,
// the tree called ft1 is assumed to be in the same file as the original tree.
//
// tree.AddFriend("ft1","friendfile1.root");
// If the friend tree has the same name as the original tree, you can give it
// an alias sin the context of the friendship:
//
// tree.AddFriend("tree1 = tree","friendfile1.root");
// Once the tree has friends, we can use TTree::Draw as if the friend's
// variables were in the original tree. To specify which tree to use in
// the Draw method, use the syntax:
//
// <treeName>.<branchname>.<varname>
// If the variablename is enough to uniquely identify the variable, you can
// leave out the tree and/or branch name.
// For example, these commands generate a 3-d scatter plot of variable "var"
// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
// TTree ft2.
//
// tree.AddFriend("ft1","friendfile1.root");
// tree.AddFriend("ft2","friendfile2.root");
// tree.Draw("var:ft1.v1:ft2.v2");
//
//Begin_Html
/*
<img src="gif/tree_friend2.gif">
*/
//End_Html
//
// The picture illustrates the access of the tree and its friends with a
// Draw command.
// When AddFriend is called, the ROOT file is automatically opened and the
// friend tree (ft1) is read into memory. The new friend (ft1) is added to
// the list of friends of tree.
// The number of entries in the friend must be equal or greater to the number
// of entries of the original tree. If the friend tree has fewer entries a
// warning is given and the missing entries are not included in the histogram.
// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
// When the tree is written to file (TTree::Write), the friends list is saved
// with it. And when the tree is retrieved, the trees on the friends list are
// also retrieved and the friendship restored.
// When a tree is deleted, the elements of the friend list are also deleted.
// It is possible to declare a friend tree that has the same internal
// structure (same branches and leaves) as the original tree, and compare the
// same values by specifying the tree.
//
// tree.Draw("var:ft1.var:ft2.var")
//if (kAddFriend & fFriendLockStatus)
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, treename, filename);
R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %g than its parent Tree: %g", treename, filename, t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "Cannot add FriendElement %s in file %s", treename, filename);
}
return fe;
}
//______________________________________________________________________________
TFriendElement* TTree::AddFriend(const char* treename, TFile* file)
{
// Add a TFriendElement to the list of friends.
//
// The TFile is managed by the user (e.g. the user must delete the file).
// For complete description see AddFriend(const char *, const char *).
// This function:
// -reads a Tree with name treename from the file
// -adds the Tree to the list of friends
if (!fFriends) {
fFriends = new TList();
}
TFriendElement *fe = new TFriendElement(this, treename, file);
R__ASSERT(fe);
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %g than its parent tree: %g", treename, file->GetName(), t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "unknown tree '%s' in file '%s'", treename, file->GetName());
}
return fe;
}
//______________________________________________________________________________
TFriendElement* TTree::AddFriend(TTree* tree, const char* alias, Bool_t warn)
{
// Add a TFriendElement to the list of friends.
//
// The TTree is managed by the user (e.g., the user must delete the file).
// For a complete description see AddFriend(const char *, const char *).
if (!tree) {
return 0;
}
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, tree, alias);
R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (warn && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %g than its parent tree: %g", tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(), fEntries);
}
return fe;
}
//______________________________________________________________________________
Long64_t TTree::AutoSave(Option_t* option)
{
// AutoSave tree header every fAutoSave bytes.
//
// When large Trees are produced, it is safe to activate the AutoSave
// procedure. Some branches may have buffers holding many entries.
// AutoSave is automatically called by TTree::Fill when the number of bytes
// generated since the previous AutoSave is greater than fAutoSave bytes.
// This function may also be invoked by the user, for example every
// N entries.
// Each AutoSave generates a new key on the file.
// Once the key with the tree header has been written, the previous cycle
// (if any) is deleted.
//
// Note that calling TTree::AutoSave too frequently (or similarly calling
// TTree::SetAutoSave with a small value) is an expensive operation.
// You should make tests for your own application to find a compromize
// between speed and the quantity of information you may loose in case of
// a job crash.
//
// In case your program crashes before closing the file holding this tree,
// the file will be automatically recovered when you will connect the file
// in UPDATE mode.
// The Tree will be recovered at the status corresponding to the last AutoSave.
//
// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
// This allows another process to analyze the Tree while the Tree is being filled.
//
// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
// the current basket are closed-out and written to disk individually.
//
// By default the previous header is deleted after having written the new header.
// if option contains "Overwrite", the previous Tree header is deleted
// before written the new header. This option is slightly faster, but
// the default option is safer in case of a problem (disk quota exceeded)
// when writing the new header.
//
// The function returns the number of bytes written to the file.
// if the number of bytes is null, an error has occured while writing
// the header to the file.
//
// How to write a Tree in one process and view it from another process
// ===================================================================
// The following two scripts illustrate how to do this.
// The script treew.C is executed by process1, treer.C by process2
//
// ----- script treew.C
// void treew() {
// TFile f("test.root","recreate");
// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
// Float_t px, py, pz;
// for ( Int_t i=0; i<10000000; i++) {
// gRandom->Rannor(px,py);
// pz = px*px + py*py;
// Float_t random = gRandom->Rndm(1);
// ntuple->Fill(px,py,pz,random,i);
// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
// }
// }
//
// ----- script treer.C
// void treer() {
// TFile f("test.root");
// TTree *ntuple = (TTree*)f.Get("ntuple");
// TCanvas c1;
// Int_t first = 0;
// while(1) {
// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
// else ntuple->Draw("px>>+hpx","","",10000000,first);
// first = (Int_t)ntuple->GetEntries();
// c1.Update();
// gSystem->Sleep(1000); //sleep 1 second
// ntuple->Refresh();
// }
// }
if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
if (gDebug > 0) {
printf("AutoSave Tree:%s after %lld bytes written\n",GetName(),fTotBytes);
}
TString opt = option;
opt.ToLower();
if (opt.Contains("flushbaskets")) {
if (gDebug > 0) printf("AutoSave: calling FlushBaskets \n");
FlushBaskets();
}
fSavedBytes = fZipBytes;
TKey *key = (TKey*)fDirectory->GetListOfKeys()->FindObject(GetName());
Long64_t nbytes;
if (opt.Contains("overwrite")) {
nbytes = fDirectory->WriteTObject(this,"","",TObject::kOverwrite);
} else {
nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
if (nbytes && key) {
key->Delete();
delete key;
}
}
// save StreamerInfo
TFile *file = fDirectory->GetFile();
if (file) file->WriteStreamerInfo();
if (opt.Contains("saveself")) fDirectory->SaveSelf();
return nbytes;
}
//______________________________________________________________________________
TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
// Same as TTree::Branch() with added check that addobj matches className.
//
// See TTree::Branch() for other details.
//
if (!ptrClass) {
TClass* claim = TClass::GetClass(classname);
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
TClass* claim = TClass::GetClass(classname);
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr) {
actualClass = ptrClass->GetActualClass(*addr);
}
if (ptrClass && claim) {
if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
// Note we currently do not warn in case of splicing or over-expectation).
if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
claim->GetName(), branchname, ptrClass->GetName());
}
} else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
actualClass->GetName(), branchname, claim->GetName());
}
}
}
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
//______________________________________________________________________________
TBranch* TTree::BranchImp(const char* branchname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
// Same as TTree::Branch but automatic detection of the class name.
// See TTree::Branch for other details.
if (!ptrClass) {
Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
return 0;
}
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr && *addr) {
actualClass = ptrClass->GetActualClass(*addr);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part", branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
} else {
actualClass = ptrClass;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
}
//______________________________________________________________________________
TBranch* TTree::BranchImpRef(const char* branchname, TClass* ptrClass, EDataType datatype, void* addobj, Int_t bufsize, Int_t splitlevel)
{
// Same as TTree::Branch but automatic detection of the class name.
// See TTree::Branch for other details.
if (!ptrClass) {
if (datatype == kOther_t || datatype == kNoType_t) {
Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
} else {
TString varname; varname.Form("%s/%c",branchname,DataTypeToChar(datatype));
return Branch(branchname,addobj,varname.Data(),bufsize);
}
return 0;
}
TClass* actualClass = 0;
if (!addobj) {
Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
return 0;
}
actualClass = ptrClass->GetActualClass(addobj);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part", branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
}
//______________________________________________________________________________
Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
{
// Deprecated function. Use next function instead.
return Branch((TCollection*) li, bufsize, splitlevel);
}
//______________________________________________________________________________
Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
{
// Create one branch for each element in the collection.
//
// Each entry in the collection becomes a top level branch if the
// corresponding class is not a collection. If it is a collection, the entry
// in the collection becomes in turn top level branches, etc.
// The splitlevel is decreased by 1 everytime a new collection is found.
// For example if list is a TObjArray*
// - if splitlevel = 1, one top level branch is created for each element
// of the TObjArray.
// - if splitlevel = 2, one top level branch is created for each array element.
// if, in turn, one of the array elements is a TCollection, one top level
// branch will be created for each element of this collection.
//
// In case a collection element is a TClonesArray, the special Tree constructor
// for TClonesArray is called.
// The collection itself cannot be a TClonesArray.
//
// The function returns the total number of branches created.
//
// If name is given, all branch names will be prefixed with name_.
//
// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
//
// IMPORTANT NOTE2: The branches created by this function will have names
// corresponding to the collection or object names. It is important
// to give names to collections to avoid misleading branch names or
// identical branch names. By default collections have a name equal to
// the corresponding class name, eg the default name for a TList is "TList".
//
// Example--------------------------------------------------------------:
/*
{
TTree T("T","test list");
TList *l = new TList();
TObjArray *a1 = new TObjArray();
a1->SetName("a1");
l->Add(a1);
TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
a1->Add(ha1a);
a1->Add(ha1b);
TObjArray *b1 = new TObjArray();
b1->SetName("b1");
l->Add(b1);
TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
b1->Add(hb1a);
b1->Add(hb1b);
TObjArray *a2 = new TObjArray();
a2->SetName("a2");
l->Add(a2);
TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
a2->Add(ha2a);
a2->Add(ha2b);
T.Branch(l,16000,2);
T.Print();
}
*/
//----------------------------------------------------------------------
if (!li) {
return 0;
}
TObject* obj = 0;
Int_t nbranches = GetListOfBranches()->GetEntries();
if (li->InheritsFrom(TClonesArray::Class())) {
Error("Branch", "Cannot call this constructor for a TClonesArray");
return 0;
}
Int_t nch = strlen(name);
TString branchname;
TIter next(li);
while ((obj = next())) {
if ((splitlevel > 1) && obj->InheritsFrom(TCollection::Class()) && !obj->InheritsFrom(TClonesArray::Class())) {
TCollection* col = (TCollection*) obj;
if (nch) {
branchname.Form("%s_%s_", name, col->GetName());
} else {
branchname.Form("%s_", col->GetName());
}
Branch(col, bufsize, splitlevel - 1, branchname);
} else {
if (nch && (name[nch-1] == '_')) {
branchname.Form("%s%s", name, obj->GetName());
} else {
if (nch) {
branchname.Form("%s_%s", name, obj->GetName());
} else {
branchname.Form("%s", obj->GetName());
}
}
if (splitlevel > 99) {
branchname += ".";
}
Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
}
}
return GetListOfBranches()->GetEntries() - nbranches;
}
//______________________________________________________________________________
Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Create one branch for each element in the folder.
// Returns the total number of branches created.
TObject* ob = gROOT->FindObjectAny(foldername);
if (!ob) {
return 0;
}
if (ob->IsA() != TFolder::Class()) {
return 0;
}
Int_t nbranches = GetListOfBranches()->GetEntries();
TFolder* folder = (TFolder*) ob;
TIter next(folder->GetListOfFolders());
TObject* obj = 0;
char* curname = new char[1000];
char occur[20];
while ((obj = next())) {
sprintf(curname, "%s/%s", foldername, obj->GetName());
if (obj->IsA() == TFolder::Class()) {
Branch(curname, bufsize, splitlevel - 1);
} else {
void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
for (Int_t i = 0; i < 1000; ++i) {
if (curname[i] == 0) {
break;
}
if (curname[i] == '/') {
curname[i] = '.';
}
}
Int_t noccur = folder->Occurence(obj);
if (noccur > 0) {
sprintf(occur, "_%d", noccur);
strcat(curname, occur);
}
TBranchElement* br = (TBranchElement*) Bronch(curname, obj->ClassName(), add, bufsize, splitlevel - 1);
br->SetBranchFolder();
}
}
delete[] curname;
return GetListOfBranches()->GetEntries() - nbranches;
}
//______________________________________________________________________________
TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
{
// Create a new TTree Branch.
//
// This Branch constructor is provided to support non-objects in
// a Tree. The variables described in leaflist may be simple
// variables or structures. // See the two following
// constructors for writing objects in a Tree.
//
// By default the branch buffers are stored in the same file as the Tree.
// use TBranch::SetFile to specify a different file
//
// * address is the address of the first item of a structure.
// * leaflist is the concatenation of all the variable names and types
// separated by a colon character :
// The variable name and the variable type are separated by a slash (/).
// The variable type may be 0,1 or 2 characters. If no type is given,
// the type of the variable is assumed to be the same as the previous
// variable. If the first variable does not have a type, it is assumed
// of type F by default. The list of currently supported types is given below:
// - C : a character string terminated by the 0 character
// - B : an 8 bit signed integer (Char_t)
// - b : an 8 bit unsigned integer (UChar_t)
// - S : a 16 bit signed integer (Short_t)
// - s : a 16 bit unsigned integer (UShort_t)
// - I : a 32 bit signed integer (Int_t)
// - i : a 32 bit unsigned integer (UInt_t)
// - F : a 32 bit floating point (Float_t)
// - D : a 64 bit floating point (Double_t)
// - L : a 64 bit signed integer (Long64_t)
// - l : a 64 bit unsigned integer (ULong64_t)
// - O : a boolean (Bool_t)
//
// By default, a variable will be copied to the buffer with the number of
// bytes specified in the type descriptor character. However, if the type
// consists of 2 characters, the second character is an integer that
// specifies the number of bytes to be used when copying the variable
// to the output buffer. Example:
// X ; variable X, type Float_t
// Y/I : variable Y, type Int_t
// Y/I2 ; variable Y, type Int_t converted to a 16 bits integer
//
// Note that the TTree will assume that all the item are contiguous in memory.
// On some platform, this is not always true of the member of a struct or a class,
// due to padding and alignment. Sorting your data member in order of decreasing
// sizeof usually leads to their being contiguous in memory.
//
// * bufsize is the buffer size in bytes for this branch
// The default value is 32000 bytes and should be ok for most cases.
// You can specify a larger value (eg 256000) if your Tree is not split
// and each entry is large (Megabytes)
// A small value for bufsize is optimum if you intend to access
// the entries in the Tree randomly and your Tree is in split mode.
gTree = this;
TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
if (branch->IsZombie()) {
delete branch;
branch = 0;
return 0;
}
fBranches.Add(branch);
return branch;
}
//______________________________________________________________________________
TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Create a new branch with the object of class classname at address addobj.
//
// WARNING:
// Starting with Root version 3.01, the Branch function uses the new style
// branches (TBranchElement). To get the old behaviour, you can:
// - call BranchOld or
// - call TTree::SetBranchStyle(0)
//
// Note that with the new style, classname does not need to derive from TObject.
// It must derived from TObject if the branch style has been set to 0 (old)
//
// Note: See the comments in TBranchElement::SetAddress() for a more
// detailed discussion of the meaning of the addobj parameter in
// the case of new-style branches.
//
// Use splitlevel < 0 instead of splitlevel=0 when the class
// has a custom Streamer
//
// Note: if the split level is set to the default (99), TTree::Branch will
// not issue a warning if the class can not be split.
if (fgBranchStyle == 1) {
return Bronch(name, classname, addobj, bufsize, splitlevel);
} else {
if (splitlevel < 0) {
splitlevel = 0;
}
return BranchOld(name, classname, addobj, bufsize, splitlevel);
}
}
//______________________________________________________________________________
TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
{
// Create a new TTree BranchObject.
//
// Build a TBranchObject for an object of class classname.
// addobj is the address of a pointer to an object of class classname.
// IMPORTANT: classname must derive from TObject.
// The class dictionary must be available (ClassDef in class header).
//
// This option requires access to the library where the corresponding class
// is defined. Accessing one single data member in the object implies
// reading the full object.
// See the next Branch constructor for a more efficient storage
// in case the entry consists of arrays of identical objects.
//
// By default the branch buffers are stored in the same file as the Tree.
// use TBranch::SetFile to specify a different file
//
// IMPORTANT NOTE about branch names
// In case two or more master branches contain subbranches with
// identical names, one must add a "." (dot) character at the end
// of the master branch name. This will force the name of the subbranch
// to be master.subbranch instead of simply subbranch.
// This situation happens when the top level object (say event)
// has two or more members referencing the same class.
// For example, if a Tree has two branches B1 and B2 corresponding
// to objects of the same class MyClass, one can do:
// tree.Branch("B1.","MyClass",&b1,8000,1);
// tree.Branch("B2.","MyClass",&b2,8000,1);
// if MyClass has 3 members a,b,c, the two instructions above will generate
// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
//
// bufsize is the buffer size in bytes for this branch
// The default value is 32000 bytes and should be ok for most cases.
// You can specify a larger value (eg 256000) if your Tree is not split
// and each entry is large (Megabytes)
// A small value for bufsize is optimum if you intend to access
// the entries in the Tree randomly and your Tree is in split mode.
gTree = this;
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("BranchOld", "Cannot find class: '%s'", classname);
return 0;
}
TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
fBranches.Add(branch);
if (!splitlevel) {
return branch;
}
// We are going to fully split the class now.
TObjArray* blist = branch->GetListOfBranches();
const char* rdname = 0;
const char* dname = 0;
TString branchname;
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
Bool_t delobj = kFALSE;
if (!obj) {
obj = (TObject*) cl->New();
delobj = kTRUE;
}
// Build the StreamerInfo if first time for the class.
BuildStreamerInfo(cl, obj);
// Loop on all public data members of the class and its base classes.
Int_t lenName = strlen(name);
Int_t isDot = 0;
if (name[lenName-1] == '.') {
isDot = 1;
}
TBranch* branch1 = 0;
TRealData* rd = 0;
TRealData* rdi = 0;
TIter nexti(cl->GetListOfRealData());
TIter next(cl->GetListOfRealData());
// Note: This loop results in a full split because the
// real data list includes all data members of
// data members.
while ((rd = (TRealData*) next())) {
if (rd->TestBit(TRealData::kTransient)) continue;
// Loop over all data members creating branches for each one.
TDataMember* dm = rd->GetDataMember();
if (!dm->IsPersistent()) {
// Do not process members with an "!" as the first character in the comment field.
continue;
}
if (rd->IsObject()) {
// We skip data members of class type.
// But we do build their real data, their
// streamer info, and write their streamer
// info to the current directory's file.
// Oh yes, and we also do this for all of
// their base classes.
TClass* clm = TClass::GetClass(dm->GetFullTypeName());
if (clm) {
BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
}
continue;
}
rdname = rd->GetName();
dname = dm->GetName();
if (cl->CanIgnoreTObjectStreamer()) {
// Skip the TObject base class data members.
// FIXME: This prevents a user from ever
// using these names himself!
if (!strcmp(dname, "fBits")) {
continue;
}
if (!strcmp(dname, "fUniqueID")) {
continue;
}
}
TDataType* dtype = dm->GetDataType();
Int_t code = 0;
if (dtype) {
code = dm->GetDataType()->GetType();
}
// Encode branch name. Use real data member name
branchname = rdname;
if (isDot) {
if (dm->IsaPointer()) {
// FIXME: This is wrong! The asterisk is not usually in the front!
branchname.Form("%s%s", name, &rdname[1]);
} else {
branchname.Form("%s%s", name, &rdname[0]);
}
}
// FIXME: Change this to a string stream.
TString leaflist;
Int_t offset = rd->GetThisOffset();
char* pointer = ((char*) obj) + offset;
if (dm->IsaPointer()) {
// We have a pointer to an object or a pointer to an array of basic types.
TClass* clobj = 0;
if (!dm->IsBasic()) {
clobj = TClass::GetClass(dm->GetTypeName());
}
if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
// We have a pointer to a clones array.
char* cpointer = (char*) pointer;
char** ppointer = (char**) cpointer;
TClonesArray* li = (TClonesArray*) *ppointer;
if (splitlevel != 2) {
if (isDot) {
branch1 = new TBranchClones(branch,branchname, pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
}
blist->Add(branch1);
} else {
if (isDot) {
branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
}
blist->Add(branch1);
}
} else if (clobj) {
// We have a pointer to an object.
//
// It must be a TObject object.
if (!clobj->InheritsFrom(TObject::Class())) {
continue;
}
branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
if (isDot) {
branch1->SetName(branchname);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
// Do not use the first character (*).
branch1->SetName(&branchname.Data()[1]);
}
blist->Add(branch1);
} else {
// We have a pointer to an array of basic types.
//
// Check the comments in the text of the code for an index specification.
const char* index = dm->GetArrayIndex();
if (strlen(index) != 0) {
// We are a pointer to a varying length array of basic types.
//check that index is a valid data member name
//if member is part of an object (eg fA and index=fN)
//index must be changed from fN to fA.fN
TString aindex (rd->GetName());
Ssiz_t rdot = aindex.Last('.');
if (rdot>=0) {
aindex.Remove(rdot+1);
aindex.Append(index);
}
nexti.Reset();
while ((rdi = (TRealData*) nexti())) {
if (rdi->TestBit(TRealData::kTransient)) continue;
if (!strcmp(rdi->GetName(), index)) {
break;
}
if (!strcmp(rdi->GetName(), aindex)) {
index = rdi->GetName();
break;
}
}
char vcode = DataTypeToChar((EDataType)code);
// Note that we differentiate between strings and
// char array by the fact that there is NO specified
// size for a string (see next if (code == 1)
if (vcode) {
leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
} else {
// We are possibly a character string.
if (code == 1) {
// We are a character string.
leaflist.Form("%s/%s", dname, "C");
} else {
// Invalid array specification.
// FIXME: We need an error message here.
continue;
}
}
// There are '*' in both the branchname and leaflist, remove them.
TString bname( branchname );
bname.ReplaceAll("*","");
leaflist.ReplaceAll("*","");
// Add the branch to the tree and indicate that the address
// is that of a pointer to be dereferenced before using.
branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
leaf->SetBit(TLeaf::kIndirectAddress);
leaf->SetAddress((void**) pointer);
blist->Add(branch1);
}
} else if (dm->IsBasic()) {
// We have a basic type.
char vcode = DataTypeToChar((EDataType)code);
if (vcode) {
leaflist.Form("%s/%c", rdname, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
branch1->SetTitle(rdname);
blist->Add(branch1);
} else {
// We have a class type.
// Note: This cannot happen due to the rd->IsObject() test above.
// FIXME: Put an error message here just in case.
}
if (branch1) {
branch1->SetOffset(offset);
} else {
Warning("BranchOld", "Cannot process member: '%s'", rdname);
}
}
if (delobj) {
delete obj;
obj = 0;
}
return branch;
}
//______________________________________________________________________________
TBranch* TTree::BranchRef()
{
// Build the optional branch supporting the TRefTable.
// This branch will keep all the information to find the branches
// containing referenced objects.
//
// At each Tree::Fill, the branch numbers containing the
// referenced objects are saved to the TBranchRef basket.
// When the Tree header is saved (via TTree::Write), the branch
// is saved keeping the information with the pointers to the branches
// having referenced objects.
if (!fBranchRef) {
fBranchRef = new TBranchRef(this);
}
return fBranchRef;
}
//______________________________________________________________________________
TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Create a new TTree BranchElement.
//
// WARNING about this new function
// ===============================
// This function is designed to replace the function TTree::Branch above.
// This function is far more powerful than the Branch function.
// It supports the full C++, including STL and has the same behaviour
// in split or non-split mode. classname does not have to derive from TObject.
// The function is based on the new TStreamerInfo.
//
// Build a TBranchElement for an object of class classname.
//
// addr is the address of a pointer to an object of class classname.
// The class dictionary must be available (ClassDef in class header).
//
// Note: See the comments in TBranchElement::SetAddress() for a more
// detailed discussion of the meaning of the addr parameter.
//
// This option requires access to the library where the corresponding class
// is defined. Accessing one single data member in the object implies
// reading the full object.
//
// By default the branch buffers are stored in the same file as the Tree.
// use TBranch::SetFile to specify a different file
//
// IMPORTANT NOTE about branch names
// In case two or more master branches contain subbranches with
// identical names, one must add a "." (dot) character at the end
// of the master branch name. This will force the name of the subbranch
// to be master.subbranch instead of simply subbranch.
// This situation happens when the top level object (say event)
// has two or more members referencing the same class.
// For example, if a Tree has two branches B1 and B2 corresponding
// to objects of the same class MyClass, one can do:
// tree.Branch("B1.","MyClass",&b1,8000,1);
// tree.Branch("B2.","MyClass",&b2,8000,1);
// if MyClass has 3 members a,b,c, the two instructions above will generate
// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
//
// bufsize is the buffer size in bytes for this branch
// The default value is 32000 bytes and should be ok for most cases.
// You can specify a larger value (eg 256000) if your Tree is not split
// and each entry is large (Megabytes)
// A small value for bufsize is optimum if you intend to access
// the entries in the Tree randomly and your Tree is in split mode.
//
// Use splitlevel < 0 instead of splitlevel=0 when the class
// has a custom Streamer
//
// Note: if the split level is set to the default (99), TTree::Branch will
// not issue a warning if the class can not be split.
return BronchExec(name, classname, addr, kTRUE, bufsize, splitlevel);
}
//______________________________________________________________________________
TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, Bool_t isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
gTree = this;
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("Bronch", "Cannot find class:%s", classname);
return 0;
}
//if splitlevel <= 0 and class has a custom Streamer, we must create
//a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
//with the custom Streamer. The penalty is that one cannot process
//this Tree without the class library containing the class.
//The following convention is used for the RootFlag
// #pragma link C++ class TExMap; rootflag = 0
// #pragma link C++ class TList-; rootflag = 1
// #pragma link C++ class TArray!; rootflag = 2
// #pragma link C++ class TArrayC-!; rootflag = 3
// #pragma link C++ class TBits+; rootflag = 4
// #pragma link C++ class Txxxx+!; rootflag = 6
char* objptr = 0;
if (!isptrptr) {
objptr = (char*)addr;
} else if (addr) {
objptr = *((char**) addr);
}
if (cl == TClonesArray::Class()) {
TClonesArray* clones = (TClonesArray*) objptr;
if (!clones) {
Error("Bronch", "Pointer to TClonesArray is null");
return 0;
}
if (!clones->GetClass()) {
Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
return 0;
}
void* classinfo = clones->GetClass()->GetClassInfo();
if (!classinfo) {
Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
return 0;
}
int rootflag = gCint->ClassInfo_RootFlag(classinfo);
if (splitlevel > 0) {
if (rootflag & 1)
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
} else {
if (rootflag & 1) clones->BypassStreamer(kFALSE);
TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,isptrptr);
fBranches.Add(branch);
return branch;
}
}
if (cl->GetCollectionProxy()) {
TVirtualCollectionProxy* collProxy = cl->GetCollectionProxy();
//if (!collProxy) {
// Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
//}
TClass* inklass = collProxy->GetValueClass();
if (!inklass && (collProxy->GetType() == 0)) {
Error("Bronch", "%s with no class defined in branch: %s", classname, name);
return 0;
}
if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == 0)) {
Int_t stl = -TClassEdit::IsSTLCont(cl->GetName(), 0);
if ((stl != TClassEdit::kMap) && (stl != TClassEdit::kMultiMap)) {
void *classinfo = inklass->GetClassInfo();
if (!classinfo) {
Error("Bronch", "Container with no dictionary defined in branch: %s", name);
return 0;
}
if (gCint->ClassInfo_RootFlag(classinfo) & 1) {
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
}
}
}
//-------------------------------------------------------------------------
// If the splitting switch is enabled, the split level is big enough and
// the collection contains pointers we can split it
//-------------------------------------------------------------------------
TBranch *branch;
if( splitlevel > 100 && collProxy->HasPointers() )
branch = new TBranchSTL( this, name, collProxy, bufsize, splitlevel );
else
branch = new TBranchElement(this, name, collProxy, bufsize, splitlevel);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
Bool_t hasCustomStreamer = kFALSE;
if (!cl->GetClassInfo() && !cl->GetCollectionProxy()) {
Error("Bronch", "Cannot find dictionary for class: %s", classname);
return 0;
}
if (!cl->GetCollectionProxy() && (gCint->ClassInfo_RootFlag(cl->GetClassInfo()) & 1)) {
// Not an STL container and the linkdef file had a "-" after the class name.
hasCustomStreamer = kTRUE;
}
if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->InheritsFrom(TObject::Class()))) {
TBranchObject* branch = new TBranchObject(this, name, classname, addr, bufsize, 0, isptrptr);
fBranches.Add(branch);
return branch;
}
if (cl == TClonesArray::Class()) {
// Special case of TClonesArray.
// No dummy object is created.
// The streamer info is not rebuilt unoptimized.
// No dummy top-level branch is created.
// No splitting is attempted.
TBranchElement* branch = new TBranchElement(this, name, (TClonesArray*) objptr, bufsize, splitlevel%100);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
//
// If we are not given an object to use as an i/o buffer
// then create a temporary one which we will delete just
// before returning.
//
Bool_t delobj = kFALSE;
if (!objptr) {
objptr = (char*) cl->New();
delobj = kTRUE;
}
//
// Avoid splitting unsplittable classes.
//
if ((splitlevel > 0) && !cl->CanSplit()) {
if (splitlevel != 99) {
Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
}
splitlevel = 0;
}
//
// Make sure the streamer info is built and fetch it.
//
// If we are splitting, then make sure the streamer info
// is built unoptimized (data members are not combined).
//
TStreamerInfo* sinfo = BuildStreamerInfo(cl, objptr, splitlevel==0);
//
// Do we have a final dot in our name?
//
// Note: The branch constructor which takes a folder as input
// creates top-level branch names with dots in them to
// indicate the folder heirarchy.
char* dot = (char*) strchr(name, '.');
Int_t nch = strlen(name);
Bool_t dotlast = kFALSE;
if (nch && (name[nch-1] == '.')) {
dotlast = kTRUE;
}
//
// Create a dummy top level branch object.
//
Int_t id = -1;
if (splitlevel > 0) {
id = -2;
}
TBranchElement* branch = new TBranchElement(this, name, sinfo, id, objptr, bufsize, splitlevel);
fBranches.Add(branch);
//
// Do splitting, if requested.
//
if (splitlevel%100 > 0) {
// Loop on all public data members of the class and its base classes and create branches for each one.
TObjArray* blist = branch->GetListOfBranches();
TIter next(sinfo->GetElements());
TStreamerElement* element = 0;
TString bname;
for (id = 0; (element = (TStreamerElement*) next()); ++id) {
if (element->IsA() == TStreamerArtificial::Class()) {
continue;
}
if (element->TestBit(TStreamerElement::kRepeat)) {
continue;
}
char* pointer = (char*) (objptr + element->GetOffset());
// FIXME: This is not good enough, an STL container can be
// a base, and the test will fail.
// See TBranchElement::InitializeOffsets() for the
// correct test.
Bool_t isBase = (element->IsA() == TStreamerBase::Class());
if (isBase) {
TClass* clbase = element->GetClassPointer();
if ((clbase == TObject::Class()) && cl->CanIgnoreTObjectStreamer()) {
// Note: TStreamerInfo::Compile() leaves this element
// out of the compiled info, although it does
// exists in the non-compiled info. We must
// account for the fact that this element is
// missing in the compiled streamer info by
// making sure that we do not consume an id
// number for it.
// FIXME: The test that TStreamerInfo::Compile() uses
// is element->GetType() < 0, so that is what
// we should do as well.
--id;
continue;
}
}
if (dot) {
if (dotlast) {
bname.Form("%s%s", name, element->GetFullName());
} else {
// FIXME: We are in the case where we have a top-level
// branch name that was created by the branch
// constructor which takes a folder as input.
// The internal dots in the name are in place of
// of the original slashes and represent the
// folder heirarchy.
if (isBase) {
// FIXME: This is very strange, this is the only case where
// we create a branch for a base class that does
// not have the base class name in the branch name.
// FIXME: This is also quite bad since classes with two
// or more base classes end up with sub-branches
// that have the same name.
bname = name;
} else {
bname.Form("%s.%s", name, element->GetFullName());
}
}
} else {
// Note: For a base class element, this results in the branchname
// being the name of the base class.
bname.Form("%s", element->GetFullName());
}
if( splitlevel > 100 && element->GetClass() &&
element->GetClass()->GetCollectionProxy() &&
element->GetClass()->GetCollectionProxy()->HasPointers() )
{
TBranchSTL* brSTL = new TBranchSTL( branch, bname, element->GetClass()->GetCollectionProxy(), bufsize, splitlevel-1, sinfo, id );
blist->Add(brSTL);
}
else
{
TBranchElement* bre = new TBranchElement(branch, bname, sinfo, id, pointer, bufsize, splitlevel - 1);
bre->SetParentClass(cl);
blist->Add(bre);
}
}
}
//
// Setup our offsets into the user's i/o buffer.
//
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
if (delobj) {
cl->Destructor(objptr);
objptr = 0;
}
return branch;
}
//______________________________________________________________________________
void TTree::Browse(TBrowser* b)
{
// Browse content of the TTree.
fBranches.Browse(b);
if (fUserInfo) {
if (strcmp("TList",fUserInfo->GetName())==0) {
fUserInfo->SetName("UserInfo");
b->Add(fUserInfo);
fUserInfo->SetName("TList");
} else {
b->Add(fUserInfo);
}
}
}
//______________________________________________________________________________
Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
{
// Build a Tree Index (default is TTreeIndex).
// See a description of the parameters and functionality in
// TTreeIndex::TTreeIndex().
//
// The return value is the number of entries in the Index (< 0 indicates failure).
//
// A TTreeIndex object pointed by fTreeIndex is created.
// This object will be automatically deleted by the TTree destructor.
// See also comments in TTree::SetTreeIndex().
fTreeIndex = GetPlayer()->BuildIndex(this, majorname, minorname);
if (fTreeIndex->IsZombie()) {
delete fTreeIndex;
fTreeIndex = 0;
return 0;
}
return fTreeIndex->GetN();
}
//______________________________________________________________________________
TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, Bool_t canOptimize /* = kTRUE */ )
{
// Build StreamerInfo for class cl.
// pointer is an optional argument that may contain a pointer to an object of cl.
if (!cl) {
return 0;
}
cl->BuildRealData(pointer);
TStreamerInfo* sinfo = (TStreamerInfo*)cl->GetStreamerInfo(cl->GetClassVersion());
if (!canOptimize && (!sinfo->IsCompiled() || sinfo->IsOptimized()) ) {
// Streamer info has not yet been compiled.
//
// Optimizing does not work with splitting.
sinfo->SetBit(TVirtualStreamerInfo::kCannotOptimize);
sinfo->Compile();
}
// Create StreamerInfo for all base classes.
TBaseClass* base = 0;
TIter nextb(cl->GetListOfBases());
while((base = (TBaseClass*) nextb())) {
if (base->IsSTLContainer()) {
continue;
}
TClass* clm = TClass::GetClass(base->GetName());
BuildStreamerInfo(clm, pointer, canOptimize);
}
if (fDirectory) {
sinfo->ForceWriteInfo(fDirectory->GetFile());
}
return sinfo;
}
//______________________________________________________________________________
TFile* TTree::ChangeFile(TFile* file)
{
// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
// Create a new file. If the original file is named "myfile.root",
// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
//
// Returns a pointer to the new file.
//
// Currently, the automatic change of file is restricted
// to the case where the tree is in the top level directory.
// The file should not contain sub-directories.
//
// Before switching to a new file, the tree header is written
// to the current file, then the current file is closed.
//
// To process the multiple files created by ChangeFile, one must use
// a TChain.
//
// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
// By default a Root session starts with fFileNumber=0. One can set
// fFileNumber to a different value via TTree::SetFileNumber.
// In case a file named "_N" already exists, the function will try
// a file named "__N", then "___N", etc.
//
// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
// The default value of fgMaxTreeSize is 100 Gigabytes.
//
// If the current file contains other objects like TH1 and TTree,
// these objects are automatically moved to the new file.
//
// IMPORTANT NOTE:
// Be careful when writing the final Tree header to the file!
// Don't do:
// TFile *file = new TFile("myfile.root","recreate");
// TTree *T = new TTree("T","title");
// T->Fill(); //loop
// file->Write();
// file->Close();
// but do the following:
// TFile *file = new TFile("myfile.root","recreate");
// TTree *T = new TTree("T","title");
// T->Fill(); //loop
// file = T->GetCurrentFile(); //to get the pointer to the current file
// file->Write();
// file->Close();
file->cd();
Write();
Reset();
char* fname = new char[2000];
++fFileNumber;
char uscore[10];
for (Int_t i = 0; i < 10; ++i) {
uscore[i] = 0;
}
Int_t nus = 0;
// Try to find a suitable file name that does not already exist.
while (nus < 10) {
uscore[nus] = '_';
fname[0] = 0;
strcpy(fname, file->GetName());
if (fFileNumber > 1) {
char* cunder = strrchr(fname, '_');
if (cunder) {
sprintf(cunder, "%s%d", uscore, fFileNumber);
const char* cdot = strrchr(file->GetName(), '.');
if (cdot) {
strcat(fname, cdot);
}
} else {
char fcount[10];
sprintf(fcount, "%s%d", uscore, fFileNumber);
strcat(fname, fcount);
}
} else {
char* cdot = strrchr(fname, '.');
if (cdot) {
sprintf(cdot, "%s%d", uscore, fFileNumber);
strcat(fname, strrchr(file->GetName(), '.'));
} else {
char fcount[10];
sprintf(fcount, "%s%d", uscore, fFileNumber);
strcat(fname, fcount);
}
}
if (gSystem->AccessPathName(fname)) {
break;
}
++nus;
Warning("ChangeFile", "file %s already exist, trying with %d underscores", fname, nus+1);
}
Int_t compress = file->GetCompressionLevel();
TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
Printf("Fill: Switching to new file: %s", fname);
// The current directory may contain histograms and trees.
// These objects must be moved to the new file.
TBranch* branch = 0;
TObject* obj = 0;
while ((obj = file->GetList()->First())) {
file->Remove(obj);
// Histogram: just change the directory.
if (obj->InheritsFrom("TH1")) {
gROOT->ProcessLine(Form("((%s*)0x%lx)->SetDirectory((TDirectory*)0x%lx);", obj->ClassName(), (Long_t) obj, (Long_t) newfile));
continue;
}
// Tree: must save all trees in the old file, reset them.
if (obj->InheritsFrom(TTree::Class())) {
TTree* t = (TTree*) obj;
if (t != this) {
t->AutoSave();
t->Reset();
t->fFileNumber = fFileNumber;
}
t->SetDirectory(newfile);
TIter nextb(t->GetListOfBranches());
while ((branch = (TBranch*)nextb())) {
branch->SetFile(newfile);
}
if (t->GetBranchRef()) {
t->GetBranchRef()->SetFile(newfile);
}
continue;
}
// Not a TH1 or a TTree, move object to new file.
newfile->Append(obj);
file->Remove(obj);
}
delete file;
file = 0;
delete[] fname;
fname = 0;
return newfile;
}
//______________________________________________________________________________
Int_t TTree::CheckBranchAddressType(TBranch* branch, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
// Check whether or not the address described by the last 3 parameters
// matches the content of the branch. If a Data Model Evolution conversion
// is involved, reset the fInfo of the branch.
// The return values are:
// kMissingBranch (-5) : Missing branch
// kInternalError (-4) : Internal error (could not find the type corresponding to a data type number
// kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
// kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
// kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
// kMatch (0) : perfect match
// kMatchConversion (1) : match with (I/O) conversion
// kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
// kMakeClass (3) : MakeClass mode so we can not check.
// kVoidPtr (4) : void* passed so no check was made.
// kNoCheck (5) : Underlying TBranch not yet available so no check was made.
if (GetMakeClass()) {
// If we are in MakeClass mode so we do not really use classes.
return kMakeClass;
}
// Let's determine what we need!
TClass* expectedClass = 0;
EDataType expectedType = kOther_t;
TStreamerInfo* sinfo = 0;
if (branch->InheritsFrom(TBranchObject::Class())) {
TLeafObject* lobj = (TLeafObject*) branch->GetListOfLeaves()->At(0);
expectedClass = lobj->GetClass();
} else if (branch->InheritsFrom(TBranchElement::Class())) {
TBranchElement* branchEl = (TBranchElement*) branch;
Int_t type = branchEl->GetStreamerType();
sinfo = branchEl->GetInfo();
if ((type == -1) || (branchEl->GetID() == -1)) {
expectedClass = TClass::GetClass( branchEl->GetClassName() );
// expectedClass = branchEl->GetInfo()->GetClass();
} else {
// Case of an object data member. Here we allow for the
// variable name to be ommitted. Eg, for Event.root with split
// level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()")
TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()];
if (element) {
expectedClass = element->GetClassPointer();
if (!expectedClass) {
TDataType* data = gROOT->GetType(element->GetTypeNameBasic());
if (!data) {
Error("CheckBranchAddress", "Did not find the type number for %s", element->GetTypeNameBasic());
return kInternalError;
} else {
expectedType = (EDataType) data->GetType();
}
}
} else {
Error("CheckBranchAddress", "Did not find the type for %s",branchEl->GetName());
}
}
if (ptrClass && (branch->GetMother() == branch)) {
// Top Level branch
if (!isptr) {
Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
}
}
} else {
TLeaf* l = (TLeaf*) branch->GetListOfLeaves()->At(0);
if (l) {
expectedType = (EDataType) gROOT->GetType(l->GetTypeName())->GetType();
}
}
if (expectedType == kFloat16_t) {
expectedType = kFloat_t;
}
if (expectedType == kDouble32_t) {
expectedType = kDouble_t;
}
if (datatype == kFloat16_t) {
datatype = kFloat_t;
}
if (datatype == kDouble32_t) {
datatype = kDouble_t;
}
//---------------------------------------------------------------------------
// Deal with the class renaming
//---------------------------------------------------------------------------
if( expectedClass && ptrClass &&
expectedClass != ptrClass &&
branch->InheritsFrom( TBranchElement::Class() ) &&
ptrClass->GetSchemaRules() &&
ptrClass->GetSchemaRules()->HasRuleWithSourceClass(expectedClass->GetName() ) ) {
TBranchElement* bEl = (TBranchElement*)branch;
if( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
!ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" by the branch: %s", ptrClass->GetName(), bEl->GetClassName(), branch->GetName());
return kClassMismatch;
}
else {
bEl->SetTargetClassName( ptrClass->GetName() );
return kMatchConversion;
}
} else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
branch->InheritsFrom( TBranchElement::Class() ) &&
expectedClass->GetCollectionProxy()->GetValueClass() &&
ptrClass->GetCollectionProxy()->GetValueClass() )
{
// In case of collection, we know how to convert them, if we know how to convert their content.
// NOTE: we need to extend this to std::pair ...
TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
if (inmemValueClass->GetSchemaRules() &&
inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
{
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClassName( ptrClass->GetName() );
return kMatchConversionCollection;
}
}
Error("SetBranchAddress", "The pointer type given (%s) does not correspond to the class needed (%s) by the branch: %s", ptrClass->GetName(), expectedClass->GetName(), branch->GetName());
return kClassMismatch;
} else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
if (datatype != kChar_t) {
// For backward compatibility we assume that (char*) was just a cast and/or a generic address
Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s", TDataType::GetTypeName(datatype), datatype, TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
return kMismatch;
}
}
if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
Error("SetBranchAddress", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
return kMissingCompiledCollectionProxy;
}
return kMatch;
}
//______________________________________________________________________________
TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
// Create a clone of this tree and copy nentries.
//
// By default copy all entries.
// Note that only active branches are copied.
// The compression level of the cloned tree is set to the destination file's
// compression level.
//
// IMPORTANT: The cloned tree stays connected with this tree until this tree
// is deleted. In particular, any changes in branch addresses
// in this tree are forwarded to the clone trees, unless a branch
// in a clone tree has had its address changed, in which case
// that change stays in effect. When this tree is deleted, all the
// addresses of the cloned tree are reset to their default values.
//
// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
// raw bytes on disk).
//
// When 'fast' is specified, 'option' can also contains a
// sorting order for the baskets in the output file.
//
// There are currently 3 supported sorting order:
// SortBasketsByOffset (the default)
// SortBasketsByBranch
// SortBasketsByEntry
//
// When using SortBasketsByOffset the baskets are written in
// the output file in the same order as in the original file
// (i.e. the basket are sorted on their offset in the original
// file; Usually this also means that the baskets are sorted
// on the index/number of the _last_ entry they contain)
//
// When using SortBasketsByBranch all the baskets of each
// individual branches are stored contiguously. This tends to
// optimize reading speed when reading a small number (1->5) of
// branches, since all their baskets will be clustered together
// instead of being spread across the file. However it might
// decrease the performance when reading more branches (or the full
// entry).
//
// When using SortBasketsByEntry the baskets with the lowest
// starting entry are written first. (i.e. the baskets are
// sorted on the index/number of the first entry they contain).
// This means that on the file the baskets will be in the order
// in which they will be needed when reading the whole tree
// sequentially.
//
// For examples of CloneTree, see tutorials:
//
// -- copytree
//
// A macro to copy a subset of a TTree to a new TTree.
//
// The input file has been generated by the program in $ROOTSYS/test/Event
// with: Event 1000 1 1 1
//
// -- copytree2
//
// A macro to copy a subset of a TTree to a new TTree.
//
// One branch of the new Tree is written to a separate file.
//
// The input file has been generated by the program in $ROOTSYS/test/Event
// with: Event 1000 1 1 1
//
// Options
Bool_t fastClone = kFALSE;
TString opt = option;
opt.ToLower();
if (opt.Contains("fast")) {
fastClone = kTRUE;
}
// If we are a chain, switch to the first tree.
if ((fEntries > 0) && (LoadTree(0) < 0)) {
// FIXME: We need an error message here.
return 0;
}
// Note: For a tree we get the this pointer, for
// a chain we get the chain's current tree.
TTree* thistree = GetTree();
// Note: For a chain, the returned clone will be
// a clone of the chain's first tree.
TTree* newtree = (TTree*) thistree->Clone();
if (!newtree) {
return 0;
}
// The clone should not delete any objects allocated by SetAddress().
TObjArray* branches = newtree->GetListOfBranches();
Int_t nb = branches->GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
}
// Add the new tree to the list of clones so that
// we can later inform it of changes to branch addresses.
thistree->AddClone(newtree);
newtree->Reset();
TDirectory* ndir = newtree->GetDirectory();
TFile* nfile = 0;
if (ndir) {
nfile = ndir->GetFile();
}
Int_t newcomp = -1;
if (nfile) {
newcomp = nfile->GetCompressionLevel();
}
//
// Delete non-active branches from the clone.
//
// Note: If we are a chain, this does nothing
// since chains have no leaves.
TObjArray* leaves = newtree->GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
if (!leaf) {
continue;
}
TBranch* branch = leaf->GetBranch();
if (branch && (newcomp > -1)) {
branch->SetCompressionLevel(newcomp);
}
if (!branch || !branch->TestBit(kDoNotProcess)) {
continue;
}
// TObjArray* branches = newtree->GetListOfBranches();
// Int_t nb = branches->GetEntriesFast();
for (Long64_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br == branch) {
branches->RemoveAt(i);
delete br;
br = 0;
branches->Compress();
break;
}
TObjArray* lb = br->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; ++j) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!b1) {
continue;
}
if (b1 == branch) {
lb->RemoveAt(j);
delete b1;
b1 = 0;
lb->Compress();
break;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; ++k) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!b2) {
continue;
}
if (b2 == branch) {
lb1->RemoveAt(k);
delete b2;
b2 = 0;
lb1->Compress();
break;
}
}
}
}
}
leaves->Compress();
// Copy MakeClass status.
newtree->SetMakeClass(fMakeClass);
// Copy branch addresses.
CopyAddresses(newtree);
//
// Copy entries if requested.
//
if (nentries != 0) {
if (fastClone && (nentries < 0)) {
if ( newtree->CopyEntries( this, -1, option ) < 0 ) {
// There was a problem!
Error("Merge", "TTree has not been cloned\n");
delete newtree;
newtree = 0;
return 0;
}
} else {
newtree->CopyEntries( this, nentries, option );
}
}
return newtree;
}
//______________________________________________________________________________
void TTree::CopyAddresses(TTree* tree, Bool_t undo)
{
// Set branch addresses of passed tree equal to ours.
// If undo is true, reset the branch address instead of copying them.
// This insures 'separation' of a cloned tree from its original
// Copy branch addresses starting from branches.
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
TBranch* br = tree->GetBranch(branch->GetName());
tree->ResetBranchAddress(br);
} else {
char* addr = branch->GetAddress();
if (!addr) {
if (branch->IsA() == TBranch::Class()) {
// If the branch was created using a leaflist, the branch itself may not have
// an address but the leat might already do.
TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
if (!firstleaf || firstleaf->GetValuePointer()) {
// Either there is no leaf (and thus no point in copying the address)
// or the leaf has an address but we can not copy it via the branche
// this will be copied via the the next loop (over the leaf).
continue;
}
}
// Note: This may cause an object to be allocated.
branch->SetAddress(0);
addr = branch->GetAddress();
}
// FIXME: The GetBranch() function is braindead and may
// not find the branch!
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
br->SetAddress(addr);
// The copy does not own any object allocated by SetAddress().
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
}
}
// Copy branch addresses starting from leaves.
TObjArray* tleaves = tree->GetListOfLeaves();
Int_t ntleaves = tleaves->GetEntriesFast();
for (Int_t i = 0; i < ntleaves; ++i) {
TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
TBranch* tbranch = tleaf->GetBranch();
TBranch* branch = GetBranch(tbranch->GetName());
if (!branch) {
continue;
}
TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
if (!leaf) {
continue;
}
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
// Now we know wether the address has been transfered
tree->ResetBranchAddress(tbranch);
} else {
if (!branch->GetAddress() && !leaf->GetValuePointer()) {
// We should attempts to set the address of the branch.
// something like:
//(TBranchElement*)branch->GetMother()->SetAddress(0)
//plus a few more subtilities (see TBranchElement::GetEntry).
//but for now we go the simpliest route:
//
// Note: This may result in the allocation of an object.
branch->GetEntry(0);
}
if (branch->GetAddress()) {
tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
// The copy does not own any object allocated by SetAddress().
// FIXME: We do too much here, br may not be a top-level branch.
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
} else {
tleaf->SetAddress(leaf->GetValuePointer());
}
}
}
if (undo &&
( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
) {
tree->ResetBranchAddresses();
}
}
namespace {
enum EOnIndexError { kDrop, kKeep, kBuild };
static bool R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
{
// Return true if we should continue to handle indices, false otherwise.
bool withIndex = kTRUE;
if ( newtree->GetTreeIndex() ) {
if ( oldtree->GetTree()->GetTreeIndex() == 0 ) {
switch (onIndexError) {
case kDrop:
delete newtree->GetTreeIndex();
newtree->SetTreeIndex(0);
withIndex = kFALSE;
break;
case kKeep:
// Nothing to do really.
break;
case kBuild:
// Build the index then copy it
oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName());
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
// Clean up
delete oldtree->GetTree()->GetTreeIndex();
oldtree->GetTree()->SetTreeIndex(0);
break;
}
} else {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
} else if ( oldtree->GetTree()->GetTreeIndex() != 0 ) {
// We discover the first index in the middle of the chain.
switch (onIndexError) {
case kDrop:
// Nothing to do really.
break;
case kKeep: {
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
break;
}
case kBuild:
if (newtree->GetEntries() == 0) {
// Start an index.
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
} else {
// Build the index so far.
newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName());
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
break;
}
} else if ( onIndexError == kDrop ) {
// There is no index on this or on tree->GetTree(), we know we have to ignore any further
// index
withIndex = kFALSE;
}
return withIndex;
}
}
//______________________________________________________________________________
Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
// Copy nentries from given tree to this tree.
// This routines assumes that the branches that intended to be copied are
// already connected. The typical case is that this tree was created using
// tree->CloneTree(0).
//
// By default copy all entries.
//
// Returns number of bytes copied to this tree.
//
// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
// raw bytes on disk).
//
// When 'fast' is specified, 'option' can also contains a sorting order for the
// baskets in the output file.
//
// There are currently 3 supported sorting order:
// SortBasketsByOffset (the default)
// SortBasketsByBranch
// SortBasketsByEntry
//
// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
//
// If the tree or any of the underlying tree of the chain has an index, that index and any
// index in the subsequent underlying TTree objects will be merged.
//
// There are currently three 'options' to control this merging:
// NoIndex : all the TTreeIndex object are dropped.
// DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
// they are all dropped.
// AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
// BuildIndexOnError : If any of the underlying TTree object do no have a TTreeIndex,
// all TTreeIndex are 'ignored' and the mising piece are rebuilt.
if (!tree) {
return 0;
}
// Options
TString opt = option;
opt.ToLower();
Bool_t fastClone = opt.Contains("fast");
Bool_t withIndex = !opt.Contains("noindex");
EOnIndexError onIndexError;
if (opt.Contains("asisindex")) {
onIndexError = kKeep;
} else if (opt.Contains("buildindex")) {
onIndexError = kBuild;
} else if (opt.Contains("dropindex")) {
onIndexError = kDrop;
} else {
onIndexError = kBuild;
}
Long64_t nbytes = 0;
Long64_t treeEntries = tree->GetEntriesFast();
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
// Quickly copy the basket without decompression and streaming.
Long64_t totbytes = GetTotBytes();
for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
if (tree->LoadTree(i) < 0) {
break;
}
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
if (this->GetDirectory()) {
TFile* file2 = this->GetDirectory()->GetFile();
if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
if (this->GetDirectory() == (TDirectory*) file2) {
this->ChangeFile(file2);
}
}
}
TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
if (cloner.IsValid()) {
this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
cloner.Exec();
} else {
if (i == 0) {
// If the first cloning does not work, something is really wrong
// (since apriori the source and target are exactly the same structure!)
return -1;
} else {
if (cloner.NeedConversion()) {
TTree *localtree = tree->GetTree();
Long64_t tentries = localtree->GetEntries();
for (Long64_t ii = 0; ii < tentries; ii++) {
if (localtree->GetEntry(ii) <= 0) {
break;
}
this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), kTRUE);
}
} else {
Warning("CopyEntries",cloner.GetWarning());
if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
} else {
Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
}
}
}
}
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
nbytes = GetTotBytes() - totbytes;
} else {
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
Int_t treenumber = -1;
for (Long64_t i = 0; i < nentries; i++) {
if (tree->LoadTree(i) < 0) {
break;
}
if (treenumber != tree->GetTreeNumber()) {
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
treenumber = tree->GetTreeNumber();
}
if (tree->GetEntry(i) <= 0) {
break;
}
nbytes += this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
}
return nbytes;
}
//______________________________________________________________________________
TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = 1000000000 */, Long64_t firstentry /* = 0 */)
{
// Copy a tree with selection.
//
// IMPORTANT:
//
// The returned copied tree stays connected with the original tree
// until the original tree is deleted. In particular, any changes
// to the branch addresses in the original tree are also made to
// the copied tree. Any changes made to the branch addresses of the
// copied tree are overridden anytime the original tree changes its
// branch addresses. When the original tree is deleted, all the
// branch addresses of the copied tree are set to zero.
//
// For examples of CopyTree, see the tutorials:
//
// copytree
//
// Example macro to copy a subset of a tree to a new tree.
//
// The input file was generated by running the program in
// $ROOTSYS/test/Event in this way:
//
// ./Event 1000 1 1 1
//
// copytree2
//
// Example macro to copy a subset of a tree to a new tree.
//
// One branch of the new tree is written to a separate file.
//
// The input file was generated by running the program in
// $ROOTSYS/test/Event in this way:
//
// ./Event 1000 1 1 1
//
// copytree3
//
// Example macro to copy a subset of a tree to a new tree.
//
// Only selected entries are copied to the new tree.
// NOTE that only the active branches are copied.
//
GetPlayer();
if (fPlayer) {
return fPlayer->CopyTree(selection, option, nentries, firstentry);
}
return 0;
}
//______________________________________________________________________________
TBasket* TTree::CreateBasket(TBranch* branch)
{
// Create a basket for this tree and given branch.
if (!branch) {
return 0;
}
return new TBasket(branch->GetName(), GetName(), branch);
}
//______________________________________________________________________________
void TTree::Delete(Option_t* option /* = "" */)
{
// Delete this tree from memory or/and disk.
//
// if option == "all" delete Tree object from memory AND from disk
// all baskets on disk are deleted. All keys with same name
// are deleted.
// if option =="" only Tree object in memory is deleted.
TFile *file = GetCurrentFile();
// delete all baskets and header from file
if (file && !strcmp(option,"all")) {
if (!file->IsWritable()) {
Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
return;
}
//find key and import Tree header in memory
TKey *key = fDirectory->GetKey(GetName());
if (!key) return;
TDirectory *dirsav = gDirectory;
file->cd();
//get list of leaves and loop on all the branches baskets
TIter next(GetListOfLeaves());
TLeaf *leaf;
char header[16];
Int_t ntot = 0;
Int_t nbask = 0;
Int_t nbytes,objlen,keylen;
while ((leaf = (TLeaf*)next())) {
TBranch *branch = leaf->GetBranch();
Int_t nbaskets = branch->GetMaxBaskets();
for (Int_t i=0;i<nbaskets;i++) {
Long64_t pos = branch->GetBasketSeek(i);
if (!pos) continue;
TFile *branchFile = branch->GetFile();
if (!branchFile) continue;
branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
if (nbytes <= 0) continue;
branchFile->MakeFree(pos,pos+nbytes-1);
ntot += nbytes;
nbask++;
}
}
// delete Tree header key and all keys with the same name
// A Tree may have been saved many times. Previous cycles are invalid.
while (key) {
ntot += key->GetNbytes();
key->Delete();
delete key;
key = fDirectory->GetKey(GetName());
}
if (dirsav) dirsav->cd();
if (gDebug) printf(" Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
}
if (fDirectory) {
fDirectory->Remove(this);
fDirectory = 0;
ResetBit(kMustCleanup);
}
// Delete object from CINT symbol table so it can not be used anymore.
gCint->DeleteGlobal(this);
// Warning: We have intentional invalidated this object while inside a member function!
delete this;
}
//______________________________________________________________________________
void TTree::DirectoryAutoAdd(TDirectory* dir)
{
// Called by TKey and TObject::Clone to automatically add us to a directory
// when we are read from a file.
if (fDirectory == dir) return;
if (fDirectory) fDirectory->Remove(this);
fDirectory = dir;
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->UpdateFile();
}
if (fBranchRef) {
fBranchRef->UpdateFile();
}
if (fDirectory) fDirectory->Append(this);
}
//______________________________________________________________________________
Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Draw expression varexp for specified entries.
// Returns -1 in case of error or number of selected events in case of success.
//
// This function accepts TCut objects as arguments.
// Useful to use the string operator +
// example:
// ntuple.Draw("x",cut1+cut2+cut3);
//
return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
}
//______________________________________________________________________________
Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Draw expression varexp for specified entries.
// Returns -1 in case of error or number of selected events in case of success.
//
// varexp is an expression of the general form
// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1" versus "e2"
// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
// versus "e2" versus "e3"
// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
// versus "e2" versus "e3" and "e4" mapped on the color number.
// (to create histograms in the 2, 3, and 4 dimesional case, see section "Saving
// the result of Draw to an histogram")
//
// Example:
// varexp = x simplest case: draw a 1-Dim distribution of column named x
// = sqrt(x) : draw distribution of sqrt(x)
// = x*y/z
// = y:sqrt(x) 2-Dim distribution of y versus sqrt(x)
// = px:py:pz:2.5*E produces a 3-d scatter-plot of px vs py ps pz
// and the color number of each marker will be 2.5*E.
// If the color number is negative it is set to 0.
// If the color number is greater than the current number of colors
// it is set to the highest color number.
// The default number of colors is 50.
// see TStyle::SetPalette for setting a new color palette.
//
// Note that the variables e1, e2 or e3 may contain a selection.
// example, if e1= x*(y<0), the value histogrammed will be x if y<0
// and will be 0 otherwise.
//
// The expressions can use all the operations and build-in functions
// supported by TFormula (See TFormula::Analyze), including free
// standing function taking numerical arguments (TMath::Bessel).
// In addition, you can call member functions taking numerical
// arguments. For example:
// - "TMath::BreitWigner(fPx,3,2)"
// - "event.GetHistogram().GetXaxis().GetXmax()"
// Note: You can only pass expression that depend on the TTree's data
// to static functions and you can only call non-static member function
// with 'fixed' parameters.
//
// selection is an expression with a combination of the columns.
// In a selection all the C++ operators are authorized.
// The value corresponding to the selection expression is used as a weight
// to fill the histogram.
// If the expression includes only boolean operations, the result
// is 0 or 1. If the result is 0, the histogram is not filled.
// In general, the expression may be of the form:
// value*(boolean expression)
// if boolean expression is true, the histogram is filled with
// a weight = value.
// Examples:
// selection1 = "x<y && sqrt(z)>3.2"
// selection2 = "(x+y)*(sqrt(z)>3.2)"
// selection1 returns a weigth = 0 or 1
// selection2 returns a weight = x+y if sqrt(z)>3.2
// returns a weight = 0 otherwise.
//
// option is the drawing option.
// - See TH1::Draw for the list of all drawing options.
// - If option COL is specified when varexp has three fields:
// tree.Draw("e1:e2:e3","","col");
// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the color
// table.
// - If option contains the string "goff", no graphics is generated.
//
// nentries is the number of entries to process (default is all)
// first is the first entry to process (default is 0)
//
// This function returns the number of selected entries. It returns -1
// if an error occurs.
//
// Drawing expressions using arrays and array elements
// ===================================================
// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
// or a TClonesArray.
// In a TTree::Draw expression you can now access fMatrix using the following
// syntaxes:
//
// String passed What is used for each entry of the tree
//
// "fMatrix" the 9 elements of fMatrix
// "fMatrix[][]" the 9 elements of fMatrix
// "fMatrix[2][2]" only the elements fMatrix[2][2]
// "fMatrix[1]" the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2]
// "fMatrix[1][]" the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2]
// "fMatrix[][0]" the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0]
//
// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
//
// In summary, if a specific index is not specified for a dimension, TTree::Draw
// will loop through all the indices along this dimension. Leaving off the
// last (right most) dimension of specifying then with the two characters '[]'
// is equivalent. For variable size arrays (and TClonesArray) the range
// of the first dimension is recalculated for each entry of the tree.
//
// TTree::Draw also now properly handling operations involving 2 or more arrays.
//
// Let assume a second matrix fResults[5][2], here are a sample of some
// of the possible combinations, the number of elements they produce and
// the loop used:
//
// expression element(s) Loop
//
// "fMatrix[2][1] - fResults[5][2]" one no loop
// "fMatrix[2][] - fResults[5][2]" three on 2nd dim fMatrix
// "fMatrix[2][] - fResults[5][]" two on both 2nd dimensions
// "fMatrix[][2] - fResults[][1]" three on both 1st dimensions
// "fMatrix[][2] - fResults[][]" six on both 1st and 2nd dimensions of
// fResults
// "fMatrix[][2] - fResults[3][]" two on 1st dim of fMatrix and 2nd of
// fResults (at the same time)
// "fMatrix[][] - fResults[][]" six on 1st dim then on 2nd dim
//
//
// In summary, TTree::Draw loops through all un-specified dimensions. To
// figure out the range of each loop, we match each unspecified dimension
// from left to right (ignoring ALL dimensions for which an index has been
// specified), in the equivalent loop matched dimensions use the same index
// and are restricted to the smallest range (of only the matched dimensions).
// When involving variable arrays, the range can of course be different
// for each entry of the tree.
//
// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
//
// for (Int_t i0; i < min(3,2); i++) {
// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
// }
//
// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
//
// for (Int_t i0; i < min(3,5); i++) {
// for (Int_t i1; i1 < 2; i1++) {
// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
// }
// }
//
// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
//
// for (Int_t i0; i < min(3,5); i++) {
// for (Int_t i1; i1 < min(3,2); i1++) {
// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
// }
// }
//
// Retrieving the result of Draw
// =============================
//
// By default the temporary histogram created is called "htemp", but only in
// the one dimensional Draw("e1") it contains the TTree's data points. For
// a two dimensional Draw, the data is filled into a TGraph which is named
// "Graph". They can be retrieved by calling
// TH1F *htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
//
// For a three and four dimensional Draw the TPloyMarker3D is unnamed, and
// cannot be retrieved.
//
// gPad always contains a TH1 derived object called "htemp" which allows to
// access the axes:
// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
// TH2F *htemp = (TH2F*)gPad->GetPrimitive("htemp"); // empty, but has axes
// TAxis *xaxis = htemp->GetXaxis();
//
// Saving the result of Draw to an histogram
// =========================================
//
// If varexp0 contains >>hnew (following the variable(s) name(s),
// the new histogram created is called hnew and it is kept in the current
// directory (and also the current pad). This works for all dimensions.
// Example:
// tree.Draw("sqrt(x)>>hsqrt","y>0")
// will draw sqrt(x) and save the histogram as "hsqrt" in the current
// directory. To retrieve it do:
// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
//
// The binning information is taken from the environment variables
//
// Hist.Binning.?D.?
//
// In addition, the name of the histogram can be followed by up to 9
// numbers between '(' and ')', where the numbers describe the
// following:
//
// 1 - bins in x-direction
// 2 - lower limit in x-direction
// 3 - upper limit in x-direction
// 4-6 same for y-direction
// 7-9 same for z-direction
//
// When a new binning is used the new value will become the default.
// Values can be skipped.
// Example:
// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
// // plot sqrt(x) between 10 and 20 using 500 bins
// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
// // plot sqrt(x) against sin(y)
// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
//
// By default, the specified histogram is reset.
// To continue to append data to an existing histogram, use "+" in front
// of the histogram name.
// A '+' in front of the histogram name is ignored, when the name is followed by
// binning information as described in the previous paragraph.
// tree.Draw("sqrt(x)>>+hsqrt","y>0")
// will not reset hsqrt, but will continue filling.
// This works for 1-D, 2-D and 3-D histograms.
//
// Accessing collection objects
// ============================
//
// TTree::Draw default's handling of collections is to assume that any
// request on a collection pertain to it content. For example, if fTracks
// is a collection of Track objects, the following:
// tree->Draw("event.fTracks.fPx");
// will plot the value of fPx for each Track objects inside the collection.
// Also
// tree->Draw("event.fTracks.size()");
// would plot the result of the member function Track::size() for each
// Track object inside the collection.
// To access information about the collection itself, TTree::Draw support
// the '@' notation. If a variable which points to a collection is prefixed
// or postfixed with '@', the next part of the expression will pertain to
// the collection object. For example:
// tree->Draw("event.@fTracks.size()");
// will plot the size of the collection refered to by fTracks (i.e the number
// of Track objects).
//
// Drawing 'objects'
// =================
//
// When a class has a member function named AsDouble or AsString, requesting
// to directly draw the object will imply a call to one of the 2 functions.
// If both AsDouble and AsString are present, AsDouble will be used.
// AsString can return either a char*, a std::string or a TString.s
// For example, the following
// tree->Draw("event.myTTimeStamp");
// will draw the same histogram as
// tree->Draw("event.myTTimeStamp.AsDouble()");
// In addition, when the object is a type TString or std::string, TTree::Draw
// will call respectively TString::Data and std::string::c_str()
//
// If the object is a TBits, the histogram will contain the index of the bit
// that are turned on.
//
// Retrieving information about the tree itself.
// ============================================
//
// You can refer to the tree (or chain) containing the data by using the
// string 'This'.
// You can then could any TTree methods. For example:
// tree->Draw("This->GetReadEntry()");
// will display the local entry numbers be read.
// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
// will display the name of the first 'user info' object.
//
// Special functions and variables
// ===============================
//
// Entry$: A TTree::Draw formula can use the special variable Entry$
// to access the entry number being read. For example to draw every
// other entry use:
// tree.Draw("myvar","Entry$%2==0");
//
// Entry$ : return the current entry number (== TTree::GetReadEntry())
// LocalEntry$ : return the current entry number in the current tree of a
// chain (== GetTree()->GetReadEntry())
// Entries$ : return the total number of entries (== TTree::GetEntries())
// Length$ : return the total number of element of this formula for this
// entry (==TTreeFormula::GetNdata())
// Iteration$: return the current iteration over this formula for this
// entry (i.e. varies from 0 to Length$).
//
// Length$(formula): return the total number of element of the formula given as a
// parameter.
// Sum$(formula): return the sum of the value of the elements of the formula given
// as a parameter. For example the mean for all the elements in
// one entry can be calculated with:
// Sum$(formula)/Length$(formula)
// Min$(formula): return the minimun (within one TTree entry) of the value of the
// elements of the formula given as a parameter.
// Max$(formula): return the maximum (within one TTree entry) of the value of the
// elements of the formula given as a parameter.
// MinIf$(formula,condition)
// MaxIf$(formula,condition): return the minimum (maximum) (within one TTree entry)
// of the value of the elements of the formula given as a parameter
// if they match the condition. If not element match the condition, the result is zero. To avoid the
// the result is zero. To avoid the consequent peak a zero, use the
// pattern:
// tree->Draw("MinIf$(formula,condition)","condition");
// which will avoid calculation MinIf$ for the entries that have no match
// for the condition.
//
// Alt$(primary,alternate) : return the value of "primary" if it is available
// for the current iteration otherwise return the value of "alternate".
// For example, with arr1[3] and arr2[2]
// tree->Draw("arr1+Alt$(arr2,0)");
// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
// Or with a variable size array arr3
// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
// As a comparison
// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
// will draw the sum arr3 for the index 0 to 2 only if the
// actual_size_of_arr3 is greater or equal to 3.
// Note that the array in 'primary' is flatened/linearilized thus using
// Alt$ with multi-dimensional arrays of different dimensions in unlikely
// to yield the expected results. To visualize a bit more what elements
// would be matched by TTree::Draw, TTree::Scan can be used:
// tree->Scan("arr1:Alt$(arr2,0)");
// will print on one line the value of arr1 and (arr2,0) that will be
// matched by
// tree->Draw("arr1-Alt$(arr2,0)");
//
// The ternary operator is not directly support in TTree::Draw however, to plot the
// equivalent of 'var2<20 ? -99 : var1', you can use:
// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
//
// Drawing a user function accessing the TTree data directly
// =========================================================
//
// If the formula contains a file name, TTree::MakeProxy will be used
// to load and execute this file. In particular it will draw the
// result of a function with the same name as the file. The function
// will be executed in a context where the name of the branches can
// be used as a C++ variable.
//
// For example draw px using the file hsimple.root (generated by the
// hsimple.C tutorial), we need a file named hsimple.cxx:
//
// double hsimple() {
// return px;
// }
//
// MakeProxy can then be used indirectly via the TTree::Draw interface
// as follow:
// new TFile("hsimple.root")
// ntuple->Draw("hsimple.cxx");
//
// A more complete example is available in the tutorials directory:
// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
// which reimplement the selector found in h1analysis.C
//
// The main features of this facility are:
//
// * on-demand loading of branches
// * ability to use the 'branchname' as if it was a data member
// * protection against array out-of-bound
// * ability to use the branch data as object (when the user code is available)
//
// See TTree::MakeProxy for more details.
//
// Making a Profile histogram
// ==========================
// In case of a 2-Dim expression, one can generate a TProfile histogram
// instead of a TH2F histogram by specyfying option=prof or option=profs.
// The option=prof is automatically selected in case of y:x>>pf
// where pf is an existing TProfile histogram.
//
// Making a 5D plot using GL
// =========================
// If option GL5D is specified together with 5 variables, a 5D plot is drawn
// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
//
// Making a parallel coordinates plot
// ==================================
// In case of a 2-Dim or more expression with the option=para, one can generate
// a parallel coordinates plot. With that option, the number of dimensions is
// arbitrary. Giving more than 4 variables without the option=para or
// option=candle or option=goff will produce an error.
//
// Making a candle sticks chart
// ============================
// In case of a 2-Dim or more expression with the option=candle, one can generate
// a candle sticks chart. With that option, the number of dimensions is
// arbitrary. Giving more than 4 variables without the option=para or
// option=candle or option=goff will produce an error.
//
// Saving the result of Draw to a TEventList or a TEntryList
// =========================================================
// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
// instead of histogramming one variable.
// If varexp0 has the form >>elist , a TEventList object named "elist"
// is created in the current directory. elist will contain the list
// of entry numbers satisfying the current selection.
// If option "entrylist" is used, a TEntryList object is created
// Example:
// tree.Draw(">>yplus","y>0")
// will create a TEventList object named "yplus" in the current directory.
// In an interactive session, one can type (after TTree::Draw)
// yplus.Print("all")
// to print the list of entry numbers in the list.
// tree.Draw(">>yplus", "y>0", "entrylist")
// will create a TEntryList object names "yplus" in the current directory
//
// By default, the specified entry list is reset.
// To continue to append data to an existing list, use "+" in front
// of the list name;
// tree.Draw(">>+yplus","y>0")
// will not reset yplus, but will enter the selected entries at the end
// of the existing list.
//
// Using a TEventList or a TEntryList as Input
// ===========================
// Once a TEventList or a TEntryList object has been generated, it can be used as input
// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
// current event list
// Example1:
// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
// tree->SetEventList(elist);
// tree->Draw("py");
// Example2:
// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
// tree->SetEntryList(elist);
// tree->Draw("py");
// If a TEventList object is used as input, a new TEntryList object is created
// inside the SetEventList function. In case of a TChain, all tree headers are loaded
// for this transformation. This new object is owned by the chain and is deleted
// with it, unless the user extracts it by calling GetEntryList() function.
// See also comments to SetEventList() function of TTree and TChain.
//
// If arrays are used in the selection critera, the entry entered in the
// list are all the entries that have at least one element of the array that
// satisfy the selection.
// Example:
// tree.Draw(">>pyplus","fTracks.fPy>0");
// tree->SetEventList(pyplus);
// tree->Draw("fTracks.fPy");
// will draw the fPy of ALL tracks in event with at least one track with
// a positive fPy.
//
// To select only the elements that did match the original selection
// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
// Example:
// tree.Draw(">>pyplus","fTracks.fPy>0");
// pyplus->SetReapplyCut(kTRUE);
// tree->SetEventList(pyplus);
// tree->Draw("fTracks.fPy");
// will draw the fPy of only the tracks that have a positive fPy.
//
// Note: Use tree->SetEventList(0) if you do not want use the list as input.
//
// How to obtain more info from TTree::Draw
// ========================================
//
// Once TTree::Draw has been called, it is possible to access useful
// information still stored in the TTree object via the following functions:
// -GetSelectedRows() // return the number of entries accepted by the
// //selection expression. In case where no selection
// //was specified, returns the number of entries processed.
// -GetV1() //returns a pointer to the double array of V1
// -GetV2() //returns a pointer to the double array of V2
// -GetV3() //returns a pointer to the double array of V3
// -GetW() //returns a pointer to the double array of Weights
// //where weight equal the result of the selection expression.
// where V1,V2,V3 correspond to the expressions in
// TTree::Draw("V1:V2:V3",selection);
//
// Example:
// Root > ntuple->Draw("py:px","pz>4");
// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
// ntuple->GetV2(), ntuple->GetV1());
// Root > gr->Draw("ap"); //draw graph in current pad
// creates a TGraph object with a number of points corresponding to the
// number of entries selected by the expression "pz>4", the x points of the graph
// being the px values of the Tree and the y points the py values.
//
// Important note: By default TTree::Draw creates the arrays obtained
// with GetV1, GetV2, GetV3, GetW with a length corresponding to the
// parameter fEstimate. By default fEstimate=1000000 and can be modified
// via TTree::SetEstimate. A possible recipee is to do
// tree->SetEstimate(tree->GetEntries());
// You must call SetEstimate if the expected number of selected rows
// is greater than 1000000.
//
// You can use the option "goff" to turn off the graphics output
// of TTree::Draw in the above example.
//
// Automatic interface to TTree::Draw via the TTreeViewer
// ======================================================
//
// A complete graphical interface to this function is implemented
// in the class TTreeViewer.
// To start the TTreeViewer, three possibilities:
// - select TTree context menu item "StartViewer"
// - type the command "TTreeViewer TV(treeName)"
// - execute statement "tree->StartViewer();"
//
GetPlayer();
if (fPlayer)
return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
return -1;
}
//______________________________________________________________________________
void TTree::DropBaskets()
{
// Remove some baskets from memory.
TBranch* branch = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
branch = (TBranch*) fBranches.UncheckedAt(i);
branch->DropBaskets("all");
}
}
//______________________________________________________________________________
void TTree::DropBuffers(Int_t)
{
// Drop branch buffers to accomodate nbytes below MaxVirtualsize.
// Be careful not to remove current read/write buffers.
Int_t ndrop = 0;
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; ++i) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
Int_t nbaskets = branch->GetListOfBaskets()->GetEntriesFast();
for (Int_t j = 0; j < nbaskets - 1; ++j) {
if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
continue;
}
TBasket* basket = branch->GetBasket(j);
ndrop += basket->DropBuffers();
if (fTotalBuffers < fMaxVirtualSize) {
return;
}
}
}
}
//______________________________________________________________________________
Int_t TTree::Fill()
{
// Fill all branches.
//
// This function loops on all the branches of this tree. For
// each branch, it copies to the branch buffer (basket) the current
// values of the leaves data types. If a leaf is a simple data type,
// a simple conversion to a machine independent format has to be done.
//
// This machine independent version of the data is copied into a
// basket (each branch has its own basket). When a basket is full
// (32k worth of data by default), it is then optionally compressed
// and written to disk (this operation is also called comitting or
// 'flushing' the basket). The committed baskets are then
// immediately removed from memory.
//
// The function returns the number of bytes committed to the
// individual branches.
//
// If a write error occurs, the number of bytes returned is -1.
//
// If no data are written, because, e.g., the branch is disabled,
// the number of bytes returned is 0.
//
// The baskets are flushed and the Tree header saved at regular intervals
// ---------------------------------------------------------------------
// At regular intervals, when the amount of data written so far is
// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
// This makes future reading faster as it guarantees that baskets belonging to nearby
// entries will be on the same disk region.
// When the first call to flush the baskets happen, we also take this opportunity
// to optimize the baskets buffers.
// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
// In this case we also write the Tree header. This makes the Tree recoverable up to this point
// in case the program writing the Tree crashes.
// The decisions to FlushBaskets and Auto Save can be made based either on the number
// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
// written (fAutoFlush and fAutoSave positive).
// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
// base on the number of events written instead of the number of bytes written.
//
// Note that calling FlushBaskets too often increases the IO time.
// Note that calling AutoSave too often increases the IO time and also the file size.
Int_t nbytes = 0;
Int_t nerror = 0;
Int_t nb = fBranches.GetEntriesFast();
if (nb == 1) {
// Case of one single super branch. Automatically update
// all the branch addresses if a new object was created.
TBranch* branch = (TBranch*) fBranches.UncheckedAt(0);
branch->UpdateAddress();
}
if (fBranchRef) {
fBranchRef->Clear();
}
for (Int_t i = 0; i < nb; ++i) {
// Loop over all branches, filling and accumulating bytes written and error counts.
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
if (branch->TestBit(kDoNotProcess)) {
continue;
}
Int_t nwrite = branch->Fill();
if (nwrite < 0) {
if (nerror < 2) {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
" This error is symptomatic of a Tree created as a memory-resident Tree\n"
" Instead of doing:\n"
" TTree *T = new TTree(...)\n"
" TFile *f = new TFile(...)\n"
" you should do:\n"
" TFile *f = new TFile(...)\n"
" TTree *T = new TTree(...)",
GetName(), branch->GetName(), nwrite,fEntries+1);
} else {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,fEntries+1);
}
++nerror;
} else {
nbytes += nwrite;
}
}
if (fBranchRef) {
fBranchRef->Fill();
}
++fEntries;
if (fEntries > fMaxEntries) {
KeepCircular();
}
if (gDebug > 0) printf("TTree::Fill - A: %d %lld %lld %lld %lld %lld %lld \n",
nbytes, fEntries, fAutoFlush,fAutoSave,fZipBytes,fFlushedBytes,fSavedBytes);
if (fAutoFlush != 0 || fAutoSave != 0) {
// Is it time to flush or autosave baskets?
if (fFlushedBytes == 0) {
// Decision can be based initially either on the number of bytes
// or the number of entries written.
if ((fAutoFlush<0 && fZipBytes > -fAutoFlush) ||
(fAutoSave <0 && fZipBytes > -fAutoSave ) ||
(fAutoFlush>0 && fEntries%TMath::Max((Long64_t)1,fAutoFlush) == 0) ||
(fAutoSave >0 && fEntries%TMath::Max((Long64_t)1,fAutoSave) == 0) ) {
//we take the opportunity to Optimizebaskets at this point (it calls FlushBaskets)
OptimizeBaskets(fTotBytes,1,"");
if (gDebug > 0) printf("OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",fEntries,fZipBytes,fFlushedBytes);
fFlushedBytes = fZipBytes;
fAutoFlush = fEntries; // Use test on entries rather than bytes
// subsequently in run
if (fAutoSave < 0) {
// Set fAutoSave to the largest integer multiple of
// fAutoFlush events such that fAutoSave*fFlushedBytes
// < (minus the input value of fAutoSave)
fAutoSave = TMath::Max( fAutoFlush, fEntries*((-fAutoSave/fZipBytes)/fEntries));
} else if(fAutoSave > 0) {
fAutoSave = fEntries*(fAutoSave/fEntries);
}
if (fAutoSave!=0 && fEntries >= fAutoSave) AutoSave(); // FlushBaskets not called in AutoSave
if (gDebug > 0) printf("TTree::Fill: First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
}
} else if (fEntries > 1 && fEntries%fAutoFlush == 0) {
if (fEntries%fAutoSave == 0) {
//We are at an AutoSave point. AutoSave flushes baskets and saves the Tree header
AutoSave("flushbaskets");
if (gDebug > 0) printf("AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n",fEntries,fZipBytes,fSavedBytes);
} else {
//We only FlushBaskets
FlushBaskets();
if (gDebug > 0) printf("FlushBasket called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",fEntries,fZipBytes,fFlushedBytes);
}
fFlushedBytes = fZipBytes;
}
}
// Check that output file is still below the maximum size.
// If above, close the current file and continue on a new file.
// Currently, the automatic change of file is restricted
// to the case where the tree is in the top level directory.
if (!fDirectory) {
return nbytes;
}
TFile* file = fDirectory->GetFile();
if (file && (file->GetEND() > fgMaxTreeSize)) {
if (fDirectory == (TDirectory*) file) {
ChangeFile(file);
}
}
if (nerror) {
return -1;
}
return nbytes;
}
//______________________________________________________________________________
static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
// Search in the array for a branch matching the branch name,
// with the branch possibly expressed as a 'full' path name (with dots).
if (list==0 || branchname == 0 || branchname[0] == '\0') return 0;
Int_t nbranches = list->GetEntries();
UInt_t brlen = strlen(branchname);
for(Int_t index = 0; index < nbranches; ++index) {
TBranch *where = (TBranch*)list->UncheckedAt(index);
const char *name = where->GetName();
UInt_t len = strlen(name);
if (name[len-1]==']') {
const char *dim = strchr(name,'[');
if (dim) {
len = dim - name;
}
}
if (brlen == len && strncmp(branchname,name,len)==0) {
return where;
}
TBranch *next = 0;
if ((brlen >= len) && (branchname[len] == '.')
&& strncmp(name, branchname, len) == 0) {
// The prefix subbranch name match the branch name.
next = where->FindBranch(branchname);
if (!next) {
next = where->FindBranch(branchname+len+1);
}
if (next) return next;
}
const char *dot = strchr((char*)branchname,'.');
if (dot) {
if (len==(size_t)(dot-branchname) &&
strncmp(branchname,name,dot-branchname)==0 ) {
return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
}
}
}
return 0;
}
//______________________________________________________________________________
TBranch* TTree::FindBranch(const char* branchname)
{
// Return the branch that correspond to the path 'branchname', which can
// include the name of the tree or the ommited name of the parent branches.
// In case of ambiguity, returns the first match.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kFindBranch & fFriendLockStatus) {
return 0;
}
TBranch* branch = 0;
// If the first part of the name match the TTree name, look for the right part in the
// list of branches.
// This will allow the branchname to be preceded by
// the name of this tree.
if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
if (branch) return branch;
}
// If we did not find it, let's try to find the full name in the list of branches.
branch = R__FindBranchHelper(GetListOfBranches(), branchname);
if (branch) return branch;
// If we still did not find, let's try to find it within each branch assuming it does not the branch name.
TIter next(GetListOfBranches());
while ((branch = (TBranch*) next())) {
TBranch* nestedbranch = branch->FindBranch(branchname);
if (nestedbranch) {
return nestedbranch;
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindBranch);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
const char *subbranch = strstr(branchname, fe->GetName());
if (subbranch != branchname) {
subbranch = 0;
}
if (subbranch) {
subbranch += strlen(fe->GetName());
if (*subbranch != '.') {
subbranch = 0;
} else {
++subbranch;
}
}
std::ostringstream name;
if (subbranch) {
name << t->GetName() << "." << subbranch;
} else {
name << branchname;
}
branch = t->FindBranch(name.str().c_str());
if (branch) {
return branch;
}
}
return 0;
}
//______________________________________________________________________________
TLeaf* TTree::FindLeaf(const char* searchname)
{
// FIXME: Describe this function.
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kFindLeaf & fFriendLockStatus) {
return 0;
}
// This will allow the branchname to be preceded by
// the name of this tree.
char* subsearchname = (char*) strstr(searchname, GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
if (subsearchname[0]==0) {
subsearchname = 0;
}
}
}
TString leafname;
TString leaftitle;
TString longname;
TString longtitle;
// For leaves we allow for one level up to be prefixed to the name.
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leafname = leaf->GetName();
Ssiz_t dim = leafname.First('[');
if (dim >= 0) leafname.Remove(dim);
if (leafname == searchname) {
return leaf;
}
if (subsearchname && leafname == subsearchname) {
return leaf;
}
// The TLeafElement contains the branch name
// in its name, let's use the title.
leaftitle = leaf->GetTitle();
dim = leaftitle.First('[');
if (dim >= 0) leaftitle.Remove(dim);
if (leaftitle == searchname) {
return leaf;
}
if (subsearchname && leaftitle == subsearchname) {
return leaf;
}
TBranch* branch = leaf->GetBranch();
if (branch) {
longname.Form("%s.%s",branch->GetName(),leafname.Data());
dim = longname.First('[');
if (dim>=0) longname.Remove(dim);
if (longname == searchname) {
return leaf;
}
if (subsearchname && longname == subsearchname) {
return leaf;
}
longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
dim = longtitle.First('[');
if (dim>=0) longtitle.Remove(dim);
if (longtitle == searchname) {
return leaf;
}
if (subsearchname && longtitle == subsearchname) {
return leaf;
}
// The following is for the case where the branch is only
// a sub-branch. Since we do not see it through
// TTree::GetListOfBranches, we need to see it indirectly.
// This is the less sturdy part of this search ... it may
// need refining ...
if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
return leaf;
}
if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
return leaf;
}
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindLeaf);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
subsearchname = (char*) strstr(searchname, fe->GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(fe->GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
}
}
if (subsearchname) {
leafname.Form("%s.%s",t->GetName(),subsearchname);
} else {
leafname = searchname;
}
leaf = t->FindLeaf(leafname);
if (leaf) {
return leaf;
}
}
return 0;
}
//______________________________________________________________________________
Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
{
// Fit a projected item(s) from a tree.
//
// funcname is a TF1 function.
//
// See TTree::Draw() for explanations of the other parameters.
//
// By default the temporary histogram created is called htemp.
// If varexp contains >>hnew , the new histogram created is called hnew
// and it is kept in the current directory.
//
// The function returns the number of selected entries.
//
// Example:
// tree.Fit(pol4,sqrt(x)>>hsqrt,y>0)
// will fit sqrt(x) and save the histogram as "hsqrt" in the current
// directory.
//
// See also TTree::UnbinnedFit
//
// Return status
// =============
// The function returns the status of the histogram fit (see TH1::Fit)
// If no entries were selected, the function returns -1;
// (ie fitResult is null is the fit is OK)
GetPlayer();
if (fPlayer) {
return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Int_t TTree::FlushBaskets() const
{
// Write to disk all the basket that have not yet been individually written.
//
// Return the number of bytes written or -1 in case of write error.
if (!fDirectory) return 0;
Int_t nbytes = 0;
Int_t nerror = 0;
TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
Int_t nb = lb->GetEntriesFast();
for (Int_t j = 0; j < nb; j++) {
TBranch* branch = (TBranch*) lb->UncheckedAt(j);
if (branch) {
Int_t nwrite = branch->FlushBaskets();
if (nwrite<0) {
++nerror;
} else {
nbytes += nwrite;
}
}
}
if (nerror) {
return -1;
} else {
return nbytes;
}
}
//______________________________________________________________________________
const char* TTree::GetAlias(const char* aliasName) const
{
// Returns the expanded value of the alias. Search in the friends if any.
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetAlias & fFriendLockStatus) {
return 0;
}
if (fAliases) {
TObject* alias = fAliases->FindObject(aliasName);
if (alias) {
return alias->GetTitle();
}
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t) {
const char* alias = t->GetAlias(aliasName);
if (alias) {
return alias;
}
const char* subAliasName = strstr(aliasName, fe->GetName());
if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
if (alias) {
return alias;
}
}
}
}
return 0;
}
//______________________________________________________________________________
TBranch* TTree::GetBranch(const char* name)
{
// Return pointer to the branch with the given name in this tree or its friends.
if (name == 0) return 0;
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetBranch & fFriendLockStatus) {
return 0;
}
// Search using branches.
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
if (!strcmp(branch->GetName(), name)) {
return branch;
}
TObjArray* lb = branch->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; j++) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!strcmp(b1->GetName(), name)) {
return b1;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; k++) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!strcmp(b2->GetName(), name)) {
return b2;
}
}
}
}
// Search using leaves.
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (!strcmp(branch->GetName(), name)) {
return branch;
}
}
if (!fFriends) {
return 0;
}
// Search in list of friends.
TFriendLock lock(this, kGetBranch);
TIter next(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (t) {
TBranch* branch = t->GetBranch(name);
if (branch) {
return branch;
}
}
}
// Second pass in the list of friends when
// the branch name is prefixed by the tree name.
next.Reset();
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
char* subname = (char*) strstr(name, fe->GetName());
if (subname != name) {
continue;
}
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') {
continue;
}
subname++;
TBranch* branch = t->GetBranch(subname);
if (branch) {
return branch;
}
}
return 0;
}
//______________________________________________________________________________
Bool_t TTree::GetBranchStatus(const char* branchname) const
{
// Return status of branch with name branchname.
// 0 if branch is not activated
// 1 if branch is activated
TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
if (br) {
return br->TestBit(kDoNotProcess) == 0;
}
return 0;
}
//______________________________________________________________________________
Int_t TTree::GetBranchStyle()
{
// Static function returning the current branch style.
// style = 0 old Branch
// style = 1 new Bronch
return fgBranchStyle;
}
//______________________________________________________________________________
TFile* TTree::GetCurrentFile() const
{
// Return pointer to the current file.
if (!fDirectory || fDirectory==gROOT) {
return 0;
}
return fDirectory->GetFile();
}
//______________________________________________________________________________
Long64_t TTree::GetEntries(const char *selection)
{
// Return the number of entries matching the selection.
// Return -1 in case of errors.
//
// If the selection uses any arrays or containers, we return the number
// of entries where at least one element match the selection.
// GetEntries is implemented using the selector class TSelectorEntries,
// which can be used directly (see code in TTreePlayer::GetEntries) for
// additional option.
// If SetEventList was used on the TTree or TChain, only that subset
// of entries will be considered.
GetPlayer();
if (fPlayer) {
return fPlayer->GetEntries(selection);
}
return -1;
}
//______________________________________________________________________________
Long64_t TTree::GetEntriesFriend() const
{
// Return pointer to the 1st Leaf named name in any Branch of this Tree or
// any branch in the list of friend trees.
if (fEntries) return fEntries;
if (!fFriends) return 0;
TFriendElement *fr = (TFriendElement*)fFriends->At(0);
if (!fr) return 0;
TTree *t = fr->GetTree();
if (t==0) return 0;
return t->GetEntriesFriend();
}
//______________________________________________________________________________
Int_t TTree::GetEntry(Long64_t entry, Int_t getall)
{
// Read all branches of entry and return total number of bytes read.
//
// getall = 0 : get only active branches
// getall = 1 : get all branches
//
// The function returns the number of bytes read from the input buffer.
// If entry does not exist the function returns 0.
// If an I/O error occurs, the function returns -1.
//
// If the Tree has friends, also read the friends entry
//
// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
// For example, if you have a Tree with several hundred branches, and you
// are interested only by branches named "u" and "v", do
// mytree.SetBranchStatus("*",0); //disable all branches
// mytree.SetBranchStatus("a",1);
// mytree.SetBranchStatus("b",1);
// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
//
// WARNING!!
// If your Tree has been created in split mode with a parent branch "parent",
// mytree.SetBranchStatus("parent",1);
// will not activate the sub-branches of "parent". You should do:
// mytree.SetBranchStatus("parent*",1);
//
// An alternative is to call directly
// brancha.GetEntry(i)
// branchb.GetEntry(i);
//
// IMPORTANT NOTE
// ==============
// By default, GetEntry reuses the space allocated by the previous object
// for each branch. You can force the previous object to be automatically
// deleted if you call mybranch.SetAutoDelete(kTRUE) (default is kFALSE).
// Example:
// Consider the example in $ROOTSYS/test/Event.h
// The top level branch in the tree T is declared with:
// Event *event = 0; //event must be null or point to a valid object
// //it must be initialized
// T.SetBranchAddress("event",&event);
// When reading the Tree, one can choose one of these 3 options:
//
// OPTION 1
// --------
//
// for (Long64_t i=0;i<nentries;i++) {
// T.GetEntry(i);
// // the object event has been filled at this point
// }
// The default (recommended). At the first entry an object of the
// class Event will be created and pointed by event.
// At the following entries, event will be overwritten by the new data.
// All internal members that are TObject* are automatically deleted.
// It is important that these members be in a valid state when GetEntry
// is called. Pointers must be correctly initialized.
// However these internal members will not be deleted if the characters "->"
// are specified as the first characters in the comment field of the data
// member declaration.
// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
// In this case, it is assumed that the pointer is never null (case
// of pointer TClonesArray *fTracks in the Event example).
// If "->" is not specified, the pointer member is read via buf >> pointer.
// In this case the pointer may be null. Note that the option with "->"
// is faster to read or write and it also consumes less space in the file.
//
// OPTION 2
// --------
// The option AutoDelete is set
// TBranch *branch = T.GetBranch("event");
// branch->SetAddress(&event);
// branch->SetAutoDelete(kTRUE);
// for (Long64_t i=0;i<nentries;i++) {
// T.GetEntry(i);
// // the object event has been filled at this point
// }
// In this case, at each iteration, the object event is deleted by GetEntry
// and a new instance of Event is created and filled.
//
// OPTION 3
// --------
// Same as option 1, but you delete yourself the event.
// for (Long64_t i=0;i<nentries;i++) {
// delete event;
// event = 0; // EXTREMELY IMPORTANT
// T.GetEntry(i);
// // the object event has been filled at this point
// }
//
// It is strongly recommended to use the default option 1. It has the
// additional advantage that functions like TTree::Draw (internally
// calling TTree::GetEntry) will be functional even when the classes in the
// file are not available.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetEntry & fFriendLockStatus) return 0;
if (entry < 0 || entry >= fEntries) return 0;
Int_t i;
Int_t nbytes = 0;
fReadEntry = entry;
TBranch *branch;
Int_t nbranches = fBranches.GetEntriesFast();
Int_t nb=0;
for (i=0;i<nbranches;i++) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(entry, getall);
if (nb < 0) return nb;
nbytes += nb;
}
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntry);
TIter nextf(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t) {
if (fe->TestBit(TFriendElement::kFromChain)) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else {
if ( t->LoadTreeFriend(entry,this) >= 0 ) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else nb = 0;
}
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
//______________________________________________________________________________
TEntryList* TTree::GetEntryList()
{
//Returns the entry list, set to this tree
return fEntryList;
}
//______________________________________________________________________________
Long64_t TTree::GetEntryNumber(Long64_t entry) const
{
// Return entry number corresponding to entry.
//
// if no TEntryList set returns entry
// else returns the entry number corresponding to the list index=entry
if (!fEntryList) {
return entry;
}
return fEntryList->GetEntry(entry);
}
//______________________________________________________________________________
Long64_t TTree::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const
{
// Return entry number corresponding to major and minor number.
// Note that this function returns only the entry number, not the data
// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
// the BuildIndex function has created a table of Long64_t* of sorted values
// corresponding to val = major<<31 + minor;
// The function performs binary search in this sorted table.
// If it finds a pair that maches val, it returns directly the
// index in the table.
// If an entry corresponding to major and minor is not found, the function
// returns the index of the major,minor pair immediatly lower than the
// requested value, ie it will return -1 if the pair is lower than
// the first entry in the index.
//
// See also GetEntryNumberWithIndex
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithBestIndex(major, minor);
}
//______________________________________________________________________________
Long64_t TTree::GetEntryNumberWithIndex(Int_t major, Int_t minor) const
{
// Return entry number corresponding to major and minor number.
// Note that this function returns only the entry number, not the data
// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
// the BuildIndex function has created a table of Long64_t* of sorted values
// corresponding to val = major<<31 + minor;
// The function performs binary search in this sorted table.
// If it finds a pair that maches val, it returns directly the
// index in the table, otherwise it returns -1.
//
// See also GetEntryNumberWithBestIndex
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithIndex(major, minor);
}
//______________________________________________________________________________
Int_t TTree::GetEntryWithIndex(Int_t major, Int_t minor)
{
// Read entry corresponding to major and minor number.
//
// The function returns the total number of bytes read.
// If the Tree has friend trees, the corresponding entry with
// the index values (major,minor) is read. Note that the master Tree
// and its friend may have different entry serial numbers corresponding
// to (major,minor).
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetEntryWithIndex & fFriendLockStatus) {
return 0;
}
Long64_t serial = GetEntryNumberWithIndex(major, minor);
if (serial < 0) {
return -1;
}
Int_t i;
Int_t nbytes = 0;
fReadEntry = serial;
TBranch *branch;
Int_t nbranches = fBranches.GetEntriesFast();
Int_t nb;
for (i = 0; i < nbranches; ++i) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntryWithIndex);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *t = fe->GetTree();
if (t) {
serial = t->GetEntryNumberWithIndex(major,minor);
if (serial <0) return -nbytes;
nb = t->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
//______________________________________________________________________________
TTree* TTree::GetFriend(const char *friendname) const
{
// Return a pointer to the TTree friend whose name or alias is 'friendname.
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriend & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (strcmp(friendname,fe->GetName())==0
|| strcmp(friendname,fe->GetTreeName())==0) {
return fe->GetTree();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *res = fe->GetTree()->GetFriend(friendname);
if (res) {
return res;
}
}
return 0;
}
//______________________________________________________________________________
const char* TTree::GetFriendAlias(TTree* tree) const
{
// If the the 'tree' is a friend, this method returns its alias name.
//
// This alias is an alternate name for the tree.
//
// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
// to specify in which particular tree the branch or leaf can be found if
// the friend trees have branches or leaves with the same name as the master
// tree.
//
// It can also be used in conjunction with an alias created using
// TTree::SetAlias in a TTreeFormula, e.g.:
//
// maintree->Draw("treealias.fPx - treealias.myAlias");
//
// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
// was created using TTree::SetAlias on the friend tree.
//
// However, note that 'treealias.myAlias' will be expanded literally,
// without remembering that it comes from the aliased friend and thus
// the branch name might not be disambiguated properly, which means
// that you may not be able to take advantage of this feature.
//
if ((tree == this) || (tree == GetTree())) {
return 0;
}
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriendAlias & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t == tree) {
return fe->GetName();
}
// Case of a chain:
if (t->GetTree() == tree) {
return fe->GetName();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
const char* res = fe->GetTree()->GetFriendAlias(tree);
if (res) {
return res;
}
}
return 0;
}
//______________________________________________________________________________
TIterator* TTree::GetIteratorOnAllLeaves(Bool_t dir)
{
// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
return new TTreeFriendLeafIter(this, dir);
}
//______________________________________________________________________________
TLeaf* TTree::GetLeaf(const char* aname)
{
// Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of friend trees.
//
// aname may be of the form branchname/leafname
if (aname == 0) return 0;
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetLeaf & fFriendLockStatus) {
return 0;
}
TLeaf *leaf = 0;
char* slash = (char*) strchr(aname, '/');
char* name = 0;
UInt_t nbch = 0;
if (slash) {
name = slash + 1;
nbch = slash - aname;
TString brname(aname,nbch);
TBranch *branch = FindBranch(brname);
if (branch) {
leaf = branch->GetLeaf(name);
if (leaf) {
return leaf;
}
}
} else {
name = (char*) aname;
}
TIter nextl(GetListOfLeaves());
while ((leaf = (TLeaf*)nextl())) {
if (strcmp(leaf->GetName(),name)) continue;
if (slash) {
TBranch *br = leaf->GetBranch();
const char* brname = br->GetName();
TBranch *mother = br->GetMother();
if (strncmp(brname,aname,nbch)) {
if (mother != br) {
const char *mothername = mother->GetName();
UInt_t motherlen = strlen(mothername);
if (nbch > motherlen && strncmp(mothername,aname,motherlen)==0 && (mothername[motherlen-1]=='.' || aname[motherlen]=='.')) {
// The left part of the requested name match the name of the mother, let's see if the right part match the name of the branch.
if (strncmp(brname,aname+motherlen+1,nbch-motherlen-1)) {
// No it does not
continue;
} // else we have match so we can proceed.
} else {
// no match
continue;
}
} else {
continue;
}
}
// The start of the branch name is indentical to the content
// of 'aname' before the first '/'.
// Let's make sure that it is not longer (we are trying
// to avoid having jet2/value match the branch jet23
if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
continue;
}
}
return leaf;
}
if (!fFriends) return 0;
TFriendLock lock(this,kGetLeaf);
TIter next(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t) {
leaf = t->GetLeaf(aname);
if (leaf) return leaf;
}
}
//second pass in the list of friends when the leaf name
//is prefixed by the tree name
TString strippedArg;
next.Reset();
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t==0) continue;
char *subname = (char*)strstr(name,fe->GetName());
if (subname != name) continue;
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') continue;
subname++;
if (slash) {
strippedArg = aname;
strippedArg.Remove(nbch+1);
} else {
strippedArg = "";
}
strippedArg += subname;
leaf = t->GetLeaf(strippedArg);
if (leaf) return leaf;
}
return 0;
}
//______________________________________________________________________________
Double_t TTree::GetMaximum(const char* columname)
{
// Return maximum of column with name columname.
// if the Tree has an associated TEventList or TEntryList, the maximum
// is computed for the entries in this list.
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
TBranch* branch = leaf->GetBranch();
Double_t cmax = -FLT_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0; j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val > cmax) {
cmax = val;
}
}
}
return cmax;
}
//______________________________________________________________________________
Long64_t TTree::GetMaxTreeSize()
{
// Static function which returns the tree file size limit.
return fgMaxTreeSize;
}
//______________________________________________________________________________
Double_t TTree::GetMinimum(const char* columname)
{
// Return minimum of column with name columname.
// if the Tree has an associated TEventList or TEntryList, the minimum
// is computed for the entries in this list.
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
TBranch* branch = leaf->GetBranch();
Double_t cmin = FLT_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0;j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val < cmin) {
cmin = val;
}
}
}
return cmin;
}
//______________________________________________________________________________
TVirtualTreePlayer* TTree::GetPlayer()
{
// Load the TTreePlayer (if not already done).
if (fPlayer) {
return fPlayer;
}
fPlayer = TVirtualTreePlayer::TreePlayer(this);
return fPlayer;
}
//______________________________________________________________________________
TList* TTree::GetUserInfo()
{
// Return a pointer to the list containing user objects associated to this tree.
//
// The list is automatically created if it does not exist.
//
// WARNING: By default the TTree destructor will delete all objects added
// to this list. If you do not want these objects to be deleted,
// call:
//
// mytree->GetUserInfo()->Clear();
//
// before deleting the tree.
if (!fUserInfo) {
fUserInfo = new TList();
fUserInfo->SetName("UserInfo");
}
return fUserInfo;
}
//______________________________________________________________________________
void TTree::KeepCircular()
{
// Keep a maximum of fMaxEntries in memory.
Int_t nb = fBranches.GetEntriesFast();
Long64_t maxEntries = fMaxEntries - (fMaxEntries / 10);
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->KeepCircular(maxEntries);
}
fEntries = maxEntries;
fReadEntry = -1;
}
//______________________________________________________________________________
Int_t TTree::LoadBaskets(Long64_t maxmemory)
{
// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
//
// If maxmemory is non null and positive SetMaxVirtualSize is called
// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
// The function returns the total number of baskets read into memory
// if negative an error occured while loading the branches.
// This method may be called to force branch baskets in memory
// when random access to branch entries is required.
// If random access to only a few branches is required, you should
// call directly TBranch::LoadBaskets.
if (maxmemory > 0) SetMaxVirtualSize(maxmemory);
TIter next(GetListOfLeaves());
TLeaf *leaf;
Int_t nimported = 0;
while ((leaf=(TLeaf*)next())) {
nimported += leaf->GetBranch()->LoadBaskets();//break;
}
return nimported;
}
//______________________________________________________________________________
Long64_t TTree::LoadTree(Long64_t entry)
{
// Set current entry.
//
// Returns -2 if entry does not exist (just as TChain::LoadTree()).
//
// Note: This function is overloaded in TChain.
//
// We already have been visited while recursively looking
// through the friends tree, let return
if (kLoadTree & fFriendLockStatus) {
// We need to return a negative value to avoid a circular list of friend
// to think that there is always an entry somewhere in the lisst.
return -1;
}
if (fNotify) {
if (fReadEntry < 0) {
fNotify->Notify();
}
}
fReadEntry = entry;
Bool_t friendHasEntry = kFALSE;
if (fFriends) {
// Set current entry in friends as well.
//
// An alternative would move this code to each of the
// functions calling LoadTree (and to overload a few more).
Bool_t needUpdate = kFALSE;
{
// This scope is need to insure the lock is released at the right time
TIter nextf(fFriends);
TFriendLock lock(this, kLoadTree);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (fe->TestBit(TFriendElement::kFromChain)) {
// This friend element was added by the chain that owns this
// tree, the chain will deal with loading the correct entry.
continue;
}
TTree* friendTree = fe->GetTree();
if (friendTree->IsA() == TTree::Class()) {
// Friend is actually a tree.
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
} else {
// Friend is actually a chain.
// FIXME: This logic should be in the TChain override.
Int_t oldNumber = friendTree->GetTreeNumber();
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
Int_t newNumber = friendTree->GetTreeNumber();
if (oldNumber != newNumber) {
// We can not just compare the tree pointers because they could be reused.
// So we compare the tree number instead.
needUpdate = kTRUE;
}
}
} // for each friend
}
if (needUpdate) {
//update list of leaves in all TTreeFormula of the TTreePlayer (if any)
if (fPlayer) {
fPlayer->UpdateFormulaLeaves();
}
//Notify user if requested
if (fNotify) {
fNotify->Notify();
}
}
}
if ((fReadEntry >= fEntries) && !friendHasEntry) {
fReadEntry = -1;
return -2;
}
return fReadEntry;
}
//______________________________________________________________________________
Long64_t TTree::LoadTreeFriend(Long64_t entry, TTree* masterTree)
{
// Load entry on behalf of our master tree, we may use an index.
//
// Called by LoadTree() when the masterTree looks for the entry
// number in a friend tree (us) corresponding to the passed entry
// number in the masterTree.
//
// If we have no index, our entry number and the masterTree entry
// number are the same.
//
// If we *do* have an index, we must find the (major, minor) value pair
// in masterTree to locate our corresponding entry.
//
if (!fTreeIndex) {
return LoadTree(entry);
}
return LoadTree(fTreeIndex->GetEntryNumberFriend(masterTree));
}
//______________________________________________________________________________
Int_t TTree::MakeClass(const char* classname, Option_t* option)
{
// Generate a skeleton analysis class for this tree.
//
// The following files are produced: classname.h and classname.C.
// If classname is 0, classname will be called "nameoftree".
//
// The generated code in classname.h includes the following:
// - Identification of the original tree and the input file name.
// - Definition of an analysis class (data members and member functions).
// - The following member functions:
// - constructor (by default opening the tree file),
// - GetEntry(Long64_t entry),
// - Init(TTree* tree) to initialize a new TTree,
// - Show(Long64_t entry) to read and dump entry.
//
// The generated code in classname.C includes only the main
// analysis function Loop.
//
// To use this function:
// - Open your tree file (eg: TFile f("myfile.root");)
// - T->MakeClass("MyClass");
// where T is the name of the TTree in file myfile.root,
// and MyClass.h, MyClass.C the name of the files created by this function.
// In a ROOT session, you can do:
// root > .L MyClass.C
// root > MyClass* t = new MyClass;
// root > t->GetEntry(12); // Fill data members of t with entry number 12.
// root > t->Show(); // Show values of entry 12.
// root > t->Show(16); // Read and show values of entry 16.
// root > t->Loop(); // Loop on all entries.
//
// NOTE: Do not use the code generated for a single TTree which is part
// of a TChain to process that entire TChain. The maximum dimensions
// calculated for arrays on the basis of a single TTree from the TChain
// might be (will be!) too small when processing all of the TTrees in
// the TChain. You must use myChain.MakeClass() to generate the code,
// not myTree.MakeClass(...).
//
GetPlayer();
if (!fPlayer) {
return 0;
}
return fPlayer->MakeClass(classname, option);
}
//______________________________________________________________________________
Int_t TTree::MakeCode(const char* filename)
{
// Generate a skeleton function for this tree.
//
// The function code is written on filename.
// If filename is 0, filename will be called nameoftree.C
//
// The generated code includes the following:
// - Identification of the original Tree and Input file name,
// - Opening the Tree file,
// - Declaration of Tree variables,
// - Setting of branches addresses,
// - A skeleton for the entry loop.
//
// To use this function:
// - Open your Tree file (eg: TFile f("myfile.root");)
// - T->MakeCode("MyAnalysis.C");
// where T is the name of the TTree in file myfile.root
// and MyAnalysis.C the name of the file created by this function.
//
// NOTE: Since the implementation of this function, a new and better
// function TTree::MakeClass() has been developed.
Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeCode(filename);
}
//______________________________________________________________________________
Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
{
// Generate a skeleton analysis class for this Tree using TBranchProxy.
//
// TBranchProxy is the base of a class hierarchy implementing an
// indirect access to the content of the branches of a TTree.
//
// "proxyClassname" is expected to be of the form:
// [path/]fileprefix
// The skeleton will then be generated in the file:
// fileprefix.h
// located in the current directory or in 'path/' if it is specified.
// The class generated will be named 'fileprefix'
//
// "macrofilename" and optionally "cutfilename" are expected to point
// to source files which will be included by the generated skeleton.
// Method of the same name as the file(minus the extension and path)
// will be called by the generated skeleton's Process method as follow:
// [if (cutfilename())] htemp->Fill(macrofilename());
//
// "option" can be used select some of the optional features during
// the code generation. The possible options are:
// nohist : indicates that the generated ProcessFill should not
// fill the histogram.
//
// 'maxUnrolling' controls how deep in the class hierachy does the
// system 'unroll' classes that are not split. Unrolling a class
// allows direct access to its data members (this emulates the behavior
// of TTreeFormula).
//
// The main features of this skeleton are:
//
// * on-demand loading of branches
// * ability to use the 'branchname' as if it was a data member
// * protection against array out-of-bounds errors
// * ability to use the branch data as an object (when the user code is available)
//
// For example with Event.root, if
// Double_t somePx = fTracks.fPx[2];
// is executed by one of the method of the skeleton,
// somePx will updated with the current value of fPx of the 3rd track.
//
// Both macrofilename and the optional cutfilename are expected to be
// the name of source files which contain at least a free standing
// function with the signature:
// x_t macrofilename(); // i.e function with the same name as the file
// and
// y_t cutfilename(); // i.e function with the same name as the file
//
// x_t and y_t needs to be types that can convert respectively to a double
// and a bool (because the skeleton uses:
// if (cutfilename()) htemp->Fill(macrofilename());
//
// These two functions are run in a context such that the branch names are
// available as local variables of the correct (read-only) type.
//
// Note that if you use the same 'variable' twice, it is more efficient
// to 'cache' the value. For example
// Int_t n = fEventNumber; // Read fEventNumber
// if (n<10 || n>10) { ... }
// is more efficient than
// if (fEventNumber<10 || fEventNumber>10)
//
// Also, optionally, the generated selector will also call methods named
// macrofilename_methodname in each of 6 main selector methods if the method
// macrofilename_methodname exist (Where macrofilename is stripped of its
// extension).
//
// Concretely, with the script named h1analysisProxy.C,
//
// The method calls the method (if it exist)
// Begin -> void h1analysisProxy_Begin(TTree*);
// SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
// Notify -> Bool_t h1analysisProxy_Notify();
// Process -> Bool_t h1analysisProxy_Process(Long64_t);
// SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
// Terminate -> void h1analysisProxy_Terminate();
//
// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
// it is included before the declaration of the proxy class. This can
// be used in particular to insure that the include files needed by
// the macro file are properly loaded.
//
// The default histogram is accessible via the variable named 'htemp'.
//
// If the library of the classes describing the data in the branch is
// loaded, the skeleton will add the needed #include statements and
// give the ability to access the object stored in the branches.
//
// To draw px using the file hsimple.root (generated by the
// hsimple.C tutorial), we need a file named hsimple.cxx:
//
// double hsimple() {
// return px;
// }
//
// MakeProxy can then be used indirectly via the TTree::Draw interface
// as follow:
// new TFile("hsimple.root")
// ntuple->Draw("hsimple.cxx");
//
// A more complete example is available in the tutorials directory:
// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
// which reimplement the selector found in h1analysis.C
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeProxy(proxyClassname,macrofilename,cutfilename,option,maxUnrolling);
}
//______________________________________________________________________________
Int_t TTree::MakeSelector(const char* selector)
{
// Generate skeleton selector class for this tree.
//
// The following files are produced: selector.h and selector.C.
// If selector is 0, the selector will be called "nameoftree".
//
// The generated code in selector.h includes the following:
// - Identification of the original Tree and Input file name
// - Definition of selector class (data and functions)
// - The following class functions:
// - constructor and destructor
// - void Begin(TTree *tree)
// - void SlaveBegin(TTree *tree)
// - void Init(TTree *tree)
// - Bool_t Notify()
// - Bool_t Process(Long64_t entry)
// - void Terminate()
// - void SlaveTerminate()
//
// The class selector derives from TSelector.
// The generated code in selector.C includes empty functions defined above.
//
// To use this function:
// - connect your Tree file (eg: TFile f("myfile.root");)
// - T->MakeSelector("myselect");
// where T is the name of the Tree in file myfile.root
// and myselect.h, myselect.C the name of the files created by this function.
// In a ROOT session, you can do:
// root > T->Process("myselect.C")
return MakeClass(selector, "selector");
}
//______________________________________________________________________________
Bool_t TTree::MemoryFull(Int_t nbytes)
{
// Check if adding nbytes to memory we are still below MaxVirtualsize.
if ((fTotalBuffers + nbytes) < fMaxVirtualSize) {
return kFALSE;
}
return kTRUE;
}
//______________________________________________________________________________
TTree* TTree::MergeTrees(TList* li, Option_t* /* option */)
{
// Static function merging the trees in the TList into a new tree.
//
// Trees in the list can be memory or disk-resident trees.
// The new tree is created in the current directory (memory if gROOT).
//
if (!li) return 0;
TIter next(li);
TTree *newtree = 0;
TObject *obj;
while ((obj=next())) {
if (!obj->InheritsFrom(TTree::Class())) continue;
TTree *tree = (TTree*)obj;
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
if (!newtree) {
newtree = (TTree*)tree->CloneTree();
// Once the cloning is done, separate the trees,
// to avoid as many side-effects as possible
tree->GetListOfClones()->Remove(newtree);
tree->ResetBranchAddresses();
newtree->ResetBranchAddresses();
continue;
}
newtree->CopyAddresses(tree);
for (Long64_t i=0;i<nentries;i++) {
tree->GetEntry(i);
newtree->Fill();
}
tree->ResetBranchAddresses(); // Disconnect from new tree.
if (newtree->GetTreeIndex()) {
newtree->GetTreeIndex()->Append(tree->GetTreeIndex(),kTRUE);
}
}
if (newtree && newtree->GetTreeIndex()) {
newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
return newtree;
}
//______________________________________________________________________________
Long64_t TTree::Merge(TCollection* li, Option_t* /* option */)
{
// Merge the trees in the TList into this tree.
//
// Returns the total number of entries in the merged tree.
//
if (!li) return 0;
TIter next(li);
TTree *tree;
while ((tree = (TTree*)next())) {
if (tree==this) continue;
if (!tree->InheritsFrom(TTree::Class())) {
Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
return -1;
}
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
CopyAddresses(tree);
for (Long64_t i=0; i<nentries ; i++) {
tree->GetEntry(i);
Fill();
}
if (GetTreeIndex()) {
GetTreeIndex()->Append(tree->GetTreeIndex(),kTRUE);
}
tree->ResetBranchAddresses();
}
if (GetTreeIndex()) {
GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
return GetEntries();
}
//______________________________________________________________________________
Bool_t TTree::Notify()
{
// Function called when loading a new class library.
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leaf->Notify();
leaf->GetBranch()->Notify();
}
return kTRUE;
}
//______________________________________________________________________________
void TTree::OptimizeBaskets(Int_t maxMemory, Float_t minComp, Option_t *option)
{
//This function may be called after having filled some entries in a Tree
//Using the information in the existing branch buffers, it will reassign
//new branch buffer sizes to optimize time and memory.
//
//The function computes the best values for branch buffer sizes such that
//the total buffer sizes is less than maxMemory and nearby entries written
//at the same time.
//In case the branch compression factor for the data written so far is less
//than compMin, the compression is disabled.
//
//if option ="d" an analysis report is printed.
//Flush existing baskets if the file is writable
if (this->GetDirectory()->IsWritable()) this->FlushBaskets();
TString opt( option );
opt.ToLower();
Bool_t pDebug = opt.Contains("d");
TObjArray *leaves = this->GetListOfLeaves();
Int_t nleaves = leaves->GetEntries();
Double_t treeSize = (Double_t)this->GetTotBytes();
if (nleaves == 0 || treeSize == 0) {
// We're being called too early, we really have nothing to do ...
return;
}
Double_t aveSize = treeSize/nleaves;
Int_t bmin = 512;
Int_t bmax = 256000;
Double_t memFactor = 1;
Int_t i, oldMemsize,newMemsize,oldBaskets,newBaskets;
//we make two passes
//one pass to compute the relative branch buffer sizes
//a second pass to compute the absolute values
for (Int_t pass =0;pass<2;pass++) {
oldMemsize = 0; //to count size of baskets in memory with old buffer size
newMemsize = 0; //to count size of baskets in memory with new buffer size
oldBaskets = 0; //to count number of baskets with old buffer size
newBaskets = 0; //to count number of baskets with new buffer size
for (i=0;i<nleaves;i++) {
TLeaf *leaf = (TLeaf*)leaves->At(i);
TBranch *branch = leaf->GetBranch();
Double_t totBytes = (Double_t)branch->GetTotBytes();
Double_t idealFactor = totBytes/aveSize;
Int_t oldBsize = branch->GetBasketSize();
oldMemsize += oldBsize;
oldBaskets += 1+Int_t(totBytes/oldBsize);
Int_t nb = branch->GetListOfBranches()->GetEntries();
if (nb > 0) {
newBaskets += 1+Int_t(totBytes/oldBsize);
continue;
}
Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
if (bsize < 0) bsize = bmax;
if (bsize > bmax) bsize = bmax;
Int_t newBsize = Int_t(bsize);
newBsize = newBsize - newBsize%512;
if (newBsize < bmin) newBsize = bmin;
if (newBsize > 10000000) newBsize = bmax;
if (pass) {
if (pDebug) printf("Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
branch->SetBasketSize(newBsize);
}
newMemsize += newBsize;
newBaskets += 1+Int_t(totBytes/newBsize);
if (pass == 0) continue;
//Reset the compression level in case the compression factor is small
Double_t comp = 1;
if (branch->GetZipBytes() > 0) comp = Double_t(oldBsize)/Double_t(branch->GetZipBytes());
if (comp > 1 && comp < minComp) {
if (pDebug) printf("Disabling compression for branch : %s\n",branch->GetName());
branch->SetCompressionLevel(0);
}
}
memFactor = Double_t(maxMemory)/Double_t(newMemsize);
if (memFactor > 100) memFactor = 100;
bmin = Int_t(bmin*memFactor);
bmax = Int_t(bmax*memFactor);
}
if (pDebug) {
printf("oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
printf("oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
}
}
//______________________________________________________________________________
TPrincipal* TTree::Principal(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Interface to the Principal Components Analysis class.
//
// Create an instance of TPrincipal
// Fill it with the selected variables
// if option "n" is specified, the TPrincipal object is filled with
// normalized variables.
// If option "p" is specified, compute the principal components
// If option "p" and "d" print results of analysis
// If option "p" and "h" generate standard histograms
// If option "p" and "c" generate code of conversion functions
// return a pointer to the TPrincipal object. It is the user responsability
// to delete this object.
// The option default value is "np"
//
// see TTree::Draw for explanation of the other parameters.
//
// The created object is named "principal" and a reference to it
// is added to the list of specials Root objects.
// you can retrieve a pointer to the created object via:
// TPrincipal *principal =
// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
//
GetPlayer();
if (fPlayer) {
return fPlayer->Principal(varexp, selection, option, nentries, firstentry);
}
return 0;
}
//______________________________________________________________________________
void TTree::Print(Option_t* option) const
{
// Print a summary of the tree contents.
//
// If option contains "all" friend trees are also printed.
// If option contains "toponly" only the top level branches are printed.
//
// Wildcarding can be used to print only a subset of the branches, e.g.,
// T.Print("Elec*") will print all branches with name starting with "Elec".
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kPrint & fFriendLockStatus) {
return;
}
Int_t s = 0;
Int_t skey = 0;
if (fDirectory) {
TKey* key = fDirectory->GetKey(GetName());
if (key) {
skey = key->GetKeylen();
s = key->GetNbytes();
}
}
Long64_t total = skey;
if (fZipBytes > 0) {
total += fTotBytes;
}
TBufferFile b(TBuffer::kWrite, 10000);
TTree::Class()->WriteBuffer(b, (TTree*) this);
total += b.Length();
Long64_t file = fZipBytes + s;
Float_t cx = 1;
if (fZipBytes) {
cx = (fTotBytes + 0.00001) / fZipBytes;
}
Printf("******************************************************************************");
Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
Printf("* : : Tree compression factor = %6.2f *", cx);
Printf("******************************************************************************");
Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
Int_t l;
TBranch* br = 0;
TLeaf* leaf = 0;
if (strstr(option, "toponly")) {
Long64_t *count = new Long64_t[nl];
Int_t keep =0;
for (l=0;l<nl;l++) {
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
if (strchr(br->GetName(),'.')) {
count[l] = -1;
count[keep] += br->GetZipBytes();
} else {
keep = l;
count[keep] = br->GetZipBytes();
}
}
for (l=0;l<nl;l++) {
if (count[l] < 0) continue;
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
printf("branch: %-20s %9lld\n",br->GetName(),count[l]);
}
delete [] count;
} else {
TString reg = "*";
if (strlen(option) && strchr(option,'*')) reg = option;
TRegexp re(reg,kTRUE);
TIter next(const_cast<TTree*>(this)->GetListOfBranches());
TBranch::ResetCount();
while ((br= (TBranch*)next())) {
TString st = br->GetName();
st.ReplaceAll("/","_");
if (st.Index(re) == kNPOS) continue;
br->Print(option);
}
}
//print TRefTable (if one)
if (fBranchRef) fBranchRef->Print(option);
//print friends if option "all"
if (!fFriends || !strstr(option,"all")) return;
TIter nextf(fFriends);
TFriendLock lock(const_cast<TTree*>(this),kPrint);
TFriendElement *fr;
while ((fr = (TFriendElement*)nextf())) {
TTree * t = fr->GetTree();
if (t) t->Print(option);
}
}
//______________________________________________________________________________
void TTree::PrintCacheStats(Option_t* option) const
{
// print statistics about the TreeCache for this tree, like
// ******TreeCache statistics for file: cms2.root ******
// Reading 73921562 bytes in 716 transactions
// Average transaction = 103.242405 Kbytes
// Number of blocks in current cache: 202, total size : 6001193
//
// if option = "a" the list of blocks in the cache is printed
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->Print(option);
}
//______________________________________________________________________________
Long64_t TTree::Process(const char* filename, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Process this tree executing the TSelector code in the specified filename.
// The return value is -1 in case of error and TSelector::GetStatus() in
// in case of success.
//
// The code in filename is loaded (interpreted or compiled, see below),
// filename must contain a valid class implementation derived from TSelector,
// where TSelector has the following member functions:
//
// Begin(): called everytime 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.
//
// If filename is of the form file.C, the file will be interpreted.
// If filename is of the form file.C++, the file file.C will be compiled
// and dynamically loaded.
// If filename is of the form file.C+, the file file.C will be compiled
// and dynamically loaded. At next call, if file.C is older than file.o
// and file.so, the file.C is not compiled, only file.so is loaded.
//
// NOTE1
// It may be more interesting to invoke directly the other Process function
// accepting a TSelector* as argument.eg
// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
// selector->CallSomeFunction(..);
// mytree.Process(selector,..);
//
// NOTE2
// One should not call this function twice with the same selector file
// in the same script. If this is required, proceed as indicated in NOTE1,
// by getting a pointer to the corresponding TSelector,eg
// workaround 1
// ------------
//void stubs1() {
// TSelector *selector = TSelector::GetSelector("h1test.C");
// TFile *f1 = new TFile("stubs_nood_le1.root");
// TTree *h1 = (TTree*)f1->Get("h1");
// h1->Process(selector);
// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
// TTree *h2 = (TTree*)f2->Get("h1");
// h2->Process(selector);
//}
// or use ACLIC to compile the selector
// workaround 2
// ------------
//void stubs2() {
// TFile *f1 = new TFile("stubs_nood_le1.root");
// TTree *h1 = (TTree*)f1->Get("h1");
// h1->Process("h1test.C+");
// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
// TTree *h2 = (TTree*)f2->Get("h1");
// h2->Process("h1test.C+");
//}
GetPlayer();
if (fPlayer) {
return fPlayer->Process(filename, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Long64_t TTree::Process(TSelector* selector, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Process this tree executing the code in the specified selector.
// The return value is -1 in case of error and TSelector::GetStatus() in
// in case of success.
//
// The TSelector class has the following member functions:
//
// Begin(): called everytime 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.
//
// If the Tree (Chain) has an associated EventList, the loop is on the nentries
// of the EventList, starting at firstentry, otherwise the loop is on the
// specified Tree entries.
GetPlayer();
if (fPlayer) {
return fPlayer->Process(selector, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Long64_t TTree::Project(const char* hname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Make a projection of a tree using selections.
//
// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
// projection of the tree will be filled in histogram hname.
// Note that the dimension of hname must match with the dimension of varexp.
//
TString var;
var.Form("%s>>%s", varexp, hname);
TString opt("goff");
if (option) {
opt.Form("%sgoff", option);
}
Long64_t nsel = Draw(var, selection, opt, nentries, firstentry);
return nsel;
}
//______________________________________________________________________________
TSQLResult* TTree::Query(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Loop over entries and return a TSQLResult object containing entries following selection.
GetPlayer();
if (fPlayer) {
return fPlayer->Query(varexp, selection, option, nentries, firstentry);
}
return 0;
}
//______________________________________________________________________________
Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor)
{
// Create or simply read branches from filename.
//
// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
// is given in the first line of the file with a syntax like
// A/D:Table[2]/F:Ntracks/I:astring/C
// otherwise branchDescriptor must be specified with the above syntax.
// -If the type of the first variable is not specified, it is assumed to be "/F"
// -if the type of any other variable is not specified, the type of the previous
// variable is assumed. eg
// x:y:z (all variables are assumed of type "F"
// x/D:y:z (all variables are of type "D"
// x:y/D:z (x is type "F", y and z of type "D"
// -If the type is a string of characters. This will read
// subsequent characters until a whitespace is found (whitespace
// characters are considered to be blank, newline and tab).
//
// Lines in the input file starting with "#" are ignored.
// This function will read and ignore any whitespace characters
// (this includes blank spaces and the newline and tab characters).
//
// A TBranch object is created for each variable in the expression.
// The total number of rows read from the file is returned.
//
// FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
// ----------------------------------------------
// To fill a TTree with multiple input text files, proceed as indicated above
// for the first input file and omit the second argument for subsequent calls
// T.ReadFile("file1.dat","branch descriptor");
// T.ReadFile("file2.dat");
gTree = this;
std::ifstream in;
in.open(filename);
if (!in.good()) {
Error("ReadFile","Cannot open file: %s",filename);
return 0;
}
TBranch *branch;
Int_t nbranches = fBranches.GetEntries();
if (nbranches == 0) {
char *bdname = new char[4000];
char *bd = new char[100000];
Int_t nch = 0;
if (branchDescriptor) nch = strlen(branchDescriptor);
// branch Descriptor is null, read its definition from the first line in the file
if (!nch) {
in >> bd;
if (!in.good()) {
Error("ReadFile","Error reading file: %s",filename);
return 0;
}
in.ignore(8192,'\n');
nch = strlen(bd);
} else {
strcpy(bd,branchDescriptor);
}
//parse the branch descriptor and create a branch for each element
//separated by ":"
void *address = &bd[90000];
char *bdcur = bd;
TString desc="", olddesc="F";
while (bdcur) {
char *colon = strchr(bdcur,':');
if (colon) *colon = 0;
strcpy(bdname,bdcur);
char *slash = strchr(bdname,'/');
if (slash) {
*slash = 0;
desc = bdcur;
olddesc = slash+1;
} else {
desc = Form("%s/%s",bdname,olddesc.Data());
}
char *bracket = strchr(bdname,'[');
if (bracket) {
*bracket = 0;
}
branch = new TBranch(this,bdname,address,desc.Data(),32000);
if (branch->IsZombie()) {
delete branch;
Warning("ReadFile","Illegal branch definition: %s",bdcur);
} else {
fBranches.Add(branch);
branch->SetAddress(0);
}
if (!colon)break;
bdcur = colon+1;
}
delete [] bdname;
delete [] bd;
}
//loop on all lines in the file
nbranches = fBranches.GetEntries();
Bool_t status = kTRUE;
Long64_t nlines = 0;
while(1) {
while (isspace(in.peek())) {
in.get();
}
if ( in.peek() != '#' ) {
//loop on branches and read the branch values into their buffer
for (Int_t i=0;i<nbranches;i++) {
branch = (TBranch*)fBranches.At(i);
TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
leaf->ReadValue(in);
if (in.eof()) return nlines;
status = in.good();
if (!status) {
Warning("ReadFile","Illegal value after line %d\n",nlines);
in.clear();
break;
}
}
//we are now ready to fill the tree
if (status) {
Fill();
nlines++;
}
}
in.ignore(8192,'\n');
}
return nlines;
}
//______________________________________________________________________________
void TTree::RecursiveRemove(TObject *obj)
{
// Make sure that obj (which is being deleted or will soon be) is no
// longer referenced by this TTree.
if (obj == fEventList) {
fEventList = 0;
}
if (obj == fEntryList) {
fEntryList = 0;
}
if (fUserInfo) {
fUserInfo->RecursiveRemove(obj);
}
if (fPlayer == obj) {
fPlayer = 0;
}
if (fTreeIndex == obj) {
fTreeIndex = 0;
}
if (fAliases) {
fAliases->RecursiveRemove(obj);
}
if (fFriends) {
fFriends->RecursiveRemove(obj);
}
}
//______________________________________________________________________________
void TTree::Refresh()
{
// Refresh contents of this tree and its branches from the current status on disk.
//
// One can call this function in case the tree file is being
// updated by another process.
if (!fDirectory->GetFile()) {
return;
}
fDirectory->ReadKeys();
fDirectory->Remove(this);
TTree* tree; fDirectory->GetObject(GetName(),tree);
if (!tree) {
return;
}
//copy info from tree header into this Tree
fEntries = tree->fEntries;
fTotBytes = tree->fTotBytes;
fZipBytes = tree->fZipBytes;
fSavedBytes = tree->fSavedBytes;
fTotalBuffers = tree->fTotalBuffers;
//loop on all branches and update them
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
branch->Refresh(tree->GetBranch(branch->GetName()));
}
fDirectory->Remove(tree);
fDirectory->Append(this);
delete tree;
tree = 0;
}
//______________________________________________________________________________
void TTree::RemoveFriend(TTree* oldFriend)
{
// Remove a friend from the list of friends.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kRemoveFriend & fFriendLockStatus) {
return;
}
if (!fFriends) {
return;
}
TFriendLock lock(this, kRemoveFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* friend_t = fe->GetTree();
if (friend_t == oldFriend) {
fFriends->Remove(fe);
delete fe;
fe = 0;
}
}
}
//______________________________________________________________________________
void TTree::Reset(Option_t* option)
{
// Reset baskets, buffers and entries count in all branches and leaves.
fNotify = 0;
fEntries = 0;
fTotBytes = 0;
fZipBytes = 0;
fSavedBytes = 0;
fTotalBuffers = 0;
fChainOffset = 0;
fReadEntry = -1;
delete fTreeIndex;
fTreeIndex = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->Reset(option);
}
if (fBranchRef) {
fBranchRef->Reset();
}
}
//______________________________________________________________________________
void TTree::ResetBranchAddress(TBranch *br)
{
// Tell all of our branches to set their addresses to zero.
//
// Note: If any of our branches own any objects, they are deleted.
if (br && br->GetTree()) {
br->ResetAddress();
}
}
//______________________________________________________________________________
void TTree::ResetBranchAddresses()
{
// Tell all of our branches to drop their current objects and allocate new ones.
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
branch->ResetAddress();
}
}
//______________________________________________________________________________
Long64_t TTree::Scan(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Loop over tree entries and print entries passing selection.
//
// If varexp is 0 (or "") then print only first 8 columns.
// If varexp = "*" print all columns.
// Otherwise a columns selection can be made using "var1:var2:var3".
// See TTreePlayer::Scan for more information
//
GetPlayer();
if (fPlayer) {
return fPlayer->Scan(varexp, selection, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Bool_t TTree::SetAlias(const char* aliasName, const char* aliasFormula)
{
// Set a tree variable alias.
//
// Set an alias for an expression/formula based on the tree 'variables'.
//
// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
// TTree::Scan, TTreeViewer) and will be evaluated as the content of
// 'aliasFormula'.
// If the content of 'aliasFormula' only contains symbol names, periods and
// array index specification (for example event.fTracks[3]), then
// the content of 'aliasName' can be used as the start of symbol.
//
// If the alias 'aliasName' already existed, it is replaced by the new
// value.
//
// When being used, the alias can be preceded by an eventual 'Friend Alias'
// (see TTree::GetFriendAlias)
//
// Return true if it was added properly.
//
// For example:
// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
// tree->Draw("y2-y1:x2-x1");
//
// tree->SetAlias("theGoodTrack","event.fTracks[3]");
// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
if (!aliasName || !aliasFormula) {
return kFALSE;
}
if (!strlen(aliasName) || !strlen(aliasFormula)) {
return kFALSE;
}
if (!fAliases) {
fAliases = new TList;
} else {
TNamed* oldHolder = (TNamed*) fAliases->FindObject(aliasName);
if (oldHolder) {
oldHolder->SetTitle(aliasFormula);
return kTRUE;
}
}
TNamed* holder = new TNamed(aliasName, aliasFormula);
fAliases->Add(holder);
return kTRUE;
}
//_______________________________________________________________________
void TTree::SetAutoFlush(Long64_t autof)
{
// This function may be called at the start of a program to change
// the default value for fAutoFlush.
//
// CASE 1 : autof > 0
// ------------------
// autof is the number of consecutive entries after which TTree::Fill will
// flush all branch buffers to disk.
//
// CASE 2 : autof < 0
// ------------------
// When filling the Tree the branch buffers will be flushed to disk when
// more than autof bytes have been written to the file. At the first FlushBaskets
// TTree::Fill will replace fAutoFlush by the current value of fEntries.
//
// Calling this function with autof<0 is interesting when it is hard to estimate
// the size of one entry. This value is also independent of the Tree.
//
// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
// the first AutoFlush will be done when 30 MBytes of data are written to the file.
//
// CASE 3 : autof = 0
// ------------------
// The AutoFlush mechanism is disabled.
//
// Flushing the buffers at regular intervals optimize the location of
// consecutive entries on the disk.
fAutoFlush = autof;
}
//_______________________________________________________________________
void TTree::SetAutoSave(Long64_t autos)
{
//This function may be called at the start of a program to change
//the default value for fAutoSave(300000000, ie 300 MBytes).
//When filling the Tree the branch buffers as well as the Tree header
//will be flushed to disk when more than fAutoSave bytes have been written to the file.
//In case of a program crash, it will be possible to recover the data in the Tree
//up to the last AutoSave point.
fAutoSave = autos;
}
//_______________________________________________________________________
void TTree::SetBasketSize(const char* bname, Int_t buffsize)
{
// Set a branch's basket size.
//
// bname is the name of a branch.
// if bname="*", apply to all branches.
// if bname="xxx*", apply to all branches with name starting with xxx
// see TRegexp for wildcarding options
// buffsize = branc basket size
//
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname, kTRUE);
Int_t nb = 0;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
continue;
}
nb++;
branch->SetBasketSize(buffsize);
}
if (!nb) {
Error("SetBasketSize", "unknown branch -> '%s'", bname);
}
}
//_______________________________________________________________________
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
{
// Change branch address, dealing with clone trees properly.
// See TTree::CheckBranchAddressType for the semantic of the return value.
//
// Note: See the comments in TBranchElement::SetAddress() for the
// meaning of the addr parameter.
//
TBranch* branch = GetBranch(bname);
if (!branch) {
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kNoCheck;
}
if (ptr) {
*ptr = branch;
}
if (fClones) {
void* oldAddr = branch->GetAddress();
TIter next(fClones);
TTree* clone = 0;
while ((clone = (TTree*) next())) {
TBranch* cloneBr = clone->GetBranch(bname);
if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
cloneBr->SetAddress(addr);
}
}
}
branch->SetAddress(addr);
return kVoidPtr;
}
//_______________________________________________________________________
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
// Verify the validity of the type of addr before calling SetBranchAddress.
// See TTree::CheckBranchAddressType for the semantic of the return value.
//
// Note: See the comments in TBranchElement::SetAddress() for the
// meaning of the addr parameter.
//
return SetBranchAddress(bname, addr, 0, ptrClass, datatype, isptr);
}
//_______________________________________________________________________
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
// Verify the validity of the type of addr before calling SetBranchAddress.
// See TTree::CheckBranchAddressType for the semantic of the return value.
//
// Note: See the comments in TBranchElement::SetAddress() for the
// meaning of the addr parameter.
//
TBranch* branch = GetBranch(bname);
if (!branch) {
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kMissingBranch;
}
if (ptr) {
*ptr = branch;
}
Int_t res = CheckBranchAddressType(branch, ptrClass, datatype, isptr);
SetBranchAddress(bname, addr);
return res;
}
//_______________________________________________________________________
void TTree::SetBranchStatus(const char* bname, Bool_t status, UInt_t* found)
{
// Set branch status to Process or DoNotProcess.
//
// When reading a Tree, by default, all branches are read.
// One can speed up considerably the analysis phase by activating
// only the branches that hold variables involved in a query.
//
// bname is the name of a branch.
// if bname="*", apply to all branches.
// if bname="xxx*", apply to all branches with name starting with xxx
// see TRegexp for wildcarding options
// status = 1 branch will be processed
// = 0 branch will not be processed
// Example:
// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
// when doing T.GetEntry(i) all branches are read for entry i.
// to read only the branches c and e, one can do
// T.SetBranchStatus("*",0); //disable all branches
// T.SetBranchStatus("c",1);
// T.setBranchStatus("e",1);
// T.GetEntry(i);
//
// WARNING! WARNING! WARNING!
// SetBranchStatus is matching the branch based on regular expression match
// of the branch 'name' and not on the branch hierarchy!
// In order to be able to selectively enable a top level object that is 'split'
// you need to make sure the name of the top level branch is prefixed to the
// sub-branches' name(by adding a dot ('.') at the end of the Branch creation
// and use the corresponding regular expression.
//
// I.e If your Tree has been created in split mode with a parent branch "parent."
// (note the trailing dot).
// T.SetBranchStatus("parent",1);
// will not activate the sub-branches of "parent". You should do:
// T.SetBranchStatus("parent*",1);
//
// Without the trailing dot in the branch creation you have no choice but to
// call SetBranchStatus explicitly for each of the sub branches.
//
//
// An alternative to this function is to read directly and only
// the interesting branches. Example:
// TBranch *brc = T.GetBranch("c");
// TBranch *bre = T.GetBranch("e");
// brc->GetEntry(i);
// bre->GetEntry(i);
//
// If found is not 0, the number of branch(es) found matching the regular
// expression is returned in *found AND the error message 'unknown branch'
// is suppressed.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kSetBranchStatus & fFriendLockStatus) {
return;
}
TBranch *branch, *bcount, *bson;
TLeaf *leaf, *leafcount;
Int_t i,j;
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname,kTRUE);
Int_t nb = 0;
// first pass, loop on all branches
// for leafcount branches activate/deactivate in function of status
for (i=0;i<nleaves;i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
TString longname;
longname.Form("%s.%s",GetName(),branch->GetName());
if (strcmp(bname,branch->GetName())
&& longname != bname
&& s.Index(re) == kNPOS) continue;
}
nb++;
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
if (status) bcount->ResetBit(kDoNotProcess);
else bcount->SetBit(kDoNotProcess);
}
}
if (nb==0 && strchr(bname,'*')==0) {
branch = GetBranch(bname);
if (branch) {
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
++nb;
}
}
//search in list of friends
UInt_t foundInFriend = 0;
if (fFriends) {
TFriendLock lock(this,kSetBranchStatus);
TIter nextf(fFriends);
TFriendElement *fe;
TString name;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t==0) continue;
// If the alias is present replace it with the real name.
char *subbranch = (char*)strstr(bname,fe->GetName());
if (subbranch!=bname) subbranch = 0;
if (subbranch) {
subbranch += strlen(fe->GetName());
if ( *subbranch != '.' ) subbranch = 0;
else subbranch ++;
}
if (subbranch) {
name.Form("%s.%s",t->GetName(),subbranch);
} else {
name = bname;
}
t->SetBranchStatus(name,status, &foundInFriend);
}
}
if (!nb && !foundInFriend) {
if (found==0) Error("SetBranchStatus", "unknown branch -> %s", bname);
return;
}
if (found) *found = nb + foundInFriend;
// second pass, loop again on all branches
// activate leafcount branches for active branches only
for (i = 0; i < nleaves; i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
if (!branch->TestBit(kDoNotProcess)) {
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
bcount->ResetBit(kDoNotProcess);
}
} else {
//Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
Int_t nbranches = branch->GetListOfBranches()->GetEntries();
for (j=0;j<nbranches;j++) {
bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
if (!bson) continue;
if (!bson->TestBit(kDoNotProcess)) {
if (bson->GetNleaves() <= 0) continue;
branch->ResetBit(kDoNotProcess);
break;
}
}
}
}
}
//______________________________________________________________________________
void TTree::SetBranchStyle(Int_t style)
{
// Set the current branch style. (static function)
//
// style = 0 old Branch
// style = 1 new Bronch
fgBranchStyle = style;
}
//______________________________________________________________________________
void TTree::SetCacheSize(Long64_t cacheSize)
{
// Set maximum size of the file cache .
// if cachesize = 0 the existing cache (if any) is deleted.
// if cachesize = -1 (default) it is set to the AutoFlush value when writing
// the Tree (default is 30 MBytes).
// WARNING: Currently only ONE TTree object can be 'cached' per TFile object.
// This call disable the cache for the other TTree objects read from the same
// TFile object as this TTree (The SetCacheSize called __last__ wins).
// To cache multiple TTree objects in the same ROOT file, you must create
// one TFile object per TTree object.
if (cacheSize < 0) {
if (fAutoFlush < 0) cacheSize = -fAutoFlush;
else cacheSize = Long64_t(1.5*fAutoFlush*fZipBytes/(fEntries+1));
}
TFile* file = GetCurrentFile();
if (!file) {
fCacheSize = cacheSize;
return;
}
TFileCacheRead* pf = file->GetCacheRead();
if (pf) {
if (cacheSize == fCacheSize) {
return;
}
delete pf;
pf = 0;
if (cacheSize == 0) {
file->SetCacheRead(0);
fCacheSize=0;
return;
}
}
fCacheSize = cacheSize;
if (cacheSize == 0) {
return;
}
if(TTreeCacheUnzip::IsParallelUnzip() && file->GetCompressionLevel() > 0)
new TTreeCacheUnzip(this, cacheSize);
else
new TTreeCache(this, cacheSize);
}
//______________________________________________________________________________
void TTree::SetCacheEntryRange(Long64_t first, Long64_t last)
{
//interface to TTreeCache to set the cache entry range
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->SetEntryRange(first,last);
}
//______________________________________________________________________________
void TTree::SetCacheLearnEntries(Int_t n)
{
//interface to TTreeCache to set the number of entries for the learning phase
TTreeCache::SetLearnEntries(n);
}
//______________________________________________________________________________
void TTree::SetCircular(Long64_t maxEntries)
{
// Enable/Disable circularity for this tree.
//
// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
// per branch in memory.
// Note that when this function is called (maxEntries>0) the Tree
// must be empty or having only one basket per branch.
// if maxEntries <= 0 the tree circularity is disabled.
//
// NOTE 1:
// Circular Trees are interesting in online real time environments
// to store the results of the last maxEntries events.
// NOTE 2:
// Calling SetCircular with maxEntries <= 0 is necessary before
// merging circular Trees that have been saved on files.
// NOTE 3:
// SetCircular with maxEntries <= 0 is automatically called
// by TChain::Merge
// NOTE 4:
// A circular Tree can still be saved in a file. When read back,
// it is still a circular Tree and can be filled again.
if (maxEntries <= 0) {
// Disable circularity.
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
ResetBit(kCircular);
//in case the Tree was originally created in gROOT, the branch
//compression level was set to -1. If the Tree is now associated to
//a file, reset the compression level to the file compression level
if (fDirectory) {
TFile* bfile = fDirectory->GetFile();
Int_t compress = 1;
if (bfile) {
compress = bfile->GetCompressionLevel();
}
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->SetCompressionLevel(compress);
}
}
} else {
// Enable circularity.
fMaxEntries = maxEntries;
SetBit(kCircular);
}
}
//______________________________________________________________________________
void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
{
// Set the debug level and the debug range.
//
// For entries in the debug range, the functions TBranchElement::Fill
// and TBranchElement::GetEntry will print the number of bytes filled
// or read for each branch.
fDebug = level;
fDebugMin = min;
fDebugMax = max;
}
//______________________________________________________________________________
void TTree::SetDefaultEntryOffsetLen(Int_t newdefault, Bool_t updateExisting)
{
// Update the default value for the branch's fEntryOffsetLen.
// If updateExisting is true, also update all the existing branches.
// If newdefault is less than 10, the new default value will be 10.
if (newdefault < 10) {
newdefault = 10;
}
fDefaultEntryOffsetLen = newdefault;
if (updateExisting) {
TIter next( GetListOfBranches() );
TBranch *b;
while ( ( b = (TBranch*)next() ) ) {
b->SetEntryOffsetLen( newdefault, kTRUE );
}
if (fBranchRef) {
fBranchRef->SetEntryOffsetLen( newdefault, kTRUE );
}
}
}
//______________________________________________________________________________
void TTree::SetDirectory(TDirectory* dir)
{
// Change the tree's directory.
//
// Remove reference to this tree from current directory and
// add reference to new directory dir. The dir parameter can
// be 0 in which case the tree does not belong to any directory.
//
if (fDirectory == dir) {
return;
}
if (fDirectory) {
fDirectory->Remove(this);
}
fDirectory = dir;
if (fDirectory) {
fDirectory->Append(this);
}
TFile* file = 0;
if (fDirectory) {
file = fDirectory->GetFile();
}
if (fBranchRef) {
fBranchRef->SetFile(file);
}
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->SetFile(file);
}
}
//_______________________________________________________________________
Long64_t TTree::SetEntries(Long64_t n)
{
// Change number of entries in the tree.
//
// If n >= 0, set number of entries in the tree = n.
//
// If n < 0, set number of entries in the tree to match the
// number of entries in each branch. (default for n is -1)
//
// This function should be called only when one fills each branch
// independently via TBranch::Fill without calling TTree::Fill.
// Calling TTree::SetEntries() make sense only if the number of entries
// in each branch is identical, a warning is issued otherwise.
// The function returns the number of entries.
//
// case 1 : force number of entries to n
if (n >= 0) {
fEntries = n;
return n;
}
// case 2; compute the number of entries from the number of entries in the branches
TBranch* b = 0;
Long64_t nMin = 99999999;
Long64_t nMax = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())){
Long64_t n2 = b->GetEntries();
if (n2 < nMin) {
nMin = n2;
}
if (n2 > nMax) {
nMax = n2;
}
}
if (nMin != nMax) {
Warning("SetEntries", "Tree branches have different numbers of entries, with %lld maximum.", nMax);
}
fEntries = nMax;
return fEntries;
}
//_______________________________________________________________________
void TTree::SetEntryList(TEntryList *enlist, Option_t * /*opt*/)
{
//Set an EntryList
if (fEntryList) {
//check if the previous entry list is owned by the tree
if (fEntryList->TestBit(kCanDelete)){
delete fEntryList;
}
}
fEventList = 0;
if (!enlist) {
fEntryList = 0;
return;
}
fEntryList = enlist;
fEntryList->SetTree(this);
}
//_______________________________________________________________________
void TTree::SetEventList(TEventList *evlist)
{
//This function transfroms the given TEventList into a TEntryList
//The new TEntryList is owned by the TTree and gets deleted when the tree
//is deleted. This TEntryList can be returned by GetEntryList() function.
fEventList = evlist;
if (fEntryList){
if (fEntryList->TestBit(kCanDelete)) {
TEntryList *tmp = fEntryList;
fEntryList = 0; // Avoid problem with RecursiveRemove.
delete tmp;
} else {
fEntryList = 0;
}
}
if (!evlist) {
fEntryList = 0;
fEventList = 0;
return;
}
fEventList = evlist;
char enlistname[100];
sprintf(enlistname, "%s_%s", evlist->GetName(), "entrylist");
fEntryList = new TEntryList(enlistname, evlist->GetTitle());
fEntryList->SetDirectory(0); // We own this.
Int_t nsel = evlist->GetN();
fEntryList->SetTree(this);
Long64_t entry;
for (Int_t i=0; i<nsel; i++){
entry = evlist->GetEntry(i);
fEntryList->Enter(entry);
}
fEntryList->SetReapplyCut(evlist->GetReapplyCut());
fEntryList->SetBit(kCanDelete, kTRUE);
}
//_______________________________________________________________________
void TTree::SetEstimate(Long64_t n)
{
// Set number of entries to estimate variable limits.
if (n <= 0) {
n = 10000;
}
fEstimate = n;
GetPlayer();
if (fPlayer) {
fPlayer->SetEstimate(n);
}
}
//_______________________________________________________________________
void TTree::SetFileNumber(Int_t number)
{
// Set fFileNumber to number.
// fFileNumber is used by TTree::Fill to set the file name
// for a new file to be created when the current file exceeds fgTreeMaxSize.
// (see TTree::ChangeFile)
// if fFileNumber=10, the new file name will have a suffix "_11",
// ie, fFileNumber is incremented before setting the file name
if (fFileNumber < 0) {
Warning("SetFileNumber", "file number must be positive. Set to 0");
fFileNumber = 0;
return;
}
fFileNumber = number;
}
//______________________________________________________________________________
void TTree::SetMaxTreeSize(Long64_t maxsize)
{
// Set the maximum size of a Tree file (static function).
//
// In TTree::Fill, when the file has a size > fgMaxTreeSize,
// the function closes the current file and starts writing into
// a new file with a name of the style "file_1.root" if the original
// requested file name was "file.root".
//
fgMaxTreeSize = maxsize;
}
//______________________________________________________________________________
void TTree::SetName(const char* name)
{
// Change the name of this tree.
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update the hashlist if we change the name.
if (fDirectory) {
fDirectory->Remove(this);
}
// This changes our hash value.
fName = name;
if (fDirectory) {
fDirectory->Append(this);
}
}
//______________________________________________________________________________
void TTree::SetObject(const char* name, const char* title)
{
// Change the name and title of this tree.
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update the hashlist if we change the name
if (fDirectory) {
fDirectory->Remove(this);
}
// This changes our hash value.
fName = name;
fTitle = title;
if (fDirectory) {
fDirectory->Append(this);
}
}
//______________________________________________________________________________
void TTree::SetParallelUnzip(Bool_t opt, Float_t RelSize)
{
//enable or disable parallel unzipping of Tree buffers
if (opt) TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);
else TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kDisable);
if (RelSize > 0)
TTreeCacheUnzip::SetUnzipRelBufferSize(RelSize);
}
//______________________________________________________________________________
void TTree::SetTreeIndex(TVirtualIndex* index)
{
// The current TreeIndex is replaced by the new index.
// Note that this function does not delete the previous index.
// This gives the possibility to play with more than one index, e.g.,
// TVirtualIndex* oldIndex = tree.GetTreeIndex();
// tree.SetTreeIndex(newIndex);
// tree.Draw();
// tree.SetTreeIndex(oldIndex);
// tree.Draw(); etc
if (fTreeIndex) {
fTreeIndex->SetTree(0);
}
fTreeIndex = index;
}
//______________________________________________________________________________
void TTree::SetWeight(Double_t w, Option_t*)
{
// Set tree weight.
//
// The weight is used by TTree::Draw to automatically weight each
// selected entry in the resulting histogram.
//
// For example the equivalent of:
//
// T.Draw("x", "w")
//
// is:
//
// T.SetWeight(w);
// T.Draw("x");
//
// This function is redefined by TChain::SetWeight. In case of a
// TChain, an option "global" may be specified to set the same weight
// for all trees in the TChain instead of the default behaviour
// using the weights of each tree in the chain (see TChain::SetWeight).
fWeight = w;
}
//______________________________________________________________________________
void TTree::Show(Long64_t entry, Int_t lenmax)
{
// Print values of all active leaves for entry.
//
// if entry==-1, print current entry (default)
// if a leaf is an array, a maximum of lenmax elements is printed.
//
if (entry != -1) {
Int_t ret = LoadTree(entry);
if (ret == -2) {
Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
return;
} else if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
}
ret = GetEntry(entry);
if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
} else if (ret == 0) {
Error("Show()", "Cannot read entry %lld (no data read)", entry);
return;
}
}
printf("======> EVENT:%lld\n", fReadEntry);
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
Int_t ltype;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (branch->TestBit(kDoNotProcess)) {
continue;
}
Int_t len = leaf->GetLen();
if (len <= 0) {
continue;
}
len = TMath::Min(len, lenmax);
if (leaf->IsA() == TLeafElement::Class()) {
leaf->PrintValue(lenmax);
continue;
}
if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
continue;
}
ltype = 10;
if (leaf->IsA() == TLeafF::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafD::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafC::Class()) {
len = 1;
ltype = 5;
};
printf(" %-15s = ", leaf->GetName());
for (Int_t l = 0; l < len; l++) {
leaf->PrintValue(l);
if (l == (len - 1)) {
printf("\n");
continue;
}
printf(", ");
if ((l % ltype) == 0) {
printf("\n ");
}
}
}
}
//______________________________________________________________________________
void TTree::StartViewer()
{
// Start the TTreeViewer on this tree.
//
// ww is the width of the canvas in pixels
// wh is the height of the canvas in pixels
GetPlayer();
if (fPlayer) {
fPlayer->StartViewer(600, 400);
}
}
//______________________________________________________________________________
void TTree::StopCacheLearningPhase()
{
// stop the cache learning phase
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->StopLearningPhase();
}
//______________________________________________________________________________
void TTree::Streamer(TBuffer& b)
{
// Stream a class object.
if (b.IsReading()) {
UInt_t R__s, R__c;
gTree = this;
fDirectory = 0;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 4) {
b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
if (fTreeIndex) {
fTreeIndex->SetTree(this);
}
if (fIndex.fN) {
Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
fIndex.Set(0);
fIndexValues.Set(0);
}
if (fEstimate <= 10000) {
fEstimate = 1000000;
}
fCacheSize = fAutoFlush;
ResetBit(kMustCleanup);
return;
}
//====process old versions before automatic schema evolution
Stat_t djunk;
Int_t ijunk;
TNamed::Streamer(b);
TAttLine::Streamer(b);
TAttFill::Streamer(b);
TAttMarker::Streamer(b);
b >> fScanField;
b >> ijunk; fMaxEntryLoop = (Long64_t)ijunk;
b >> ijunk; fMaxVirtualSize = (Long64_t)ijunk;
b >> djunk; fEntries = (Long64_t)djunk;
b >> djunk; fTotBytes = (Long64_t)djunk;
b >> djunk; fZipBytes = (Long64_t)djunk;
b >> ijunk; fAutoSave = (Long64_t)ijunk;
b >> ijunk; fEstimate = (Long64_t)ijunk;
if (fEstimate <= 10000) fEstimate = 1000000;
fBranches.Streamer(b);
fLeaves.Streamer(b);
fSavedBytes = fTotBytes;
if (R__v > 1) fIndexValues.Streamer(b);
if (R__v > 2) fIndex.Streamer(b);
if (R__v > 3) {
TList OldInfoList;
OldInfoList.Streamer(b);
OldInfoList.Delete();
}
fDefaultEntryOffsetLen = 1000;
ResetBit(kMustCleanup);
b.CheckByteCount(R__s, R__c, TTree::IsA());
//====end of old versions
} else {
if (fBranchRef) {
fBranchRef->Clear();
}
b.WriteClassBuffer(TTree::Class(), this);
}
}
//______________________________________________________________________________
Int_t TTree::UnbinnedFit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Unbinned fit of one or more variable(s) from a tree.
//
// funcname is a TF1 function.
//
// See TTree::Draw for explanations of the other parameters.
//
// Fit the variable varexp using the function funcname using the
// selection cuts given by selection.
//
// The list of fit options is given in parameter option.
// option = "Q" Quiet mode (minimum printing)
// = "V" Verbose mode (default is between Q and V)
// = "E" Perform better Errors estimation using Minos technique
// = "M" More. Improve fit results
//
// You can specify boundary limits for some or all parameters via
// func->SetParLimits(p_number, parmin, parmax);
// if parmin>=parmax, the parameter is fixed
// Note that you are not forced to fix the limits for all parameters.
// For example, if you fit a function with 6 parameters, you can do:
// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
// func->SetParLimits(4,-10,-4);
// func->SetParLimits(5, 1,1);
// With this setup, parameters 0->3 can vary freely
// Parameter 4 has boundaries [-10,-4] with initial value -8
// Parameter 5 is fixed to 100.
//
// For the fit to be meaningful, the function must be self-normalized.
//
// i.e. It must have the same integral regardless of the parameter
// settings. Otherwise the fit will effectively just maximize the
// area.
//
// It is mandatory to have a normalization variable
// which is fixed for the fit. e.g.
//
// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
// f1->SetParameters(1, 3.1, 0.01);
// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
// //
//
// 1, 2 and 3 Dimensional fits are supported.
// See also TTree::Fit
//
// Return status
// =============
// The function return the status of the fit in the following form
// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
// The fitResult is 0 is the fit is OK.
// The fitResult is negative in case of an error not connected with the fit.
// The number of entries used in the fit can be obtained via
// mytree.GetSelectedRows();
// If the number of selected entries is null the function returns -1
GetPlayer();
if (fPlayer) {
return fPlayer->UnbinnedFit(funcname, varexp, selection, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
void TTree::UseCurrentStyle()
{
// Replace current attributes by current style.
if (gStyle->IsReading()) {
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
} else {
gStyle->SetHistFillColor(GetFillColor());
gStyle->SetHistFillStyle(GetFillStyle());
gStyle->SetHistLineColor(GetLineColor());
gStyle->SetHistLineStyle(GetLineStyle());
gStyle->SetHistLineWidth(GetLineWidth());
gStyle->SetMarkerColor(GetMarkerColor());
gStyle->SetMarkerStyle(GetMarkerStyle());
gStyle->SetMarkerSize(GetMarkerSize());
}
}
//______________________________________________________________________________
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
{
// Write this object to the current directory. For more see TObject::Write
// Write calls TTree::FlushBaskets before writing the tree.
FlushBaskets();
return TObject::Write(name, option, bufsize);
}
//______________________________________________________________________________
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize)
{
// Write this object to the current directory. For more see TObject::Write
// If option & kFlushBasket, call FlushBasket before writing the tree.
return ((const TTree*)this)->Write(name, option, bufsize);
}
//////////////////////////////////////////////////////////////////////////
// //
// TTreeFriendLeafIter //
// //
// Iterator on all the leaves in a TTree and its friend //
// //
//////////////////////////////////////////////////////////////////////////
ClassImp(TTreeFriendLeafIter)
//______________________________________________________________________________
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTree* tree, Bool_t dir)
: fTree(const_cast<TTree*>(tree))
, fLeafIter(0)
, fTreeIter(0)
, fDirection(dir)
{
// Create a new iterator. By default the iteration direction
// is kIterForward. To go backward use kIterBackward.
}
//______________________________________________________________________________
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTreeFriendLeafIter& iter)
: TIterator(iter)
, fTree(iter.fTree)
, fLeafIter(0)
, fTreeIter(0)
, fDirection(iter.fDirection)
{
// Copy constructor. Does NOT copy the 'cursor' location!
}
//______________________________________________________________________________
TIterator& TTreeFriendLeafIter::operator=(const TIterator& rhs)
{
// Overridden assignment operator. Does NOT copy the 'cursor' location!
if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
const TTreeFriendLeafIter &rhs1 = (const TTreeFriendLeafIter &)rhs;
fDirection = rhs1.fDirection;
}
return *this;
}
//______________________________________________________________________________
TTreeFriendLeafIter& TTreeFriendLeafIter::operator=(const TTreeFriendLeafIter& rhs)
{
// Overridden assignment operator. Does NOT copy the 'cursor' location!
if (this != &rhs) {
fDirection = rhs.fDirection;
}
return *this;
}
//______________________________________________________________________________
TObject* TTreeFriendLeafIter::Next()
{
// Go the next friend element
if (!fTree) return 0;
TObject * next;
TTree * nextTree;
if (!fLeafIter) {
TObjArray *list = fTree->GetListOfLeaves();
if (!list) return 0; // Can happen with an empty chain.
fLeafIter = list->MakeIterator(fDirection);
}
next = fLeafIter->Next();
if (!next) {
if (!fTreeIter) {
TCollection * list = fTree->GetListOfFriends();
if (!list) return next;
fTreeIter = list->MakeIterator(fDirection);
}
TFriendElement * nextFriend = (TFriendElement*) fTreeIter->Next();
///nextTree = (TTree*)fTreeIter->Next();
if (nextFriend) {
nextTree = const_cast<TTree*>(nextFriend->GetTree());
if (!nextTree) return Next();
SafeDelete(fLeafIter);
fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
next = fLeafIter->Next();
}
}
return next;
}
//______________________________________________________________________________
Option_t* TTreeFriendLeafIter::GetOption() const
{
// Returns the object option stored in the list.
if (fLeafIter) return fLeafIter->GetOption();
return "";
}
Fix format in Warning and Error statements
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@34217 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/tree:$Id$
// Author: Rene Brun 12/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TTree //
// //
// A TTree object has a header with a name and a title.
// It consists of a list of independent branches (TBranch). Each branch
// has its own definition and list of buffers. Branch buffers may be
// automatically written to disk or kept in memory until the Tree attribute
// fMaxVirtualSize is reached. Variables of one branch are written to the
// same buffer. A branch buffer is automatically compressed if the file
// compression attribute is set (default).
//
// Branches may be written to different files (see TBranch::SetFile).
//
// The ROOT user can decide to make one single branch and serialize one
// object into one single I/O buffer or to make several branches.
// Making one single branch and one single buffer can be the right choice
// when one wants to process only a subset of all entries in the tree.
// (you know for example the list of entry numbers you want to process).
// Making several branches is particularly interesting in the data analysis
// phase, when one wants to histogram some attributes of an object (entry)
// without reading all the attributes.
//
// ==> TTree *tree = new TTree(name, title)
// Creates a Tree with name and title.
//
// Various kinds of branches can be added to a tree:
//
// ==> Case A
// ======
// TBranch *branch = tree->Branch(branchname, address, leaflist, bufsize)
// * address is the address of the first item of a structure
// * leaflist is the concatenation of all the variable names and types
// separated by a colon character :
// The variable name and the variable type are separated by a slash (/).
// The variable type may be 0,1 or 2 characters. If no type is given,
// the type of the variable is assumed to be the same as the previous
// variable. If the first variable does not have a type, it is assumed
// of type F by default. The list of currently supported types is given below:
// - C : a character string terminated by the 0 character
// - B : an 8 bit signed integer (Char_t)
// - b : an 8 bit unsigned integer (UChar_t)
// - S : a 16 bit signed integer (Short_t)
// - s : a 16 bit unsigned integer (UShort_t)
// - I : a 32 bit signed integer (Int_t)
// - i : a 32 bit unsigned integer (UInt_t)
// - F : a 32 bit floating point (Float_t)
// - D : a 64 bit floating point (Double_t)
// - L : a 64 bit signed integer (Long64_t)
// - l : a 64 bit unsigned integer (ULong64_t)
// - O : a boolean (Bool_t)
// * If the address points to a single numerical variable, the leaflist is optional:
// int value;
// tree->Branch(branchname, &value);
// * If the address points to more than one numerical variable, we strongly recommend
// that the variable be sorted in decreasing order of size. Any other order will
// result in a non-portable (even between CINT and compiled code on the platform)
// TTree (i.e. you will not be able to read it back on a platform with a different
// padding strategy).
//
// ==> Case B
// ======
// TBranch *branch = tree->Branch(branchname, &p_object, bufsize, splitlevel)/
// TBranch *branch = tree->Branch(branchname, className, &p_object, bufsize, splitlevel)
// * p_object is a pointer to an object.
// * If className is not specified, Branch uses the type of p_object to determine the
// type of the object.
// * If className is used to specify explicitly the object type, the className must
// be of a type related to the one pointed to by the pointer. It should be either
// a parent or derived class.
// * if splitlevel=0, the object is serialized in the branch buffer.
// * if splitlevel=1 (default), this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// the mechanism described in case C is applied to this array.
// * if splitlevel=2 ,this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// it is processed as a TObject*, only one branch.
//
// Note: The pointer whose address is passed to TTree::Branch must not
// be destroyed (i.e. go out of scope) until the TTree is deleted or
// TTree::ResetBranchAddress is called.
//
// Note: The pointer p_object must be initialized before calling TTree::Branch
// Do either:
// MyDataClass* p_object = 0;
// tree->Branch(branchname, &p_object);
// Or
// MyDataClass* p_object = new MyDataClass;
// tree->Branch(branchname, &p_object);
//
// ==> Case C
// ======
// MyClass object;
// TBranch *branch = tree->Branch(branchname, &object, bufsize, splitlevel)
//
// Note: The 2nd parameter must be the address of a valid object.
// The object must not be destroyed (i.e. be deleted) until the TTree
// is deleted or TTree::ResetBranchAddress is called.
//
// * if splitlevel=0, the object is serialized in the branch buffer.
// * if splitlevel=1 (default), this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// the mechanism described in case C is applied to this array.
// * if splitlevel=2 ,this branch will automatically be split
// into subbranches, with one subbranch for each data member or object
// of the object itself. In case the object member is a TClonesArray,
// it is processed as a TObject*, only one branch.
//
// ==> Case D
// ======
// TBranch *branch = tree->Branch(branchname,clonesarray, bufsize, splitlevel)
// clonesarray is the address of a pointer to a TClonesArray.
// The TClonesArray is a direct access list of objects of the same class.
// For example, if the TClonesArray is an array of TTrack objects,
// this function will create one subbranch for each data member of
// the object TTrack.
//
// ==> Case E
// ======
// TBranch *branch = tree->Branch( branchname, STLcollection, buffsize, splitlevel);
// STLcollection is the address of a pointer to std::vector, std::list,
// std::deque, std::set or std::multiset containing pointers to objects.
// If the splitlevel is a value bigger than 100 then the collection
// will be written in split mode. Ie. if it contains objects of any
// types deriving from TTrack this function will sort the objects
// basing on their type and store them in separate branches in split
// mode.
//
// ==> branch->SetAddress(Void *address)
// In case of dynamic structures changing with each entry for example, one must
// redefine the branch address before filling the branch again.
// This is done via the TBranch::SetAddress member function.
//
// ==> tree->Fill()
// loops on all defined branches and for each branch invokes the Fill function.
//
// See also the class TNtuple (a simple Tree with branches of floats)
//
// Adding a Branch to an Existing Tree
// ===================================
// You may want to add a branch to an existing tree. For example,
// if one variable in the tree was computed with a certain algorithm,
// you may want to try another algorithm and compare the results.
// One solution is to add a new branch, fill it, and save the tree.
// The code below adds a simple branch to an existing tree.
// Note the kOverwrite option in the Write method, it overwrites the
// existing tree. If it is not specified, two copies of the tree headers
// are saved.
//
// void tree3AddBranch(){
// TFile f("tree3.root", "update");
//
// Float_t new_v;
// TTree *t3 = (TTree*)f->Get("t3");
// TBranch *newBranch = t3->Branch("new_v", &new_v, "new_v/F");
//
// //read the number of entries in the t3
// Long64_t nentries = t3->GetEntries();
//
// for (Long64_t i = 0; i < nentries; i++){
// new_v= gRandom->Gaus(0, 1);
// newBranch->Fill();
// }
// // save only the new version of the tree
// t3->Write("", TObject::kOverwrite);
// }
// Adding a branch is often not possible because the tree is in a read-only
// file and you do not have permission to save the modified tree with the
// new branch. Even if you do have the permission, you risk losing the
// original tree with an unsuccessful attempt to save the modification.
// Since trees are usually large, adding a branch could extend it over the
// 2GB limit. In this case, the attempt to write the tree fails, and the
// original data is erased.
// In addition, adding a branch to a tree enlarges the tree and increases
// the amount of memory needed to read an entry, and therefore decreases
// the performance.
//
// For these reasons, ROOT offers the concept of friends for trees (and chains).
// We encourage you to use TTree::AddFriend rather than adding a branch manually.
//
//Begin_Html
/*
<img src="gif/tree_layout.gif">
*/
//End_Html
// =============================================================================
//______________________________________________________________________________
//*-*-*-*-*-*-*A simple example with histograms and a tree*-*-*-*-*-*-*-*-*-*
//*-* ===========================================
//
// This program creates :
// - a one dimensional histogram
// - a two dimensional histogram
// - a profile histogram
// - a tree
//
// These objects are filled with some random numbers and saved on a file.
//
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//
// #include "TFile.h"
// #include "TH1.h"
// #include "TH2.h"
// #include "TProfile.h"
// #include "TRandom.h"
// #include "TTree.h"
//
//
// //______________________________________________________________________________
// main(int argc, char **argv)
// {
// // Create a new ROOT binary machine independent file.
// // Note that this file may contain any kind of ROOT objects, histograms,trees
// // pictures, graphics objects, detector geometries, tracks, events, etc..
// // This file is now becoming the current directory.
// TFile hfile("htree.root","RECREATE","Demo ROOT file with histograms & trees");
//
// // Create some histograms and a profile histogram
// TH1F *hpx = new TH1F("hpx","This is the px distribution",100,-4,4);
// TH2F *hpxpy = new TH2F("hpxpy","py ps px",40,-4,4,40,-4,4);
// TProfile *hprof = new TProfile("hprof","Profile of pz versus px",100,-4,4,0,20);
//
// // Define some simple structures
// typedef struct {Float_t x,y,z;} POINT;
// typedef struct {
// Int_t ntrack,nseg,nvertex;
// UInt_t flag;
// Float_t temperature;
// } EVENTN;
// static POINT point;
// static EVENTN eventn;
//
// // Create a ROOT Tree
// TTree *tree = new TTree("T","An example of ROOT tree with a few branches");
// tree->Branch("point",&point,"x:y:z");
// tree->Branch("eventn",&eventn,"ntrack/I:nseg:nvertex:flag/i:temperature/F");
// tree->Branch("hpx","TH1F",&hpx,128000,0);
//
// Float_t px,py,pz;
// static Float_t p[3];
//
// //--------------------Here we start a loop on 1000 events
// for ( Int_t i=0; i<1000; i++) {
// gRandom->Rannor(px,py);
// pz = px*px + py*py;
// Float_t random = gRandom->::Rndm(1);
//
// // Fill histograms
// hpx->Fill(px);
// hpxpy->Fill(px,py,1);
// hprof->Fill(px,pz,1);
//
// // Fill structures
// p[0] = px;
// p[1] = py;
// p[2] = pz;
// point.x = 10*(random-1);;
// point.y = 5*random;
// point.z = 20*random;
// eventn.ntrack = Int_t(100*random);
// eventn.nseg = Int_t(2*eventn.ntrack);
// eventn.nvertex = 1;
// eventn.flag = Int_t(random+0.5);
// eventn.temperature = 20+random;
//
// // Fill the tree. For each event, save the 2 structures and 3 objects
// // In this simple example, the objects hpx, hprof and hpxpy are slightly
// // different from event to event. We expect a big compression factor!
// tree->Fill();
// }
// //--------------End of the loop
//
// tree->Print();
//
// // Save all objects in this file
// hfile.Write();
//
// // Close the file. Note that this is automatically done when you leave
// // the application.
// hfile.Close();
//
// return 0;
// }
// //
//////////////////////////////////////////////////////////////////////////
#include "RConfig.h"
#include "TTree.h"
#include "TArrayC.h"
#include "TBufferFile.h"
#include "TBaseClass.h"
#include "TBasket.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TBranchRef.h"
#include "TBrowser.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TClonesArray.h"
#include "TCut.h"
#include "TDataMember.h"
#include "TDataType.h"
#include "TDirectory.h"
#include "TError.h"
#include "TEntryList.h"
#include "TEventList.h"
#include "TFile.h"
#include "TFolder.h"
#include "TFriendElement.h"
#include "TInterpreter.h"
#include "TLeaf.h"
#include "TLeafB.h"
#include "TLeafC.h"
#include "TLeafD.h"
#include "TLeafElement.h"
#include "TLeafF.h"
#include "TLeafI.h"
#include "TLeafL.h"
#include "TLeafObject.h"
#include "TLeafS.h"
#include "TList.h"
#include "TMath.h"
#include "TROOT.h"
#include "TRealData.h"
#include "TRegexp.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
#include "TStyle.h"
#include "TSystem.h"
#include "TTreeCloner.h"
#include "TTreeCache.h"
#include "TTreeCacheUnzip.h"
#include "TVirtualCollectionProxy.h"
#include "TEmulatedCollectionProxy.h"
#include "TVirtualFitter.h"
#include "TVirtualIndex.h"
#include "TVirtualPad.h"
#include "TBranchSTL.h"
#include "TSchemaRuleSet.h"
#include <cstddef>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
Long64_t TTree::fgMaxTreeSize = 100000000000LL;
TTree* gTree;
ClassImp(TTree)
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
static char DataTypeToChar(EDataType datatype)
{
// Return the leaflist 'char' for a given datatype.
switch(datatype) {
case kChar_t: return 'B';
case kUChar_t: return 'b';
case kBool_t: return 'O';
case kShort_t: return 'S';
case kUShort_t: return 's';
case kCounter:
case kInt_t: return 'I';
case kUInt_t: return 'i';
case kDouble_t:
case kDouble32_t: return 'D';
case kFloat_t:
case kFloat16_t: return 'F';
case kLong_t: return 0; // unsupported
case kULong_t: return 0; // unsupported?
case kchar: return 0; // unsupported
case kLong64_t: return 'L';
case kULong64_t: return 'l';
case kCharStar: return 'C';
case kBits: return 0; //unsupported
case kOther_t:
case kNoType_t:
default:
return 0;
}
return 0;
}
//______________________________________________________________________________
// Helper class to prevent infinite recursion in the usage of TTree Friends.
//______________________________________________________________________________
TTree::TFriendLock::TFriendLock(TTree* tree, UInt_t methodbit)
: fTree(tree)
{
// Record in tree that it has been used while recursively looks through the friends.
// We could also add some code to acquire an actual
// lock to prevent multi-thread issues
fMethodBit = methodbit;
if (fTree) {
fPrevious = fTree->fFriendLockStatus & fMethodBit;
fTree->fFriendLockStatus |= fMethodBit;
} else {
fPrevious = 0;
}
}
//______________________________________________________________________________
TTree::TFriendLock::TFriendLock(const TFriendLock& tfl) :
fTree(tfl.fTree),
fMethodBit(tfl.fMethodBit),
fPrevious(tfl.fPrevious)
{
//copy constructor
}
//______________________________________________________________________________
TTree::TFriendLock& TTree::TFriendLock::operator=(const TTree::TFriendLock& tfl)
{
//assignement operator
if(this!=&tfl) {
fTree=tfl.fTree;
fMethodBit=tfl.fMethodBit;
fPrevious=tfl.fPrevious;
}
return *this;
}
//______________________________________________________________________________
TTree::TFriendLock::~TFriendLock()
{
// Restore the state of tree the same as before we set the lock.
if (fTree) {
if (!fPrevious) {
fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
}
}
}
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
//______________________________________________________________________________
TTree::TTree()
: TNamed()
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(0)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
{
// Default constructor and I/O constructor.
//
// Note: We do *not* insert ourself into the current directory.
//
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
}
//______________________________________________________________________________
TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */)
: TNamed(name, title)
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(0)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
{
// Normal tree constructor.
//
// The tree is created in the current directory.
// Use the various functions Branch below to add branches to this tree.
//
// If the first character of title is a "/", the function assumes a folder name.
// In this case, it creates automatically branches following the folder hierarchy.
// splitlevel may be used in this case to control the split level.
// TAttLine state.
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
// TAttFill state.
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
// TAttMarkerState.
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
// Insert ourself into the current directory.
// FIXME: This is very annoying behaviour, we should
// be able to choose to not do this like we
// can with a histogram.
fDirectory = gDirectory;
fDirectory->Append(this);
// We become the current tree.
gTree = this;
// If title starts with "/" and is a valid folder name, a superbranch
// is created.
// FIXME: Why?
if (strlen(title) > 2) {
if (title[0] == '/') {
Branch(title+1,32000,splitlevel);
}
}
}
//______________________________________________________________________________
TTree::~TTree()
{
// Destructor.
if (fDirectory) {
// We are in a directory, which may possibly be a file.
if (fDirectory->GetList()) {
// Remove us from the directory listing.
fDirectory->Remove(this);
}
//delete the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
if (file) {
TFileCacheRead *pf = file->GetCacheRead();
if (pf && pf->InheritsFrom(TTreeCache::Class())) {
TTreeCache *tpf = (TTreeCache*)pf;
if (tpf->GetOwner() == this) {
delete tpf;
tpf = 0;
file->SetCacheRead(0);
}
}
}
}
// We don't own the leaves in fLeaves, the branches do.
fLeaves.Clear();
// I'm ready to destroy any objects allocated by
// SetAddress() by my branches. If I have clones,
// tell them to zero their pointers to this shared
// memory.
if (fClones && fClones->GetEntries()) {
// I have clones.
// I am about to delete the objects created by
// SetAddress() which we are sharing, so tell
// the clones to release their pointers to them.
for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
TTree* clone = (TTree*) lnk->GetObject();
// clone->ResetBranchAddresses();
// Reset only the branch we have set the address of.
CopyAddresses(clone,kTRUE);
}
}
// Get rid of our branches, note that this will also release
// any memory allocated by TBranchElement::SetAddress().
fBranches.Delete();
// FIXME: We must consider what to do with the reset of these if we are a clone.
delete fPlayer;
fPlayer = 0;
if (fFriends) {
fFriends->Delete();
delete fFriends;
fFriends = 0;
}
if (fAliases) {
fAliases->Delete();
delete fAliases;
fAliases = 0;
}
if (fUserInfo) {
fUserInfo->Delete();
delete fUserInfo;
fUserInfo = 0;
}
if (fClones) {
// Clone trees should no longer be removed from fClones when they are deleted.
gROOT->GetListOfCleanups()->Remove(fClones);
// Note: fClones does not own its content.
delete fClones;
fClones = 0;
}
if (fEntryList) {
if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==0) {
// Delete the entry list if it is marked to be deleted and it is not also
// owned by a directory. (Otherwise we would need to make sure that a
// TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
delete fEntryList;
fEntryList=0;
}
}
delete fTreeIndex;
fTreeIndex = 0;
delete fBranchRef;
fBranchRef = 0;
// Must be done after the destruction of friends.
// Note: We do *not* own our directory.
fDirectory = 0;
}
//______________________________________________________________________________
void TTree::AddBranchToCache(const char*bname, Bool_t subbranches)
{
// Add branch with name bname to the Tree cache.
// If bname="*" all branches are added to the cache.
// if subbranches is true all the branches of the subbranches are
// also put to the cache.
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->AddBranch(bname,subbranches);
}
//______________________________________________________________________________
void TTree::AddBranchToCache(TBranch *b, Bool_t subbranches)
{
// Add branch b to the Tree cache.
// if subbranches is true all the branches of the subbranches are
// also put to the cache.
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->AddBranch(b,subbranches);
}
//______________________________________________________________________________
void TTree::AddClone(TTree* clone)
{
// Add a cloned tree to our list of trees to be notified whenever we change
// our branch addresses or when we are deleted.
if (!fClones) {
fClones = new TList();
fClones->SetOwner(false);
// So that the clones are automatically removed from the list when
// they are deleted.
gROOT->GetListOfCleanups()->Add(fClones);
}
if (!fClones->FindObject(clone)) {
fClones->Add(clone);
}
}
//______________________________________________________________________________
TFriendElement* TTree::AddFriend(const char* treename, const char* filename)
{
// Add a TFriendElement to the list of friends.
//
// This function:
// -opens a file if filename is specified
// -reads a Tree with name treename from the file (current directory)
// -adds the Tree to the list of friends
// see other AddFriend functions
//
// A TFriendElement TF describes a TTree object TF in a file.
// When a TFriendElement TF is added to the the list of friends of an
// existing TTree T, any variable from TF can be referenced in a query
// to T.
//
// A tree keeps a list of friends. In the context of a tree (or a chain),
// friendship means unrestricted access to the friends data. In this way
// it is much like adding another branch to the tree without taking the risk
// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
// method. The tree in the diagram below has two friends (friend_tree1 and
// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
//
//Begin_Html
/*
<img src="gif/tree_friend1.gif">
*/
//End_Html
//
// The AddFriend method has two parameters, the first is the tree name and the
// second is the name of the ROOT file where the friend tree is saved.
// AddFriend automatically opens the friend file. If no file name is given,
// the tree called ft1 is assumed to be in the same file as the original tree.
//
// tree.AddFriend("ft1","friendfile1.root");
// If the friend tree has the same name as the original tree, you can give it
// an alias sin the context of the friendship:
//
// tree.AddFriend("tree1 = tree","friendfile1.root");
// Once the tree has friends, we can use TTree::Draw as if the friend's
// variables were in the original tree. To specify which tree to use in
// the Draw method, use the syntax:
//
// <treeName>.<branchname>.<varname>
// If the variablename is enough to uniquely identify the variable, you can
// leave out the tree and/or branch name.
// For example, these commands generate a 3-d scatter plot of variable "var"
// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
// TTree ft2.
//
// tree.AddFriend("ft1","friendfile1.root");
// tree.AddFriend("ft2","friendfile2.root");
// tree.Draw("var:ft1.v1:ft2.v2");
//
//Begin_Html
/*
<img src="gif/tree_friend2.gif">
*/
//End_Html
//
// The picture illustrates the access of the tree and its friends with a
// Draw command.
// When AddFriend is called, the ROOT file is automatically opened and the
// friend tree (ft1) is read into memory. The new friend (ft1) is added to
// the list of friends of tree.
// The number of entries in the friend must be equal or greater to the number
// of entries of the original tree. If the friend tree has fewer entries a
// warning is given and the missing entries are not included in the histogram.
// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
// When the tree is written to file (TTree::Write), the friends list is saved
// with it. And when the tree is retrieved, the trees on the friends list are
// also retrieved and the friendship restored.
// When a tree is deleted, the elements of the friend list are also deleted.
// It is possible to declare a friend tree that has the same internal
// structure (same branches and leaves) as the original tree, and compare the
// same values by specifying the tree.
//
// tree.Draw("var:ft1.var:ft2.var")
//if (kAddFriend & fFriendLockStatus)
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, treename, filename);
R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename, filename, t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "Cannot add FriendElement %s in file %s", treename, filename);
}
return fe;
}
//______________________________________________________________________________
TFriendElement* TTree::AddFriend(const char* treename, TFile* file)
{
// Add a TFriendElement to the list of friends.
//
// The TFile is managed by the user (e.g. the user must delete the file).
// For complete description see AddFriend(const char *, const char *).
// This function:
// -reads a Tree with name treename from the file
// -adds the Tree to the list of friends
if (!fFriends) {
fFriends = new TList();
}
TFriendElement *fe = new TFriendElement(this, treename, file);
R__ASSERT(fe);
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename, file->GetName(), t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "unknown tree '%s' in file '%s'", treename, file->GetName());
}
return fe;
}
//______________________________________________________________________________
TFriendElement* TTree::AddFriend(TTree* tree, const char* alias, Bool_t warn)
{
// Add a TFriendElement to the list of friends.
//
// The TTree is managed by the user (e.g., the user must delete the file).
// For a complete description see AddFriend(const char *, const char *).
if (!tree) {
return 0;
}
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, tree, alias);
R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (warn && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld", tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(), fEntries);
}
return fe;
}
//______________________________________________________________________________
Long64_t TTree::AutoSave(Option_t* option)
{
// AutoSave tree header every fAutoSave bytes.
//
// When large Trees are produced, it is safe to activate the AutoSave
// procedure. Some branches may have buffers holding many entries.
// AutoSave is automatically called by TTree::Fill when the number of bytes
// generated since the previous AutoSave is greater than fAutoSave bytes.
// This function may also be invoked by the user, for example every
// N entries.
// Each AutoSave generates a new key on the file.
// Once the key with the tree header has been written, the previous cycle
// (if any) is deleted.
//
// Note that calling TTree::AutoSave too frequently (or similarly calling
// TTree::SetAutoSave with a small value) is an expensive operation.
// You should make tests for your own application to find a compromize
// between speed and the quantity of information you may loose in case of
// a job crash.
//
// In case your program crashes before closing the file holding this tree,
// the file will be automatically recovered when you will connect the file
// in UPDATE mode.
// The Tree will be recovered at the status corresponding to the last AutoSave.
//
// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
// This allows another process to analyze the Tree while the Tree is being filled.
//
// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
// the current basket are closed-out and written to disk individually.
//
// By default the previous header is deleted after having written the new header.
// if option contains "Overwrite", the previous Tree header is deleted
// before written the new header. This option is slightly faster, but
// the default option is safer in case of a problem (disk quota exceeded)
// when writing the new header.
//
// The function returns the number of bytes written to the file.
// if the number of bytes is null, an error has occured while writing
// the header to the file.
//
// How to write a Tree in one process and view it from another process
// ===================================================================
// The following two scripts illustrate how to do this.
// The script treew.C is executed by process1, treer.C by process2
//
// ----- script treew.C
// void treew() {
// TFile f("test.root","recreate");
// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
// Float_t px, py, pz;
// for ( Int_t i=0; i<10000000; i++) {
// gRandom->Rannor(px,py);
// pz = px*px + py*py;
// Float_t random = gRandom->Rndm(1);
// ntuple->Fill(px,py,pz,random,i);
// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
// }
// }
//
// ----- script treer.C
// void treer() {
// TFile f("test.root");
// TTree *ntuple = (TTree*)f.Get("ntuple");
// TCanvas c1;
// Int_t first = 0;
// while(1) {
// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
// else ntuple->Draw("px>>+hpx","","",10000000,first);
// first = (Int_t)ntuple->GetEntries();
// c1.Update();
// gSystem->Sleep(1000); //sleep 1 second
// ntuple->Refresh();
// }
// }
if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
if (gDebug > 0) {
printf("AutoSave Tree:%s after %lld bytes written\n",GetName(),fTotBytes);
}
TString opt = option;
opt.ToLower();
if (opt.Contains("flushbaskets")) {
if (gDebug > 0) printf("AutoSave: calling FlushBaskets \n");
FlushBaskets();
}
fSavedBytes = fZipBytes;
TKey *key = (TKey*)fDirectory->GetListOfKeys()->FindObject(GetName());
Long64_t nbytes;
if (opt.Contains("overwrite")) {
nbytes = fDirectory->WriteTObject(this,"","",TObject::kOverwrite);
} else {
nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
if (nbytes && key) {
key->Delete();
delete key;
}
}
// save StreamerInfo
TFile *file = fDirectory->GetFile();
if (file) file->WriteStreamerInfo();
if (opt.Contains("saveself")) fDirectory->SaveSelf();
return nbytes;
}
//______________________________________________________________________________
TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
// Same as TTree::Branch() with added check that addobj matches className.
//
// See TTree::Branch() for other details.
//
if (!ptrClass) {
TClass* claim = TClass::GetClass(classname);
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
TClass* claim = TClass::GetClass(classname);
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr) {
actualClass = ptrClass->GetActualClass(*addr);
}
if (ptrClass && claim) {
if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
// Note we currently do not warn in case of splicing or over-expectation).
if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
claim->GetName(), branchname, ptrClass->GetName());
}
} else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
actualClass->GetName(), branchname, claim->GetName());
}
}
}
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
//______________________________________________________________________________
TBranch* TTree::BranchImp(const char* branchname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
// Same as TTree::Branch but automatic detection of the class name.
// See TTree::Branch for other details.
if (!ptrClass) {
Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
return 0;
}
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr && *addr) {
actualClass = ptrClass->GetActualClass(*addr);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part", branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
} else {
actualClass = ptrClass;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
}
//______________________________________________________________________________
TBranch* TTree::BranchImpRef(const char* branchname, TClass* ptrClass, EDataType datatype, void* addobj, Int_t bufsize, Int_t splitlevel)
{
// Same as TTree::Branch but automatic detection of the class name.
// See TTree::Branch for other details.
if (!ptrClass) {
if (datatype == kOther_t || datatype == kNoType_t) {
Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
} else {
TString varname; varname.Form("%s/%c",branchname,DataTypeToChar(datatype));
return Branch(branchname,addobj,varname.Data(),bufsize);
}
return 0;
}
TClass* actualClass = 0;
if (!addobj) {
Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
return 0;
}
actualClass = ptrClass->GetActualClass(addobj);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part", branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
}
//______________________________________________________________________________
Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
{
// Deprecated function. Use next function instead.
return Branch((TCollection*) li, bufsize, splitlevel);
}
//______________________________________________________________________________
Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
{
// Create one branch for each element in the collection.
//
// Each entry in the collection becomes a top level branch if the
// corresponding class is not a collection. If it is a collection, the entry
// in the collection becomes in turn top level branches, etc.
// The splitlevel is decreased by 1 everytime a new collection is found.
// For example if list is a TObjArray*
// - if splitlevel = 1, one top level branch is created for each element
// of the TObjArray.
// - if splitlevel = 2, one top level branch is created for each array element.
// if, in turn, one of the array elements is a TCollection, one top level
// branch will be created for each element of this collection.
//
// In case a collection element is a TClonesArray, the special Tree constructor
// for TClonesArray is called.
// The collection itself cannot be a TClonesArray.
//
// The function returns the total number of branches created.
//
// If name is given, all branch names will be prefixed with name_.
//
// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
//
// IMPORTANT NOTE2: The branches created by this function will have names
// corresponding to the collection or object names. It is important
// to give names to collections to avoid misleading branch names or
// identical branch names. By default collections have a name equal to
// the corresponding class name, eg the default name for a TList is "TList".
//
// Example--------------------------------------------------------------:
/*
{
TTree T("T","test list");
TList *l = new TList();
TObjArray *a1 = new TObjArray();
a1->SetName("a1");
l->Add(a1);
TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
a1->Add(ha1a);
a1->Add(ha1b);
TObjArray *b1 = new TObjArray();
b1->SetName("b1");
l->Add(b1);
TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
b1->Add(hb1a);
b1->Add(hb1b);
TObjArray *a2 = new TObjArray();
a2->SetName("a2");
l->Add(a2);
TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
a2->Add(ha2a);
a2->Add(ha2b);
T.Branch(l,16000,2);
T.Print();
}
*/
//----------------------------------------------------------------------
if (!li) {
return 0;
}
TObject* obj = 0;
Int_t nbranches = GetListOfBranches()->GetEntries();
if (li->InheritsFrom(TClonesArray::Class())) {
Error("Branch", "Cannot call this constructor for a TClonesArray");
return 0;
}
Int_t nch = strlen(name);
TString branchname;
TIter next(li);
while ((obj = next())) {
if ((splitlevel > 1) && obj->InheritsFrom(TCollection::Class()) && !obj->InheritsFrom(TClonesArray::Class())) {
TCollection* col = (TCollection*) obj;
if (nch) {
branchname.Form("%s_%s_", name, col->GetName());
} else {
branchname.Form("%s_", col->GetName());
}
Branch(col, bufsize, splitlevel - 1, branchname);
} else {
if (nch && (name[nch-1] == '_')) {
branchname.Form("%s%s", name, obj->GetName());
} else {
if (nch) {
branchname.Form("%s_%s", name, obj->GetName());
} else {
branchname.Form("%s", obj->GetName());
}
}
if (splitlevel > 99) {
branchname += ".";
}
Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
}
}
return GetListOfBranches()->GetEntries() - nbranches;
}
//______________________________________________________________________________
Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Create one branch for each element in the folder.
// Returns the total number of branches created.
TObject* ob = gROOT->FindObjectAny(foldername);
if (!ob) {
return 0;
}
if (ob->IsA() != TFolder::Class()) {
return 0;
}
Int_t nbranches = GetListOfBranches()->GetEntries();
TFolder* folder = (TFolder*) ob;
TIter next(folder->GetListOfFolders());
TObject* obj = 0;
char* curname = new char[1000];
char occur[20];
while ((obj = next())) {
sprintf(curname, "%s/%s", foldername, obj->GetName());
if (obj->IsA() == TFolder::Class()) {
Branch(curname, bufsize, splitlevel - 1);
} else {
void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
for (Int_t i = 0; i < 1000; ++i) {
if (curname[i] == 0) {
break;
}
if (curname[i] == '/') {
curname[i] = '.';
}
}
Int_t noccur = folder->Occurence(obj);
if (noccur > 0) {
sprintf(occur, "_%d", noccur);
strcat(curname, occur);
}
TBranchElement* br = (TBranchElement*) Bronch(curname, obj->ClassName(), add, bufsize, splitlevel - 1);
br->SetBranchFolder();
}
}
delete[] curname;
return GetListOfBranches()->GetEntries() - nbranches;
}
//______________________________________________________________________________
TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
{
// Create a new TTree Branch.
//
// This Branch constructor is provided to support non-objects in
// a Tree. The variables described in leaflist may be simple
// variables or structures. // See the two following
// constructors for writing objects in a Tree.
//
// By default the branch buffers are stored in the same file as the Tree.
// use TBranch::SetFile to specify a different file
//
// * address is the address of the first item of a structure.
// * leaflist is the concatenation of all the variable names and types
// separated by a colon character :
// The variable name and the variable type are separated by a slash (/).
// The variable type may be 0,1 or 2 characters. If no type is given,
// the type of the variable is assumed to be the same as the previous
// variable. If the first variable does not have a type, it is assumed
// of type F by default. The list of currently supported types is given below:
// - C : a character string terminated by the 0 character
// - B : an 8 bit signed integer (Char_t)
// - b : an 8 bit unsigned integer (UChar_t)
// - S : a 16 bit signed integer (Short_t)
// - s : a 16 bit unsigned integer (UShort_t)
// - I : a 32 bit signed integer (Int_t)
// - i : a 32 bit unsigned integer (UInt_t)
// - F : a 32 bit floating point (Float_t)
// - D : a 64 bit floating point (Double_t)
// - L : a 64 bit signed integer (Long64_t)
// - l : a 64 bit unsigned integer (ULong64_t)
// - O : a boolean (Bool_t)
//
// By default, a variable will be copied to the buffer with the number of
// bytes specified in the type descriptor character. However, if the type
// consists of 2 characters, the second character is an integer that
// specifies the number of bytes to be used when copying the variable
// to the output buffer. Example:
// X ; variable X, type Float_t
// Y/I : variable Y, type Int_t
// Y/I2 ; variable Y, type Int_t converted to a 16 bits integer
//
// Note that the TTree will assume that all the item are contiguous in memory.
// On some platform, this is not always true of the member of a struct or a class,
// due to padding and alignment. Sorting your data member in order of decreasing
// sizeof usually leads to their being contiguous in memory.
//
// * bufsize is the buffer size in bytes for this branch
// The default value is 32000 bytes and should be ok for most cases.
// You can specify a larger value (eg 256000) if your Tree is not split
// and each entry is large (Megabytes)
// A small value for bufsize is optimum if you intend to access
// the entries in the Tree randomly and your Tree is in split mode.
gTree = this;
TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
if (branch->IsZombie()) {
delete branch;
branch = 0;
return 0;
}
fBranches.Add(branch);
return branch;
}
//______________________________________________________________________________
TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Create a new branch with the object of class classname at address addobj.
//
// WARNING:
// Starting with Root version 3.01, the Branch function uses the new style
// branches (TBranchElement). To get the old behaviour, you can:
// - call BranchOld or
// - call TTree::SetBranchStyle(0)
//
// Note that with the new style, classname does not need to derive from TObject.
// It must derived from TObject if the branch style has been set to 0 (old)
//
// Note: See the comments in TBranchElement::SetAddress() for a more
// detailed discussion of the meaning of the addobj parameter in
// the case of new-style branches.
//
// Use splitlevel < 0 instead of splitlevel=0 when the class
// has a custom Streamer
//
// Note: if the split level is set to the default (99), TTree::Branch will
// not issue a warning if the class can not be split.
if (fgBranchStyle == 1) {
return Bronch(name, classname, addobj, bufsize, splitlevel);
} else {
if (splitlevel < 0) {
splitlevel = 0;
}
return BranchOld(name, classname, addobj, bufsize, splitlevel);
}
}
//______________________________________________________________________________
TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
{
// Create a new TTree BranchObject.
//
// Build a TBranchObject for an object of class classname.
// addobj is the address of a pointer to an object of class classname.
// IMPORTANT: classname must derive from TObject.
// The class dictionary must be available (ClassDef in class header).
//
// This option requires access to the library where the corresponding class
// is defined. Accessing one single data member in the object implies
// reading the full object.
// See the next Branch constructor for a more efficient storage
// in case the entry consists of arrays of identical objects.
//
// By default the branch buffers are stored in the same file as the Tree.
// use TBranch::SetFile to specify a different file
//
// IMPORTANT NOTE about branch names
// In case two or more master branches contain subbranches with
// identical names, one must add a "." (dot) character at the end
// of the master branch name. This will force the name of the subbranch
// to be master.subbranch instead of simply subbranch.
// This situation happens when the top level object (say event)
// has two or more members referencing the same class.
// For example, if a Tree has two branches B1 and B2 corresponding
// to objects of the same class MyClass, one can do:
// tree.Branch("B1.","MyClass",&b1,8000,1);
// tree.Branch("B2.","MyClass",&b2,8000,1);
// if MyClass has 3 members a,b,c, the two instructions above will generate
// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
//
// bufsize is the buffer size in bytes for this branch
// The default value is 32000 bytes and should be ok for most cases.
// You can specify a larger value (eg 256000) if your Tree is not split
// and each entry is large (Megabytes)
// A small value for bufsize is optimum if you intend to access
// the entries in the Tree randomly and your Tree is in split mode.
gTree = this;
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("BranchOld", "Cannot find class: '%s'", classname);
return 0;
}
TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
fBranches.Add(branch);
if (!splitlevel) {
return branch;
}
// We are going to fully split the class now.
TObjArray* blist = branch->GetListOfBranches();
const char* rdname = 0;
const char* dname = 0;
TString branchname;
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
Bool_t delobj = kFALSE;
if (!obj) {
obj = (TObject*) cl->New();
delobj = kTRUE;
}
// Build the StreamerInfo if first time for the class.
BuildStreamerInfo(cl, obj);
// Loop on all public data members of the class and its base classes.
Int_t lenName = strlen(name);
Int_t isDot = 0;
if (name[lenName-1] == '.') {
isDot = 1;
}
TBranch* branch1 = 0;
TRealData* rd = 0;
TRealData* rdi = 0;
TIter nexti(cl->GetListOfRealData());
TIter next(cl->GetListOfRealData());
// Note: This loop results in a full split because the
// real data list includes all data members of
// data members.
while ((rd = (TRealData*) next())) {
if (rd->TestBit(TRealData::kTransient)) continue;
// Loop over all data members creating branches for each one.
TDataMember* dm = rd->GetDataMember();
if (!dm->IsPersistent()) {
// Do not process members with an "!" as the first character in the comment field.
continue;
}
if (rd->IsObject()) {
// We skip data members of class type.
// But we do build their real data, their
// streamer info, and write their streamer
// info to the current directory's file.
// Oh yes, and we also do this for all of
// their base classes.
TClass* clm = TClass::GetClass(dm->GetFullTypeName());
if (clm) {
BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
}
continue;
}
rdname = rd->GetName();
dname = dm->GetName();
if (cl->CanIgnoreTObjectStreamer()) {
// Skip the TObject base class data members.
// FIXME: This prevents a user from ever
// using these names himself!
if (!strcmp(dname, "fBits")) {
continue;
}
if (!strcmp(dname, "fUniqueID")) {
continue;
}
}
TDataType* dtype = dm->GetDataType();
Int_t code = 0;
if (dtype) {
code = dm->GetDataType()->GetType();
}
// Encode branch name. Use real data member name
branchname = rdname;
if (isDot) {
if (dm->IsaPointer()) {
// FIXME: This is wrong! The asterisk is not usually in the front!
branchname.Form("%s%s", name, &rdname[1]);
} else {
branchname.Form("%s%s", name, &rdname[0]);
}
}
// FIXME: Change this to a string stream.
TString leaflist;
Int_t offset = rd->GetThisOffset();
char* pointer = ((char*) obj) + offset;
if (dm->IsaPointer()) {
// We have a pointer to an object or a pointer to an array of basic types.
TClass* clobj = 0;
if (!dm->IsBasic()) {
clobj = TClass::GetClass(dm->GetTypeName());
}
if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
// We have a pointer to a clones array.
char* cpointer = (char*) pointer;
char** ppointer = (char**) cpointer;
TClonesArray* li = (TClonesArray*) *ppointer;
if (splitlevel != 2) {
if (isDot) {
branch1 = new TBranchClones(branch,branchname, pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
}
blist->Add(branch1);
} else {
if (isDot) {
branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
}
blist->Add(branch1);
}
} else if (clobj) {
// We have a pointer to an object.
//
// It must be a TObject object.
if (!clobj->InheritsFrom(TObject::Class())) {
continue;
}
branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
if (isDot) {
branch1->SetName(branchname);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
// Do not use the first character (*).
branch1->SetName(&branchname.Data()[1]);
}
blist->Add(branch1);
} else {
// We have a pointer to an array of basic types.
//
// Check the comments in the text of the code for an index specification.
const char* index = dm->GetArrayIndex();
if (strlen(index) != 0) {
// We are a pointer to a varying length array of basic types.
//check that index is a valid data member name
//if member is part of an object (eg fA and index=fN)
//index must be changed from fN to fA.fN
TString aindex (rd->GetName());
Ssiz_t rdot = aindex.Last('.');
if (rdot>=0) {
aindex.Remove(rdot+1);
aindex.Append(index);
}
nexti.Reset();
while ((rdi = (TRealData*) nexti())) {
if (rdi->TestBit(TRealData::kTransient)) continue;
if (!strcmp(rdi->GetName(), index)) {
break;
}
if (!strcmp(rdi->GetName(), aindex)) {
index = rdi->GetName();
break;
}
}
char vcode = DataTypeToChar((EDataType)code);
// Note that we differentiate between strings and
// char array by the fact that there is NO specified
// size for a string (see next if (code == 1)
if (vcode) {
leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
} else {
// We are possibly a character string.
if (code == 1) {
// We are a character string.
leaflist.Form("%s/%s", dname, "C");
} else {
// Invalid array specification.
// FIXME: We need an error message here.
continue;
}
}
// There are '*' in both the branchname and leaflist, remove them.
TString bname( branchname );
bname.ReplaceAll("*","");
leaflist.ReplaceAll("*","");
// Add the branch to the tree and indicate that the address
// is that of a pointer to be dereferenced before using.
branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
leaf->SetBit(TLeaf::kIndirectAddress);
leaf->SetAddress((void**) pointer);
blist->Add(branch1);
}
} else if (dm->IsBasic()) {
// We have a basic type.
char vcode = DataTypeToChar((EDataType)code);
if (vcode) {
leaflist.Form("%s/%c", rdname, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
branch1->SetTitle(rdname);
blist->Add(branch1);
} else {
// We have a class type.
// Note: This cannot happen due to the rd->IsObject() test above.
// FIXME: Put an error message here just in case.
}
if (branch1) {
branch1->SetOffset(offset);
} else {
Warning("BranchOld", "Cannot process member: '%s'", rdname);
}
}
if (delobj) {
delete obj;
obj = 0;
}
return branch;
}
//______________________________________________________________________________
TBranch* TTree::BranchRef()
{
// Build the optional branch supporting the TRefTable.
// This branch will keep all the information to find the branches
// containing referenced objects.
//
// At each Tree::Fill, the branch numbers containing the
// referenced objects are saved to the TBranchRef basket.
// When the Tree header is saved (via TTree::Write), the branch
// is saved keeping the information with the pointers to the branches
// having referenced objects.
if (!fBranchRef) {
fBranchRef = new TBranchRef(this);
}
return fBranchRef;
}
//______________________________________________________________________________
TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Create a new TTree BranchElement.
//
// WARNING about this new function
// ===============================
// This function is designed to replace the function TTree::Branch above.
// This function is far more powerful than the Branch function.
// It supports the full C++, including STL and has the same behaviour
// in split or non-split mode. classname does not have to derive from TObject.
// The function is based on the new TStreamerInfo.
//
// Build a TBranchElement for an object of class classname.
//
// addr is the address of a pointer to an object of class classname.
// The class dictionary must be available (ClassDef in class header).
//
// Note: See the comments in TBranchElement::SetAddress() for a more
// detailed discussion of the meaning of the addr parameter.
//
// This option requires access to the library where the corresponding class
// is defined. Accessing one single data member in the object implies
// reading the full object.
//
// By default the branch buffers are stored in the same file as the Tree.
// use TBranch::SetFile to specify a different file
//
// IMPORTANT NOTE about branch names
// In case two or more master branches contain subbranches with
// identical names, one must add a "." (dot) character at the end
// of the master branch name. This will force the name of the subbranch
// to be master.subbranch instead of simply subbranch.
// This situation happens when the top level object (say event)
// has two or more members referencing the same class.
// For example, if a Tree has two branches B1 and B2 corresponding
// to objects of the same class MyClass, one can do:
// tree.Branch("B1.","MyClass",&b1,8000,1);
// tree.Branch("B2.","MyClass",&b2,8000,1);
// if MyClass has 3 members a,b,c, the two instructions above will generate
// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
//
// bufsize is the buffer size in bytes for this branch
// The default value is 32000 bytes and should be ok for most cases.
// You can specify a larger value (eg 256000) if your Tree is not split
// and each entry is large (Megabytes)
// A small value for bufsize is optimum if you intend to access
// the entries in the Tree randomly and your Tree is in split mode.
//
// Use splitlevel < 0 instead of splitlevel=0 when the class
// has a custom Streamer
//
// Note: if the split level is set to the default (99), TTree::Branch will
// not issue a warning if the class can not be split.
return BronchExec(name, classname, addr, kTRUE, bufsize, splitlevel);
}
//______________________________________________________________________________
TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, Bool_t isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
gTree = this;
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("Bronch", "Cannot find class:%s", classname);
return 0;
}
//if splitlevel <= 0 and class has a custom Streamer, we must create
//a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
//with the custom Streamer. The penalty is that one cannot process
//this Tree without the class library containing the class.
//The following convention is used for the RootFlag
// #pragma link C++ class TExMap; rootflag = 0
// #pragma link C++ class TList-; rootflag = 1
// #pragma link C++ class TArray!; rootflag = 2
// #pragma link C++ class TArrayC-!; rootflag = 3
// #pragma link C++ class TBits+; rootflag = 4
// #pragma link C++ class Txxxx+!; rootflag = 6
char* objptr = 0;
if (!isptrptr) {
objptr = (char*)addr;
} else if (addr) {
objptr = *((char**) addr);
}
if (cl == TClonesArray::Class()) {
TClonesArray* clones = (TClonesArray*) objptr;
if (!clones) {
Error("Bronch", "Pointer to TClonesArray is null");
return 0;
}
if (!clones->GetClass()) {
Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
return 0;
}
void* classinfo = clones->GetClass()->GetClassInfo();
if (!classinfo) {
Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
return 0;
}
int rootflag = gCint->ClassInfo_RootFlag(classinfo);
if (splitlevel > 0) {
if (rootflag & 1)
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
} else {
if (rootflag & 1) clones->BypassStreamer(kFALSE);
TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,isptrptr);
fBranches.Add(branch);
return branch;
}
}
if (cl->GetCollectionProxy()) {
TVirtualCollectionProxy* collProxy = cl->GetCollectionProxy();
//if (!collProxy) {
// Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
//}
TClass* inklass = collProxy->GetValueClass();
if (!inklass && (collProxy->GetType() == 0)) {
Error("Bronch", "%s with no class defined in branch: %s", classname, name);
return 0;
}
if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == 0)) {
Int_t stl = -TClassEdit::IsSTLCont(cl->GetName(), 0);
if ((stl != TClassEdit::kMap) && (stl != TClassEdit::kMultiMap)) {
void *classinfo = inklass->GetClassInfo();
if (!classinfo) {
Error("Bronch", "Container with no dictionary defined in branch: %s", name);
return 0;
}
if (gCint->ClassInfo_RootFlag(classinfo) & 1) {
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
}
}
}
//-------------------------------------------------------------------------
// If the splitting switch is enabled, the split level is big enough and
// the collection contains pointers we can split it
//-------------------------------------------------------------------------
TBranch *branch;
if( splitlevel > 100 && collProxy->HasPointers() )
branch = new TBranchSTL( this, name, collProxy, bufsize, splitlevel );
else
branch = new TBranchElement(this, name, collProxy, bufsize, splitlevel);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
Bool_t hasCustomStreamer = kFALSE;
if (!cl->GetClassInfo() && !cl->GetCollectionProxy()) {
Error("Bronch", "Cannot find dictionary for class: %s", classname);
return 0;
}
if (!cl->GetCollectionProxy() && (gCint->ClassInfo_RootFlag(cl->GetClassInfo()) & 1)) {
// Not an STL container and the linkdef file had a "-" after the class name.
hasCustomStreamer = kTRUE;
}
if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->InheritsFrom(TObject::Class()))) {
TBranchObject* branch = new TBranchObject(this, name, classname, addr, bufsize, 0, isptrptr);
fBranches.Add(branch);
return branch;
}
if (cl == TClonesArray::Class()) {
// Special case of TClonesArray.
// No dummy object is created.
// The streamer info is not rebuilt unoptimized.
// No dummy top-level branch is created.
// No splitting is attempted.
TBranchElement* branch = new TBranchElement(this, name, (TClonesArray*) objptr, bufsize, splitlevel%100);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
//
// If we are not given an object to use as an i/o buffer
// then create a temporary one which we will delete just
// before returning.
//
Bool_t delobj = kFALSE;
if (!objptr) {
objptr = (char*) cl->New();
delobj = kTRUE;
}
//
// Avoid splitting unsplittable classes.
//
if ((splitlevel > 0) && !cl->CanSplit()) {
if (splitlevel != 99) {
Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
}
splitlevel = 0;
}
//
// Make sure the streamer info is built and fetch it.
//
// If we are splitting, then make sure the streamer info
// is built unoptimized (data members are not combined).
//
TStreamerInfo* sinfo = BuildStreamerInfo(cl, objptr, splitlevel==0);
//
// Do we have a final dot in our name?
//
// Note: The branch constructor which takes a folder as input
// creates top-level branch names with dots in them to
// indicate the folder heirarchy.
char* dot = (char*) strchr(name, '.');
Int_t nch = strlen(name);
Bool_t dotlast = kFALSE;
if (nch && (name[nch-1] == '.')) {
dotlast = kTRUE;
}
//
// Create a dummy top level branch object.
//
Int_t id = -1;
if (splitlevel > 0) {
id = -2;
}
TBranchElement* branch = new TBranchElement(this, name, sinfo, id, objptr, bufsize, splitlevel);
fBranches.Add(branch);
//
// Do splitting, if requested.
//
if (splitlevel%100 > 0) {
// Loop on all public data members of the class and its base classes and create branches for each one.
TObjArray* blist = branch->GetListOfBranches();
TIter next(sinfo->GetElements());
TStreamerElement* element = 0;
TString bname;
for (id = 0; (element = (TStreamerElement*) next()); ++id) {
if (element->IsA() == TStreamerArtificial::Class()) {
continue;
}
if (element->TestBit(TStreamerElement::kRepeat)) {
continue;
}
char* pointer = (char*) (objptr + element->GetOffset());
// FIXME: This is not good enough, an STL container can be
// a base, and the test will fail.
// See TBranchElement::InitializeOffsets() for the
// correct test.
Bool_t isBase = (element->IsA() == TStreamerBase::Class());
if (isBase) {
TClass* clbase = element->GetClassPointer();
if ((clbase == TObject::Class()) && cl->CanIgnoreTObjectStreamer()) {
// Note: TStreamerInfo::Compile() leaves this element
// out of the compiled info, although it does
// exists in the non-compiled info. We must
// account for the fact that this element is
// missing in the compiled streamer info by
// making sure that we do not consume an id
// number for it.
// FIXME: The test that TStreamerInfo::Compile() uses
// is element->GetType() < 0, so that is what
// we should do as well.
--id;
continue;
}
}
if (dot) {
if (dotlast) {
bname.Form("%s%s", name, element->GetFullName());
} else {
// FIXME: We are in the case where we have a top-level
// branch name that was created by the branch
// constructor which takes a folder as input.
// The internal dots in the name are in place of
// of the original slashes and represent the
// folder heirarchy.
if (isBase) {
// FIXME: This is very strange, this is the only case where
// we create a branch for a base class that does
// not have the base class name in the branch name.
// FIXME: This is also quite bad since classes with two
// or more base classes end up with sub-branches
// that have the same name.
bname = name;
} else {
bname.Form("%s.%s", name, element->GetFullName());
}
}
} else {
// Note: For a base class element, this results in the branchname
// being the name of the base class.
bname.Form("%s", element->GetFullName());
}
if( splitlevel > 100 && element->GetClass() &&
element->GetClass()->GetCollectionProxy() &&
element->GetClass()->GetCollectionProxy()->HasPointers() )
{
TBranchSTL* brSTL = new TBranchSTL( branch, bname, element->GetClass()->GetCollectionProxy(), bufsize, splitlevel-1, sinfo, id );
blist->Add(brSTL);
}
else
{
TBranchElement* bre = new TBranchElement(branch, bname, sinfo, id, pointer, bufsize, splitlevel - 1);
bre->SetParentClass(cl);
blist->Add(bre);
}
}
}
//
// Setup our offsets into the user's i/o buffer.
//
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
if (delobj) {
cl->Destructor(objptr);
objptr = 0;
}
return branch;
}
//______________________________________________________________________________
void TTree::Browse(TBrowser* b)
{
// Browse content of the TTree.
fBranches.Browse(b);
if (fUserInfo) {
if (strcmp("TList",fUserInfo->GetName())==0) {
fUserInfo->SetName("UserInfo");
b->Add(fUserInfo);
fUserInfo->SetName("TList");
} else {
b->Add(fUserInfo);
}
}
}
//______________________________________________________________________________
Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
{
// Build a Tree Index (default is TTreeIndex).
// See a description of the parameters and functionality in
// TTreeIndex::TTreeIndex().
//
// The return value is the number of entries in the Index (< 0 indicates failure).
//
// A TTreeIndex object pointed by fTreeIndex is created.
// This object will be automatically deleted by the TTree destructor.
// See also comments in TTree::SetTreeIndex().
fTreeIndex = GetPlayer()->BuildIndex(this, majorname, minorname);
if (fTreeIndex->IsZombie()) {
delete fTreeIndex;
fTreeIndex = 0;
return 0;
}
return fTreeIndex->GetN();
}
//______________________________________________________________________________
TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, Bool_t canOptimize /* = kTRUE */ )
{
// Build StreamerInfo for class cl.
// pointer is an optional argument that may contain a pointer to an object of cl.
if (!cl) {
return 0;
}
cl->BuildRealData(pointer);
TStreamerInfo* sinfo = (TStreamerInfo*)cl->GetStreamerInfo(cl->GetClassVersion());
if (!canOptimize && (!sinfo->IsCompiled() || sinfo->IsOptimized()) ) {
// Streamer info has not yet been compiled.
//
// Optimizing does not work with splitting.
sinfo->SetBit(TVirtualStreamerInfo::kCannotOptimize);
sinfo->Compile();
}
// Create StreamerInfo for all base classes.
TBaseClass* base = 0;
TIter nextb(cl->GetListOfBases());
while((base = (TBaseClass*) nextb())) {
if (base->IsSTLContainer()) {
continue;
}
TClass* clm = TClass::GetClass(base->GetName());
BuildStreamerInfo(clm, pointer, canOptimize);
}
if (fDirectory) {
sinfo->ForceWriteInfo(fDirectory->GetFile());
}
return sinfo;
}
//______________________________________________________________________________
TFile* TTree::ChangeFile(TFile* file)
{
// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
// Create a new file. If the original file is named "myfile.root",
// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
//
// Returns a pointer to the new file.
//
// Currently, the automatic change of file is restricted
// to the case where the tree is in the top level directory.
// The file should not contain sub-directories.
//
// Before switching to a new file, the tree header is written
// to the current file, then the current file is closed.
//
// To process the multiple files created by ChangeFile, one must use
// a TChain.
//
// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
// By default a Root session starts with fFileNumber=0. One can set
// fFileNumber to a different value via TTree::SetFileNumber.
// In case a file named "_N" already exists, the function will try
// a file named "__N", then "___N", etc.
//
// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
// The default value of fgMaxTreeSize is 100 Gigabytes.
//
// If the current file contains other objects like TH1 and TTree,
// these objects are automatically moved to the new file.
//
// IMPORTANT NOTE:
// Be careful when writing the final Tree header to the file!
// Don't do:
// TFile *file = new TFile("myfile.root","recreate");
// TTree *T = new TTree("T","title");
// T->Fill(); //loop
// file->Write();
// file->Close();
// but do the following:
// TFile *file = new TFile("myfile.root","recreate");
// TTree *T = new TTree("T","title");
// T->Fill(); //loop
// file = T->GetCurrentFile(); //to get the pointer to the current file
// file->Write();
// file->Close();
file->cd();
Write();
Reset();
char* fname = new char[2000];
++fFileNumber;
char uscore[10];
for (Int_t i = 0; i < 10; ++i) {
uscore[i] = 0;
}
Int_t nus = 0;
// Try to find a suitable file name that does not already exist.
while (nus < 10) {
uscore[nus] = '_';
fname[0] = 0;
strcpy(fname, file->GetName());
if (fFileNumber > 1) {
char* cunder = strrchr(fname, '_');
if (cunder) {
sprintf(cunder, "%s%d", uscore, fFileNumber);
const char* cdot = strrchr(file->GetName(), '.');
if (cdot) {
strcat(fname, cdot);
}
} else {
char fcount[10];
sprintf(fcount, "%s%d", uscore, fFileNumber);
strcat(fname, fcount);
}
} else {
char* cdot = strrchr(fname, '.');
if (cdot) {
sprintf(cdot, "%s%d", uscore, fFileNumber);
strcat(fname, strrchr(file->GetName(), '.'));
} else {
char fcount[10];
sprintf(fcount, "%s%d", uscore, fFileNumber);
strcat(fname, fcount);
}
}
if (gSystem->AccessPathName(fname)) {
break;
}
++nus;
Warning("ChangeFile", "file %s already exist, trying with %d underscores", fname, nus+1);
}
Int_t compress = file->GetCompressionLevel();
TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
Printf("Fill: Switching to new file: %s", fname);
// The current directory may contain histograms and trees.
// These objects must be moved to the new file.
TBranch* branch = 0;
TObject* obj = 0;
while ((obj = file->GetList()->First())) {
file->Remove(obj);
// Histogram: just change the directory.
if (obj->InheritsFrom("TH1")) {
gROOT->ProcessLine(Form("((%s*)0x%lx)->SetDirectory((TDirectory*)0x%lx);", obj->ClassName(), (Long_t) obj, (Long_t) newfile));
continue;
}
// Tree: must save all trees in the old file, reset them.
if (obj->InheritsFrom(TTree::Class())) {
TTree* t = (TTree*) obj;
if (t != this) {
t->AutoSave();
t->Reset();
t->fFileNumber = fFileNumber;
}
t->SetDirectory(newfile);
TIter nextb(t->GetListOfBranches());
while ((branch = (TBranch*)nextb())) {
branch->SetFile(newfile);
}
if (t->GetBranchRef()) {
t->GetBranchRef()->SetFile(newfile);
}
continue;
}
// Not a TH1 or a TTree, move object to new file.
newfile->Append(obj);
file->Remove(obj);
}
delete file;
file = 0;
delete[] fname;
fname = 0;
return newfile;
}
//______________________________________________________________________________
Int_t TTree::CheckBranchAddressType(TBranch* branch, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
// Check whether or not the address described by the last 3 parameters
// matches the content of the branch. If a Data Model Evolution conversion
// is involved, reset the fInfo of the branch.
// The return values are:
// kMissingBranch (-5) : Missing branch
// kInternalError (-4) : Internal error (could not find the type corresponding to a data type number
// kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
// kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
// kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
// kMatch (0) : perfect match
// kMatchConversion (1) : match with (I/O) conversion
// kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
// kMakeClass (3) : MakeClass mode so we can not check.
// kVoidPtr (4) : void* passed so no check was made.
// kNoCheck (5) : Underlying TBranch not yet available so no check was made.
if (GetMakeClass()) {
// If we are in MakeClass mode so we do not really use classes.
return kMakeClass;
}
// Let's determine what we need!
TClass* expectedClass = 0;
EDataType expectedType = kOther_t;
TStreamerInfo* sinfo = 0;
if (branch->InheritsFrom(TBranchObject::Class())) {
TLeafObject* lobj = (TLeafObject*) branch->GetListOfLeaves()->At(0);
expectedClass = lobj->GetClass();
} else if (branch->InheritsFrom(TBranchElement::Class())) {
TBranchElement* branchEl = (TBranchElement*) branch;
Int_t type = branchEl->GetStreamerType();
sinfo = branchEl->GetInfo();
if ((type == -1) || (branchEl->GetID() == -1)) {
expectedClass = TClass::GetClass( branchEl->GetClassName() );
// expectedClass = branchEl->GetInfo()->GetClass();
} else {
// Case of an object data member. Here we allow for the
// variable name to be ommitted. Eg, for Event.root with split
// level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()")
TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()];
if (element) {
expectedClass = element->GetClassPointer();
if (!expectedClass) {
TDataType* data = gROOT->GetType(element->GetTypeNameBasic());
if (!data) {
Error("CheckBranchAddress", "Did not find the type number for %s", element->GetTypeNameBasic());
return kInternalError;
} else {
expectedType = (EDataType) data->GetType();
}
}
} else {
Error("CheckBranchAddress", "Did not find the type for %s",branchEl->GetName());
}
}
if (ptrClass && (branch->GetMother() == branch)) {
// Top Level branch
if (!isptr) {
Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
}
}
} else {
TLeaf* l = (TLeaf*) branch->GetListOfLeaves()->At(0);
if (l) {
expectedType = (EDataType) gROOT->GetType(l->GetTypeName())->GetType();
}
}
if (expectedType == kFloat16_t) {
expectedType = kFloat_t;
}
if (expectedType == kDouble32_t) {
expectedType = kDouble_t;
}
if (datatype == kFloat16_t) {
datatype = kFloat_t;
}
if (datatype == kDouble32_t) {
datatype = kDouble_t;
}
//---------------------------------------------------------------------------
// Deal with the class renaming
//---------------------------------------------------------------------------
if( expectedClass && ptrClass &&
expectedClass != ptrClass &&
branch->InheritsFrom( TBranchElement::Class() ) &&
ptrClass->GetSchemaRules() &&
ptrClass->GetSchemaRules()->HasRuleWithSourceClass(expectedClass->GetName() ) ) {
TBranchElement* bEl = (TBranchElement*)branch;
if( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
!ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" by the branch: %s", ptrClass->GetName(), bEl->GetClassName(), branch->GetName());
return kClassMismatch;
}
else {
bEl->SetTargetClassName( ptrClass->GetName() );
return kMatchConversion;
}
} else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
branch->InheritsFrom( TBranchElement::Class() ) &&
expectedClass->GetCollectionProxy()->GetValueClass() &&
ptrClass->GetCollectionProxy()->GetValueClass() )
{
// In case of collection, we know how to convert them, if we know how to convert their content.
// NOTE: we need to extend this to std::pair ...
TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
if (inmemValueClass->GetSchemaRules() &&
inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
{
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClassName( ptrClass->GetName() );
return kMatchConversionCollection;
}
}
Error("SetBranchAddress", "The pointer type given (%s) does not correspond to the class needed (%s) by the branch: %s", ptrClass->GetName(), expectedClass->GetName(), branch->GetName());
return kClassMismatch;
} else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
if (datatype != kChar_t) {
// For backward compatibility we assume that (char*) was just a cast and/or a generic address
Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s", TDataType::GetTypeName(datatype), datatype, TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
return kMismatch;
}
}
if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
Error("SetBranchAddress", "The class requested (%s) for the branch \"%s\" refer to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
return kMissingCompiledCollectionProxy;
}
return kMatch;
}
//______________________________________________________________________________
TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
// Create a clone of this tree and copy nentries.
//
// By default copy all entries.
// Note that only active branches are copied.
// The compression level of the cloned tree is set to the destination file's
// compression level.
//
// IMPORTANT: The cloned tree stays connected with this tree until this tree
// is deleted. In particular, any changes in branch addresses
// in this tree are forwarded to the clone trees, unless a branch
// in a clone tree has had its address changed, in which case
// that change stays in effect. When this tree is deleted, all the
// addresses of the cloned tree are reset to their default values.
//
// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
// raw bytes on disk).
//
// When 'fast' is specified, 'option' can also contains a
// sorting order for the baskets in the output file.
//
// There are currently 3 supported sorting order:
// SortBasketsByOffset (the default)
// SortBasketsByBranch
// SortBasketsByEntry
//
// When using SortBasketsByOffset the baskets are written in
// the output file in the same order as in the original file
// (i.e. the basket are sorted on their offset in the original
// file; Usually this also means that the baskets are sorted
// on the index/number of the _last_ entry they contain)
//
// When using SortBasketsByBranch all the baskets of each
// individual branches are stored contiguously. This tends to
// optimize reading speed when reading a small number (1->5) of
// branches, since all their baskets will be clustered together
// instead of being spread across the file. However it might
// decrease the performance when reading more branches (or the full
// entry).
//
// When using SortBasketsByEntry the baskets with the lowest
// starting entry are written first. (i.e. the baskets are
// sorted on the index/number of the first entry they contain).
// This means that on the file the baskets will be in the order
// in which they will be needed when reading the whole tree
// sequentially.
//
// For examples of CloneTree, see tutorials:
//
// -- copytree
//
// A macro to copy a subset of a TTree to a new TTree.
//
// The input file has been generated by the program in $ROOTSYS/test/Event
// with: Event 1000 1 1 1
//
// -- copytree2
//
// A macro to copy a subset of a TTree to a new TTree.
//
// One branch of the new Tree is written to a separate file.
//
// The input file has been generated by the program in $ROOTSYS/test/Event
// with: Event 1000 1 1 1
//
// Options
Bool_t fastClone = kFALSE;
TString opt = option;
opt.ToLower();
if (opt.Contains("fast")) {
fastClone = kTRUE;
}
// If we are a chain, switch to the first tree.
if ((fEntries > 0) && (LoadTree(0) < 0)) {
// FIXME: We need an error message here.
return 0;
}
// Note: For a tree we get the this pointer, for
// a chain we get the chain's current tree.
TTree* thistree = GetTree();
// Note: For a chain, the returned clone will be
// a clone of the chain's first tree.
TTree* newtree = (TTree*) thistree->Clone();
if (!newtree) {
return 0;
}
// The clone should not delete any objects allocated by SetAddress().
TObjArray* branches = newtree->GetListOfBranches();
Int_t nb = branches->GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
}
// Add the new tree to the list of clones so that
// we can later inform it of changes to branch addresses.
thistree->AddClone(newtree);
newtree->Reset();
TDirectory* ndir = newtree->GetDirectory();
TFile* nfile = 0;
if (ndir) {
nfile = ndir->GetFile();
}
Int_t newcomp = -1;
if (nfile) {
newcomp = nfile->GetCompressionLevel();
}
//
// Delete non-active branches from the clone.
//
// Note: If we are a chain, this does nothing
// since chains have no leaves.
TObjArray* leaves = newtree->GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
if (!leaf) {
continue;
}
TBranch* branch = leaf->GetBranch();
if (branch && (newcomp > -1)) {
branch->SetCompressionLevel(newcomp);
}
if (!branch || !branch->TestBit(kDoNotProcess)) {
continue;
}
// TObjArray* branches = newtree->GetListOfBranches();
// Int_t nb = branches->GetEntriesFast();
for (Long64_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br == branch) {
branches->RemoveAt(i);
delete br;
br = 0;
branches->Compress();
break;
}
TObjArray* lb = br->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; ++j) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!b1) {
continue;
}
if (b1 == branch) {
lb->RemoveAt(j);
delete b1;
b1 = 0;
lb->Compress();
break;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; ++k) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!b2) {
continue;
}
if (b2 == branch) {
lb1->RemoveAt(k);
delete b2;
b2 = 0;
lb1->Compress();
break;
}
}
}
}
}
leaves->Compress();
// Copy MakeClass status.
newtree->SetMakeClass(fMakeClass);
// Copy branch addresses.
CopyAddresses(newtree);
//
// Copy entries if requested.
//
if (nentries != 0) {
if (fastClone && (nentries < 0)) {
if ( newtree->CopyEntries( this, -1, option ) < 0 ) {
// There was a problem!
Error("Merge", "TTree has not been cloned\n");
delete newtree;
newtree = 0;
return 0;
}
} else {
newtree->CopyEntries( this, nentries, option );
}
}
return newtree;
}
//______________________________________________________________________________
void TTree::CopyAddresses(TTree* tree, Bool_t undo)
{
// Set branch addresses of passed tree equal to ours.
// If undo is true, reset the branch address instead of copying them.
// This insures 'separation' of a cloned tree from its original
// Copy branch addresses starting from branches.
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
TBranch* br = tree->GetBranch(branch->GetName());
tree->ResetBranchAddress(br);
} else {
char* addr = branch->GetAddress();
if (!addr) {
if (branch->IsA() == TBranch::Class()) {
// If the branch was created using a leaflist, the branch itself may not have
// an address but the leat might already do.
TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
if (!firstleaf || firstleaf->GetValuePointer()) {
// Either there is no leaf (and thus no point in copying the address)
// or the leaf has an address but we can not copy it via the branche
// this will be copied via the the next loop (over the leaf).
continue;
}
}
// Note: This may cause an object to be allocated.
branch->SetAddress(0);
addr = branch->GetAddress();
}
// FIXME: The GetBranch() function is braindead and may
// not find the branch!
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
br->SetAddress(addr);
// The copy does not own any object allocated by SetAddress().
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
}
}
// Copy branch addresses starting from leaves.
TObjArray* tleaves = tree->GetListOfLeaves();
Int_t ntleaves = tleaves->GetEntriesFast();
for (Int_t i = 0; i < ntleaves; ++i) {
TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
TBranch* tbranch = tleaf->GetBranch();
TBranch* branch = GetBranch(tbranch->GetName());
if (!branch) {
continue;
}
TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
if (!leaf) {
continue;
}
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
// Now we know wether the address has been transfered
tree->ResetBranchAddress(tbranch);
} else {
if (!branch->GetAddress() && !leaf->GetValuePointer()) {
// We should attempts to set the address of the branch.
// something like:
//(TBranchElement*)branch->GetMother()->SetAddress(0)
//plus a few more subtilities (see TBranchElement::GetEntry).
//but for now we go the simpliest route:
//
// Note: This may result in the allocation of an object.
branch->GetEntry(0);
}
if (branch->GetAddress()) {
tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
// The copy does not own any object allocated by SetAddress().
// FIXME: We do too much here, br may not be a top-level branch.
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
} else {
tleaf->SetAddress(leaf->GetValuePointer());
}
}
}
if (undo &&
( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
) {
tree->ResetBranchAddresses();
}
}
namespace {
enum EOnIndexError { kDrop, kKeep, kBuild };
static bool R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
{
// Return true if we should continue to handle indices, false otherwise.
bool withIndex = kTRUE;
if ( newtree->GetTreeIndex() ) {
if ( oldtree->GetTree()->GetTreeIndex() == 0 ) {
switch (onIndexError) {
case kDrop:
delete newtree->GetTreeIndex();
newtree->SetTreeIndex(0);
withIndex = kFALSE;
break;
case kKeep:
// Nothing to do really.
break;
case kBuild:
// Build the index then copy it
oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName());
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
// Clean up
delete oldtree->GetTree()->GetTreeIndex();
oldtree->GetTree()->SetTreeIndex(0);
break;
}
} else {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
} else if ( oldtree->GetTree()->GetTreeIndex() != 0 ) {
// We discover the first index in the middle of the chain.
switch (onIndexError) {
case kDrop:
// Nothing to do really.
break;
case kKeep: {
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
break;
}
case kBuild:
if (newtree->GetEntries() == 0) {
// Start an index.
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
} else {
// Build the index so far.
newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName());
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
break;
}
} else if ( onIndexError == kDrop ) {
// There is no index on this or on tree->GetTree(), we know we have to ignore any further
// index
withIndex = kFALSE;
}
return withIndex;
}
}
//______________________________________________________________________________
Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
// Copy nentries from given tree to this tree.
// This routines assumes that the branches that intended to be copied are
// already connected. The typical case is that this tree was created using
// tree->CloneTree(0).
//
// By default copy all entries.
//
// Returns number of bytes copied to this tree.
//
// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
// raw bytes on disk).
//
// When 'fast' is specified, 'option' can also contains a sorting order for the
// baskets in the output file.
//
// There are currently 3 supported sorting order:
// SortBasketsByOffset (the default)
// SortBasketsByBranch
// SortBasketsByEntry
//
// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
//
// If the tree or any of the underlying tree of the chain has an index, that index and any
// index in the subsequent underlying TTree objects will be merged.
//
// There are currently three 'options' to control this merging:
// NoIndex : all the TTreeIndex object are dropped.
// DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
// they are all dropped.
// AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
// BuildIndexOnError : If any of the underlying TTree object do no have a TTreeIndex,
// all TTreeIndex are 'ignored' and the mising piece are rebuilt.
if (!tree) {
return 0;
}
// Options
TString opt = option;
opt.ToLower();
Bool_t fastClone = opt.Contains("fast");
Bool_t withIndex = !opt.Contains("noindex");
EOnIndexError onIndexError;
if (opt.Contains("asisindex")) {
onIndexError = kKeep;
} else if (opt.Contains("buildindex")) {
onIndexError = kBuild;
} else if (opt.Contains("dropindex")) {
onIndexError = kDrop;
} else {
onIndexError = kBuild;
}
Long64_t nbytes = 0;
Long64_t treeEntries = tree->GetEntriesFast();
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
// Quickly copy the basket without decompression and streaming.
Long64_t totbytes = GetTotBytes();
for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
if (tree->LoadTree(i) < 0) {
break;
}
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
if (this->GetDirectory()) {
TFile* file2 = this->GetDirectory()->GetFile();
if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
if (this->GetDirectory() == (TDirectory*) file2) {
this->ChangeFile(file2);
}
}
}
TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
if (cloner.IsValid()) {
this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
cloner.Exec();
} else {
if (i == 0) {
// If the first cloning does not work, something is really wrong
// (since apriori the source and target are exactly the same structure!)
return -1;
} else {
if (cloner.NeedConversion()) {
TTree *localtree = tree->GetTree();
Long64_t tentries = localtree->GetEntries();
for (Long64_t ii = 0; ii < tentries; ii++) {
if (localtree->GetEntry(ii) <= 0) {
break;
}
this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), kTRUE);
}
} else {
Warning("CopyEntries",cloner.GetWarning());
if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
} else {
Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
}
}
}
}
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
nbytes = GetTotBytes() - totbytes;
} else {
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
Int_t treenumber = -1;
for (Long64_t i = 0; i < nentries; i++) {
if (tree->LoadTree(i) < 0) {
break;
}
if (treenumber != tree->GetTreeNumber()) {
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
treenumber = tree->GetTreeNumber();
}
if (tree->GetEntry(i) <= 0) {
break;
}
nbytes += this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
}
return nbytes;
}
//______________________________________________________________________________
TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = 1000000000 */, Long64_t firstentry /* = 0 */)
{
// Copy a tree with selection.
//
// IMPORTANT:
//
// The returned copied tree stays connected with the original tree
// until the original tree is deleted. In particular, any changes
// to the branch addresses in the original tree are also made to
// the copied tree. Any changes made to the branch addresses of the
// copied tree are overridden anytime the original tree changes its
// branch addresses. When the original tree is deleted, all the
// branch addresses of the copied tree are set to zero.
//
// For examples of CopyTree, see the tutorials:
//
// copytree
//
// Example macro to copy a subset of a tree to a new tree.
//
// The input file was generated by running the program in
// $ROOTSYS/test/Event in this way:
//
// ./Event 1000 1 1 1
//
// copytree2
//
// Example macro to copy a subset of a tree to a new tree.
//
// One branch of the new tree is written to a separate file.
//
// The input file was generated by running the program in
// $ROOTSYS/test/Event in this way:
//
// ./Event 1000 1 1 1
//
// copytree3
//
// Example macro to copy a subset of a tree to a new tree.
//
// Only selected entries are copied to the new tree.
// NOTE that only the active branches are copied.
//
GetPlayer();
if (fPlayer) {
return fPlayer->CopyTree(selection, option, nentries, firstentry);
}
return 0;
}
//______________________________________________________________________________
TBasket* TTree::CreateBasket(TBranch* branch)
{
// Create a basket for this tree and given branch.
if (!branch) {
return 0;
}
return new TBasket(branch->GetName(), GetName(), branch);
}
//______________________________________________________________________________
void TTree::Delete(Option_t* option /* = "" */)
{
// Delete this tree from memory or/and disk.
//
// if option == "all" delete Tree object from memory AND from disk
// all baskets on disk are deleted. All keys with same name
// are deleted.
// if option =="" only Tree object in memory is deleted.
TFile *file = GetCurrentFile();
// delete all baskets and header from file
if (file && !strcmp(option,"all")) {
if (!file->IsWritable()) {
Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
return;
}
//find key and import Tree header in memory
TKey *key = fDirectory->GetKey(GetName());
if (!key) return;
TDirectory *dirsav = gDirectory;
file->cd();
//get list of leaves and loop on all the branches baskets
TIter next(GetListOfLeaves());
TLeaf *leaf;
char header[16];
Int_t ntot = 0;
Int_t nbask = 0;
Int_t nbytes,objlen,keylen;
while ((leaf = (TLeaf*)next())) {
TBranch *branch = leaf->GetBranch();
Int_t nbaskets = branch->GetMaxBaskets();
for (Int_t i=0;i<nbaskets;i++) {
Long64_t pos = branch->GetBasketSeek(i);
if (!pos) continue;
TFile *branchFile = branch->GetFile();
if (!branchFile) continue;
branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
if (nbytes <= 0) continue;
branchFile->MakeFree(pos,pos+nbytes-1);
ntot += nbytes;
nbask++;
}
}
// delete Tree header key and all keys with the same name
// A Tree may have been saved many times. Previous cycles are invalid.
while (key) {
ntot += key->GetNbytes();
key->Delete();
delete key;
key = fDirectory->GetKey(GetName());
}
if (dirsav) dirsav->cd();
if (gDebug) printf(" Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
}
if (fDirectory) {
fDirectory->Remove(this);
fDirectory = 0;
ResetBit(kMustCleanup);
}
// Delete object from CINT symbol table so it can not be used anymore.
gCint->DeleteGlobal(this);
// Warning: We have intentional invalidated this object while inside a member function!
delete this;
}
//______________________________________________________________________________
void TTree::DirectoryAutoAdd(TDirectory* dir)
{
// Called by TKey and TObject::Clone to automatically add us to a directory
// when we are read from a file.
if (fDirectory == dir) return;
if (fDirectory) fDirectory->Remove(this);
fDirectory = dir;
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->UpdateFile();
}
if (fBranchRef) {
fBranchRef->UpdateFile();
}
if (fDirectory) fDirectory->Append(this);
}
//______________________________________________________________________________
Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Draw expression varexp for specified entries.
// Returns -1 in case of error or number of selected events in case of success.
//
// This function accepts TCut objects as arguments.
// Useful to use the string operator +
// example:
// ntuple.Draw("x",cut1+cut2+cut3);
//
return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
}
//______________________________________________________________________________
Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Draw expression varexp for specified entries.
// Returns -1 in case of error or number of selected events in case of success.
//
// varexp is an expression of the general form
// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1" versus "e2"
// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
// versus "e2" versus "e3"
// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
// versus "e2" versus "e3" and "e4" mapped on the color number.
// (to create histograms in the 2, 3, and 4 dimesional case, see section "Saving
// the result of Draw to an histogram")
//
// Example:
// varexp = x simplest case: draw a 1-Dim distribution of column named x
// = sqrt(x) : draw distribution of sqrt(x)
// = x*y/z
// = y:sqrt(x) 2-Dim distribution of y versus sqrt(x)
// = px:py:pz:2.5*E produces a 3-d scatter-plot of px vs py ps pz
// and the color number of each marker will be 2.5*E.
// If the color number is negative it is set to 0.
// If the color number is greater than the current number of colors
// it is set to the highest color number.
// The default number of colors is 50.
// see TStyle::SetPalette for setting a new color palette.
//
// Note that the variables e1, e2 or e3 may contain a selection.
// example, if e1= x*(y<0), the value histogrammed will be x if y<0
// and will be 0 otherwise.
//
// The expressions can use all the operations and build-in functions
// supported by TFormula (See TFormula::Analyze), including free
// standing function taking numerical arguments (TMath::Bessel).
// In addition, you can call member functions taking numerical
// arguments. For example:
// - "TMath::BreitWigner(fPx,3,2)"
// - "event.GetHistogram().GetXaxis().GetXmax()"
// Note: You can only pass expression that depend on the TTree's data
// to static functions and you can only call non-static member function
// with 'fixed' parameters.
//
// selection is an expression with a combination of the columns.
// In a selection all the C++ operators are authorized.
// The value corresponding to the selection expression is used as a weight
// to fill the histogram.
// If the expression includes only boolean operations, the result
// is 0 or 1. If the result is 0, the histogram is not filled.
// In general, the expression may be of the form:
// value*(boolean expression)
// if boolean expression is true, the histogram is filled with
// a weight = value.
// Examples:
// selection1 = "x<y && sqrt(z)>3.2"
// selection2 = "(x+y)*(sqrt(z)>3.2)"
// selection1 returns a weigth = 0 or 1
// selection2 returns a weight = x+y if sqrt(z)>3.2
// returns a weight = 0 otherwise.
//
// option is the drawing option.
// - See TH1::Draw for the list of all drawing options.
// - If option COL is specified when varexp has three fields:
// tree.Draw("e1:e2:e3","","col");
// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the color
// table.
// - If option contains the string "goff", no graphics is generated.
//
// nentries is the number of entries to process (default is all)
// first is the first entry to process (default is 0)
//
// This function returns the number of selected entries. It returns -1
// if an error occurs.
//
// Drawing expressions using arrays and array elements
// ===================================================
// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
// or a TClonesArray.
// In a TTree::Draw expression you can now access fMatrix using the following
// syntaxes:
//
// String passed What is used for each entry of the tree
//
// "fMatrix" the 9 elements of fMatrix
// "fMatrix[][]" the 9 elements of fMatrix
// "fMatrix[2][2]" only the elements fMatrix[2][2]
// "fMatrix[1]" the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2]
// "fMatrix[1][]" the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2]
// "fMatrix[][0]" the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0]
//
// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
//
// In summary, if a specific index is not specified for a dimension, TTree::Draw
// will loop through all the indices along this dimension. Leaving off the
// last (right most) dimension of specifying then with the two characters '[]'
// is equivalent. For variable size arrays (and TClonesArray) the range
// of the first dimension is recalculated for each entry of the tree.
//
// TTree::Draw also now properly handling operations involving 2 or more arrays.
//
// Let assume a second matrix fResults[5][2], here are a sample of some
// of the possible combinations, the number of elements they produce and
// the loop used:
//
// expression element(s) Loop
//
// "fMatrix[2][1] - fResults[5][2]" one no loop
// "fMatrix[2][] - fResults[5][2]" three on 2nd dim fMatrix
// "fMatrix[2][] - fResults[5][]" two on both 2nd dimensions
// "fMatrix[][2] - fResults[][1]" three on both 1st dimensions
// "fMatrix[][2] - fResults[][]" six on both 1st and 2nd dimensions of
// fResults
// "fMatrix[][2] - fResults[3][]" two on 1st dim of fMatrix and 2nd of
// fResults (at the same time)
// "fMatrix[][] - fResults[][]" six on 1st dim then on 2nd dim
//
//
// In summary, TTree::Draw loops through all un-specified dimensions. To
// figure out the range of each loop, we match each unspecified dimension
// from left to right (ignoring ALL dimensions for which an index has been
// specified), in the equivalent loop matched dimensions use the same index
// and are restricted to the smallest range (of only the matched dimensions).
// When involving variable arrays, the range can of course be different
// for each entry of the tree.
//
// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
//
// for (Int_t i0; i < min(3,2); i++) {
// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
// }
//
// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
//
// for (Int_t i0; i < min(3,5); i++) {
// for (Int_t i1; i1 < 2; i1++) {
// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
// }
// }
//
// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
//
// for (Int_t i0; i < min(3,5); i++) {
// for (Int_t i1; i1 < min(3,2); i1++) {
// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
// }
// }
//
// Retrieving the result of Draw
// =============================
//
// By default the temporary histogram created is called "htemp", but only in
// the one dimensional Draw("e1") it contains the TTree's data points. For
// a two dimensional Draw, the data is filled into a TGraph which is named
// "Graph". They can be retrieved by calling
// TH1F *htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
//
// For a three and four dimensional Draw the TPloyMarker3D is unnamed, and
// cannot be retrieved.
//
// gPad always contains a TH1 derived object called "htemp" which allows to
// access the axes:
// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
// TH2F *htemp = (TH2F*)gPad->GetPrimitive("htemp"); // empty, but has axes
// TAxis *xaxis = htemp->GetXaxis();
//
// Saving the result of Draw to an histogram
// =========================================
//
// If varexp0 contains >>hnew (following the variable(s) name(s),
// the new histogram created is called hnew and it is kept in the current
// directory (and also the current pad). This works for all dimensions.
// Example:
// tree.Draw("sqrt(x)>>hsqrt","y>0")
// will draw sqrt(x) and save the histogram as "hsqrt" in the current
// directory. To retrieve it do:
// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
//
// The binning information is taken from the environment variables
//
// Hist.Binning.?D.?
//
// In addition, the name of the histogram can be followed by up to 9
// numbers between '(' and ')', where the numbers describe the
// following:
//
// 1 - bins in x-direction
// 2 - lower limit in x-direction
// 3 - upper limit in x-direction
// 4-6 same for y-direction
// 7-9 same for z-direction
//
// When a new binning is used the new value will become the default.
// Values can be skipped.
// Example:
// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
// // plot sqrt(x) between 10 and 20 using 500 bins
// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
// // plot sqrt(x) against sin(y)
// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
//
// By default, the specified histogram is reset.
// To continue to append data to an existing histogram, use "+" in front
// of the histogram name.
// A '+' in front of the histogram name is ignored, when the name is followed by
// binning information as described in the previous paragraph.
// tree.Draw("sqrt(x)>>+hsqrt","y>0")
// will not reset hsqrt, but will continue filling.
// This works for 1-D, 2-D and 3-D histograms.
//
// Accessing collection objects
// ============================
//
// TTree::Draw default's handling of collections is to assume that any
// request on a collection pertain to it content. For example, if fTracks
// is a collection of Track objects, the following:
// tree->Draw("event.fTracks.fPx");
// will plot the value of fPx for each Track objects inside the collection.
// Also
// tree->Draw("event.fTracks.size()");
// would plot the result of the member function Track::size() for each
// Track object inside the collection.
// To access information about the collection itself, TTree::Draw support
// the '@' notation. If a variable which points to a collection is prefixed
// or postfixed with '@', the next part of the expression will pertain to
// the collection object. For example:
// tree->Draw("event.@fTracks.size()");
// will plot the size of the collection refered to by fTracks (i.e the number
// of Track objects).
//
// Drawing 'objects'
// =================
//
// When a class has a member function named AsDouble or AsString, requesting
// to directly draw the object will imply a call to one of the 2 functions.
// If both AsDouble and AsString are present, AsDouble will be used.
// AsString can return either a char*, a std::string or a TString.s
// For example, the following
// tree->Draw("event.myTTimeStamp");
// will draw the same histogram as
// tree->Draw("event.myTTimeStamp.AsDouble()");
// In addition, when the object is a type TString or std::string, TTree::Draw
// will call respectively TString::Data and std::string::c_str()
//
// If the object is a TBits, the histogram will contain the index of the bit
// that are turned on.
//
// Retrieving information about the tree itself.
// ============================================
//
// You can refer to the tree (or chain) containing the data by using the
// string 'This'.
// You can then could any TTree methods. For example:
// tree->Draw("This->GetReadEntry()");
// will display the local entry numbers be read.
// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
// will display the name of the first 'user info' object.
//
// Special functions and variables
// ===============================
//
// Entry$: A TTree::Draw formula can use the special variable Entry$
// to access the entry number being read. For example to draw every
// other entry use:
// tree.Draw("myvar","Entry$%2==0");
//
// Entry$ : return the current entry number (== TTree::GetReadEntry())
// LocalEntry$ : return the current entry number in the current tree of a
// chain (== GetTree()->GetReadEntry())
// Entries$ : return the total number of entries (== TTree::GetEntries())
// Length$ : return the total number of element of this formula for this
// entry (==TTreeFormula::GetNdata())
// Iteration$: return the current iteration over this formula for this
// entry (i.e. varies from 0 to Length$).
//
// Length$(formula): return the total number of element of the formula given as a
// parameter.
// Sum$(formula): return the sum of the value of the elements of the formula given
// as a parameter. For example the mean for all the elements in
// one entry can be calculated with:
// Sum$(formula)/Length$(formula)
// Min$(formula): return the minimun (within one TTree entry) of the value of the
// elements of the formula given as a parameter.
// Max$(formula): return the maximum (within one TTree entry) of the value of the
// elements of the formula given as a parameter.
// MinIf$(formula,condition)
// MaxIf$(formula,condition): return the minimum (maximum) (within one TTree entry)
// of the value of the elements of the formula given as a parameter
// if they match the condition. If not element match the condition, the result is zero. To avoid the
// the result is zero. To avoid the consequent peak a zero, use the
// pattern:
// tree->Draw("MinIf$(formula,condition)","condition");
// which will avoid calculation MinIf$ for the entries that have no match
// for the condition.
//
// Alt$(primary,alternate) : return the value of "primary" if it is available
// for the current iteration otherwise return the value of "alternate".
// For example, with arr1[3] and arr2[2]
// tree->Draw("arr1+Alt$(arr2,0)");
// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
// Or with a variable size array arr3
// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
// As a comparison
// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
// will draw the sum arr3 for the index 0 to 2 only if the
// actual_size_of_arr3 is greater or equal to 3.
// Note that the array in 'primary' is flatened/linearilized thus using
// Alt$ with multi-dimensional arrays of different dimensions in unlikely
// to yield the expected results. To visualize a bit more what elements
// would be matched by TTree::Draw, TTree::Scan can be used:
// tree->Scan("arr1:Alt$(arr2,0)");
// will print on one line the value of arr1 and (arr2,0) that will be
// matched by
// tree->Draw("arr1-Alt$(arr2,0)");
//
// The ternary operator is not directly support in TTree::Draw however, to plot the
// equivalent of 'var2<20 ? -99 : var1', you can use:
// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
//
// Drawing a user function accessing the TTree data directly
// =========================================================
//
// If the formula contains a file name, TTree::MakeProxy will be used
// to load and execute this file. In particular it will draw the
// result of a function with the same name as the file. The function
// will be executed in a context where the name of the branches can
// be used as a C++ variable.
//
// For example draw px using the file hsimple.root (generated by the
// hsimple.C tutorial), we need a file named hsimple.cxx:
//
// double hsimple() {
// return px;
// }
//
// MakeProxy can then be used indirectly via the TTree::Draw interface
// as follow:
// new TFile("hsimple.root")
// ntuple->Draw("hsimple.cxx");
//
// A more complete example is available in the tutorials directory:
// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
// which reimplement the selector found in h1analysis.C
//
// The main features of this facility are:
//
// * on-demand loading of branches
// * ability to use the 'branchname' as if it was a data member
// * protection against array out-of-bound
// * ability to use the branch data as object (when the user code is available)
//
// See TTree::MakeProxy for more details.
//
// Making a Profile histogram
// ==========================
// In case of a 2-Dim expression, one can generate a TProfile histogram
// instead of a TH2F histogram by specyfying option=prof or option=profs.
// The option=prof is automatically selected in case of y:x>>pf
// where pf is an existing TProfile histogram.
//
// Making a 5D plot using GL
// =========================
// If option GL5D is specified together with 5 variables, a 5D plot is drawn
// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
//
// Making a parallel coordinates plot
// ==================================
// In case of a 2-Dim or more expression with the option=para, one can generate
// a parallel coordinates plot. With that option, the number of dimensions is
// arbitrary. Giving more than 4 variables without the option=para or
// option=candle or option=goff will produce an error.
//
// Making a candle sticks chart
// ============================
// In case of a 2-Dim or more expression with the option=candle, one can generate
// a candle sticks chart. With that option, the number of dimensions is
// arbitrary. Giving more than 4 variables without the option=para or
// option=candle or option=goff will produce an error.
//
// Saving the result of Draw to a TEventList or a TEntryList
// =========================================================
// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
// instead of histogramming one variable.
// If varexp0 has the form >>elist , a TEventList object named "elist"
// is created in the current directory. elist will contain the list
// of entry numbers satisfying the current selection.
// If option "entrylist" is used, a TEntryList object is created
// Example:
// tree.Draw(">>yplus","y>0")
// will create a TEventList object named "yplus" in the current directory.
// In an interactive session, one can type (after TTree::Draw)
// yplus.Print("all")
// to print the list of entry numbers in the list.
// tree.Draw(">>yplus", "y>0", "entrylist")
// will create a TEntryList object names "yplus" in the current directory
//
// By default, the specified entry list is reset.
// To continue to append data to an existing list, use "+" in front
// of the list name;
// tree.Draw(">>+yplus","y>0")
// will not reset yplus, but will enter the selected entries at the end
// of the existing list.
//
// Using a TEventList or a TEntryList as Input
// ===========================
// Once a TEventList or a TEntryList object has been generated, it can be used as input
// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
// current event list
// Example1:
// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
// tree->SetEventList(elist);
// tree->Draw("py");
// Example2:
// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
// tree->SetEntryList(elist);
// tree->Draw("py");
// If a TEventList object is used as input, a new TEntryList object is created
// inside the SetEventList function. In case of a TChain, all tree headers are loaded
// for this transformation. This new object is owned by the chain and is deleted
// with it, unless the user extracts it by calling GetEntryList() function.
// See also comments to SetEventList() function of TTree and TChain.
//
// If arrays are used in the selection critera, the entry entered in the
// list are all the entries that have at least one element of the array that
// satisfy the selection.
// Example:
// tree.Draw(">>pyplus","fTracks.fPy>0");
// tree->SetEventList(pyplus);
// tree->Draw("fTracks.fPy");
// will draw the fPy of ALL tracks in event with at least one track with
// a positive fPy.
//
// To select only the elements that did match the original selection
// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
// Example:
// tree.Draw(">>pyplus","fTracks.fPy>0");
// pyplus->SetReapplyCut(kTRUE);
// tree->SetEventList(pyplus);
// tree->Draw("fTracks.fPy");
// will draw the fPy of only the tracks that have a positive fPy.
//
// Note: Use tree->SetEventList(0) if you do not want use the list as input.
//
// How to obtain more info from TTree::Draw
// ========================================
//
// Once TTree::Draw has been called, it is possible to access useful
// information still stored in the TTree object via the following functions:
// -GetSelectedRows() // return the number of entries accepted by the
// //selection expression. In case where no selection
// //was specified, returns the number of entries processed.
// -GetV1() //returns a pointer to the double array of V1
// -GetV2() //returns a pointer to the double array of V2
// -GetV3() //returns a pointer to the double array of V3
// -GetW() //returns a pointer to the double array of Weights
// //where weight equal the result of the selection expression.
// where V1,V2,V3 correspond to the expressions in
// TTree::Draw("V1:V2:V3",selection);
//
// Example:
// Root > ntuple->Draw("py:px","pz>4");
// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
// ntuple->GetV2(), ntuple->GetV1());
// Root > gr->Draw("ap"); //draw graph in current pad
// creates a TGraph object with a number of points corresponding to the
// number of entries selected by the expression "pz>4", the x points of the graph
// being the px values of the Tree and the y points the py values.
//
// Important note: By default TTree::Draw creates the arrays obtained
// with GetV1, GetV2, GetV3, GetW with a length corresponding to the
// parameter fEstimate. By default fEstimate=1000000 and can be modified
// via TTree::SetEstimate. A possible recipee is to do
// tree->SetEstimate(tree->GetEntries());
// You must call SetEstimate if the expected number of selected rows
// is greater than 1000000.
//
// You can use the option "goff" to turn off the graphics output
// of TTree::Draw in the above example.
//
// Automatic interface to TTree::Draw via the TTreeViewer
// ======================================================
//
// A complete graphical interface to this function is implemented
// in the class TTreeViewer.
// To start the TTreeViewer, three possibilities:
// - select TTree context menu item "StartViewer"
// - type the command "TTreeViewer TV(treeName)"
// - execute statement "tree->StartViewer();"
//
GetPlayer();
if (fPlayer)
return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
return -1;
}
//______________________________________________________________________________
void TTree::DropBaskets()
{
// Remove some baskets from memory.
TBranch* branch = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
branch = (TBranch*) fBranches.UncheckedAt(i);
branch->DropBaskets("all");
}
}
//______________________________________________________________________________
void TTree::DropBuffers(Int_t)
{
// Drop branch buffers to accomodate nbytes below MaxVirtualsize.
// Be careful not to remove current read/write buffers.
Int_t ndrop = 0;
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; ++i) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
Int_t nbaskets = branch->GetListOfBaskets()->GetEntriesFast();
for (Int_t j = 0; j < nbaskets - 1; ++j) {
if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
continue;
}
TBasket* basket = branch->GetBasket(j);
ndrop += basket->DropBuffers();
if (fTotalBuffers < fMaxVirtualSize) {
return;
}
}
}
}
//______________________________________________________________________________
Int_t TTree::Fill()
{
// Fill all branches.
//
// This function loops on all the branches of this tree. For
// each branch, it copies to the branch buffer (basket) the current
// values of the leaves data types. If a leaf is a simple data type,
// a simple conversion to a machine independent format has to be done.
//
// This machine independent version of the data is copied into a
// basket (each branch has its own basket). When a basket is full
// (32k worth of data by default), it is then optionally compressed
// and written to disk (this operation is also called comitting or
// 'flushing' the basket). The committed baskets are then
// immediately removed from memory.
//
// The function returns the number of bytes committed to the
// individual branches.
//
// If a write error occurs, the number of bytes returned is -1.
//
// If no data are written, because, e.g., the branch is disabled,
// the number of bytes returned is 0.
//
// The baskets are flushed and the Tree header saved at regular intervals
// ---------------------------------------------------------------------
// At regular intervals, when the amount of data written so far is
// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
// This makes future reading faster as it guarantees that baskets belonging to nearby
// entries will be on the same disk region.
// When the first call to flush the baskets happen, we also take this opportunity
// to optimize the baskets buffers.
// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
// In this case we also write the Tree header. This makes the Tree recoverable up to this point
// in case the program writing the Tree crashes.
// The decisions to FlushBaskets and Auto Save can be made based either on the number
// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
// written (fAutoFlush and fAutoSave positive).
// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
// base on the number of events written instead of the number of bytes written.
//
// Note that calling FlushBaskets too often increases the IO time.
// Note that calling AutoSave too often increases the IO time and also the file size.
Int_t nbytes = 0;
Int_t nerror = 0;
Int_t nb = fBranches.GetEntriesFast();
if (nb == 1) {
// Case of one single super branch. Automatically update
// all the branch addresses if a new object was created.
TBranch* branch = (TBranch*) fBranches.UncheckedAt(0);
branch->UpdateAddress();
}
if (fBranchRef) {
fBranchRef->Clear();
}
for (Int_t i = 0; i < nb; ++i) {
// Loop over all branches, filling and accumulating bytes written and error counts.
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
if (branch->TestBit(kDoNotProcess)) {
continue;
}
Int_t nwrite = branch->Fill();
if (nwrite < 0) {
if (nerror < 2) {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
" This error is symptomatic of a Tree created as a memory-resident Tree\n"
" Instead of doing:\n"
" TTree *T = new TTree(...)\n"
" TFile *f = new TFile(...)\n"
" you should do:\n"
" TFile *f = new TFile(...)\n"
" TTree *T = new TTree(...)",
GetName(), branch->GetName(), nwrite,fEntries+1);
} else {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,fEntries+1);
}
++nerror;
} else {
nbytes += nwrite;
}
}
if (fBranchRef) {
fBranchRef->Fill();
}
++fEntries;
if (fEntries > fMaxEntries) {
KeepCircular();
}
if (gDebug > 0) printf("TTree::Fill - A: %d %lld %lld %lld %lld %lld %lld \n",
nbytes, fEntries, fAutoFlush,fAutoSave,fZipBytes,fFlushedBytes,fSavedBytes);
if (fAutoFlush != 0 || fAutoSave != 0) {
// Is it time to flush or autosave baskets?
if (fFlushedBytes == 0) {
// Decision can be based initially either on the number of bytes
// or the number of entries written.
if ((fAutoFlush<0 && fZipBytes > -fAutoFlush) ||
(fAutoSave <0 && fZipBytes > -fAutoSave ) ||
(fAutoFlush>0 && fEntries%TMath::Max((Long64_t)1,fAutoFlush) == 0) ||
(fAutoSave >0 && fEntries%TMath::Max((Long64_t)1,fAutoSave) == 0) ) {
//we take the opportunity to Optimizebaskets at this point (it calls FlushBaskets)
OptimizeBaskets(fTotBytes,1,"");
if (gDebug > 0) printf("OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",fEntries,fZipBytes,fFlushedBytes);
fFlushedBytes = fZipBytes;
fAutoFlush = fEntries; // Use test on entries rather than bytes
// subsequently in run
if (fAutoSave < 0) {
// Set fAutoSave to the largest integer multiple of
// fAutoFlush events such that fAutoSave*fFlushedBytes
// < (minus the input value of fAutoSave)
fAutoSave = TMath::Max( fAutoFlush, fEntries*((-fAutoSave/fZipBytes)/fEntries));
} else if(fAutoSave > 0) {
fAutoSave = fEntries*(fAutoSave/fEntries);
}
if (fAutoSave!=0 && fEntries >= fAutoSave) AutoSave(); // FlushBaskets not called in AutoSave
if (gDebug > 0) printf("TTree::Fill: First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
}
} else if (fEntries > 1 && fEntries%fAutoFlush == 0) {
if (fEntries%fAutoSave == 0) {
//We are at an AutoSave point. AutoSave flushes baskets and saves the Tree header
AutoSave("flushbaskets");
if (gDebug > 0) printf("AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n",fEntries,fZipBytes,fSavedBytes);
} else {
//We only FlushBaskets
FlushBaskets();
if (gDebug > 0) printf("FlushBasket called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",fEntries,fZipBytes,fFlushedBytes);
}
fFlushedBytes = fZipBytes;
}
}
// Check that output file is still below the maximum size.
// If above, close the current file and continue on a new file.
// Currently, the automatic change of file is restricted
// to the case where the tree is in the top level directory.
if (!fDirectory) {
return nbytes;
}
TFile* file = fDirectory->GetFile();
if (file && (file->GetEND() > fgMaxTreeSize)) {
if (fDirectory == (TDirectory*) file) {
ChangeFile(file);
}
}
if (nerror) {
return -1;
}
return nbytes;
}
//______________________________________________________________________________
static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
// Search in the array for a branch matching the branch name,
// with the branch possibly expressed as a 'full' path name (with dots).
if (list==0 || branchname == 0 || branchname[0] == '\0') return 0;
Int_t nbranches = list->GetEntries();
UInt_t brlen = strlen(branchname);
for(Int_t index = 0; index < nbranches; ++index) {
TBranch *where = (TBranch*)list->UncheckedAt(index);
const char *name = where->GetName();
UInt_t len = strlen(name);
if (name[len-1]==']') {
const char *dim = strchr(name,'[');
if (dim) {
len = dim - name;
}
}
if (brlen == len && strncmp(branchname,name,len)==0) {
return where;
}
TBranch *next = 0;
if ((brlen >= len) && (branchname[len] == '.')
&& strncmp(name, branchname, len) == 0) {
// The prefix subbranch name match the branch name.
next = where->FindBranch(branchname);
if (!next) {
next = where->FindBranch(branchname+len+1);
}
if (next) return next;
}
const char *dot = strchr((char*)branchname,'.');
if (dot) {
if (len==(size_t)(dot-branchname) &&
strncmp(branchname,name,dot-branchname)==0 ) {
return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
}
}
}
return 0;
}
//______________________________________________________________________________
TBranch* TTree::FindBranch(const char* branchname)
{
// Return the branch that correspond to the path 'branchname', which can
// include the name of the tree or the ommited name of the parent branches.
// In case of ambiguity, returns the first match.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kFindBranch & fFriendLockStatus) {
return 0;
}
TBranch* branch = 0;
// If the first part of the name match the TTree name, look for the right part in the
// list of branches.
// This will allow the branchname to be preceded by
// the name of this tree.
if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
if (branch) return branch;
}
// If we did not find it, let's try to find the full name in the list of branches.
branch = R__FindBranchHelper(GetListOfBranches(), branchname);
if (branch) return branch;
// If we still did not find, let's try to find it within each branch assuming it does not the branch name.
TIter next(GetListOfBranches());
while ((branch = (TBranch*) next())) {
TBranch* nestedbranch = branch->FindBranch(branchname);
if (nestedbranch) {
return nestedbranch;
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindBranch);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
const char *subbranch = strstr(branchname, fe->GetName());
if (subbranch != branchname) {
subbranch = 0;
}
if (subbranch) {
subbranch += strlen(fe->GetName());
if (*subbranch != '.') {
subbranch = 0;
} else {
++subbranch;
}
}
std::ostringstream name;
if (subbranch) {
name << t->GetName() << "." << subbranch;
} else {
name << branchname;
}
branch = t->FindBranch(name.str().c_str());
if (branch) {
return branch;
}
}
return 0;
}
//______________________________________________________________________________
TLeaf* TTree::FindLeaf(const char* searchname)
{
// FIXME: Describe this function.
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kFindLeaf & fFriendLockStatus) {
return 0;
}
// This will allow the branchname to be preceded by
// the name of this tree.
char* subsearchname = (char*) strstr(searchname, GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
if (subsearchname[0]==0) {
subsearchname = 0;
}
}
}
TString leafname;
TString leaftitle;
TString longname;
TString longtitle;
// For leaves we allow for one level up to be prefixed to the name.
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leafname = leaf->GetName();
Ssiz_t dim = leafname.First('[');
if (dim >= 0) leafname.Remove(dim);
if (leafname == searchname) {
return leaf;
}
if (subsearchname && leafname == subsearchname) {
return leaf;
}
// The TLeafElement contains the branch name
// in its name, let's use the title.
leaftitle = leaf->GetTitle();
dim = leaftitle.First('[');
if (dim >= 0) leaftitle.Remove(dim);
if (leaftitle == searchname) {
return leaf;
}
if (subsearchname && leaftitle == subsearchname) {
return leaf;
}
TBranch* branch = leaf->GetBranch();
if (branch) {
longname.Form("%s.%s",branch->GetName(),leafname.Data());
dim = longname.First('[');
if (dim>=0) longname.Remove(dim);
if (longname == searchname) {
return leaf;
}
if (subsearchname && longname == subsearchname) {
return leaf;
}
longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
dim = longtitle.First('[');
if (dim>=0) longtitle.Remove(dim);
if (longtitle == searchname) {
return leaf;
}
if (subsearchname && longtitle == subsearchname) {
return leaf;
}
// The following is for the case where the branch is only
// a sub-branch. Since we do not see it through
// TTree::GetListOfBranches, we need to see it indirectly.
// This is the less sturdy part of this search ... it may
// need refining ...
if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
return leaf;
}
if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
return leaf;
}
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindLeaf);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
subsearchname = (char*) strstr(searchname, fe->GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(fe->GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
}
}
if (subsearchname) {
leafname.Form("%s.%s",t->GetName(),subsearchname);
} else {
leafname = searchname;
}
leaf = t->FindLeaf(leafname);
if (leaf) {
return leaf;
}
}
return 0;
}
//______________________________________________________________________________
Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
{
// Fit a projected item(s) from a tree.
//
// funcname is a TF1 function.
//
// See TTree::Draw() for explanations of the other parameters.
//
// By default the temporary histogram created is called htemp.
// If varexp contains >>hnew , the new histogram created is called hnew
// and it is kept in the current directory.
//
// The function returns the number of selected entries.
//
// Example:
// tree.Fit(pol4,sqrt(x)>>hsqrt,y>0)
// will fit sqrt(x) and save the histogram as "hsqrt" in the current
// directory.
//
// See also TTree::UnbinnedFit
//
// Return status
// =============
// The function returns the status of the histogram fit (see TH1::Fit)
// If no entries were selected, the function returns -1;
// (ie fitResult is null is the fit is OK)
GetPlayer();
if (fPlayer) {
return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Int_t TTree::FlushBaskets() const
{
// Write to disk all the basket that have not yet been individually written.
//
// Return the number of bytes written or -1 in case of write error.
if (!fDirectory) return 0;
Int_t nbytes = 0;
Int_t nerror = 0;
TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
Int_t nb = lb->GetEntriesFast();
for (Int_t j = 0; j < nb; j++) {
TBranch* branch = (TBranch*) lb->UncheckedAt(j);
if (branch) {
Int_t nwrite = branch->FlushBaskets();
if (nwrite<0) {
++nerror;
} else {
nbytes += nwrite;
}
}
}
if (nerror) {
return -1;
} else {
return nbytes;
}
}
//______________________________________________________________________________
const char* TTree::GetAlias(const char* aliasName) const
{
// Returns the expanded value of the alias. Search in the friends if any.
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetAlias & fFriendLockStatus) {
return 0;
}
if (fAliases) {
TObject* alias = fAliases->FindObject(aliasName);
if (alias) {
return alias->GetTitle();
}
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t) {
const char* alias = t->GetAlias(aliasName);
if (alias) {
return alias;
}
const char* subAliasName = strstr(aliasName, fe->GetName());
if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
if (alias) {
return alias;
}
}
}
}
return 0;
}
//______________________________________________________________________________
TBranch* TTree::GetBranch(const char* name)
{
// Return pointer to the branch with the given name in this tree or its friends.
if (name == 0) return 0;
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetBranch & fFriendLockStatus) {
return 0;
}
// Search using branches.
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
if (!strcmp(branch->GetName(), name)) {
return branch;
}
TObjArray* lb = branch->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; j++) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!strcmp(b1->GetName(), name)) {
return b1;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; k++) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!strcmp(b2->GetName(), name)) {
return b2;
}
}
}
}
// Search using leaves.
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (!strcmp(branch->GetName(), name)) {
return branch;
}
}
if (!fFriends) {
return 0;
}
// Search in list of friends.
TFriendLock lock(this, kGetBranch);
TIter next(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (t) {
TBranch* branch = t->GetBranch(name);
if (branch) {
return branch;
}
}
}
// Second pass in the list of friends when
// the branch name is prefixed by the tree name.
next.Reset();
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
char* subname = (char*) strstr(name, fe->GetName());
if (subname != name) {
continue;
}
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') {
continue;
}
subname++;
TBranch* branch = t->GetBranch(subname);
if (branch) {
return branch;
}
}
return 0;
}
//______________________________________________________________________________
Bool_t TTree::GetBranchStatus(const char* branchname) const
{
// Return status of branch with name branchname.
// 0 if branch is not activated
// 1 if branch is activated
TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
if (br) {
return br->TestBit(kDoNotProcess) == 0;
}
return 0;
}
//______________________________________________________________________________
Int_t TTree::GetBranchStyle()
{
// Static function returning the current branch style.
// style = 0 old Branch
// style = 1 new Bronch
return fgBranchStyle;
}
//______________________________________________________________________________
TFile* TTree::GetCurrentFile() const
{
// Return pointer to the current file.
if (!fDirectory || fDirectory==gROOT) {
return 0;
}
return fDirectory->GetFile();
}
//______________________________________________________________________________
Long64_t TTree::GetEntries(const char *selection)
{
// Return the number of entries matching the selection.
// Return -1 in case of errors.
//
// If the selection uses any arrays or containers, we return the number
// of entries where at least one element match the selection.
// GetEntries is implemented using the selector class TSelectorEntries,
// which can be used directly (see code in TTreePlayer::GetEntries) for
// additional option.
// If SetEventList was used on the TTree or TChain, only that subset
// of entries will be considered.
GetPlayer();
if (fPlayer) {
return fPlayer->GetEntries(selection);
}
return -1;
}
//______________________________________________________________________________
Long64_t TTree::GetEntriesFriend() const
{
// Return pointer to the 1st Leaf named name in any Branch of this Tree or
// any branch in the list of friend trees.
if (fEntries) return fEntries;
if (!fFriends) return 0;
TFriendElement *fr = (TFriendElement*)fFriends->At(0);
if (!fr) return 0;
TTree *t = fr->GetTree();
if (t==0) return 0;
return t->GetEntriesFriend();
}
//______________________________________________________________________________
Int_t TTree::GetEntry(Long64_t entry, Int_t getall)
{
// Read all branches of entry and return total number of bytes read.
//
// getall = 0 : get only active branches
// getall = 1 : get all branches
//
// The function returns the number of bytes read from the input buffer.
// If entry does not exist the function returns 0.
// If an I/O error occurs, the function returns -1.
//
// If the Tree has friends, also read the friends entry
//
// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
// For example, if you have a Tree with several hundred branches, and you
// are interested only by branches named "u" and "v", do
// mytree.SetBranchStatus("*",0); //disable all branches
// mytree.SetBranchStatus("a",1);
// mytree.SetBranchStatus("b",1);
// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
//
// WARNING!!
// If your Tree has been created in split mode with a parent branch "parent",
// mytree.SetBranchStatus("parent",1);
// will not activate the sub-branches of "parent". You should do:
// mytree.SetBranchStatus("parent*",1);
//
// An alternative is to call directly
// brancha.GetEntry(i)
// branchb.GetEntry(i);
//
// IMPORTANT NOTE
// ==============
// By default, GetEntry reuses the space allocated by the previous object
// for each branch. You can force the previous object to be automatically
// deleted if you call mybranch.SetAutoDelete(kTRUE) (default is kFALSE).
// Example:
// Consider the example in $ROOTSYS/test/Event.h
// The top level branch in the tree T is declared with:
// Event *event = 0; //event must be null or point to a valid object
// //it must be initialized
// T.SetBranchAddress("event",&event);
// When reading the Tree, one can choose one of these 3 options:
//
// OPTION 1
// --------
//
// for (Long64_t i=0;i<nentries;i++) {
// T.GetEntry(i);
// // the object event has been filled at this point
// }
// The default (recommended). At the first entry an object of the
// class Event will be created and pointed by event.
// At the following entries, event will be overwritten by the new data.
// All internal members that are TObject* are automatically deleted.
// It is important that these members be in a valid state when GetEntry
// is called. Pointers must be correctly initialized.
// However these internal members will not be deleted if the characters "->"
// are specified as the first characters in the comment field of the data
// member declaration.
// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
// In this case, it is assumed that the pointer is never null (case
// of pointer TClonesArray *fTracks in the Event example).
// If "->" is not specified, the pointer member is read via buf >> pointer.
// In this case the pointer may be null. Note that the option with "->"
// is faster to read or write and it also consumes less space in the file.
//
// OPTION 2
// --------
// The option AutoDelete is set
// TBranch *branch = T.GetBranch("event");
// branch->SetAddress(&event);
// branch->SetAutoDelete(kTRUE);
// for (Long64_t i=0;i<nentries;i++) {
// T.GetEntry(i);
// // the object event has been filled at this point
// }
// In this case, at each iteration, the object event is deleted by GetEntry
// and a new instance of Event is created and filled.
//
// OPTION 3
// --------
// Same as option 1, but you delete yourself the event.
// for (Long64_t i=0;i<nentries;i++) {
// delete event;
// event = 0; // EXTREMELY IMPORTANT
// T.GetEntry(i);
// // the object event has been filled at this point
// }
//
// It is strongly recommended to use the default option 1. It has the
// additional advantage that functions like TTree::Draw (internally
// calling TTree::GetEntry) will be functional even when the classes in the
// file are not available.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetEntry & fFriendLockStatus) return 0;
if (entry < 0 || entry >= fEntries) return 0;
Int_t i;
Int_t nbytes = 0;
fReadEntry = entry;
TBranch *branch;
Int_t nbranches = fBranches.GetEntriesFast();
Int_t nb=0;
for (i=0;i<nbranches;i++) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(entry, getall);
if (nb < 0) return nb;
nbytes += nb;
}
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntry);
TIter nextf(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t) {
if (fe->TestBit(TFriendElement::kFromChain)) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else {
if ( t->LoadTreeFriend(entry,this) >= 0 ) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else nb = 0;
}
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
//______________________________________________________________________________
TEntryList* TTree::GetEntryList()
{
//Returns the entry list, set to this tree
return fEntryList;
}
//______________________________________________________________________________
Long64_t TTree::GetEntryNumber(Long64_t entry) const
{
// Return entry number corresponding to entry.
//
// if no TEntryList set returns entry
// else returns the entry number corresponding to the list index=entry
if (!fEntryList) {
return entry;
}
return fEntryList->GetEntry(entry);
}
//______________________________________________________________________________
Long64_t TTree::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const
{
// Return entry number corresponding to major and minor number.
// Note that this function returns only the entry number, not the data
// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
// the BuildIndex function has created a table of Long64_t* of sorted values
// corresponding to val = major<<31 + minor;
// The function performs binary search in this sorted table.
// If it finds a pair that maches val, it returns directly the
// index in the table.
// If an entry corresponding to major and minor is not found, the function
// returns the index of the major,minor pair immediatly lower than the
// requested value, ie it will return -1 if the pair is lower than
// the first entry in the index.
//
// See also GetEntryNumberWithIndex
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithBestIndex(major, minor);
}
//______________________________________________________________________________
Long64_t TTree::GetEntryNumberWithIndex(Int_t major, Int_t minor) const
{
// Return entry number corresponding to major and minor number.
// Note that this function returns only the entry number, not the data
// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
// the BuildIndex function has created a table of Long64_t* of sorted values
// corresponding to val = major<<31 + minor;
// The function performs binary search in this sorted table.
// If it finds a pair that maches val, it returns directly the
// index in the table, otherwise it returns -1.
//
// See also GetEntryNumberWithBestIndex
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithIndex(major, minor);
}
//______________________________________________________________________________
Int_t TTree::GetEntryWithIndex(Int_t major, Int_t minor)
{
// Read entry corresponding to major and minor number.
//
// The function returns the total number of bytes read.
// If the Tree has friend trees, the corresponding entry with
// the index values (major,minor) is read. Note that the master Tree
// and its friend may have different entry serial numbers corresponding
// to (major,minor).
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetEntryWithIndex & fFriendLockStatus) {
return 0;
}
Long64_t serial = GetEntryNumberWithIndex(major, minor);
if (serial < 0) {
return -1;
}
Int_t i;
Int_t nbytes = 0;
fReadEntry = serial;
TBranch *branch;
Int_t nbranches = fBranches.GetEntriesFast();
Int_t nb;
for (i = 0; i < nbranches; ++i) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntryWithIndex);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *t = fe->GetTree();
if (t) {
serial = t->GetEntryNumberWithIndex(major,minor);
if (serial <0) return -nbytes;
nb = t->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
//______________________________________________________________________________
TTree* TTree::GetFriend(const char *friendname) const
{
// Return a pointer to the TTree friend whose name or alias is 'friendname.
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriend & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (strcmp(friendname,fe->GetName())==0
|| strcmp(friendname,fe->GetTreeName())==0) {
return fe->GetTree();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *res = fe->GetTree()->GetFriend(friendname);
if (res) {
return res;
}
}
return 0;
}
//______________________________________________________________________________
const char* TTree::GetFriendAlias(TTree* tree) const
{
// If the the 'tree' is a friend, this method returns its alias name.
//
// This alias is an alternate name for the tree.
//
// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
// to specify in which particular tree the branch or leaf can be found if
// the friend trees have branches or leaves with the same name as the master
// tree.
//
// It can also be used in conjunction with an alias created using
// TTree::SetAlias in a TTreeFormula, e.g.:
//
// maintree->Draw("treealias.fPx - treealias.myAlias");
//
// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
// was created using TTree::SetAlias on the friend tree.
//
// However, note that 'treealias.myAlias' will be expanded literally,
// without remembering that it comes from the aliased friend and thus
// the branch name might not be disambiguated properly, which means
// that you may not be able to take advantage of this feature.
//
if ((tree == this) || (tree == GetTree())) {
return 0;
}
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriendAlias & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t == tree) {
return fe->GetName();
}
// Case of a chain:
if (t->GetTree() == tree) {
return fe->GetName();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
const char* res = fe->GetTree()->GetFriendAlias(tree);
if (res) {
return res;
}
}
return 0;
}
//______________________________________________________________________________
TIterator* TTree::GetIteratorOnAllLeaves(Bool_t dir)
{
// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
return new TTreeFriendLeafIter(this, dir);
}
//______________________________________________________________________________
TLeaf* TTree::GetLeaf(const char* aname)
{
// Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of friend trees.
//
// aname may be of the form branchname/leafname
if (aname == 0) return 0;
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetLeaf & fFriendLockStatus) {
return 0;
}
TLeaf *leaf = 0;
char* slash = (char*) strchr(aname, '/');
char* name = 0;
UInt_t nbch = 0;
if (slash) {
name = slash + 1;
nbch = slash - aname;
TString brname(aname,nbch);
TBranch *branch = FindBranch(brname);
if (branch) {
leaf = branch->GetLeaf(name);
if (leaf) {
return leaf;
}
}
} else {
name = (char*) aname;
}
TIter nextl(GetListOfLeaves());
while ((leaf = (TLeaf*)nextl())) {
if (strcmp(leaf->GetName(),name)) continue;
if (slash) {
TBranch *br = leaf->GetBranch();
const char* brname = br->GetName();
TBranch *mother = br->GetMother();
if (strncmp(brname,aname,nbch)) {
if (mother != br) {
const char *mothername = mother->GetName();
UInt_t motherlen = strlen(mothername);
if (nbch > motherlen && strncmp(mothername,aname,motherlen)==0 && (mothername[motherlen-1]=='.' || aname[motherlen]=='.')) {
// The left part of the requested name match the name of the mother, let's see if the right part match the name of the branch.
if (strncmp(brname,aname+motherlen+1,nbch-motherlen-1)) {
// No it does not
continue;
} // else we have match so we can proceed.
} else {
// no match
continue;
}
} else {
continue;
}
}
// The start of the branch name is indentical to the content
// of 'aname' before the first '/'.
// Let's make sure that it is not longer (we are trying
// to avoid having jet2/value match the branch jet23
if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
continue;
}
}
return leaf;
}
if (!fFriends) return 0;
TFriendLock lock(this,kGetLeaf);
TIter next(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t) {
leaf = t->GetLeaf(aname);
if (leaf) return leaf;
}
}
//second pass in the list of friends when the leaf name
//is prefixed by the tree name
TString strippedArg;
next.Reset();
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t==0) continue;
char *subname = (char*)strstr(name,fe->GetName());
if (subname != name) continue;
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') continue;
subname++;
if (slash) {
strippedArg = aname;
strippedArg.Remove(nbch+1);
} else {
strippedArg = "";
}
strippedArg += subname;
leaf = t->GetLeaf(strippedArg);
if (leaf) return leaf;
}
return 0;
}
//______________________________________________________________________________
Double_t TTree::GetMaximum(const char* columname)
{
// Return maximum of column with name columname.
// if the Tree has an associated TEventList or TEntryList, the maximum
// is computed for the entries in this list.
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
TBranch* branch = leaf->GetBranch();
Double_t cmax = -FLT_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0; j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val > cmax) {
cmax = val;
}
}
}
return cmax;
}
//______________________________________________________________________________
Long64_t TTree::GetMaxTreeSize()
{
// Static function which returns the tree file size limit.
return fgMaxTreeSize;
}
//______________________________________________________________________________
Double_t TTree::GetMinimum(const char* columname)
{
// Return minimum of column with name columname.
// if the Tree has an associated TEventList or TEntryList, the minimum
// is computed for the entries in this list.
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
TBranch* branch = leaf->GetBranch();
Double_t cmin = FLT_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0;j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val < cmin) {
cmin = val;
}
}
}
return cmin;
}
//______________________________________________________________________________
TVirtualTreePlayer* TTree::GetPlayer()
{
// Load the TTreePlayer (if not already done).
if (fPlayer) {
return fPlayer;
}
fPlayer = TVirtualTreePlayer::TreePlayer(this);
return fPlayer;
}
//______________________________________________________________________________
TList* TTree::GetUserInfo()
{
// Return a pointer to the list containing user objects associated to this tree.
//
// The list is automatically created if it does not exist.
//
// WARNING: By default the TTree destructor will delete all objects added
// to this list. If you do not want these objects to be deleted,
// call:
//
// mytree->GetUserInfo()->Clear();
//
// before deleting the tree.
if (!fUserInfo) {
fUserInfo = new TList();
fUserInfo->SetName("UserInfo");
}
return fUserInfo;
}
//______________________________________________________________________________
void TTree::KeepCircular()
{
// Keep a maximum of fMaxEntries in memory.
Int_t nb = fBranches.GetEntriesFast();
Long64_t maxEntries = fMaxEntries - (fMaxEntries / 10);
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->KeepCircular(maxEntries);
}
fEntries = maxEntries;
fReadEntry = -1;
}
//______________________________________________________________________________
Int_t TTree::LoadBaskets(Long64_t maxmemory)
{
// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
//
// If maxmemory is non null and positive SetMaxVirtualSize is called
// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
// The function returns the total number of baskets read into memory
// if negative an error occured while loading the branches.
// This method may be called to force branch baskets in memory
// when random access to branch entries is required.
// If random access to only a few branches is required, you should
// call directly TBranch::LoadBaskets.
if (maxmemory > 0) SetMaxVirtualSize(maxmemory);
TIter next(GetListOfLeaves());
TLeaf *leaf;
Int_t nimported = 0;
while ((leaf=(TLeaf*)next())) {
nimported += leaf->GetBranch()->LoadBaskets();//break;
}
return nimported;
}
//______________________________________________________________________________
Long64_t TTree::LoadTree(Long64_t entry)
{
// Set current entry.
//
// Returns -2 if entry does not exist (just as TChain::LoadTree()).
//
// Note: This function is overloaded in TChain.
//
// We already have been visited while recursively looking
// through the friends tree, let return
if (kLoadTree & fFriendLockStatus) {
// We need to return a negative value to avoid a circular list of friend
// to think that there is always an entry somewhere in the lisst.
return -1;
}
if (fNotify) {
if (fReadEntry < 0) {
fNotify->Notify();
}
}
fReadEntry = entry;
Bool_t friendHasEntry = kFALSE;
if (fFriends) {
// Set current entry in friends as well.
//
// An alternative would move this code to each of the
// functions calling LoadTree (and to overload a few more).
Bool_t needUpdate = kFALSE;
{
// This scope is need to insure the lock is released at the right time
TIter nextf(fFriends);
TFriendLock lock(this, kLoadTree);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (fe->TestBit(TFriendElement::kFromChain)) {
// This friend element was added by the chain that owns this
// tree, the chain will deal with loading the correct entry.
continue;
}
TTree* friendTree = fe->GetTree();
if (friendTree->IsA() == TTree::Class()) {
// Friend is actually a tree.
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
} else {
// Friend is actually a chain.
// FIXME: This logic should be in the TChain override.
Int_t oldNumber = friendTree->GetTreeNumber();
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
Int_t newNumber = friendTree->GetTreeNumber();
if (oldNumber != newNumber) {
// We can not just compare the tree pointers because they could be reused.
// So we compare the tree number instead.
needUpdate = kTRUE;
}
}
} // for each friend
}
if (needUpdate) {
//update list of leaves in all TTreeFormula of the TTreePlayer (if any)
if (fPlayer) {
fPlayer->UpdateFormulaLeaves();
}
//Notify user if requested
if (fNotify) {
fNotify->Notify();
}
}
}
if ((fReadEntry >= fEntries) && !friendHasEntry) {
fReadEntry = -1;
return -2;
}
return fReadEntry;
}
//______________________________________________________________________________
Long64_t TTree::LoadTreeFriend(Long64_t entry, TTree* masterTree)
{
// Load entry on behalf of our master tree, we may use an index.
//
// Called by LoadTree() when the masterTree looks for the entry
// number in a friend tree (us) corresponding to the passed entry
// number in the masterTree.
//
// If we have no index, our entry number and the masterTree entry
// number are the same.
//
// If we *do* have an index, we must find the (major, minor) value pair
// in masterTree to locate our corresponding entry.
//
if (!fTreeIndex) {
return LoadTree(entry);
}
return LoadTree(fTreeIndex->GetEntryNumberFriend(masterTree));
}
//______________________________________________________________________________
Int_t TTree::MakeClass(const char* classname, Option_t* option)
{
// Generate a skeleton analysis class for this tree.
//
// The following files are produced: classname.h and classname.C.
// If classname is 0, classname will be called "nameoftree".
//
// The generated code in classname.h includes the following:
// - Identification of the original tree and the input file name.
// - Definition of an analysis class (data members and member functions).
// - The following member functions:
// - constructor (by default opening the tree file),
// - GetEntry(Long64_t entry),
// - Init(TTree* tree) to initialize a new TTree,
// - Show(Long64_t entry) to read and dump entry.
//
// The generated code in classname.C includes only the main
// analysis function Loop.
//
// To use this function:
// - Open your tree file (eg: TFile f("myfile.root");)
// - T->MakeClass("MyClass");
// where T is the name of the TTree in file myfile.root,
// and MyClass.h, MyClass.C the name of the files created by this function.
// In a ROOT session, you can do:
// root > .L MyClass.C
// root > MyClass* t = new MyClass;
// root > t->GetEntry(12); // Fill data members of t with entry number 12.
// root > t->Show(); // Show values of entry 12.
// root > t->Show(16); // Read and show values of entry 16.
// root > t->Loop(); // Loop on all entries.
//
// NOTE: Do not use the code generated for a single TTree which is part
// of a TChain to process that entire TChain. The maximum dimensions
// calculated for arrays on the basis of a single TTree from the TChain
// might be (will be!) too small when processing all of the TTrees in
// the TChain. You must use myChain.MakeClass() to generate the code,
// not myTree.MakeClass(...).
//
GetPlayer();
if (!fPlayer) {
return 0;
}
return fPlayer->MakeClass(classname, option);
}
//______________________________________________________________________________
Int_t TTree::MakeCode(const char* filename)
{
// Generate a skeleton function for this tree.
//
// The function code is written on filename.
// If filename is 0, filename will be called nameoftree.C
//
// The generated code includes the following:
// - Identification of the original Tree and Input file name,
// - Opening the Tree file,
// - Declaration of Tree variables,
// - Setting of branches addresses,
// - A skeleton for the entry loop.
//
// To use this function:
// - Open your Tree file (eg: TFile f("myfile.root");)
// - T->MakeCode("MyAnalysis.C");
// where T is the name of the TTree in file myfile.root
// and MyAnalysis.C the name of the file created by this function.
//
// NOTE: Since the implementation of this function, a new and better
// function TTree::MakeClass() has been developed.
Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeCode(filename);
}
//______________________________________________________________________________
Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
{
// Generate a skeleton analysis class for this Tree using TBranchProxy.
//
// TBranchProxy is the base of a class hierarchy implementing an
// indirect access to the content of the branches of a TTree.
//
// "proxyClassname" is expected to be of the form:
// [path/]fileprefix
// The skeleton will then be generated in the file:
// fileprefix.h
// located in the current directory or in 'path/' if it is specified.
// The class generated will be named 'fileprefix'
//
// "macrofilename" and optionally "cutfilename" are expected to point
// to source files which will be included by the generated skeleton.
// Method of the same name as the file(minus the extension and path)
// will be called by the generated skeleton's Process method as follow:
// [if (cutfilename())] htemp->Fill(macrofilename());
//
// "option" can be used select some of the optional features during
// the code generation. The possible options are:
// nohist : indicates that the generated ProcessFill should not
// fill the histogram.
//
// 'maxUnrolling' controls how deep in the class hierachy does the
// system 'unroll' classes that are not split. Unrolling a class
// allows direct access to its data members (this emulates the behavior
// of TTreeFormula).
//
// The main features of this skeleton are:
//
// * on-demand loading of branches
// * ability to use the 'branchname' as if it was a data member
// * protection against array out-of-bounds errors
// * ability to use the branch data as an object (when the user code is available)
//
// For example with Event.root, if
// Double_t somePx = fTracks.fPx[2];
// is executed by one of the method of the skeleton,
// somePx will updated with the current value of fPx of the 3rd track.
//
// Both macrofilename and the optional cutfilename are expected to be
// the name of source files which contain at least a free standing
// function with the signature:
// x_t macrofilename(); // i.e function with the same name as the file
// and
// y_t cutfilename(); // i.e function with the same name as the file
//
// x_t and y_t needs to be types that can convert respectively to a double
// and a bool (because the skeleton uses:
// if (cutfilename()) htemp->Fill(macrofilename());
//
// These two functions are run in a context such that the branch names are
// available as local variables of the correct (read-only) type.
//
// Note that if you use the same 'variable' twice, it is more efficient
// to 'cache' the value. For example
// Int_t n = fEventNumber; // Read fEventNumber
// if (n<10 || n>10) { ... }
// is more efficient than
// if (fEventNumber<10 || fEventNumber>10)
//
// Also, optionally, the generated selector will also call methods named
// macrofilename_methodname in each of 6 main selector methods if the method
// macrofilename_methodname exist (Where macrofilename is stripped of its
// extension).
//
// Concretely, with the script named h1analysisProxy.C,
//
// The method calls the method (if it exist)
// Begin -> void h1analysisProxy_Begin(TTree*);
// SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
// Notify -> Bool_t h1analysisProxy_Notify();
// Process -> Bool_t h1analysisProxy_Process(Long64_t);
// SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
// Terminate -> void h1analysisProxy_Terminate();
//
// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
// it is included before the declaration of the proxy class. This can
// be used in particular to insure that the include files needed by
// the macro file are properly loaded.
//
// The default histogram is accessible via the variable named 'htemp'.
//
// If the library of the classes describing the data in the branch is
// loaded, the skeleton will add the needed #include statements and
// give the ability to access the object stored in the branches.
//
// To draw px using the file hsimple.root (generated by the
// hsimple.C tutorial), we need a file named hsimple.cxx:
//
// double hsimple() {
// return px;
// }
//
// MakeProxy can then be used indirectly via the TTree::Draw interface
// as follow:
// new TFile("hsimple.root")
// ntuple->Draw("hsimple.cxx");
//
// A more complete example is available in the tutorials directory:
// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
// which reimplement the selector found in h1analysis.C
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeProxy(proxyClassname,macrofilename,cutfilename,option,maxUnrolling);
}
//______________________________________________________________________________
Int_t TTree::MakeSelector(const char* selector)
{
// Generate skeleton selector class for this tree.
//
// The following files are produced: selector.h and selector.C.
// If selector is 0, the selector will be called "nameoftree".
//
// The generated code in selector.h includes the following:
// - Identification of the original Tree and Input file name
// - Definition of selector class (data and functions)
// - The following class functions:
// - constructor and destructor
// - void Begin(TTree *tree)
// - void SlaveBegin(TTree *tree)
// - void Init(TTree *tree)
// - Bool_t Notify()
// - Bool_t Process(Long64_t entry)
// - void Terminate()
// - void SlaveTerminate()
//
// The class selector derives from TSelector.
// The generated code in selector.C includes empty functions defined above.
//
// To use this function:
// - connect your Tree file (eg: TFile f("myfile.root");)
// - T->MakeSelector("myselect");
// where T is the name of the Tree in file myfile.root
// and myselect.h, myselect.C the name of the files created by this function.
// In a ROOT session, you can do:
// root > T->Process("myselect.C")
return MakeClass(selector, "selector");
}
//______________________________________________________________________________
Bool_t TTree::MemoryFull(Int_t nbytes)
{
// Check if adding nbytes to memory we are still below MaxVirtualsize.
if ((fTotalBuffers + nbytes) < fMaxVirtualSize) {
return kFALSE;
}
return kTRUE;
}
//______________________________________________________________________________
TTree* TTree::MergeTrees(TList* li, Option_t* /* option */)
{
// Static function merging the trees in the TList into a new tree.
//
// Trees in the list can be memory or disk-resident trees.
// The new tree is created in the current directory (memory if gROOT).
//
if (!li) return 0;
TIter next(li);
TTree *newtree = 0;
TObject *obj;
while ((obj=next())) {
if (!obj->InheritsFrom(TTree::Class())) continue;
TTree *tree = (TTree*)obj;
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
if (!newtree) {
newtree = (TTree*)tree->CloneTree();
// Once the cloning is done, separate the trees,
// to avoid as many side-effects as possible
tree->GetListOfClones()->Remove(newtree);
tree->ResetBranchAddresses();
newtree->ResetBranchAddresses();
continue;
}
newtree->CopyAddresses(tree);
for (Long64_t i=0;i<nentries;i++) {
tree->GetEntry(i);
newtree->Fill();
}
tree->ResetBranchAddresses(); // Disconnect from new tree.
if (newtree->GetTreeIndex()) {
newtree->GetTreeIndex()->Append(tree->GetTreeIndex(),kTRUE);
}
}
if (newtree && newtree->GetTreeIndex()) {
newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
return newtree;
}
//______________________________________________________________________________
Long64_t TTree::Merge(TCollection* li, Option_t* /* option */)
{
// Merge the trees in the TList into this tree.
//
// Returns the total number of entries in the merged tree.
//
if (!li) return 0;
TIter next(li);
TTree *tree;
while ((tree = (TTree*)next())) {
if (tree==this) continue;
if (!tree->InheritsFrom(TTree::Class())) {
Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
return -1;
}
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
CopyAddresses(tree);
for (Long64_t i=0; i<nentries ; i++) {
tree->GetEntry(i);
Fill();
}
if (GetTreeIndex()) {
GetTreeIndex()->Append(tree->GetTreeIndex(),kTRUE);
}
tree->ResetBranchAddresses();
}
if (GetTreeIndex()) {
GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
return GetEntries();
}
//______________________________________________________________________________
Bool_t TTree::Notify()
{
// Function called when loading a new class library.
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leaf->Notify();
leaf->GetBranch()->Notify();
}
return kTRUE;
}
//______________________________________________________________________________
void TTree::OptimizeBaskets(Int_t maxMemory, Float_t minComp, Option_t *option)
{
//This function may be called after having filled some entries in a Tree
//Using the information in the existing branch buffers, it will reassign
//new branch buffer sizes to optimize time and memory.
//
//The function computes the best values for branch buffer sizes such that
//the total buffer sizes is less than maxMemory and nearby entries written
//at the same time.
//In case the branch compression factor for the data written so far is less
//than compMin, the compression is disabled.
//
//if option ="d" an analysis report is printed.
//Flush existing baskets if the file is writable
if (this->GetDirectory()->IsWritable()) this->FlushBaskets();
TString opt( option );
opt.ToLower();
Bool_t pDebug = opt.Contains("d");
TObjArray *leaves = this->GetListOfLeaves();
Int_t nleaves = leaves->GetEntries();
Double_t treeSize = (Double_t)this->GetTotBytes();
if (nleaves == 0 || treeSize == 0) {
// We're being called too early, we really have nothing to do ...
return;
}
Double_t aveSize = treeSize/nleaves;
Int_t bmin = 512;
Int_t bmax = 256000;
Double_t memFactor = 1;
Int_t i, oldMemsize,newMemsize,oldBaskets,newBaskets;
//we make two passes
//one pass to compute the relative branch buffer sizes
//a second pass to compute the absolute values
for (Int_t pass =0;pass<2;pass++) {
oldMemsize = 0; //to count size of baskets in memory with old buffer size
newMemsize = 0; //to count size of baskets in memory with new buffer size
oldBaskets = 0; //to count number of baskets with old buffer size
newBaskets = 0; //to count number of baskets with new buffer size
for (i=0;i<nleaves;i++) {
TLeaf *leaf = (TLeaf*)leaves->At(i);
TBranch *branch = leaf->GetBranch();
Double_t totBytes = (Double_t)branch->GetTotBytes();
Double_t idealFactor = totBytes/aveSize;
Int_t oldBsize = branch->GetBasketSize();
oldMemsize += oldBsize;
oldBaskets += 1+Int_t(totBytes/oldBsize);
Int_t nb = branch->GetListOfBranches()->GetEntries();
if (nb > 0) {
newBaskets += 1+Int_t(totBytes/oldBsize);
continue;
}
Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
if (bsize < 0) bsize = bmax;
if (bsize > bmax) bsize = bmax;
Int_t newBsize = Int_t(bsize);
newBsize = newBsize - newBsize%512;
if (newBsize < bmin) newBsize = bmin;
if (newBsize > 10000000) newBsize = bmax;
if (pass) {
if (pDebug) printf("Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
branch->SetBasketSize(newBsize);
}
newMemsize += newBsize;
newBaskets += 1+Int_t(totBytes/newBsize);
if (pass == 0) continue;
//Reset the compression level in case the compression factor is small
Double_t comp = 1;
if (branch->GetZipBytes() > 0) comp = Double_t(oldBsize)/Double_t(branch->GetZipBytes());
if (comp > 1 && comp < minComp) {
if (pDebug) printf("Disabling compression for branch : %s\n",branch->GetName());
branch->SetCompressionLevel(0);
}
}
memFactor = Double_t(maxMemory)/Double_t(newMemsize);
if (memFactor > 100) memFactor = 100;
bmin = Int_t(bmin*memFactor);
bmax = Int_t(bmax*memFactor);
}
if (pDebug) {
printf("oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
printf("oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
}
}
//______________________________________________________________________________
TPrincipal* TTree::Principal(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Interface to the Principal Components Analysis class.
//
// Create an instance of TPrincipal
// Fill it with the selected variables
// if option "n" is specified, the TPrincipal object is filled with
// normalized variables.
// If option "p" is specified, compute the principal components
// If option "p" and "d" print results of analysis
// If option "p" and "h" generate standard histograms
// If option "p" and "c" generate code of conversion functions
// return a pointer to the TPrincipal object. It is the user responsability
// to delete this object.
// The option default value is "np"
//
// see TTree::Draw for explanation of the other parameters.
//
// The created object is named "principal" and a reference to it
// is added to the list of specials Root objects.
// you can retrieve a pointer to the created object via:
// TPrincipal *principal =
// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
//
GetPlayer();
if (fPlayer) {
return fPlayer->Principal(varexp, selection, option, nentries, firstentry);
}
return 0;
}
//______________________________________________________________________________
void TTree::Print(Option_t* option) const
{
// Print a summary of the tree contents.
//
// If option contains "all" friend trees are also printed.
// If option contains "toponly" only the top level branches are printed.
//
// Wildcarding can be used to print only a subset of the branches, e.g.,
// T.Print("Elec*") will print all branches with name starting with "Elec".
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kPrint & fFriendLockStatus) {
return;
}
Int_t s = 0;
Int_t skey = 0;
if (fDirectory) {
TKey* key = fDirectory->GetKey(GetName());
if (key) {
skey = key->GetKeylen();
s = key->GetNbytes();
}
}
Long64_t total = skey;
if (fZipBytes > 0) {
total += fTotBytes;
}
TBufferFile b(TBuffer::kWrite, 10000);
TTree::Class()->WriteBuffer(b, (TTree*) this);
total += b.Length();
Long64_t file = fZipBytes + s;
Float_t cx = 1;
if (fZipBytes) {
cx = (fTotBytes + 0.00001) / fZipBytes;
}
Printf("******************************************************************************");
Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
Printf("* : : Tree compression factor = %6.2f *", cx);
Printf("******************************************************************************");
Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
Int_t l;
TBranch* br = 0;
TLeaf* leaf = 0;
if (strstr(option, "toponly")) {
Long64_t *count = new Long64_t[nl];
Int_t keep =0;
for (l=0;l<nl;l++) {
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
if (strchr(br->GetName(),'.')) {
count[l] = -1;
count[keep] += br->GetZipBytes();
} else {
keep = l;
count[keep] = br->GetZipBytes();
}
}
for (l=0;l<nl;l++) {
if (count[l] < 0) continue;
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
printf("branch: %-20s %9lld\n",br->GetName(),count[l]);
}
delete [] count;
} else {
TString reg = "*";
if (strlen(option) && strchr(option,'*')) reg = option;
TRegexp re(reg,kTRUE);
TIter next(const_cast<TTree*>(this)->GetListOfBranches());
TBranch::ResetCount();
while ((br= (TBranch*)next())) {
TString st = br->GetName();
st.ReplaceAll("/","_");
if (st.Index(re) == kNPOS) continue;
br->Print(option);
}
}
//print TRefTable (if one)
if (fBranchRef) fBranchRef->Print(option);
//print friends if option "all"
if (!fFriends || !strstr(option,"all")) return;
TIter nextf(fFriends);
TFriendLock lock(const_cast<TTree*>(this),kPrint);
TFriendElement *fr;
while ((fr = (TFriendElement*)nextf())) {
TTree * t = fr->GetTree();
if (t) t->Print(option);
}
}
//______________________________________________________________________________
void TTree::PrintCacheStats(Option_t* option) const
{
// print statistics about the TreeCache for this tree, like
// ******TreeCache statistics for file: cms2.root ******
// Reading 73921562 bytes in 716 transactions
// Average transaction = 103.242405 Kbytes
// Number of blocks in current cache: 202, total size : 6001193
//
// if option = "a" the list of blocks in the cache is printed
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->Print(option);
}
//______________________________________________________________________________
Long64_t TTree::Process(const char* filename, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Process this tree executing the TSelector code in the specified filename.
// The return value is -1 in case of error and TSelector::GetStatus() in
// in case of success.
//
// The code in filename is loaded (interpreted or compiled, see below),
// filename must contain a valid class implementation derived from TSelector,
// where TSelector has the following member functions:
//
// Begin(): called everytime 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.
//
// If filename is of the form file.C, the file will be interpreted.
// If filename is of the form file.C++, the file file.C will be compiled
// and dynamically loaded.
// If filename is of the form file.C+, the file file.C will be compiled
// and dynamically loaded. At next call, if file.C is older than file.o
// and file.so, the file.C is not compiled, only file.so is loaded.
//
// NOTE1
// It may be more interesting to invoke directly the other Process function
// accepting a TSelector* as argument.eg
// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
// selector->CallSomeFunction(..);
// mytree.Process(selector,..);
//
// NOTE2
// One should not call this function twice with the same selector file
// in the same script. If this is required, proceed as indicated in NOTE1,
// by getting a pointer to the corresponding TSelector,eg
// workaround 1
// ------------
//void stubs1() {
// TSelector *selector = TSelector::GetSelector("h1test.C");
// TFile *f1 = new TFile("stubs_nood_le1.root");
// TTree *h1 = (TTree*)f1->Get("h1");
// h1->Process(selector);
// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
// TTree *h2 = (TTree*)f2->Get("h1");
// h2->Process(selector);
//}
// or use ACLIC to compile the selector
// workaround 2
// ------------
//void stubs2() {
// TFile *f1 = new TFile("stubs_nood_le1.root");
// TTree *h1 = (TTree*)f1->Get("h1");
// h1->Process("h1test.C+");
// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
// TTree *h2 = (TTree*)f2->Get("h1");
// h2->Process("h1test.C+");
//}
GetPlayer();
if (fPlayer) {
return fPlayer->Process(filename, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Long64_t TTree::Process(TSelector* selector, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Process this tree executing the code in the specified selector.
// The return value is -1 in case of error and TSelector::GetStatus() in
// in case of success.
//
// The TSelector class has the following member functions:
//
// Begin(): called everytime 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.
//
// If the Tree (Chain) has an associated EventList, the loop is on the nentries
// of the EventList, starting at firstentry, otherwise the loop is on the
// specified Tree entries.
GetPlayer();
if (fPlayer) {
return fPlayer->Process(selector, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Long64_t TTree::Project(const char* hname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Make a projection of a tree using selections.
//
// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
// projection of the tree will be filled in histogram hname.
// Note that the dimension of hname must match with the dimension of varexp.
//
TString var;
var.Form("%s>>%s", varexp, hname);
TString opt("goff");
if (option) {
opt.Form("%sgoff", option);
}
Long64_t nsel = Draw(var, selection, opt, nentries, firstentry);
return nsel;
}
//______________________________________________________________________________
TSQLResult* TTree::Query(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Loop over entries and return a TSQLResult object containing entries following selection.
GetPlayer();
if (fPlayer) {
return fPlayer->Query(varexp, selection, option, nentries, firstentry);
}
return 0;
}
//______________________________________________________________________________
Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor)
{
// Create or simply read branches from filename.
//
// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
// is given in the first line of the file with a syntax like
// A/D:Table[2]/F:Ntracks/I:astring/C
// otherwise branchDescriptor must be specified with the above syntax.
// -If the type of the first variable is not specified, it is assumed to be "/F"
// -if the type of any other variable is not specified, the type of the previous
// variable is assumed. eg
// x:y:z (all variables are assumed of type "F"
// x/D:y:z (all variables are of type "D"
// x:y/D:z (x is type "F", y and z of type "D"
// -If the type is a string of characters. This will read
// subsequent characters until a whitespace is found (whitespace
// characters are considered to be blank, newline and tab).
//
// Lines in the input file starting with "#" are ignored.
// This function will read and ignore any whitespace characters
// (this includes blank spaces and the newline and tab characters).
//
// A TBranch object is created for each variable in the expression.
// The total number of rows read from the file is returned.
//
// FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
// ----------------------------------------------
// To fill a TTree with multiple input text files, proceed as indicated above
// for the first input file and omit the second argument for subsequent calls
// T.ReadFile("file1.dat","branch descriptor");
// T.ReadFile("file2.dat");
gTree = this;
std::ifstream in;
in.open(filename);
if (!in.good()) {
Error("ReadFile","Cannot open file: %s",filename);
return 0;
}
TBranch *branch;
Int_t nbranches = fBranches.GetEntries();
if (nbranches == 0) {
char *bdname = new char[4000];
char *bd = new char[100000];
Int_t nch = 0;
if (branchDescriptor) nch = strlen(branchDescriptor);
// branch Descriptor is null, read its definition from the first line in the file
if (!nch) {
in >> bd;
if (!in.good()) {
Error("ReadFile","Error reading file: %s",filename);
return 0;
}
in.ignore(8192,'\n');
nch = strlen(bd);
} else {
strcpy(bd,branchDescriptor);
}
//parse the branch descriptor and create a branch for each element
//separated by ":"
void *address = &bd[90000];
char *bdcur = bd;
TString desc="", olddesc="F";
while (bdcur) {
char *colon = strchr(bdcur,':');
if (colon) *colon = 0;
strcpy(bdname,bdcur);
char *slash = strchr(bdname,'/');
if (slash) {
*slash = 0;
desc = bdcur;
olddesc = slash+1;
} else {
desc = Form("%s/%s",bdname,olddesc.Data());
}
char *bracket = strchr(bdname,'[');
if (bracket) {
*bracket = 0;
}
branch = new TBranch(this,bdname,address,desc.Data(),32000);
if (branch->IsZombie()) {
delete branch;
Warning("ReadFile","Illegal branch definition: %s",bdcur);
} else {
fBranches.Add(branch);
branch->SetAddress(0);
}
if (!colon)break;
bdcur = colon+1;
}
delete [] bdname;
delete [] bd;
}
//loop on all lines in the file
nbranches = fBranches.GetEntries();
Bool_t status = kTRUE;
Long64_t nlines = 0;
while(1) {
while (isspace(in.peek())) {
in.get();
}
if ( in.peek() != '#' ) {
//loop on branches and read the branch values into their buffer
for (Int_t i=0;i<nbranches;i++) {
branch = (TBranch*)fBranches.At(i);
TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
leaf->ReadValue(in);
if (in.eof()) return nlines;
status = in.good();
if (!status) {
Warning("ReadFile","Illegal value after line %lld\n",nlines);
in.clear();
break;
}
}
//we are now ready to fill the tree
if (status) {
Fill();
nlines++;
}
}
in.ignore(8192,'\n');
}
return nlines;
}
//______________________________________________________________________________
void TTree::RecursiveRemove(TObject *obj)
{
// Make sure that obj (which is being deleted or will soon be) is no
// longer referenced by this TTree.
if (obj == fEventList) {
fEventList = 0;
}
if (obj == fEntryList) {
fEntryList = 0;
}
if (fUserInfo) {
fUserInfo->RecursiveRemove(obj);
}
if (fPlayer == obj) {
fPlayer = 0;
}
if (fTreeIndex == obj) {
fTreeIndex = 0;
}
if (fAliases) {
fAliases->RecursiveRemove(obj);
}
if (fFriends) {
fFriends->RecursiveRemove(obj);
}
}
//______________________________________________________________________________
void TTree::Refresh()
{
// Refresh contents of this tree and its branches from the current status on disk.
//
// One can call this function in case the tree file is being
// updated by another process.
if (!fDirectory->GetFile()) {
return;
}
fDirectory->ReadKeys();
fDirectory->Remove(this);
TTree* tree; fDirectory->GetObject(GetName(),tree);
if (!tree) {
return;
}
//copy info from tree header into this Tree
fEntries = tree->fEntries;
fTotBytes = tree->fTotBytes;
fZipBytes = tree->fZipBytes;
fSavedBytes = tree->fSavedBytes;
fTotalBuffers = tree->fTotalBuffers;
//loop on all branches and update them
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
branch->Refresh(tree->GetBranch(branch->GetName()));
}
fDirectory->Remove(tree);
fDirectory->Append(this);
delete tree;
tree = 0;
}
//______________________________________________________________________________
void TTree::RemoveFriend(TTree* oldFriend)
{
// Remove a friend from the list of friends.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kRemoveFriend & fFriendLockStatus) {
return;
}
if (!fFriends) {
return;
}
TFriendLock lock(this, kRemoveFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* friend_t = fe->GetTree();
if (friend_t == oldFriend) {
fFriends->Remove(fe);
delete fe;
fe = 0;
}
}
}
//______________________________________________________________________________
void TTree::Reset(Option_t* option)
{
// Reset baskets, buffers and entries count in all branches and leaves.
fNotify = 0;
fEntries = 0;
fTotBytes = 0;
fZipBytes = 0;
fSavedBytes = 0;
fTotalBuffers = 0;
fChainOffset = 0;
fReadEntry = -1;
delete fTreeIndex;
fTreeIndex = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->Reset(option);
}
if (fBranchRef) {
fBranchRef->Reset();
}
}
//______________________________________________________________________________
void TTree::ResetBranchAddress(TBranch *br)
{
// Tell all of our branches to set their addresses to zero.
//
// Note: If any of our branches own any objects, they are deleted.
if (br && br->GetTree()) {
br->ResetAddress();
}
}
//______________________________________________________________________________
void TTree::ResetBranchAddresses()
{
// Tell all of our branches to drop their current objects and allocate new ones.
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
branch->ResetAddress();
}
}
//______________________________________________________________________________
Long64_t TTree::Scan(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Loop over tree entries and print entries passing selection.
//
// If varexp is 0 (or "") then print only first 8 columns.
// If varexp = "*" print all columns.
// Otherwise a columns selection can be made using "var1:var2:var3".
// See TTreePlayer::Scan for more information
//
GetPlayer();
if (fPlayer) {
return fPlayer->Scan(varexp, selection, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
Bool_t TTree::SetAlias(const char* aliasName, const char* aliasFormula)
{
// Set a tree variable alias.
//
// Set an alias for an expression/formula based on the tree 'variables'.
//
// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
// TTree::Scan, TTreeViewer) and will be evaluated as the content of
// 'aliasFormula'.
// If the content of 'aliasFormula' only contains symbol names, periods and
// array index specification (for example event.fTracks[3]), then
// the content of 'aliasName' can be used as the start of symbol.
//
// If the alias 'aliasName' already existed, it is replaced by the new
// value.
//
// When being used, the alias can be preceded by an eventual 'Friend Alias'
// (see TTree::GetFriendAlias)
//
// Return true if it was added properly.
//
// For example:
// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
// tree->Draw("y2-y1:x2-x1");
//
// tree->SetAlias("theGoodTrack","event.fTracks[3]");
// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
if (!aliasName || !aliasFormula) {
return kFALSE;
}
if (!strlen(aliasName) || !strlen(aliasFormula)) {
return kFALSE;
}
if (!fAliases) {
fAliases = new TList;
} else {
TNamed* oldHolder = (TNamed*) fAliases->FindObject(aliasName);
if (oldHolder) {
oldHolder->SetTitle(aliasFormula);
return kTRUE;
}
}
TNamed* holder = new TNamed(aliasName, aliasFormula);
fAliases->Add(holder);
return kTRUE;
}
//_______________________________________________________________________
void TTree::SetAutoFlush(Long64_t autof)
{
// This function may be called at the start of a program to change
// the default value for fAutoFlush.
//
// CASE 1 : autof > 0
// ------------------
// autof is the number of consecutive entries after which TTree::Fill will
// flush all branch buffers to disk.
//
// CASE 2 : autof < 0
// ------------------
// When filling the Tree the branch buffers will be flushed to disk when
// more than autof bytes have been written to the file. At the first FlushBaskets
// TTree::Fill will replace fAutoFlush by the current value of fEntries.
//
// Calling this function with autof<0 is interesting when it is hard to estimate
// the size of one entry. This value is also independent of the Tree.
//
// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
// the first AutoFlush will be done when 30 MBytes of data are written to the file.
//
// CASE 3 : autof = 0
// ------------------
// The AutoFlush mechanism is disabled.
//
// Flushing the buffers at regular intervals optimize the location of
// consecutive entries on the disk.
fAutoFlush = autof;
}
//_______________________________________________________________________
void TTree::SetAutoSave(Long64_t autos)
{
//This function may be called at the start of a program to change
//the default value for fAutoSave(300000000, ie 300 MBytes).
//When filling the Tree the branch buffers as well as the Tree header
//will be flushed to disk when more than fAutoSave bytes have been written to the file.
//In case of a program crash, it will be possible to recover the data in the Tree
//up to the last AutoSave point.
fAutoSave = autos;
}
//_______________________________________________________________________
void TTree::SetBasketSize(const char* bname, Int_t buffsize)
{
// Set a branch's basket size.
//
// bname is the name of a branch.
// if bname="*", apply to all branches.
// if bname="xxx*", apply to all branches with name starting with xxx
// see TRegexp for wildcarding options
// buffsize = branc basket size
//
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname, kTRUE);
Int_t nb = 0;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
continue;
}
nb++;
branch->SetBasketSize(buffsize);
}
if (!nb) {
Error("SetBasketSize", "unknown branch -> '%s'", bname);
}
}
//_______________________________________________________________________
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
{
// Change branch address, dealing with clone trees properly.
// See TTree::CheckBranchAddressType for the semantic of the return value.
//
// Note: See the comments in TBranchElement::SetAddress() for the
// meaning of the addr parameter.
//
TBranch* branch = GetBranch(bname);
if (!branch) {
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kNoCheck;
}
if (ptr) {
*ptr = branch;
}
if (fClones) {
void* oldAddr = branch->GetAddress();
TIter next(fClones);
TTree* clone = 0;
while ((clone = (TTree*) next())) {
TBranch* cloneBr = clone->GetBranch(bname);
if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
cloneBr->SetAddress(addr);
}
}
}
branch->SetAddress(addr);
return kVoidPtr;
}
//_______________________________________________________________________
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
// Verify the validity of the type of addr before calling SetBranchAddress.
// See TTree::CheckBranchAddressType for the semantic of the return value.
//
// Note: See the comments in TBranchElement::SetAddress() for the
// meaning of the addr parameter.
//
return SetBranchAddress(bname, addr, 0, ptrClass, datatype, isptr);
}
//_______________________________________________________________________
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
// Verify the validity of the type of addr before calling SetBranchAddress.
// See TTree::CheckBranchAddressType for the semantic of the return value.
//
// Note: See the comments in TBranchElement::SetAddress() for the
// meaning of the addr parameter.
//
TBranch* branch = GetBranch(bname);
if (!branch) {
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kMissingBranch;
}
if (ptr) {
*ptr = branch;
}
Int_t res = CheckBranchAddressType(branch, ptrClass, datatype, isptr);
SetBranchAddress(bname, addr);
return res;
}
//_______________________________________________________________________
void TTree::SetBranchStatus(const char* bname, Bool_t status, UInt_t* found)
{
// Set branch status to Process or DoNotProcess.
//
// When reading a Tree, by default, all branches are read.
// One can speed up considerably the analysis phase by activating
// only the branches that hold variables involved in a query.
//
// bname is the name of a branch.
// if bname="*", apply to all branches.
// if bname="xxx*", apply to all branches with name starting with xxx
// see TRegexp for wildcarding options
// status = 1 branch will be processed
// = 0 branch will not be processed
// Example:
// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
// when doing T.GetEntry(i) all branches are read for entry i.
// to read only the branches c and e, one can do
// T.SetBranchStatus("*",0); //disable all branches
// T.SetBranchStatus("c",1);
// T.setBranchStatus("e",1);
// T.GetEntry(i);
//
// WARNING! WARNING! WARNING!
// SetBranchStatus is matching the branch based on regular expression match
// of the branch 'name' and not on the branch hierarchy!
// In order to be able to selectively enable a top level object that is 'split'
// you need to make sure the name of the top level branch is prefixed to the
// sub-branches' name(by adding a dot ('.') at the end of the Branch creation
// and use the corresponding regular expression.
//
// I.e If your Tree has been created in split mode with a parent branch "parent."
// (note the trailing dot).
// T.SetBranchStatus("parent",1);
// will not activate the sub-branches of "parent". You should do:
// T.SetBranchStatus("parent*",1);
//
// Without the trailing dot in the branch creation you have no choice but to
// call SetBranchStatus explicitly for each of the sub branches.
//
//
// An alternative to this function is to read directly and only
// the interesting branches. Example:
// TBranch *brc = T.GetBranch("c");
// TBranch *bre = T.GetBranch("e");
// brc->GetEntry(i);
// bre->GetEntry(i);
//
// If found is not 0, the number of branch(es) found matching the regular
// expression is returned in *found AND the error message 'unknown branch'
// is suppressed.
// We already have been visited while recursively looking
// through the friends tree, let return
if (kSetBranchStatus & fFriendLockStatus) {
return;
}
TBranch *branch, *bcount, *bson;
TLeaf *leaf, *leafcount;
Int_t i,j;
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname,kTRUE);
Int_t nb = 0;
// first pass, loop on all branches
// for leafcount branches activate/deactivate in function of status
for (i=0;i<nleaves;i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
TString longname;
longname.Form("%s.%s",GetName(),branch->GetName());
if (strcmp(bname,branch->GetName())
&& longname != bname
&& s.Index(re) == kNPOS) continue;
}
nb++;
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
if (status) bcount->ResetBit(kDoNotProcess);
else bcount->SetBit(kDoNotProcess);
}
}
if (nb==0 && strchr(bname,'*')==0) {
branch = GetBranch(bname);
if (branch) {
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
++nb;
}
}
//search in list of friends
UInt_t foundInFriend = 0;
if (fFriends) {
TFriendLock lock(this,kSetBranchStatus);
TIter nextf(fFriends);
TFriendElement *fe;
TString name;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t==0) continue;
// If the alias is present replace it with the real name.
char *subbranch = (char*)strstr(bname,fe->GetName());
if (subbranch!=bname) subbranch = 0;
if (subbranch) {
subbranch += strlen(fe->GetName());
if ( *subbranch != '.' ) subbranch = 0;
else subbranch ++;
}
if (subbranch) {
name.Form("%s.%s",t->GetName(),subbranch);
} else {
name = bname;
}
t->SetBranchStatus(name,status, &foundInFriend);
}
}
if (!nb && !foundInFriend) {
if (found==0) Error("SetBranchStatus", "unknown branch -> %s", bname);
return;
}
if (found) *found = nb + foundInFriend;
// second pass, loop again on all branches
// activate leafcount branches for active branches only
for (i = 0; i < nleaves; i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
if (!branch->TestBit(kDoNotProcess)) {
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
bcount->ResetBit(kDoNotProcess);
}
} else {
//Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
Int_t nbranches = branch->GetListOfBranches()->GetEntries();
for (j=0;j<nbranches;j++) {
bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
if (!bson) continue;
if (!bson->TestBit(kDoNotProcess)) {
if (bson->GetNleaves() <= 0) continue;
branch->ResetBit(kDoNotProcess);
break;
}
}
}
}
}
//______________________________________________________________________________
void TTree::SetBranchStyle(Int_t style)
{
// Set the current branch style. (static function)
//
// style = 0 old Branch
// style = 1 new Bronch
fgBranchStyle = style;
}
//______________________________________________________________________________
void TTree::SetCacheSize(Long64_t cacheSize)
{
// Set maximum size of the file cache .
// if cachesize = 0 the existing cache (if any) is deleted.
// if cachesize = -1 (default) it is set to the AutoFlush value when writing
// the Tree (default is 30 MBytes).
// WARNING: Currently only ONE TTree object can be 'cached' per TFile object.
// This call disable the cache for the other TTree objects read from the same
// TFile object as this TTree (The SetCacheSize called __last__ wins).
// To cache multiple TTree objects in the same ROOT file, you must create
// one TFile object per TTree object.
if (cacheSize < 0) {
if (fAutoFlush < 0) cacheSize = -fAutoFlush;
else cacheSize = Long64_t(1.5*fAutoFlush*fZipBytes/(fEntries+1));
}
TFile* file = GetCurrentFile();
if (!file) {
fCacheSize = cacheSize;
return;
}
TFileCacheRead* pf = file->GetCacheRead();
if (pf) {
if (cacheSize == fCacheSize) {
return;
}
delete pf;
pf = 0;
if (cacheSize == 0) {
file->SetCacheRead(0);
fCacheSize=0;
return;
}
}
fCacheSize = cacheSize;
if (cacheSize == 0) {
return;
}
if(TTreeCacheUnzip::IsParallelUnzip() && file->GetCompressionLevel() > 0)
new TTreeCacheUnzip(this, cacheSize);
else
new TTreeCache(this, cacheSize);
}
//______________________________________________________________________________
void TTree::SetCacheEntryRange(Long64_t first, Long64_t last)
{
//interface to TTreeCache to set the cache entry range
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->SetEntryRange(first,last);
}
//______________________________________________________________________________
void TTree::SetCacheLearnEntries(Int_t n)
{
//interface to TTreeCache to set the number of entries for the learning phase
TTreeCache::SetLearnEntries(n);
}
//______________________________________________________________________________
void TTree::SetCircular(Long64_t maxEntries)
{
// Enable/Disable circularity for this tree.
//
// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
// per branch in memory.
// Note that when this function is called (maxEntries>0) the Tree
// must be empty or having only one basket per branch.
// if maxEntries <= 0 the tree circularity is disabled.
//
// NOTE 1:
// Circular Trees are interesting in online real time environments
// to store the results of the last maxEntries events.
// NOTE 2:
// Calling SetCircular with maxEntries <= 0 is necessary before
// merging circular Trees that have been saved on files.
// NOTE 3:
// SetCircular with maxEntries <= 0 is automatically called
// by TChain::Merge
// NOTE 4:
// A circular Tree can still be saved in a file. When read back,
// it is still a circular Tree and can be filled again.
if (maxEntries <= 0) {
// Disable circularity.
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
ResetBit(kCircular);
//in case the Tree was originally created in gROOT, the branch
//compression level was set to -1. If the Tree is now associated to
//a file, reset the compression level to the file compression level
if (fDirectory) {
TFile* bfile = fDirectory->GetFile();
Int_t compress = 1;
if (bfile) {
compress = bfile->GetCompressionLevel();
}
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->SetCompressionLevel(compress);
}
}
} else {
// Enable circularity.
fMaxEntries = maxEntries;
SetBit(kCircular);
}
}
//______________________________________________________________________________
void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
{
// Set the debug level and the debug range.
//
// For entries in the debug range, the functions TBranchElement::Fill
// and TBranchElement::GetEntry will print the number of bytes filled
// or read for each branch.
fDebug = level;
fDebugMin = min;
fDebugMax = max;
}
//______________________________________________________________________________
void TTree::SetDefaultEntryOffsetLen(Int_t newdefault, Bool_t updateExisting)
{
// Update the default value for the branch's fEntryOffsetLen.
// If updateExisting is true, also update all the existing branches.
// If newdefault is less than 10, the new default value will be 10.
if (newdefault < 10) {
newdefault = 10;
}
fDefaultEntryOffsetLen = newdefault;
if (updateExisting) {
TIter next( GetListOfBranches() );
TBranch *b;
while ( ( b = (TBranch*)next() ) ) {
b->SetEntryOffsetLen( newdefault, kTRUE );
}
if (fBranchRef) {
fBranchRef->SetEntryOffsetLen( newdefault, kTRUE );
}
}
}
//______________________________________________________________________________
void TTree::SetDirectory(TDirectory* dir)
{
// Change the tree's directory.
//
// Remove reference to this tree from current directory and
// add reference to new directory dir. The dir parameter can
// be 0 in which case the tree does not belong to any directory.
//
if (fDirectory == dir) {
return;
}
if (fDirectory) {
fDirectory->Remove(this);
}
fDirectory = dir;
if (fDirectory) {
fDirectory->Append(this);
}
TFile* file = 0;
if (fDirectory) {
file = fDirectory->GetFile();
}
if (fBranchRef) {
fBranchRef->SetFile(file);
}
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->SetFile(file);
}
}
//_______________________________________________________________________
Long64_t TTree::SetEntries(Long64_t n)
{
// Change number of entries in the tree.
//
// If n >= 0, set number of entries in the tree = n.
//
// If n < 0, set number of entries in the tree to match the
// number of entries in each branch. (default for n is -1)
//
// This function should be called only when one fills each branch
// independently via TBranch::Fill without calling TTree::Fill.
// Calling TTree::SetEntries() make sense only if the number of entries
// in each branch is identical, a warning is issued otherwise.
// The function returns the number of entries.
//
// case 1 : force number of entries to n
if (n >= 0) {
fEntries = n;
return n;
}
// case 2; compute the number of entries from the number of entries in the branches
TBranch* b = 0;
Long64_t nMin = 99999999;
Long64_t nMax = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())){
Long64_t n2 = b->GetEntries();
if (n2 < nMin) {
nMin = n2;
}
if (n2 > nMax) {
nMax = n2;
}
}
if (nMin != nMax) {
Warning("SetEntries", "Tree branches have different numbers of entries, with %lld maximum.", nMax);
}
fEntries = nMax;
return fEntries;
}
//_______________________________________________________________________
void TTree::SetEntryList(TEntryList *enlist, Option_t * /*opt*/)
{
//Set an EntryList
if (fEntryList) {
//check if the previous entry list is owned by the tree
if (fEntryList->TestBit(kCanDelete)){
delete fEntryList;
}
}
fEventList = 0;
if (!enlist) {
fEntryList = 0;
return;
}
fEntryList = enlist;
fEntryList->SetTree(this);
}
//_______________________________________________________________________
void TTree::SetEventList(TEventList *evlist)
{
//This function transfroms the given TEventList into a TEntryList
//The new TEntryList is owned by the TTree and gets deleted when the tree
//is deleted. This TEntryList can be returned by GetEntryList() function.
fEventList = evlist;
if (fEntryList){
if (fEntryList->TestBit(kCanDelete)) {
TEntryList *tmp = fEntryList;
fEntryList = 0; // Avoid problem with RecursiveRemove.
delete tmp;
} else {
fEntryList = 0;
}
}
if (!evlist) {
fEntryList = 0;
fEventList = 0;
return;
}
fEventList = evlist;
char enlistname[100];
sprintf(enlistname, "%s_%s", evlist->GetName(), "entrylist");
fEntryList = new TEntryList(enlistname, evlist->GetTitle());
fEntryList->SetDirectory(0); // We own this.
Int_t nsel = evlist->GetN();
fEntryList->SetTree(this);
Long64_t entry;
for (Int_t i=0; i<nsel; i++){
entry = evlist->GetEntry(i);
fEntryList->Enter(entry);
}
fEntryList->SetReapplyCut(evlist->GetReapplyCut());
fEntryList->SetBit(kCanDelete, kTRUE);
}
//_______________________________________________________________________
void TTree::SetEstimate(Long64_t n)
{
// Set number of entries to estimate variable limits.
if (n <= 0) {
n = 10000;
}
fEstimate = n;
GetPlayer();
if (fPlayer) {
fPlayer->SetEstimate(n);
}
}
//_______________________________________________________________________
void TTree::SetFileNumber(Int_t number)
{
// Set fFileNumber to number.
// fFileNumber is used by TTree::Fill to set the file name
// for a new file to be created when the current file exceeds fgTreeMaxSize.
// (see TTree::ChangeFile)
// if fFileNumber=10, the new file name will have a suffix "_11",
// ie, fFileNumber is incremented before setting the file name
if (fFileNumber < 0) {
Warning("SetFileNumber", "file number must be positive. Set to 0");
fFileNumber = 0;
return;
}
fFileNumber = number;
}
//______________________________________________________________________________
void TTree::SetMaxTreeSize(Long64_t maxsize)
{
// Set the maximum size of a Tree file (static function).
//
// In TTree::Fill, when the file has a size > fgMaxTreeSize,
// the function closes the current file and starts writing into
// a new file with a name of the style "file_1.root" if the original
// requested file name was "file.root".
//
fgMaxTreeSize = maxsize;
}
//______________________________________________________________________________
void TTree::SetName(const char* name)
{
// Change the name of this tree.
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update the hashlist if we change the name.
if (fDirectory) {
fDirectory->Remove(this);
}
// This changes our hash value.
fName = name;
if (fDirectory) {
fDirectory->Append(this);
}
}
//______________________________________________________________________________
void TTree::SetObject(const char* name, const char* title)
{
// Change the name and title of this tree.
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update the hashlist if we change the name
if (fDirectory) {
fDirectory->Remove(this);
}
// This changes our hash value.
fName = name;
fTitle = title;
if (fDirectory) {
fDirectory->Append(this);
}
}
//______________________________________________________________________________
void TTree::SetParallelUnzip(Bool_t opt, Float_t RelSize)
{
//enable or disable parallel unzipping of Tree buffers
if (opt) TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);
else TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kDisable);
if (RelSize > 0)
TTreeCacheUnzip::SetUnzipRelBufferSize(RelSize);
}
//______________________________________________________________________________
void TTree::SetTreeIndex(TVirtualIndex* index)
{
// The current TreeIndex is replaced by the new index.
// Note that this function does not delete the previous index.
// This gives the possibility to play with more than one index, e.g.,
// TVirtualIndex* oldIndex = tree.GetTreeIndex();
// tree.SetTreeIndex(newIndex);
// tree.Draw();
// tree.SetTreeIndex(oldIndex);
// tree.Draw(); etc
if (fTreeIndex) {
fTreeIndex->SetTree(0);
}
fTreeIndex = index;
}
//______________________________________________________________________________
void TTree::SetWeight(Double_t w, Option_t*)
{
// Set tree weight.
//
// The weight is used by TTree::Draw to automatically weight each
// selected entry in the resulting histogram.
//
// For example the equivalent of:
//
// T.Draw("x", "w")
//
// is:
//
// T.SetWeight(w);
// T.Draw("x");
//
// This function is redefined by TChain::SetWeight. In case of a
// TChain, an option "global" may be specified to set the same weight
// for all trees in the TChain instead of the default behaviour
// using the weights of each tree in the chain (see TChain::SetWeight).
fWeight = w;
}
//______________________________________________________________________________
void TTree::Show(Long64_t entry, Int_t lenmax)
{
// Print values of all active leaves for entry.
//
// if entry==-1, print current entry (default)
// if a leaf is an array, a maximum of lenmax elements is printed.
//
if (entry != -1) {
Int_t ret = LoadTree(entry);
if (ret == -2) {
Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
return;
} else if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
}
ret = GetEntry(entry);
if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
} else if (ret == 0) {
Error("Show()", "Cannot read entry %lld (no data read)", entry);
return;
}
}
printf("======> EVENT:%lld\n", fReadEntry);
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
Int_t ltype;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (branch->TestBit(kDoNotProcess)) {
continue;
}
Int_t len = leaf->GetLen();
if (len <= 0) {
continue;
}
len = TMath::Min(len, lenmax);
if (leaf->IsA() == TLeafElement::Class()) {
leaf->PrintValue(lenmax);
continue;
}
if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
continue;
}
ltype = 10;
if (leaf->IsA() == TLeafF::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafD::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafC::Class()) {
len = 1;
ltype = 5;
};
printf(" %-15s = ", leaf->GetName());
for (Int_t l = 0; l < len; l++) {
leaf->PrintValue(l);
if (l == (len - 1)) {
printf("\n");
continue;
}
printf(", ");
if ((l % ltype) == 0) {
printf("\n ");
}
}
}
}
//______________________________________________________________________________
void TTree::StartViewer()
{
// Start the TTreeViewer on this tree.
//
// ww is the width of the canvas in pixels
// wh is the height of the canvas in pixels
GetPlayer();
if (fPlayer) {
fPlayer->StartViewer(600, 400);
}
}
//______________________________________________________________________________
void TTree::StopCacheLearningPhase()
{
// stop the cache learning phase
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = (TTreeCache*)f->GetCacheRead();
if (tc) tc->StopLearningPhase();
}
//______________________________________________________________________________
void TTree::Streamer(TBuffer& b)
{
// Stream a class object.
if (b.IsReading()) {
UInt_t R__s, R__c;
gTree = this;
fDirectory = 0;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 4) {
b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
if (fTreeIndex) {
fTreeIndex->SetTree(this);
}
if (fIndex.fN) {
Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
fIndex.Set(0);
fIndexValues.Set(0);
}
if (fEstimate <= 10000) {
fEstimate = 1000000;
}
fCacheSize = fAutoFlush;
ResetBit(kMustCleanup);
return;
}
//====process old versions before automatic schema evolution
Stat_t djunk;
Int_t ijunk;
TNamed::Streamer(b);
TAttLine::Streamer(b);
TAttFill::Streamer(b);
TAttMarker::Streamer(b);
b >> fScanField;
b >> ijunk; fMaxEntryLoop = (Long64_t)ijunk;
b >> ijunk; fMaxVirtualSize = (Long64_t)ijunk;
b >> djunk; fEntries = (Long64_t)djunk;
b >> djunk; fTotBytes = (Long64_t)djunk;
b >> djunk; fZipBytes = (Long64_t)djunk;
b >> ijunk; fAutoSave = (Long64_t)ijunk;
b >> ijunk; fEstimate = (Long64_t)ijunk;
if (fEstimate <= 10000) fEstimate = 1000000;
fBranches.Streamer(b);
fLeaves.Streamer(b);
fSavedBytes = fTotBytes;
if (R__v > 1) fIndexValues.Streamer(b);
if (R__v > 2) fIndex.Streamer(b);
if (R__v > 3) {
TList OldInfoList;
OldInfoList.Streamer(b);
OldInfoList.Delete();
}
fDefaultEntryOffsetLen = 1000;
ResetBit(kMustCleanup);
b.CheckByteCount(R__s, R__c, TTree::IsA());
//====end of old versions
} else {
if (fBranchRef) {
fBranchRef->Clear();
}
b.WriteClassBuffer(TTree::Class(), this);
}
}
//______________________________________________________________________________
Int_t TTree::UnbinnedFit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
// Unbinned fit of one or more variable(s) from a tree.
//
// funcname is a TF1 function.
//
// See TTree::Draw for explanations of the other parameters.
//
// Fit the variable varexp using the function funcname using the
// selection cuts given by selection.
//
// The list of fit options is given in parameter option.
// option = "Q" Quiet mode (minimum printing)
// = "V" Verbose mode (default is between Q and V)
// = "E" Perform better Errors estimation using Minos technique
// = "M" More. Improve fit results
//
// You can specify boundary limits for some or all parameters via
// func->SetParLimits(p_number, parmin, parmax);
// if parmin>=parmax, the parameter is fixed
// Note that you are not forced to fix the limits for all parameters.
// For example, if you fit a function with 6 parameters, you can do:
// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
// func->SetParLimits(4,-10,-4);
// func->SetParLimits(5, 1,1);
// With this setup, parameters 0->3 can vary freely
// Parameter 4 has boundaries [-10,-4] with initial value -8
// Parameter 5 is fixed to 100.
//
// For the fit to be meaningful, the function must be self-normalized.
//
// i.e. It must have the same integral regardless of the parameter
// settings. Otherwise the fit will effectively just maximize the
// area.
//
// It is mandatory to have a normalization variable
// which is fixed for the fit. e.g.
//
// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
// f1->SetParameters(1, 3.1, 0.01);
// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
// //
//
// 1, 2 and 3 Dimensional fits are supported.
// See also TTree::Fit
//
// Return status
// =============
// The function return the status of the fit in the following form
// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
// The fitResult is 0 is the fit is OK.
// The fitResult is negative in case of an error not connected with the fit.
// The number of entries used in the fit can be obtained via
// mytree.GetSelectedRows();
// If the number of selected entries is null the function returns -1
GetPlayer();
if (fPlayer) {
return fPlayer->UnbinnedFit(funcname, varexp, selection, option, nentries, firstentry);
}
return -1;
}
//______________________________________________________________________________
void TTree::UseCurrentStyle()
{
// Replace current attributes by current style.
if (gStyle->IsReading()) {
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
} else {
gStyle->SetHistFillColor(GetFillColor());
gStyle->SetHistFillStyle(GetFillStyle());
gStyle->SetHistLineColor(GetLineColor());
gStyle->SetHistLineStyle(GetLineStyle());
gStyle->SetHistLineWidth(GetLineWidth());
gStyle->SetMarkerColor(GetMarkerColor());
gStyle->SetMarkerStyle(GetMarkerStyle());
gStyle->SetMarkerSize(GetMarkerSize());
}
}
//______________________________________________________________________________
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
{
// Write this object to the current directory. For more see TObject::Write
// Write calls TTree::FlushBaskets before writing the tree.
FlushBaskets();
return TObject::Write(name, option, bufsize);
}
//______________________________________________________________________________
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize)
{
// Write this object to the current directory. For more see TObject::Write
// If option & kFlushBasket, call FlushBasket before writing the tree.
return ((const TTree*)this)->Write(name, option, bufsize);
}
//////////////////////////////////////////////////////////////////////////
// //
// TTreeFriendLeafIter //
// //
// Iterator on all the leaves in a TTree and its friend //
// //
//////////////////////////////////////////////////////////////////////////
ClassImp(TTreeFriendLeafIter)
//______________________________________________________________________________
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTree* tree, Bool_t dir)
: fTree(const_cast<TTree*>(tree))
, fLeafIter(0)
, fTreeIter(0)
, fDirection(dir)
{
// Create a new iterator. By default the iteration direction
// is kIterForward. To go backward use kIterBackward.
}
//______________________________________________________________________________
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTreeFriendLeafIter& iter)
: TIterator(iter)
, fTree(iter.fTree)
, fLeafIter(0)
, fTreeIter(0)
, fDirection(iter.fDirection)
{
// Copy constructor. Does NOT copy the 'cursor' location!
}
//______________________________________________________________________________
TIterator& TTreeFriendLeafIter::operator=(const TIterator& rhs)
{
// Overridden assignment operator. Does NOT copy the 'cursor' location!
if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
const TTreeFriendLeafIter &rhs1 = (const TTreeFriendLeafIter &)rhs;
fDirection = rhs1.fDirection;
}
return *this;
}
//______________________________________________________________________________
TTreeFriendLeafIter& TTreeFriendLeafIter::operator=(const TTreeFriendLeafIter& rhs)
{
// Overridden assignment operator. Does NOT copy the 'cursor' location!
if (this != &rhs) {
fDirection = rhs.fDirection;
}
return *this;
}
//______________________________________________________________________________
TObject* TTreeFriendLeafIter::Next()
{
// Go the next friend element
if (!fTree) return 0;
TObject * next;
TTree * nextTree;
if (!fLeafIter) {
TObjArray *list = fTree->GetListOfLeaves();
if (!list) return 0; // Can happen with an empty chain.
fLeafIter = list->MakeIterator(fDirection);
}
next = fLeafIter->Next();
if (!next) {
if (!fTreeIter) {
TCollection * list = fTree->GetListOfFriends();
if (!list) return next;
fTreeIter = list->MakeIterator(fDirection);
}
TFriendElement * nextFriend = (TFriendElement*) fTreeIter->Next();
///nextTree = (TTree*)fTreeIter->Next();
if (nextFriend) {
nextTree = const_cast<TTree*>(nextFriend->GetTree());
if (!nextTree) return Next();
SafeDelete(fLeafIter);
fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
next = fLeafIter->Next();
}
}
return next;
}
//______________________________________________________________________________
Option_t* TTreeFriendLeafIter::GetOption() const
{
// Returns the object option stored in the list.
if (fLeafIter) return fLeafIter->GetOption();
return "";
}
|
#include <config.h>
// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "localoperator.hh"
#include <assert.h>
#include <boost/assert.hpp>
#include <dune/common/fmatrix.hh>
#include <dune/common/exceptions.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/multiscale/common/heterogenous.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
namespace Dune {
namespace Multiscale {
//! holds functionals,etc for boundary correctors to make conditional usage simpler
template <class LocalNeumann>
class BoundaryValueHelper {
typedef GDT::Functionals::L2Face<LocalNeumann, CommonTraits::GdtVectorType, MsFEMTraits::LocalSpaceType>
NeumannFunctional;
typedef GDT::Functionals::L2Volume<Problem::LocalDiffusionType, CommonTraits::GdtVectorType,
MsFEMTraits::LocalSpaceType, MsFEMTraits::LocalGridViewType,
DirichletProduct> DirichletCorrectorFunctionalType;
public:
BoundaryValueHelper(const DMP::ProblemContainer& problem, const MsFEMTraits::LocalSpaceType& localSpace,
const Problem::LocalDiffusionType& local_diffusion_operator,
MsFEMTraits::LocalSolutionVectorType& allLocalRHS, std::size_t coarseBaseFunc)
: localSpace_(localSpace)
, dirichletExtensionLocal(localSpace_, "dirichletExtension")
, local_neumann(problem.getNeumannData().transfer<MsFEMTraits::LocalEntityType>())
, neumann_functional(local_neumann, allLocalRHS[coarseBaseFunc]->vector(), localSpace_)
, dl_corrector_functional(problem.getDiffusion(), dirichletExtensionLocal, local_diffusion_operator)
, dirichlet_corrector(local_diffusion_operator, allLocalRHS[++coarseBaseFunc]->vector(), localSpace_,
dl_corrector_functional)
, problem_(problem) {}
void dirichlet_projection(const CommonTraits::SpaceType& coarse_space) {
GDT::SystemAssembler<CommonTraits::SpaceType> coarse_system_assembler(coarse_space);
const auto& dirichlet_data = problem_.getDirichletData();
CommonTraits::DiscreteFunctionType dirichletExtensionCoarse(coarse_space, "Dirichlet Extension Coarse");
GDT::Operators::DirichletProjectionLocalizable<CommonTraits::GridViewType, Problem::DirichletDataBase,
CommonTraits::DiscreteFunctionType>
coarse_dirichlet_projection_operator(coarse_space.grid_view(), problem_.getModelData().boundaryInfo(),
dirichlet_data, dirichletExtensionCoarse);
coarse_system_assembler.add(coarse_dirichlet_projection_operator,
new DSG::ApplyOn::BoundaryEntities<CommonTraits::GridViewType>());
coarse_system_assembler.assemble();
GDT::Operators::LagrangeProlongation<MsFEMTraits::LocalGridViewType> projection(localSpace_.grid_view());
projection.apply(dirichletExtensionCoarse, dirichletExtensionLocal);
}
void add_to(GDT::SystemAssembler<MsFEMTraits::LocalSpaceType>& system_assembler) {
system_assembler.add(neumann_functional);
system_assembler.add(dirichlet_corrector);
}
private:
const MsFEMTraits::LocalSpaceType& localSpace_;
MsFEMTraits::LocalGridDiscreteFunctionType dirichletExtensionLocal;
LocalNeumann local_neumann;
NeumannFunctional neumann_functional;
GDT::LocalFunctional::Codim0Integral<DirichletProduct> dl_corrector_functional;
DirichletCorrectorFunctionalType dirichlet_corrector;
const DMP::ProblemContainer& problem_;
};
LocalProblemOperator::LocalProblemOperator(const DMP::ProblemContainer& problem,
const CommonTraits::SpaceType& coarse_space,
const MsFEMTraits::LocalSpaceType& space)
: localSpace_(space)
, local_diffusion_operator_(problem.getDiffusion())
, coarse_space_(coarse_space)
, system_matrix_(localSpace_.mapper().size(), localSpace_.mapper().size(), EllipticOperatorType::pattern(localSpace_))
, system_assembler_(localSpace_)
, elliptic_operator_(local_diffusion_operator_, system_matrix_, localSpace_)
, dirichletConstraints_(problem.getModelData().subBoundaryInfo(), localSpace_.mapper().maxNumDofs(),
localSpace_.mapper().maxNumDofs())
#if HAVE_UMFPACK
, use_umfpack_(problem.config().get("msfem.localproblemsolver_type", std::string("umfpack")) ==
std::string("umfpack"))
#else
, use_umfpack_(false)
#endif
, problem_(problem) {
system_assembler_.add(elliptic_operator_);
}
void LocalProblemOperator::assemble_all_local_rhs(const MsFEMTraits::CoarseEntityType& coarseEntity,
MsFEMTraits::LocalSolutionVectorType& allLocalRHS) {
BOOST_ASSERT_MSG(allLocalRHS.size() > 0, "You need to preallocate the necessary space outside this function!");
const bool is_simplex_grid = DSG::is_simplex_grid(coarse_space_);
if (is_simplex_grid)
DUNE_THROW(NotImplemented, "special treatment for simplicial grids missing");
const auto numBoundaryCorrectors = is_simplex_grid ? 1u : 2u;
const auto numInnerCorrectors = allLocalRHS.size() - numBoundaryCorrectors;
typedef BoundaryValueHelper<decltype(problem_.getNeumannData().transfer<MsFEMTraits::LocalEntityType>())> BVHelper;
std::unique_ptr<BVHelper> bv_helper(nullptr);
if (coarseEntity.hasBoundaryIntersections()) {
bv_helper =
DSC::make_unique<BVHelper>(problem_, localSpace_, local_diffusion_operator_, allLocalRHS, numInnerCorrectors);
bv_helper->dirichlet_projection(coarse_space_);
}
typedef GDT::Functionals::L2Volume<Problem::LocalDiffusionType, CommonTraits::GdtVectorType,
MsFEMTraits::LocalSpaceType, MsFEMTraits::LocalGridViewType,
CoarseBasisProduct> RhsFunctionalType;
std::vector<std::unique_ptr<RhsFunctionalType>> rhs_functionals(numInnerCorrectors);
std::size_t coarseBaseFunc = 0;
const auto coarseBaseFunctionSet = coarse_space_.base_function_set(coarseEntity);
for (; coarseBaseFunc < numInnerCorrectors; ++coarseBaseFunc) {
assert(allLocalRHS[coarseBaseFunc]);
GDT::LocalFunctional::Codim0Integral<CoarseBasisProduct> local_rhs_functional(
problem_.getDiffusion(), coarseBaseFunctionSet, local_diffusion_operator_, coarseBaseFunc);
auto& rhs_vector = allLocalRHS[coarseBaseFunc]->vector();
rhs_functionals[coarseBaseFunc] =
DSC::make_unique<RhsFunctionalType>(local_diffusion_operator_, rhs_vector, localSpace_, local_rhs_functional);
system_assembler_.add(*rhs_functionals[coarseBaseFunc]);
}
if (coarseEntity.hasBoundaryIntersections())
bv_helper->add_to(system_assembler_);
system_assembler_.assemble();
// dirichlet-0 for all rhs
typedef DSG::ApplyOn::BoundaryEntities<MsFEMTraits::LocalGridViewType> OnLocalBoundaryEntities;
system_assembler_.add(dirichletConstraints_, system_matrix_, new OnLocalBoundaryEntities());
for (auto& rhs : allLocalRHS)
system_assembler_.add(dirichletConstraints_, rhs->vector(), new OnLocalBoundaryEntities());
system_assembler_.assemble();
#if HAVE_UMFPACK
if (use_umfpack_)
local_direct_inverse_ = DSC::make_unique<LocalDirectInverseType>(
system_matrix_.backend(), problem_.config().get("msfem.localproblemsolver_verbose", 0));
#endif
}
void LocalProblemOperator::apply_inverse(const MsFEMTraits::LocalGridDiscreteFunctionType& current_rhs,
MsFEMTraits::LocalGridDiscreteFunctionType& current_solution) {
if (!current_rhs.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Local MsFEM Problem RHS invalid.");
typedef BackendChooser<MsFEMTraits::LocalSpaceType>::InverseOperatorType LocalInverseOperatorType;
const LocalInverseOperatorType local_inverse(system_matrix_, current_rhs.space().communicator());
auto options = local_inverse.options(problem_.config().get("msfem.localproblemsolver_type", "umfpack"));
options["precision"] = 1;
assert(false);
options["verbose"] = problem_.config().get("msfem.localproblemsolver_verbose", "0");
{
InverseOperatorResult stat;
auto writable_rhs = current_rhs.vector().copy();
#if HAVE_UMFPACK
if (use_umfpack_)
local_direct_inverse_->apply(current_solution.vector().backend(), writable_rhs.backend(), stat);
else
#endif
local_inverse.apply(current_solution.vector(), writable_rhs, options);
}
if (!current_solution.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Current solution of the local msfem problem invalid!");
}
} // namespace Multiscale {
} // namespace Dune {
missing fix local problem solve precision
#include <config.h>
// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "localoperator.hh"
#include <assert.h>
#include <boost/assert.hpp>
#include <dune/common/fmatrix.hh>
#include <dune/common/exceptions.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/multiscale/common/heterogenous.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
namespace Dune {
namespace Multiscale {
//! holds functionals,etc for boundary correctors to make conditional usage simpler
template <class LocalNeumann>
class BoundaryValueHelper {
typedef GDT::Functionals::L2Face<LocalNeumann, CommonTraits::GdtVectorType, MsFEMTraits::LocalSpaceType>
NeumannFunctional;
typedef GDT::Functionals::L2Volume<Problem::LocalDiffusionType, CommonTraits::GdtVectorType,
MsFEMTraits::LocalSpaceType, MsFEMTraits::LocalGridViewType,
DirichletProduct> DirichletCorrectorFunctionalType;
public:
BoundaryValueHelper(const DMP::ProblemContainer& problem, const MsFEMTraits::LocalSpaceType& localSpace,
const Problem::LocalDiffusionType& local_diffusion_operator,
MsFEMTraits::LocalSolutionVectorType& allLocalRHS, std::size_t coarseBaseFunc)
: localSpace_(localSpace)
, dirichletExtensionLocal(localSpace_, "dirichletExtension")
, local_neumann(problem.getNeumannData().transfer<MsFEMTraits::LocalEntityType>())
, neumann_functional(local_neumann, allLocalRHS[coarseBaseFunc]->vector(), localSpace_)
, dl_corrector_functional(problem.getDiffusion(), dirichletExtensionLocal, local_diffusion_operator)
, dirichlet_corrector(local_diffusion_operator, allLocalRHS[++coarseBaseFunc]->vector(), localSpace_,
dl_corrector_functional)
, problem_(problem) {}
void dirichlet_projection(const CommonTraits::SpaceType& coarse_space) {
GDT::SystemAssembler<CommonTraits::SpaceType> coarse_system_assembler(coarse_space);
const auto& dirichlet_data = problem_.getDirichletData();
CommonTraits::DiscreteFunctionType dirichletExtensionCoarse(coarse_space, "Dirichlet Extension Coarse");
GDT::Operators::DirichletProjectionLocalizable<CommonTraits::GridViewType, Problem::DirichletDataBase,
CommonTraits::DiscreteFunctionType>
coarse_dirichlet_projection_operator(coarse_space.grid_view(), problem_.getModelData().boundaryInfo(),
dirichlet_data, dirichletExtensionCoarse);
coarse_system_assembler.add(coarse_dirichlet_projection_operator,
new DSG::ApplyOn::BoundaryEntities<CommonTraits::GridViewType>());
coarse_system_assembler.assemble();
GDT::Operators::LagrangeProlongation<MsFEMTraits::LocalGridViewType> projection(localSpace_.grid_view());
projection.apply(dirichletExtensionCoarse, dirichletExtensionLocal);
}
void add_to(GDT::SystemAssembler<MsFEMTraits::LocalSpaceType>& system_assembler) {
system_assembler.add(neumann_functional);
system_assembler.add(dirichlet_corrector);
}
private:
const MsFEMTraits::LocalSpaceType& localSpace_;
MsFEMTraits::LocalGridDiscreteFunctionType dirichletExtensionLocal;
LocalNeumann local_neumann;
NeumannFunctional neumann_functional;
GDT::LocalFunctional::Codim0Integral<DirichletProduct> dl_corrector_functional;
DirichletCorrectorFunctionalType dirichlet_corrector;
const DMP::ProblemContainer& problem_;
};
LocalProblemOperator::LocalProblemOperator(const DMP::ProblemContainer& problem,
const CommonTraits::SpaceType& coarse_space,
const MsFEMTraits::LocalSpaceType& space)
: localSpace_(space)
, local_diffusion_operator_(problem.getDiffusion())
, coarse_space_(coarse_space)
, system_matrix_(localSpace_.mapper().size(), localSpace_.mapper().size(), EllipticOperatorType::pattern(localSpace_))
, system_assembler_(localSpace_)
, elliptic_operator_(local_diffusion_operator_, system_matrix_, localSpace_)
, dirichletConstraints_(problem.getModelData().subBoundaryInfo(), localSpace_.mapper().maxNumDofs(),
localSpace_.mapper().maxNumDofs())
#if HAVE_UMFPACK
, use_umfpack_(problem.config().get("msfem.localproblemsolver_type", std::string("umfpack")) ==
std::string("umfpack"))
#else
, use_umfpack_(false)
#endif
, problem_(problem) {
system_assembler_.add(elliptic_operator_);
}
void LocalProblemOperator::assemble_all_local_rhs(const MsFEMTraits::CoarseEntityType& coarseEntity,
MsFEMTraits::LocalSolutionVectorType& allLocalRHS) {
BOOST_ASSERT_MSG(allLocalRHS.size() > 0, "You need to preallocate the necessary space outside this function!");
const bool is_simplex_grid = DSG::is_simplex_grid(coarse_space_);
if (is_simplex_grid)
DUNE_THROW(NotImplemented, "special treatment for simplicial grids missing");
const auto numBoundaryCorrectors = is_simplex_grid ? 1u : 2u;
const auto numInnerCorrectors = allLocalRHS.size() - numBoundaryCorrectors;
typedef BoundaryValueHelper<decltype(problem_.getNeumannData().transfer<MsFEMTraits::LocalEntityType>())> BVHelper;
std::unique_ptr<BVHelper> bv_helper(nullptr);
if (coarseEntity.hasBoundaryIntersections()) {
bv_helper =
DSC::make_unique<BVHelper>(problem_, localSpace_, local_diffusion_operator_, allLocalRHS, numInnerCorrectors);
bv_helper->dirichlet_projection(coarse_space_);
}
typedef GDT::Functionals::L2Volume<Problem::LocalDiffusionType, CommonTraits::GdtVectorType,
MsFEMTraits::LocalSpaceType, MsFEMTraits::LocalGridViewType,
CoarseBasisProduct> RhsFunctionalType;
std::vector<std::unique_ptr<RhsFunctionalType>> rhs_functionals(numInnerCorrectors);
std::size_t coarseBaseFunc = 0;
const auto coarseBaseFunctionSet = coarse_space_.base_function_set(coarseEntity);
for (; coarseBaseFunc < numInnerCorrectors; ++coarseBaseFunc) {
assert(allLocalRHS[coarseBaseFunc]);
GDT::LocalFunctional::Codim0Integral<CoarseBasisProduct> local_rhs_functional(
problem_.getDiffusion(), coarseBaseFunctionSet, local_diffusion_operator_, coarseBaseFunc);
auto& rhs_vector = allLocalRHS[coarseBaseFunc]->vector();
rhs_functionals[coarseBaseFunc] =
DSC::make_unique<RhsFunctionalType>(local_diffusion_operator_, rhs_vector, localSpace_, local_rhs_functional);
system_assembler_.add(*rhs_functionals[coarseBaseFunc]);
}
if (coarseEntity.hasBoundaryIntersections())
bv_helper->add_to(system_assembler_);
system_assembler_.assemble();
// dirichlet-0 for all rhs
typedef DSG::ApplyOn::BoundaryEntities<MsFEMTraits::LocalGridViewType> OnLocalBoundaryEntities;
system_assembler_.add(dirichletConstraints_, system_matrix_, new OnLocalBoundaryEntities());
for (auto& rhs : allLocalRHS)
system_assembler_.add(dirichletConstraints_, rhs->vector(), new OnLocalBoundaryEntities());
system_assembler_.assemble();
#if HAVE_UMFPACK
if (use_umfpack_)
local_direct_inverse_ = DSC::make_unique<LocalDirectInverseType>(
system_matrix_.backend(), problem_.config().get("msfem.localproblemsolver_verbose", 0));
#endif
}
void LocalProblemOperator::apply_inverse(const MsFEMTraits::LocalGridDiscreteFunctionType& current_rhs,
MsFEMTraits::LocalGridDiscreteFunctionType& current_solution) {
if (!current_rhs.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Local MsFEM Problem RHS invalid.");
typedef BackendChooser<MsFEMTraits::LocalSpaceType>::InverseOperatorType LocalInverseOperatorType;
const LocalInverseOperatorType local_inverse(system_matrix_, current_rhs.space().communicator());
auto options = local_inverse.options(problem_.config().get("msfem.localproblemsolver_type", "umfpack"));
options["precision"] = problem_.config().get("msfem.localproblemsolver_precision", 1e-5);
options["verbose"] = problem_.config().get("msfem.localproblemsolver_verbose", "0");
{
InverseOperatorResult stat;
auto writable_rhs = current_rhs.vector().copy();
#if HAVE_UMFPACK
if (use_umfpack_)
local_direct_inverse_->apply(current_solution.vector().backend(), writable_rhs.backend(), stat);
else
#endif
local_inverse.apply(current_solution.vector(), writable_rhs, options);
}
if (!current_solution.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Current solution of the local msfem problem invalid!");
}
} // namespace Multiscale {
} // namespace Dune {
|
// FIXME - Something hangs if PKTCTRL0==4 (fixed length packets) when
// variable-length packets are in use.
#include <stdio.h>
#include <stdexcept>
#include <boost/format.hpp>
#include <QMutexLocker>
#include <Utils.hpp>
#include "USBRadio.hpp"
#include "cc1101.h"
#include "radio_config.h"
using namespace std;
using namespace boost;
using namespace Packet;
// Timeout for control transfers, in milliseconds
static const int Control_Timeout = 1000;
USBRadio::USBRadio() {
_sequence = 0;
_printedError = false;
_device = nullptr;
_usb_context = nullptr;
libusb_init(&_usb_context);
for (int i = 0; i < NumRXTransfers; ++i) {
_rxTransfers[i] = libusb_alloc_transfer(0);
}
}
USBRadio::~USBRadio() {
if (_device) {
libusb_close(_device);
}
for (int i = 0; i < NumRXTransfers; ++i) {
libusb_free_transfer(_rxTransfers[i]);
}
libusb_exit(_usb_context);
}
bool USBRadio::open() {
libusb_device** devices = nullptr;
ssize_t numDevices = libusb_get_device_list(_usb_context, &devices);
if (numDevices < 0) {
fprintf(stderr, "libusb_get_device_list failed\n");
return false;
}
int numRadios = 0;
for (int i = 0; i < numDevices; ++i) {
struct libusb_device_descriptor desc;
int err = libusb_get_device_descriptor(devices[i], &desc);
if (err == 0 && desc.idVendor == 0x3141 && desc.idProduct == 0x0004) {
++numRadios;
int err = libusb_open(devices[i], &_device);
if (err == 0) {
break;
}
}
}
libusb_free_device_list(devices, 1);
if (!numRadios) {
if (!_printedError) {
fprintf(stderr, "USBRadio: No radio is connected\n");
_printedError = true;
}
return false;
}
if (!_device) {
if (!_printedError) {
fprintf(stderr, "USBRadio: All radios are in use\n");
_printedError = true;
}
return false;
}
if (libusb_set_configuration(_device, 1)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't set configuration\n");
_printedError = true;
}
return false;
}
if (libusb_claim_interface(_device, 0)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't claim interface\n");
_printedError = true;
}
return false;
}
configure();
// Start the receive transfers
for (int i = 0; i < NumRXTransfers; ++i) {
// Populate the required libusb_transfer fields for a bulk transfer.
libusb_fill_bulk_transfer(
_rxTransfers[i], // the transfer to populate
_device, // handle of the device that will handle the transfer
LIBUSB_ENDPOINT_IN |
2, // address of the endpoint where this transfer will be sent
_rxBuffers[i], // data buffer
Reverse_Size + 2, // length of data buffer
rxCompleted, // callback function to be invoked on transfer
// completion
this, // user data to pass to callback function
0); // timeout for the transfer in milliseconds
libusb_submit_transfer(_rxTransfers[i]);
}
_printedError = false;
return true;
}
void USBRadio::rxCompleted(libusb_transfer* transfer) {
USBRadio* radio = (USBRadio*)transfer->user_data;
if (transfer->status == LIBUSB_TRANSFER_COMPLETED &&
transfer->actual_length == Reverse_Size + 2) {
// Parse the packet and add to the list of RadioRx's
radio->handleRxData(transfer->buffer);
}
// Restart the transfer
libusb_submit_transfer(transfer);
}
void USBRadio::command(uint8_t cmd) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
2, 0, cmd, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::command control write failed");
}
}
void USBRadio::write(uint8_t reg, uint8_t value) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
1, value, reg, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::write control write failed");
}
}
uint8_t USBRadio::read(uint8_t reg) {
uint8_t value = 0;
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
3, 0, reg, &value, 1, Control_Timeout)) {
throw runtime_error("USBRadio::read control write failed");
}
return value;
}
void USBRadio::configure() {
auto_calibrate(false);
command(SIDLE);
command(SFTX);
command(SFRX);
// Write configuration.
// This is mainly for frequency, bit rate, and packetization.
for (unsigned int i = 0; i < sizeof(cc1101_regs); i += 2) {
write(cc1101_regs[i], cc1101_regs[i + 1]);
}
write(CHANNR, _channel);
auto_calibrate(true);
}
void USBRadio::auto_calibrate(bool enable) {
int flag = enable ? 1 : 0;
assert(libusb_control_transfer(
_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, 4,
flag, 0, nullptr, 0, Control_Timeout) == 0);
}
bool USBRadio::isOpen() const { return _device; }
void USBRadio::send(Packet::RadioTx& packet) {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
uint8_t forward_packet[Forward_Size];
// Build a forward packet
forward_packet[0] = _sequence;
// Unit conversions
static const float Seconds_Per_Cycle = 0.005f;
static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f;
static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f);
int offset = 1;
int slot;
for (slot = 0; slot < 6 && slot < packet.robots_size();
++slot) {
const Packet::Control& robot =
packet.robots(slot).control();
int robot_id = packet.robots(slot).uid();
float bodyVelX =
robot.xvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2);
float bodyVelY =
robot.yvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2);
float bodyVelW =
robot.avelocity() * Seconds_Per_Cycle / Radians_Per_Tick;
int outX = clamp((int)roundf(bodyVelX), -511, 511);
int outY = clamp((int)roundf(bodyVelY), -511, 511);
int outW = clamp((int)roundf(bodyVelW), -511, 511);
uint8_t kick =
static_cast<uint8_t>(robot.shootmode() == Packet::Control::KICK);
uint8_t dribbler =
max(0, min(255, static_cast<uint16_t>(robot.dvelocity()) * 2));
forward_packet[offset++] = outX & 0xff;
forward_packet[offset++] = outY & 0xff;
forward_packet[offset++] = outW & 0xff;
forward_packet[offset++] = ((outX & 0x300) >> 8) |
((outY & 0x300) >> 6) |
((outW & 0x300) >> 4);
forward_packet[offset++] = (dribbler & 0xf0) | (robot_id & 0x0f);
forward_packet[offset++] = kick;
forward_packet[offset++] =
(robot.shootmode() == Packet::Control::CHIP) |
((robot.triggermode() == Packet::Control::IMMEDIATE) << 1) |
(robot.song() << 2) | (0 /*robot.anthem()*/ << 3);
forward_packet[offset++] = 10; // robot.accel();
forward_packet[offset++] = 10; // robot.decel();
}
// Unused slots
for (; slot < 6; ++slot) {
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0x0f;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
}
// Send the forward packet
int sent = 0;
if (libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 1, forward_packet,
sizeof(forward_packet), &sent, Control_Timeout) ||
sent != sizeof(forward_packet)) {
fprintf(stderr, "USBRadio: Bulk write failed\n");
libusb_close(_device);
_device = nullptr;
}
_sequence = (_sequence + 1) & 7;
}
void USBRadio::receive() {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
// Handle USB events. This will call callbacks.
struct timeval tv = {0, 0};
libusb_handle_events_timeout(_usb_context, &tv);
}
void USBRadio::handleRxData(uint8_t* buf) {
RJ::Time rx_time = RJ::timestamp();
_reversePackets.push_back(RadioRx());
RadioRx& packet = _reversePackets.back();
packet.set_timestamp(rx_time);
packet.set_sequence((buf[0] >> 4) & 7);
packet.set_robot_id(buf[0] & 0x0f);
packet.set_rssi((int8_t)buf[1] / 2.0 - 74);
packet.set_battery(buf[2] / 10.0f);
packet.set_kicker_status(buf[3]);
// Drive motor status
for (int i = 0; i < 4; ++i) {
packet.add_motor_status(MotorStatus((buf[4] >> (i * 2)) & 3));
}
// Dribbler status
packet.add_motor_status(MotorStatus(buf[5] & 3));
// Hardware version
if (buf[5] & (1 << 4)) {
packet.set_hardware_version(RJ2008);
} else {
packet.set_hardware_version(RJ2011);
}
packet.set_ball_sense_status(BallSenseStatus((buf[5] >> 2) & 3));
packet.set_kicker_voltage(buf[6]);
#if 0
// Encoders
for (int i = 0; i < 4; ++i)
{
int high = (buf[10] >> (i * 2)) & 3;
int16_t value = buf[6 + i] | (high << 8);
if (high & 2)
{
value |= 0xfc00;
}
packet.add_encoders(value);
}
#endif
#if 0
if (buf[5] & (1 << 5))
{
// Quaternion
int16_t q0 = buf[7] | (buf[8] << 8);
int16_t q1 = buf[9] | (buf[10] << 8);
int16_t q2 = buf[11] | (buf[12] << 8);
int16_t q3 = buf[13] | (buf[14] << 8);
packet.mutable_quaternion()->set_q0(q0 / 16384.0);
packet.mutable_quaternion()->set_q1(q1 / 16384.0);
packet.mutable_quaternion()->set_q2(q2 / 16384.0);
packet.mutable_quaternion()->set_q3(q3 / 16384.0);
}
#endif
}
void USBRadio::channel(int n) {
QMutexLocker lock(&_mutex);
if (_device) {
auto_calibrate(false);
write(CHANNR, n);
command(SIDLE);
command(SRX);
auto_calibrate(true);
}
Radio::channel(n);
}
commented accel/decel
// FIXME - Something hangs if PKTCTRL0==4 (fixed length packets) when
// variable-length packets are in use.
#include <stdio.h>
#include <stdexcept>
#include <boost/format.hpp>
#include <QMutexLocker>
#include <Utils.hpp>
#include "USBRadio.hpp"
#include "cc1101.h"
#include "radio_config.h"
using namespace std;
using namespace boost;
using namespace Packet;
// Timeout for control transfers, in milliseconds
static const int Control_Timeout = 1000;
USBRadio::USBRadio() {
_sequence = 0;
_printedError = false;
_device = nullptr;
_usb_context = nullptr;
libusb_init(&_usb_context);
for (int i = 0; i < NumRXTransfers; ++i) {
_rxTransfers[i] = libusb_alloc_transfer(0);
}
}
USBRadio::~USBRadio() {
if (_device) {
libusb_close(_device);
}
for (int i = 0; i < NumRXTransfers; ++i) {
libusb_free_transfer(_rxTransfers[i]);
}
libusb_exit(_usb_context);
}
bool USBRadio::open() {
libusb_device** devices = nullptr;
ssize_t numDevices = libusb_get_device_list(_usb_context, &devices);
if (numDevices < 0) {
fprintf(stderr, "libusb_get_device_list failed\n");
return false;
}
int numRadios = 0;
for (int i = 0; i < numDevices; ++i) {
struct libusb_device_descriptor desc;
int err = libusb_get_device_descriptor(devices[i], &desc);
if (err == 0 && desc.idVendor == 0x3141 && desc.idProduct == 0x0004) {
++numRadios;
int err = libusb_open(devices[i], &_device);
if (err == 0) {
break;
}
}
}
libusb_free_device_list(devices, 1);
if (!numRadios) {
if (!_printedError) {
fprintf(stderr, "USBRadio: No radio is connected\n");
_printedError = true;
}
return false;
}
if (!_device) {
if (!_printedError) {
fprintf(stderr, "USBRadio: All radios are in use\n");
_printedError = true;
}
return false;
}
if (libusb_set_configuration(_device, 1)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't set configuration\n");
_printedError = true;
}
return false;
}
if (libusb_claim_interface(_device, 0)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't claim interface\n");
_printedError = true;
}
return false;
}
configure();
// Start the receive transfers
for (int i = 0; i < NumRXTransfers; ++i) {
// Populate the required libusb_transfer fields for a bulk transfer.
libusb_fill_bulk_transfer(
_rxTransfers[i], // the transfer to populate
_device, // handle of the device that will handle the transfer
LIBUSB_ENDPOINT_IN |
2, // address of the endpoint where this transfer will be sent
_rxBuffers[i], // data buffer
Reverse_Size + 2, // length of data buffer
rxCompleted, // callback function to be invoked on transfer
// completion
this, // user data to pass to callback function
0); // timeout for the transfer in milliseconds
libusb_submit_transfer(_rxTransfers[i]);
}
_printedError = false;
return true;
}
void USBRadio::rxCompleted(libusb_transfer* transfer) {
USBRadio* radio = (USBRadio*)transfer->user_data;
if (transfer->status == LIBUSB_TRANSFER_COMPLETED &&
transfer->actual_length == Reverse_Size + 2) {
// Parse the packet and add to the list of RadioRx's
radio->handleRxData(transfer->buffer);
}
// Restart the transfer
libusb_submit_transfer(transfer);
}
void USBRadio::command(uint8_t cmd) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
2, 0, cmd, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::command control write failed");
}
}
void USBRadio::write(uint8_t reg, uint8_t value) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
1, value, reg, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::write control write failed");
}
}
uint8_t USBRadio::read(uint8_t reg) {
uint8_t value = 0;
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
3, 0, reg, &value, 1, Control_Timeout)) {
throw runtime_error("USBRadio::read control write failed");
}
return value;
}
void USBRadio::configure() {
auto_calibrate(false);
command(SIDLE);
command(SFTX);
command(SFRX);
// Write configuration.
// This is mainly for frequency, bit rate, and packetization.
for (unsigned int i = 0; i < sizeof(cc1101_regs); i += 2) {
write(cc1101_regs[i], cc1101_regs[i + 1]);
}
write(CHANNR, _channel);
auto_calibrate(true);
}
void USBRadio::auto_calibrate(bool enable) {
int flag = enable ? 1 : 0;
assert(libusb_control_transfer(
_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, 4,
flag, 0, nullptr, 0, Control_Timeout) == 0);
}
bool USBRadio::isOpen() const { return _device; }
void USBRadio::send(Packet::RadioTx& packet) {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
uint8_t forward_packet[Forward_Size];
// Build a forward packet
forward_packet[0] = _sequence;
// Unit conversions
static const float Seconds_Per_Cycle = 0.005f;
static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f;
static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f);
int offset = 1;
int slot;
for (slot = 0; slot < 6 && slot < packet.robots_size();
++slot) {
const Packet::Control& robot =
packet.robots(slot).control();
int robot_id = packet.robots(slot).uid();
float bodyVelX =
robot.xvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2);
float bodyVelY =
robot.yvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2);
float bodyVelW =
robot.avelocity() * Seconds_Per_Cycle / Radians_Per_Tick;
int outX = clamp((int)roundf(bodyVelX), -511, 511);
int outY = clamp((int)roundf(bodyVelY), -511, 511);
int outW = clamp((int)roundf(bodyVelW), -511, 511);
uint8_t kick =
static_cast<uint8_t>(robot.shootmode() == Packet::Control::KICK);
uint8_t dribbler =
max(0, min(255, static_cast<uint16_t>(robot.dvelocity()) * 2));
forward_packet[offset++] = outX & 0xff;
forward_packet[offset++] = outY & 0xff;
forward_packet[offset++] = outW & 0xff;
forward_packet[offset++] = ((outX & 0x300) >> 8) |
((outY & 0x300) >> 6) |
((outW & 0x300) >> 4);
forward_packet[offset++] = (dribbler & 0xf0) | (robot_id & 0x0f);
forward_packet[offset++] = kick;
forward_packet[offset++] =
(robot.shootmode() == Packet::Control::CHIP) |
((robot.triggermode() == Packet::Control::IMMEDIATE) << 1) |
(robot.song() << 2) | (0 /*robot.anthem()*/ << 3);
// TODO remove, no longer used
forward_packet[offset++] = 10; // robot.accel();
forward_packet[offset++] = 10; // robot.decel();
}
// Unused slots
for (; slot < 6; ++slot) {
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0x0f;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
forward_packet[offset++] = 0;
}
// Send the forward packet
int sent = 0;
if (libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 1, forward_packet,
sizeof(forward_packet), &sent, Control_Timeout) ||
sent != sizeof(forward_packet)) {
fprintf(stderr, "USBRadio: Bulk write failed\n");
libusb_close(_device);
_device = nullptr;
}
_sequence = (_sequence + 1) & 7;
}
void USBRadio::receive() {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
// Handle USB events. This will call callbacks.
struct timeval tv = {0, 0};
libusb_handle_events_timeout(_usb_context, &tv);
}
void USBRadio::handleRxData(uint8_t* buf) {
RJ::Time rx_time = RJ::timestamp();
_reversePackets.push_back(RadioRx());
RadioRx& packet = _reversePackets.back();
packet.set_timestamp(rx_time);
packet.set_sequence((buf[0] >> 4) & 7);
packet.set_robot_id(buf[0] & 0x0f);
packet.set_rssi((int8_t)buf[1] / 2.0 - 74);
packet.set_battery(buf[2] / 10.0f);
packet.set_kicker_status(buf[3]);
// Drive motor status
for (int i = 0; i < 4; ++i) {
packet.add_motor_status(MotorStatus((buf[4] >> (i * 2)) & 3));
}
// Dribbler status
packet.add_motor_status(MotorStatus(buf[5] & 3));
// Hardware version
if (buf[5] & (1 << 4)) {
packet.set_hardware_version(RJ2008);
} else {
packet.set_hardware_version(RJ2011);
}
packet.set_ball_sense_status(BallSenseStatus((buf[5] >> 2) & 3));
packet.set_kicker_voltage(buf[6]);
#if 0
// Encoders
for (int i = 0; i < 4; ++i)
{
int high = (buf[10] >> (i * 2)) & 3;
int16_t value = buf[6 + i] | (high << 8);
if (high & 2)
{
value |= 0xfc00;
}
packet.add_encoders(value);
}
#endif
#if 0
if (buf[5] & (1 << 5))
{
// Quaternion
int16_t q0 = buf[7] | (buf[8] << 8);
int16_t q1 = buf[9] | (buf[10] << 8);
int16_t q2 = buf[11] | (buf[12] << 8);
int16_t q3 = buf[13] | (buf[14] << 8);
packet.mutable_quaternion()->set_q0(q0 / 16384.0);
packet.mutable_quaternion()->set_q1(q1 / 16384.0);
packet.mutable_quaternion()->set_q2(q2 / 16384.0);
packet.mutable_quaternion()->set_q3(q3 / 16384.0);
}
#endif
}
void USBRadio::channel(int n) {
QMutexLocker lock(&_mutex);
if (_device) {
auto_calibrate(false);
write(CHANNR, n);
command(SIDLE);
command(SRX);
auto_calibrate(true);
}
Radio::channel(n);
}
|
// @(#)root/tree:$Id$
// Author: Rene Brun 12/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
\defgroup tree Tree Library
In order to store columnar datasets, ROOT provides the TTree, TChain,
TNtuple and TNtupleD classes.
The TTree class represents a columnar dataset. Any C++ type can be stored in the
columns. The TTree has allowed to store about **1 EB** of data coming from the LHC alone:
it is demonstrated to scale and it's battle tested. It has been optimized during the years
to reduce dataset sizes on disk and to deliver excellent runtime performance.
It allows to access only part of the columns of the datasets, too.
The TNtuple and TNtupleD classes are specialisations of the TTree class which can
only hold single precision and double precision floating-point numbers respectively;
The TChain is a collection of TTrees, which can be located also in different files.
*/
/** \class TTree
\ingroup tree
A TTree represents a columnar dataset. Any C++ type can be stored in its columns.
A TTree, often called in jargon *tree*, consists of a list of independent columns or *branches*,
represented by the TBranch class.
Behind each branch, buffers are allocated automatically by ROOT.
Such buffers are automatically written to disk or kept in memory until the size stored in the
attribute fMaxVirtualSize is reached.
Variables of one branch are written to the same buffer. A branch buffer is
automatically compressed if the file compression attribute is set (default).
Branches may be written to different files (see TBranch::SetFile).
The ROOT user can decide to make one single branch and serialize one object into
one single I/O buffer or to make several branches.
Making several branches is particularly interesting in the data analysis phase,
when it is desirable to have a high reading rate and not all columns are equally interesting
## Table of contents:
- [Creating a TTree](#creatingattree)
- [Add a Column of Fundamental Types and Arrays thereof](#addcolumnoffundamentaltypes)
- [Add a Column of a STL Collection instances](#addingacolumnofstl)
- [Add a column holding an object](#addingacolumnofobjs)
- [Add a column holding a TObjectArray](#addingacolumnofobjs)
- [Fill the tree](#fillthetree)
- [Add a column to an already existing Tree](#addcoltoexistingtree)
- [An Example](#fullexample)
## <a name="creatingattree"></a>Creating a TTree
~~~ {.cpp}
TTree tree(name, title)
~~~
Creates a Tree with name and title.
Various kinds of branches can be added to a tree:
- Variables representing fundamental types, simple classes/structures or list of variables: for example for C or Fortran
structures.
- Any C++ object or collection, provided by the STL or ROOT.
In the following, the details about the creation of different types of branches are given.
## <a name="addcolumnoffundamentaltypes"></a>Add a column (`branch`) of fundamental types and arrays thereof
This strategy works also for lists of variables, e.g. to describe simple structures.
It is strongly reccomended to persistify those as objects rather than lists of leaves.
~~~ {.cpp}
auto branch = tree.Branch(branchname, address, leaflist, bufsize)
~~~
- address is the address of the first item of a structure
- leaflist is the concatenation of all the variable names and types
separated by a colon character :
The variable name and the variable type are separated by a
slash (/). The variable type must be 1 character. (Characters
after the first are legal and will be appended to the visible
name of the leaf, but have no effect.) If no type is given, the
type of the variable is assumed to be the same as the previous
variable. If the first variable does not have a type, it is
assumed of type F by default. The list of currently supported
types is given below:
- `C` : a character string terminated by the 0 character
- `B` : an 8 bit signed integer (`Char_t`)
- `b` : an 8 bit unsigned integer (`UChar_t`)
- `S` : a 16 bit signed integer (`Short_t`)
- `s` : a 16 bit unsigned integer (`UShort_t`)
- `I` : a 32 bit signed integer (`Int_t`)
- `i` : a 32 bit unsigned integer (`UInt_t`)
- `F` : a 32 bit floating point (`Float_t`)
- `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
- `D` : a 64 bit floating point (`Double_t`)
- `d` : a 24 bit truncated floating point (`Double32_t`)
- `L` : a 64 bit signed integer (`Long64_t`)
- `l` : a 64 bit unsigned integer (`ULong64_t`)
- `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
Examples:
- A int: "myVar/I"
- A float array with fixed size: "myArrfloat[42]/F"
- An double array with variable size, held by the `myvar` column: "myArrdouble[myvar]/D"
- An Double32_t array with variable size, held by the `myvar` column , with values between 0 and 16: "myArr[myvar]/d[0,10]"
- If the address points to a single numerical variable, the leaflist is optional:
~~~ {.cpp}
int value;
`tree->Branch(branchname, &value);`
~~~
- If the address points to more than one numerical variable, we strongly recommend
that the variable be sorted in decreasing order of size. Any other order will
result in a non-portable TTree (i.e. you will not be able to read it back on a
platform with a different padding strategy).
We recommend to persistify objects rather than composite leaflists.
- In case of the truncated floating point types (Float16_t and Double32_t) you can
furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
the type character. For example, for storing a variable size array `myArr` of
`Double32_t` with values within a range of `[0, 2*pi]` and the size of which is
stored in a branch called `myArrSize`, the syntax for the `leaflist` string would
be: `myArr[myArrSize]/d[0,twopi]`. Of course the number of bits could be specified,
the standard rules of opaque typedefs annotation are valid. For example, if only
18 bits were sufficient, the syntax would become: `myArr[myArrSize]/d[0,twopi,18]`
## <a name="addingacolumnofstl"></a>Adding a column of STL collection instances (e.g. std::vector, std::list, std::unordered_map)
~~~ {.cpp}
auto branch = tree.Branch( branchname, STLcollection, buffsize, splitlevel);
~~~
STLcollection is the address of a pointer to std::vector, std::list,
std::deque, std::set or std::multiset containing pointers to objects.
If the splitlevel is a value bigger than 100 (TTree::kSplitCollectionOfPointers)
then the collection will be written in split mode, e.g. if it contains objects of
any types deriving from TTrack this function will sort the objects
based on their type and store them in separate branches in split
mode.
~~~ {.cpp}
branch->SetAddress(void *address)
~~~
In case of dynamic structures changing with each entry for example, one must
redefine the branch address before filling the branch again.
This is done via the TBranch::SetAddress member function.
## <a name="addingacolumnofobjs">Add a column of objects
~~~ {.cpp}
MyClass object;
auto branch = tree.Branch(branchname, &object, bufsize, splitlevel)
~~~
Note: The 2nd parameter must be the address of a valid object.
The object must not be destroyed (i.e. be deleted) until the TTree
is deleted or TTree::ResetBranchAddress is called.
- if splitlevel=0, the object is serialized in the branch buffer.
- if splitlevel=1 (default), this branch will automatically be split
into subbranches, with one subbranch for each data member or object
of the object itself. In case the object member is a TClonesArray,
the mechanism described in case C is applied to this array.
- if splitlevel=2 ,this branch will automatically be split
into subbranches, with one subbranch for each data member or object
of the object itself. In case the object member is a TClonesArray,
it is processed as a TObject*, only one branch.
Another available syntax is the following:
~~~ {.cpp}
auto branch = tree.Branch(branchname, &p_object, bufsize, splitlevel)
auto branch = tree.Branch(branchname, className, &p_object, bufsize, splitlevel)
~~~
- p_object is a pointer to an object.
- If className is not specified, Branch uses the type of p_object to determine the
type of the object.
- If className is used to specify explicitly the object type, the className must
be of a type related to the one pointed to by the pointer. It should be either
a parent or derived class.
Note: The pointer whose address is passed to TTree::Branch must not
be destroyed (i.e. go out of scope) until the TTree is deleted or
TTree::ResetBranchAddress is called.
Note: The pointer p_object must be initialized before calling TTree::Branch
- Do either:
~~~ {.cpp}
MyDataClass* p_object = nullptr;
tree.Branch(branchname, &p_object);
~~~
- Or:
~~~ {.cpp}
auto p_object = new MyDataClass;
tree.Branch(branchname, &p_object);
~~~
Whether the pointer is set to zero or not, the ownership of the object
is not taken over by the TTree. I.e. even though an object will be allocated
by TTree::Branch if the pointer p_object is zero, the object will <b>not</b>
be deleted when the TTree is deleted.
## <a name="addingacolumnoftclonesarray">Add a column of TClonesArray instances
*It is recommended to use STL containers instead of TClonesArrays*.
~~~ {.cpp}
// clonesarray is the address of a pointer to a TClonesArray.
auto branch = tree.Branch(branchname,clonesarray, bufsize, splitlevel)
~~~
The TClonesArray is a direct access list of objects of the same class.
For example, if the TClonesArray is an array of TTrack objects,
this function will create one subbranch for each data member of
the object TTrack.
## <a name="fillthetree">Fill the Tree:
A TTree instance is filled with the invocation of the TTree::Fill method:
~~~ {.cpp}
tree.Fill()
~~~
Upon its invocation, a loop on all defined branches takes place that for each branch invokes
the TBranch::Fill method.
## <a name="addcoltoexistingtree">Add a column to an already existing Tree
You may want to add a branch to an existing tree. For example,
if one variable in the tree was computed with a certain algorithm,
you may want to try another algorithm and compare the results.
One solution is to add a new branch, fill it, and save the tree.
The code below adds a simple branch to an existing tree.
Note the kOverwrite option in the Write method, it overwrites the
existing tree. If it is not specified, two copies of the tree headers
are saved.
~~~ {.cpp}
void tree3AddBranch() {
TFile f("tree3.root", "update");
Float_t new_v;
auto t3 = f->Get<TTree>("t3");
auto newBranch = t3->Branch("new_v", &new_v, "new_v/F");
Long64_t nentries = t3->GetEntries(); // read the number of entries in the t3
for (Long64_t i = 0; i < nentries; i++) {
new_v = gRandom->Gaus(0, 1);
newBranch->Fill();
}
t3->Write("", TObject::kOverwrite); // save only the new version of the tree
}
~~~
It is not always possible to add branches to existing datasets stored in TFiles: for example,
these files might not be writeable, just readable. In addition, modifying in place a TTree
causes a new TTree instance to be written and the previous one to be deleted.
For this reasons, ROOT offers the concept of friends for TTree and TChain:
if is good practice to rely on friend trees rather than adding a branch manually.
## <a name="fullexample">An Example
Begin_Macro
../../../tutorials/tree/tree.C
End_Macro
~~~ {.cpp}
// A simple example with histograms and a tree
//
// This program creates :
// - a one dimensional histogram
// - a two dimensional histogram
// - a profile histogram
// - a tree
//
// These objects are filled with some random numbers and saved on a file.
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TProfile.h"
#include "TRandom.h"
#include "TTree.h"
//__________________________________________________________________________
main(int argc, char **argv)
{
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,trees
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
TFile hfile("htree.root","RECREATE","Demo ROOT file with histograms & trees");
// Create some histograms and a profile histogram
TH1F hpx("hpx","This is the px distribution",100,-4,4);
TH2F hpxpy("hpxpy","py ps px",40,-4,4,40,-4,4);
TProfile hprof("hprof","Profile of pz versus px",100,-4,4,0,20);
// Define some simple structures
typedef struct {Float_t x,y,z;} POINT;
typedef struct {
Int_t ntrack,nseg,nvertex;
UInt_t flag;
Float_t temperature;
} EVENTN;
POINT point;
EVENTN eventn;
// Create a ROOT Tree
TTree tree("T","An example of ROOT tree with a few branches");
tree.Branch("point",&point,"x:y:z");
tree.Branch("eventn",&eventn,"ntrack/I:nseg:nvertex:flag/i:temperature/F");
tree.Branch("hpx","TH1F",&hpx,128000,0);
Float_t px,py,pz;
// Here we start a loop on 1000 events
for ( Int_t i=0; i<1000; i++) {
gRandom->Rannor(px,py);
pz = px*px + py*py;
const auto random = gRandom->::Rndm(1);
// Fill histograms
hpx.Fill(px);
hpxpy.Fill(px,py,1);
hprof.Fill(px,pz,1);
// Fill structures
point.x = 10*(random-1);
point.y = 5*random;
point.z = 20*random;
eventn.ntrack = Int_t(100*random);
eventn.nseg = Int_t(2*eventn.ntrack);
eventn.nvertex = 1;
eventn.flag = Int_t(random+0.5);
eventn.temperature = 20+random;
// Fill the tree. For each event, save the 2 structures and 3 objects
// In this simple example, the objects hpx, hprof and hpxpy are slightly
// different from event to event. We expect a big compression factor!
tree->Fill();
}
// End of the loop
tree.Print();
// Save all objects in this file
hfile.Write();
// Close the file. Note that this is automatically done when you leave
// the application upon file destruction.
hfile.Close();
return 0;
}
~~~
*/
#include <ROOT/RConfig.hxx>
#include "TTree.h"
#include "ROOT/TIOFeatures.hxx"
#include "TArrayC.h"
#include "TBufferFile.h"
#include "TBaseClass.h"
#include "TBasket.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TBranchRef.h"
#include "TBrowser.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TClonesArray.h"
#include "TCut.h"
#include "TDataMember.h"
#include "TDataType.h"
#include "TDirectory.h"
#include "TError.h"
#include "TEntryList.h"
#include "TEnv.h"
#include "TEventList.h"
#include "TFile.h"
#include "TFolder.h"
#include "TFriendElement.h"
#include "TInterpreter.h"
#include "TLeaf.h"
#include "TLeafB.h"
#include "TLeafC.h"
#include "TLeafD.h"
#include "TLeafElement.h"
#include "TLeafF.h"
#include "TLeafI.h"
#include "TLeafL.h"
#include "TLeafObject.h"
#include "TLeafS.h"
#include "TList.h"
#include "TMath.h"
#include "TROOT.h"
#include "TRealData.h"
#include "TRegexp.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
#include "TStyle.h"
#include "TSystem.h"
#include "TTreeCloner.h"
#include "TTreeCache.h"
#include "TTreeCacheUnzip.h"
#include "TVirtualCollectionProxy.h"
#include "TEmulatedCollectionProxy.h"
#include "TVirtualIndex.h"
#include "TVirtualPerfStats.h"
#include "TVirtualPad.h"
#include "TBranchSTL.h"
#include "TSchemaRuleSet.h"
#include "TFileMergeInfo.h"
#include "ROOT/StringConv.hxx"
#include "TVirtualMutex.h"
#include "TBranchIMTHelper.h"
#include "TNotifyLink.h"
#include <chrono>
#include <cstddef>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <limits.h>
#include <algorithm>
#ifdef R__USE_IMT
#include "ROOT/TThreadExecutor.hxx"
#include <thread>
#include <string>
#include <sstream>
#endif
constexpr Int_t kNEntriesResort = 100;
constexpr Float_t kNEntriesResortInv = 1.f/kNEntriesResort;
Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
Long64_t TTree::fgMaxTreeSize = 100000000000LL;
ClassImp(TTree);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static char DataTypeToChar(EDataType datatype)
{
// Return the leaflist 'char' for a given datatype.
switch(datatype) {
case kChar_t: return 'B';
case kUChar_t: return 'b';
case kBool_t: return 'O';
case kShort_t: return 'S';
case kUShort_t: return 's';
case kCounter:
case kInt_t: return 'I';
case kUInt_t: return 'i';
case kDouble_t: return 'D';
case kDouble32_t: return 'd';
case kFloat_t: return 'F';
case kFloat16_t: return 'f';
case kLong_t: return 0; // unsupported
case kULong_t: return 0; // unsupported?
case kchar: return 0; // unsupported
case kLong64_t: return 'L';
case kULong64_t: return 'l';
case kCharStar: return 'C';
case kBits: return 0; //unsupported
case kOther_t:
case kNoType_t:
default:
return 0;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// \class TTree::TFriendLock
/// Helper class to prevent infinite recursion in the usage of TTree Friends.
////////////////////////////////////////////////////////////////////////////////
/// Record in tree that it has been used while recursively looks through the friends.
TTree::TFriendLock::TFriendLock(TTree* tree, UInt_t methodbit)
: fTree(tree)
{
// We could also add some code to acquire an actual
// lock to prevent multi-thread issues
fMethodBit = methodbit;
if (fTree) {
fPrevious = fTree->fFriendLockStatus & fMethodBit;
fTree->fFriendLockStatus |= fMethodBit;
} else {
fPrevious = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor.
TTree::TFriendLock::TFriendLock(const TFriendLock& tfl) :
fTree(tfl.fTree),
fMethodBit(tfl.fMethodBit),
fPrevious(tfl.fPrevious)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment operator.
TTree::TFriendLock& TTree::TFriendLock::operator=(const TTree::TFriendLock& tfl)
{
if(this!=&tfl) {
fTree=tfl.fTree;
fMethodBit=tfl.fMethodBit;
fPrevious=tfl.fPrevious;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Restore the state of tree the same as before we set the lock.
TTree::TFriendLock::~TFriendLock()
{
if (fTree) {
if (!fPrevious) {
fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// \class TTree::TClusterIterator
/// Helper class to iterate over cluster of baskets.
////////////////////////////////////////////////////////////////////////////////
/// Regular constructor.
/// TTree is not set as const, since we might modify if it is a TChain.
TTree::TClusterIterator::TClusterIterator(TTree *tree, Long64_t firstEntry) : fTree(tree), fClusterRange(0), fStartEntry(0), fNextEntry(0), fEstimatedSize(-1)
{
if (fTree->fNClusterRange) {
// Find the correct cluster range.
//
// Since fClusterRangeEnd contains the inclusive upper end of the range, we need to search for the
// range that was containing the previous entry and add 1 (because BinarySearch consider the values
// to be the inclusive start of the bucket).
fClusterRange = TMath::BinarySearch(fTree->fNClusterRange, fTree->fClusterRangeEnd, firstEntry - 1) + 1;
Long64_t entryInRange;
Long64_t pedestal;
if (fClusterRange == 0) {
pedestal = 0;
entryInRange = firstEntry;
} else {
pedestal = fTree->fClusterRangeEnd[fClusterRange-1] + 1;
entryInRange = firstEntry - pedestal;
}
Long64_t autoflush;
if (fClusterRange == fTree->fNClusterRange) {
autoflush = fTree->fAutoFlush;
} else {
autoflush = fTree->fClusterSize[fClusterRange];
}
if (autoflush <= 0) {
autoflush = GetEstimatedClusterSize();
}
fStartEntry = pedestal + entryInRange - entryInRange%autoflush;
} else if ( fTree->GetAutoFlush() <= 0 ) {
// Case of old files before November 9 2009 *or* small tree where AutoFlush was never set.
fStartEntry = firstEntry;
} else {
fStartEntry = firstEntry - firstEntry%fTree->GetAutoFlush();
}
fNextEntry = fStartEntry; // Position correctly for the first call to Next()
}
////////////////////////////////////////////////////////////////////////////////
/// Estimate the cluster size.
///
/// In almost all cases, this quickly returns the size of the auto-flush
/// in the TTree.
///
/// However, in the case where the cluster size was not fixed (old files and
/// case where autoflush was explicitly set to zero), we need estimate
/// a cluster size in relation to the size of the cache.
///
/// After this value is calculated once for the TClusterIterator, it is
/// cached and reused in future calls.
Long64_t TTree::TClusterIterator::GetEstimatedClusterSize()
{
auto autoFlush = fTree->GetAutoFlush();
if (autoFlush > 0) return autoFlush;
if (fEstimatedSize > 0) return fEstimatedSize;
Long64_t zipBytes = fTree->GetZipBytes();
if (zipBytes == 0) {
fEstimatedSize = fTree->GetEntries() - 1;
} else {
Long64_t clusterEstimate = 1;
Long64_t cacheSize = fTree->GetCacheSize();
if (cacheSize == 0) {
// Humm ... let's double check on the file.
TFile *file = fTree->GetCurrentFile();
if (file) {
TFileCacheRead *cache = fTree->GetReadCache(file);
if (cache) {
cacheSize = cache->GetBufferSize();
}
}
}
// If neither file nor tree has a cache, use the current default.
if (cacheSize <= 0) {
cacheSize = 30000000;
}
clusterEstimate = fTree->GetEntries() * cacheSize / zipBytes;
// If there are no entries, then just default to 1.
fEstimatedSize = clusterEstimate ? clusterEstimate : 1;
}
return fEstimatedSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Move on to the next cluster and return the starting entry
/// of this next cluster
Long64_t TTree::TClusterIterator::Next()
{
fStartEntry = fNextEntry;
if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
if (fClusterRange == fTree->fNClusterRange) {
// We are looking at a range which size
// is defined by AutoFlush itself and goes to the GetEntries.
fNextEntry += GetEstimatedClusterSize();
} else {
if (fStartEntry > fTree->fClusterRangeEnd[fClusterRange]) {
++fClusterRange;
}
if (fClusterRange == fTree->fNClusterRange) {
// We are looking at the last range which size
// is defined by AutoFlush itself and goes to the GetEntries.
fNextEntry += GetEstimatedClusterSize();
} else {
Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
if (clusterSize == 0) {
clusterSize = GetEstimatedClusterSize();
}
fNextEntry += clusterSize;
if (fNextEntry > fTree->fClusterRangeEnd[fClusterRange]) {
// The last cluster of the range was a partial cluster,
// so the next cluster starts at the beginning of the
// next range.
fNextEntry = fTree->fClusterRangeEnd[fClusterRange] + 1;
}
}
}
} else {
// Case of old files before November 9 2009
fNextEntry = fStartEntry + GetEstimatedClusterSize();
}
if (fNextEntry > fTree->GetEntries()) {
fNextEntry = fTree->GetEntries();
}
return fStartEntry;
}
////////////////////////////////////////////////////////////////////////////////
/// Move on to the previous cluster and return the starting entry
/// of this previous cluster
Long64_t TTree::TClusterIterator::Previous()
{
fNextEntry = fStartEntry;
if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
if (fClusterRange == 0 || fTree->fNClusterRange == 0) {
// We are looking at a range which size
// is defined by AutoFlush itself.
fStartEntry -= GetEstimatedClusterSize();
} else {
if (fNextEntry <= fTree->fClusterRangeEnd[fClusterRange]) {
--fClusterRange;
}
if (fClusterRange == 0) {
// We are looking at the first range.
fStartEntry = 0;
} else {
Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
if (clusterSize == 0) {
clusterSize = GetEstimatedClusterSize();
}
fStartEntry -= clusterSize;
}
}
} else {
// Case of old files before November 9 2009 or trees that never auto-flushed.
fStartEntry = fNextEntry - GetEstimatedClusterSize();
}
if (fStartEntry < 0) {
fStartEntry = 0;
}
return fStartEntry;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// Default constructor and I/O constructor.
///
/// Note: We do *not* insert ourself into the current directory.
///
TTree::TTree()
: TNamed()
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fNClusterRange(0)
, fMaxClusterRange(0)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fClusterRangeEnd(0)
, fClusterSize(0)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(0)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fPerfStats(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
, fTransientBuffer(0)
, fCacheDoAutoInit(kTRUE)
, fCacheDoClusterPrefetch(kFALSE)
, fCacheUserSet(kFALSE)
, fIMTEnabled(ROOT::IsImplicitMTEnabled())
, fNEntriesSinceSorting(0)
{
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
fBranches.SetOwner(kTRUE);
}
////////////////////////////////////////////////////////////////////////////////
/// Normal tree constructor.
///
/// The tree is created in the current directory.
/// Use the various functions Branch below to add branches to this tree.
///
/// If the first character of title is a "/", the function assumes a folder name.
/// In this case, it creates automatically branches following the folder hierarchy.
/// splitlevel may be used in this case to control the split level.
TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */,
TDirectory* dir /* = gDirectory*/)
: TNamed(name, title)
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fNClusterRange(0)
, fMaxClusterRange(0)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fClusterRangeEnd(0)
, fClusterSize(0)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(dir)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fPerfStats(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
, fTransientBuffer(0)
, fCacheDoAutoInit(kTRUE)
, fCacheDoClusterPrefetch(kFALSE)
, fCacheUserSet(kFALSE)
, fIMTEnabled(ROOT::IsImplicitMTEnabled())
, fNEntriesSinceSorting(0)
{
// TAttLine state.
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
// TAttFill state.
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
// TAttMarkerState.
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
// Insert ourself into the current directory.
// FIXME: This is very annoying behaviour, we should
// be able to choose to not do this like we
// can with a histogram.
if (fDirectory) fDirectory->Append(this);
fBranches.SetOwner(kTRUE);
// If title starts with "/" and is a valid folder name, a superbranch
// is created.
// FIXME: Why?
if (strlen(title) > 2) {
if (title[0] == '/') {
Branch(title+1,32000,splitlevel);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor.
TTree::~TTree()
{
if (auto link = dynamic_cast<TNotifyLinkBase*>(fNotify)) {
link->Clear();
}
if (fAllocationCount && (gDebug > 0)) {
Info("TTree::~TTree", "For tree %s, allocation count is %u.", GetName(), fAllocationCount.load());
#ifdef R__TRACK_BASKET_ALLOC_TIME
Info("TTree::~TTree", "For tree %s, allocation time is %lluus.", GetName(), fAllocationTime.load());
#endif
}
if (fDirectory) {
// We are in a directory, which may possibly be a file.
if (fDirectory->GetList()) {
// Remove us from the directory listing.
fDirectory->Remove(this);
}
//delete the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,0);
}
// We don't own the leaves in fLeaves, the branches do.
fLeaves.Clear();
// I'm ready to destroy any objects allocated by
// SetAddress() by my branches. If I have clones,
// tell them to zero their pointers to this shared
// memory.
if (fClones && fClones->GetEntries()) {
// I have clones.
// I am about to delete the objects created by
// SetAddress() which we are sharing, so tell
// the clones to release their pointers to them.
for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
TTree* clone = (TTree*) lnk->GetObject();
// clone->ResetBranchAddresses();
// Reset only the branch we have set the address of.
CopyAddresses(clone,kTRUE);
}
}
// Get rid of our branches, note that this will also release
// any memory allocated by TBranchElement::SetAddress().
fBranches.Delete();
// FIXME: We must consider what to do with the reset of these if we are a clone.
delete fPlayer;
fPlayer = 0;
if (fFriends) {
fFriends->Delete();
delete fFriends;
fFriends = 0;
}
if (fAliases) {
fAliases->Delete();
delete fAliases;
fAliases = 0;
}
if (fUserInfo) {
fUserInfo->Delete();
delete fUserInfo;
fUserInfo = 0;
}
if (fClones) {
// Clone trees should no longer be removed from fClones when they are deleted.
{
R__LOCKGUARD(gROOTMutex);
gROOT->GetListOfCleanups()->Remove(fClones);
}
// Note: fClones does not own its content.
delete fClones;
fClones = 0;
}
if (fEntryList) {
if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==0) {
// Delete the entry list if it is marked to be deleted and it is not also
// owned by a directory. (Otherwise we would need to make sure that a
// TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
delete fEntryList;
fEntryList=0;
}
}
delete fTreeIndex;
fTreeIndex = 0;
delete fBranchRef;
fBranchRef = 0;
delete [] fClusterRangeEnd;
fClusterRangeEnd = 0;
delete [] fClusterSize;
fClusterSize = 0;
// Must be done after the destruction of friends.
// Note: We do *not* own our directory.
fDirectory = 0;
if (fTransientBuffer) {
delete fTransientBuffer;
fTransientBuffer = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the transient buffer currently used by this TTree for reading/writing baskets.
TBuffer* TTree::GetTransientBuffer(Int_t size)
{
if (fTransientBuffer) {
if (fTransientBuffer->BufferSize() < size) {
fTransientBuffer->Expand(size);
}
return fTransientBuffer;
}
fTransientBuffer = new TBufferFile(TBuffer::kRead, size);
return fTransientBuffer;
}
////////////////////////////////////////////////////////////////////////////////
/// Add branch with name bname to the Tree cache.
/// If bname="*" all branches are added to the cache.
/// if subbranches is true all the branches of the subbranches are
/// also put to the cache.
///
/// Returns:
/// - 0 branch added or already included
/// - -1 on error
Int_t TTree::AddBranchToCache(const char*bname, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("AddBranchToCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->AddBranchToCache(bname, subbranches);
}
} else {
Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("AddBranchToCache", "No cache is available, branch not added");
return -1;
}
return tc->AddBranch(bname,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Add branch b to the Tree cache.
/// if subbranches is true all the branches of the subbranches are
/// also put to the cache.
///
/// Returns:
/// - 0 branch added or already included
/// - -1 on error
Int_t TTree::AddBranchToCache(TBranch *b, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("AddBranchToCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
Int_t res = GetTree()->AddBranchToCache(b, subbranches);
if (res<0) {
Error("AddBranchToCache", "Error adding branch");
}
return res;
}
} else {
Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("AddBranchToCache", "No cache is available, branch not added");
return -1;
}
return tc->AddBranch(b,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Remove the branch with name 'bname' from the Tree cache.
/// If bname="*" all branches are removed from the cache.
/// if subbranches is true all the branches of the subbranches are
/// also removed from the cache.
///
/// Returns:
/// - 0 branch dropped or not in cache
/// - -1 on error
Int_t TTree::DropBranchFromCache(const char*bname, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("DropBranchFromCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->DropBranchFromCache(bname, subbranches);
}
} else {
Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("DropBranchFromCache", "No cache is available, branch not dropped");
return -1;
}
return tc->DropBranch(bname,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Remove the branch b from the Tree cache.
/// if subbranches is true all the branches of the subbranches are
/// also removed from the cache.
///
/// Returns:
/// - 0 branch dropped or not in cache
/// - -1 on error
Int_t TTree::DropBranchFromCache(TBranch *b, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("DropBranchFromCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
Int_t res = GetTree()->DropBranchFromCache(b, subbranches);
if (res<0) {
Error("DropBranchFromCache", "Error dropping branch");
}
return res;
}
} else {
Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("DropBranchFromCache", "No cache is available, branch not dropped");
return -1;
}
return tc->DropBranch(b,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Add a cloned tree to our list of trees to be notified whenever we change
/// our branch addresses or when we are deleted.
void TTree::AddClone(TTree* clone)
{
if (!fClones) {
fClones = new TList();
fClones->SetOwner(false);
// So that the clones are automatically removed from the list when
// they are deleted.
{
R__LOCKGUARD(gROOTMutex);
gROOT->GetListOfCleanups()->Add(fClones);
}
}
if (!fClones->FindObject(clone)) {
fClones->Add(clone);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TFriendElement to the list of friends.
///
/// This function:
/// - opens a file if filename is specified
/// - reads a Tree with name treename from the file (current directory)
/// - adds the Tree to the list of friends
/// see other AddFriend functions
///
/// A TFriendElement TF describes a TTree object TF in a file.
/// When a TFriendElement TF is added to the the list of friends of an
/// existing TTree T, any variable from TF can be referenced in a query
/// to T.
///
/// A tree keeps a list of friends. In the context of a tree (or a chain),
/// friendship means unrestricted access to the friends data. In this way
/// it is much like adding another branch to the tree without taking the risk
/// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
/// method. The tree in the diagram below has two friends (friend_tree1 and
/// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
///
/// \image html ttree_friend1.png
///
/// The AddFriend method has two parameters, the first is the tree name and the
/// second is the name of the ROOT file where the friend tree is saved.
/// AddFriend automatically opens the friend file. If no file name is given,
/// the tree called ft1 is assumed to be in the same file as the original tree.
///
/// tree.AddFriend("ft1","friendfile1.root");
/// If the friend tree has the same name as the original tree, you can give it
/// an alias in the context of the friendship:
///
/// tree.AddFriend("tree1 = tree","friendfile1.root");
/// Once the tree has friends, we can use TTree::Draw as if the friend's
/// variables were in the original tree. To specify which tree to use in
/// the Draw method, use the syntax:
/// ~~~ {.cpp}
/// <treeName>.<branchname>.<varname>
/// ~~~
/// If the variablename is enough to uniquely identify the variable, you can
/// leave out the tree and/or branch name.
/// For example, these commands generate a 3-d scatter plot of variable "var"
/// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
/// TTree ft2.
/// ~~~ {.cpp}
/// tree.AddFriend("ft1","friendfile1.root");
/// tree.AddFriend("ft2","friendfile2.root");
/// tree.Draw("var:ft1.v1:ft2.v2");
/// ~~~
/// \image html ttree_friend2.png
///
/// The picture illustrates the access of the tree and its friends with a
/// Draw command.
/// When AddFriend is called, the ROOT file is automatically opened and the
/// friend tree (ft1) is read into memory. The new friend (ft1) is added to
/// the list of friends of tree.
/// The number of entries in the friend must be equal or greater to the number
/// of entries of the original tree. If the friend tree has fewer entries a
/// warning is given and the missing entries are not included in the histogram.
/// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
/// When the tree is written to file (TTree::Write), the friends list is saved
/// with it. And when the tree is retrieved, the trees on the friends list are
/// also retrieved and the friendship restored.
/// When a tree is deleted, the elements of the friend list are also deleted.
/// It is possible to declare a friend tree that has the same internal
/// structure (same branches and leaves) as the original tree, and compare the
/// same values by specifying the tree.
/// ~~~ {.cpp}
/// tree.Draw("var:ft1.var:ft2.var")
/// ~~~
TFriendElement* TTree::AddFriend(const char* treename, const char* filename)
{
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, treename, filename);
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename, filename, t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "Cannot add FriendElement %s in file %s", treename, filename);
}
return fe;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TFriendElement to the list of friends.
///
/// The TFile is managed by the user (e.g. the user must delete the file).
/// For complete description see AddFriend(const char *, const char *).
/// This function:
/// - reads a Tree with name treename from the file
/// - adds the Tree to the list of friends
TFriendElement* TTree::AddFriend(const char* treename, TFile* file)
{
if (!fFriends) {
fFriends = new TList();
}
TFriendElement *fe = new TFriendElement(this, treename, file);
R__ASSERT(fe);
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename, file->GetName(), t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "unknown tree '%s' in file '%s'", treename, file->GetName());
}
return fe;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TFriendElement to the list of friends.
///
/// The TTree is managed by the user (e.g., the user must delete the file).
/// For a complete description see AddFriend(const char *, const char *).
TFriendElement* TTree::AddFriend(TTree* tree, const char* alias, Bool_t warn)
{
if (!tree) {
return 0;
}
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, tree, alias);
R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (warn && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld",
tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(), fEntries);
}
return fe;
}
////////////////////////////////////////////////////////////////////////////////
/// AutoSave tree header every fAutoSave bytes.
///
/// When large Trees are produced, it is safe to activate the AutoSave
/// procedure. Some branches may have buffers holding many entries.
/// If fAutoSave is negative, AutoSave is automatically called by
/// TTree::Fill when the number of bytes generated since the previous
/// AutoSave is greater than -fAutoSave bytes.
/// If fAutoSave is positive, AutoSave is automatically called by
/// TTree::Fill every N entries.
/// This function may also be invoked by the user.
/// Each AutoSave generates a new key on the file.
/// Once the key with the tree header has been written, the previous cycle
/// (if any) is deleted.
///
/// Note that calling TTree::AutoSave too frequently (or similarly calling
/// TTree::SetAutoSave with a small value) is an expensive operation.
/// You should make tests for your own application to find a compromise
/// between speed and the quantity of information you may loose in case of
/// a job crash.
///
/// In case your program crashes before closing the file holding this tree,
/// the file will be automatically recovered when you will connect the file
/// in UPDATE mode.
/// The Tree will be recovered at the status corresponding to the last AutoSave.
///
/// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
/// This allows another process to analyze the Tree while the Tree is being filled.
///
/// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
/// the current basket are closed-out and written to disk individually.
///
/// By default the previous header is deleted after having written the new header.
/// if option contains "Overwrite", the previous Tree header is deleted
/// before written the new header. This option is slightly faster, but
/// the default option is safer in case of a problem (disk quota exceeded)
/// when writing the new header.
///
/// The function returns the number of bytes written to the file.
/// if the number of bytes is null, an error has occurred while writing
/// the header to the file.
///
/// ## How to write a Tree in one process and view it from another process
///
/// The following two scripts illustrate how to do this.
/// The script treew.C is executed by process1, treer.C by process2
///
/// script treew.C:
/// ~~~ {.cpp}
/// void treew() {
/// TFile f("test.root","recreate");
/// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
/// Float_t px, py, pz;
/// for ( Int_t i=0; i<10000000; i++) {
/// gRandom->Rannor(px,py);
/// pz = px*px + py*py;
/// Float_t random = gRandom->Rndm(1);
/// ntuple->Fill(px,py,pz,random,i);
/// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
/// }
/// }
/// ~~~
/// script treer.C:
/// ~~~ {.cpp}
/// void treer() {
/// TFile f("test.root");
/// TTree *ntuple = (TTree*)f.Get("ntuple");
/// TCanvas c1;
/// Int_t first = 0;
/// while(1) {
/// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
/// else ntuple->Draw("px>>+hpx","","",10000000,first);
/// first = (Int_t)ntuple->GetEntries();
/// c1.Update();
/// gSystem->Sleep(1000); //sleep 1 second
/// ntuple->Refresh();
/// }
/// }
/// ~~~
Long64_t TTree::AutoSave(Option_t* option)
{
if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
if (gDebug > 0) {
Info("AutoSave", "Tree:%s after %lld bytes written\n",GetName(),GetTotBytes());
}
TString opt = option;
opt.ToLower();
if (opt.Contains("flushbaskets")) {
if (gDebug > 0) Info("AutoSave", "calling FlushBaskets \n");
FlushBasketsImpl();
}
fSavedBytes = GetZipBytes();
TKey *key = (TKey*)fDirectory->GetListOfKeys()->FindObject(GetName());
Long64_t nbytes;
if (opt.Contains("overwrite")) {
nbytes = fDirectory->WriteTObject(this,"","overwrite");
} else {
nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
if (nbytes && key) {
key->Delete();
delete key;
}
}
// save StreamerInfo
TFile *file = fDirectory->GetFile();
if (file) file->WriteStreamerInfo();
if (opt.Contains("saveself")) {
fDirectory->SaveSelf();
//the following line is required in case GetUserInfo contains a user class
//for which the StreamerInfo must be written. One could probably be a bit faster (Rene)
if (file) file->WriteHeader();
}
return nbytes;
}
namespace {
// This error message is repeated several times in the code. We write it once.
const char* writeStlWithoutProxyMsg = "The class requested (%s) for the branch \"%s\""
" is an instance of an stl collection and does not have a compiled CollectionProxy."
" Please generate the dictionary for this collection (%s) to avoid to write corrupted data.";
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch() with added check that addobj matches className.
///
/// See TTree::Branch() for other details.
///
TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
TClass* claim = TClass::GetClass(classname);
if (!ptrClass) {
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr) {
actualClass = ptrClass->GetActualClass(*addr);
}
if (ptrClass && claim) {
if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
// Note we currently do not warn in case of splicing or over-expectation).
if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
claim->GetName(), branchname, ptrClass->GetName());
}
} else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
actualClass->GetName(), branchname, claim->GetName());
}
}
}
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch but automatic detection of the class name.
/// See TTree::Branch for other details.
TBranch* TTree::BranchImp(const char* branchname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
if (!ptrClass) {
Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
return 0;
}
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr && *addr) {
actualClass = ptrClass->GetActualClass(*addr);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
} else {
actualClass = ptrClass;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch but automatic detection of the class name.
/// See TTree::Branch for other details.
TBranch* TTree::BranchImpRef(const char* branchname, const char *classname, TClass* ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
{
TClass* claim = TClass::GetClass(classname);
if (!ptrClass) {
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
claim->GetName(), branchname, claim->GetName());
return 0;
} else if (claim == 0) {
Error("Branch", "The pointer specified for %s is not of a class known to ROOT and %s is not a known class", branchname, classname);
return 0;
}
ptrClass = claim;
}
TClass* actualClass = 0;
if (!addobj) {
Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
return 0;
}
actualClass = ptrClass->GetActualClass(addobj);
if (ptrClass && claim) {
if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
// Note we currently do not warn in case of splicing or over-expectation).
if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the object passed (%s)",
claim->GetName(), branchname, ptrClass->GetName());
}
} else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
actualClass->GetName(), branchname, claim->GetName());
}
}
}
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch but automatic detection of the class name.
/// See TTree::Branch for other details.
TBranch* TTree::BranchImpRef(const char* branchname, TClass* ptrClass, EDataType datatype, void* addobj, Int_t bufsize, Int_t splitlevel)
{
if (!ptrClass) {
if (datatype == kOther_t || datatype == kNoType_t) {
Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
} else {
TString varname; varname.Form("%s/%c",branchname,DataTypeToChar(datatype));
return Branch(branchname,addobj,varname.Data(),bufsize);
}
return 0;
}
TClass* actualClass = 0;
if (!addobj) {
Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
return 0;
}
actualClass = ptrClass->GetActualClass(addobj);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
// Wrapper to turn Branch call with an std::array into the relevant leaf list
// call
TBranch *TTree::BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize,
Int_t /* splitlevel */)
{
if (datatype == kOther_t || datatype == kNoType_t) {
Error("Branch",
"The inner type of the std::array passed specified for %s is not of a class or type known to ROOT",
branchname);
} else {
TString varname;
varname.Form("%s[%d]/%c", branchname, (int)N, DataTypeToChar(datatype));
return Branch(branchname, addobj, varname.Data(), bufsize);
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Deprecated function. Use next function instead.
Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
{
return Branch((TCollection*) li, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Create one branch for each element in the collection.
///
/// Each entry in the collection becomes a top level branch if the
/// corresponding class is not a collection. If it is a collection, the entry
/// in the collection becomes in turn top level branches, etc.
/// The splitlevel is decreased by 1 every time a new collection is found.
/// For example if list is a TObjArray*
/// - if splitlevel = 1, one top level branch is created for each element
/// of the TObjArray.
/// - if splitlevel = 2, one top level branch is created for each array element.
/// if, in turn, one of the array elements is a TCollection, one top level
/// branch will be created for each element of this collection.
///
/// In case a collection element is a TClonesArray, the special Tree constructor
/// for TClonesArray is called.
/// The collection itself cannot be a TClonesArray.
///
/// The function returns the total number of branches created.
///
/// If name is given, all branch names will be prefixed with name_.
///
/// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
///
/// IMPORTANT NOTE2: The branches created by this function will have names
/// corresponding to the collection or object names. It is important
/// to give names to collections to avoid misleading branch names or
/// identical branch names. By default collections have a name equal to
/// the corresponding class name, e.g. the default name for a TList is "TList".
///
/// And in general, in case two or more master branches contain subbranches
/// with identical names, one must add a "." (dot) character at the end
/// of the master branch name. This will force the name of the subbranches
/// to be of the form `master.subbranch` instead of simply `subbranch`.
/// This situation happens when the top level object
/// has two or more members referencing the same class.
/// For example, if a Tree has two branches B1 and B2 corresponding
/// to objects of the same class MyClass, one can do:
/// ~~~ {.cpp}
/// tree.Branch("B1.","MyClass",&b1,8000,1);
/// tree.Branch("B2.","MyClass",&b2,8000,1);
/// ~~~
/// if MyClass has 3 members a,b,c, the two instructions above will generate
/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
///
/// Example:
/// ~~~ {.cpp}
/// {
/// TTree T("T","test list");
/// TList *list = new TList();
///
/// TObjArray *a1 = new TObjArray();
/// a1->SetName("a1");
/// list->Add(a1);
/// TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
/// TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
/// a1->Add(ha1a);
/// a1->Add(ha1b);
/// TObjArray *b1 = new TObjArray();
/// b1->SetName("b1");
/// list->Add(b1);
/// TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
/// TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
/// b1->Add(hb1a);
/// b1->Add(hb1b);
///
/// TObjArray *a2 = new TObjArray();
/// a2->SetName("a2");
/// list->Add(a2);
/// TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
/// TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
/// a2->Add(ha2a);
/// a2->Add(ha2b);
///
/// T.Branch(list,16000,2);
/// T.Print();
/// }
/// ~~~
Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
{
if (!li) {
return 0;
}
TObject* obj = 0;
Int_t nbranches = GetListOfBranches()->GetEntries();
if (li->InheritsFrom(TClonesArray::Class())) {
Error("Branch", "Cannot call this constructor for a TClonesArray");
return 0;
}
Int_t nch = strlen(name);
TString branchname;
TIter next(li);
while ((obj = next())) {
if ((splitlevel > 1) && obj->InheritsFrom(TCollection::Class()) && !obj->InheritsFrom(TClonesArray::Class())) {
TCollection* col = (TCollection*) obj;
if (nch) {
branchname.Form("%s_%s_", name, col->GetName());
} else {
branchname.Form("%s_", col->GetName());
}
Branch(col, bufsize, splitlevel - 1, branchname);
} else {
if (nch && (name[nch-1] == '_')) {
branchname.Form("%s%s", name, obj->GetName());
} else {
if (nch) {
branchname.Form("%s_%s", name, obj->GetName());
} else {
branchname.Form("%s", obj->GetName());
}
}
if (splitlevel > 99) {
branchname += ".";
}
Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
}
}
return GetListOfBranches()->GetEntries() - nbranches;
}
////////////////////////////////////////////////////////////////////////////////
/// Create one branch for each element in the folder.
/// Returns the total number of branches created.
Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
TObject* ob = gROOT->FindObjectAny(foldername);
if (!ob) {
return 0;
}
if (ob->IsA() != TFolder::Class()) {
return 0;
}
Int_t nbranches = GetListOfBranches()->GetEntries();
TFolder* folder = (TFolder*) ob;
TIter next(folder->GetListOfFolders());
TObject* obj = 0;
char* curname = new char[1000];
char occur[20];
while ((obj = next())) {
snprintf(curname,1000, "%s/%s", foldername, obj->GetName());
if (obj->IsA() == TFolder::Class()) {
Branch(curname, bufsize, splitlevel - 1);
} else {
void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
for (Int_t i = 0; i < 1000; ++i) {
if (curname[i] == 0) {
break;
}
if (curname[i] == '/') {
curname[i] = '.';
}
}
Int_t noccur = folder->Occurence(obj);
if (noccur > 0) {
snprintf(occur,20, "_%d", noccur);
strlcat(curname, occur,1000);
}
TBranchElement* br = (TBranchElement*) Bronch(curname, obj->ClassName(), add, bufsize, splitlevel - 1);
if (br) br->SetBranchFolder();
}
}
delete[] curname;
return GetListOfBranches()->GetEntries() - nbranches;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new TTree Branch.
///
/// This Branch constructor is provided to support non-objects in
/// a Tree. The variables described in leaflist may be simple
/// variables or structures. // See the two following
/// constructors for writing objects in a Tree.
///
/// By default the branch buffers are stored in the same file as the Tree.
/// use TBranch::SetFile to specify a different file
///
/// * address is the address of the first item of a structure.
/// * leaflist is the concatenation of all the variable names and types
/// separated by a colon character :
/// The variable name and the variable type are separated by a slash (/).
/// The variable type may be 0,1 or 2 characters. If no type is given,
/// the type of the variable is assumed to be the same as the previous
/// variable. If the first variable does not have a type, it is assumed
/// of type F by default. The list of currently supported types is given below:
/// - `C` : a character string terminated by the 0 character
/// - `B` : an 8 bit signed integer (`Char_t`)
/// - `b` : an 8 bit unsigned integer (`UChar_t`)
/// - `S` : a 16 bit signed integer (`Short_t`)
/// - `s` : a 16 bit unsigned integer (`UShort_t`)
/// - `I` : a 32 bit signed integer (`Int_t`)
/// - `i` : a 32 bit unsigned integer (`UInt_t`)
/// - `F` : a 32 bit floating point (`Float_t`)
/// - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
/// - `D` : a 64 bit floating point (`Double_t`)
/// - `d` : a 24 bit truncated floating point (`Double32_t`)
/// - `L` : a 64 bit signed integer (`Long64_t`)
/// - `l` : a 64 bit unsigned integer (`ULong64_t`)
/// - `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
///
/// Arrays of values are supported with the following syntax:
/// - If leaf name has the form var[nelem], where nelem is alphanumeric, then
/// if nelem is a leaf name, it is used as the variable size of the array,
/// otherwise return 0.
/// - If leaf name has the form var[nelem], where nelem is a non-negative integer, then
/// it is used as the fixed size of the array.
/// - If leaf name has the form of a multi-dimensional array (e.g. var[nelem][nelem2])
/// where nelem and nelem2 are non-negative integer) then
/// it is used as a 2 dimensional array of fixed size.
/// - In case of the truncated floating point types (Float16_t and Double32_t) you can
/// furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
/// the type character. See `TStreamerElement::GetRange()` for further information.
///
/// Any of other form is not supported.
///
/// Note that the TTree will assume that all the item are contiguous in memory.
/// On some platform, this is not always true of the member of a struct or a class,
/// due to padding and alignment. Sorting your data member in order of decreasing
/// sizeof usually leads to their being contiguous in memory.
///
/// * bufsize is the buffer size in bytes for this branch
/// The default value is 32000 bytes and should be ok for most cases.
/// You can specify a larger value (e.g. 256000) if your Tree is not split
/// and each entry is large (Megabytes)
/// A small value for bufsize is optimum if you intend to access
/// the entries in the Tree randomly and your Tree is in split mode.
TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
{
TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
if (branch->IsZombie()) {
delete branch;
branch = 0;
return 0;
}
fBranches.Add(branch);
return branch;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new branch with the object of class classname at address addobj.
///
/// WARNING:
///
/// Starting with Root version 3.01, the Branch function uses the new style
/// branches (TBranchElement). To get the old behaviour, you can:
/// - call BranchOld or
/// - call TTree::SetBranchStyle(0)
///
/// Note that with the new style, classname does not need to derive from TObject.
/// It must derived from TObject if the branch style has been set to 0 (old)
///
/// Note: See the comments in TBranchElement::SetAddress() for a more
/// detailed discussion of the meaning of the addobj parameter in
/// the case of new-style branches.
///
/// Use splitlevel < 0 instead of splitlevel=0 when the class
/// has a custom Streamer
///
/// Note: if the split level is set to the default (99), TTree::Branch will
/// not issue a warning if the class can not be split.
TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
if (fgBranchStyle == 1) {
return Bronch(name, classname, addobj, bufsize, splitlevel);
} else {
if (splitlevel < 0) {
splitlevel = 0;
}
return BranchOld(name, classname, addobj, bufsize, splitlevel);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new TTree BranchObject.
///
/// Build a TBranchObject for an object of class classname.
/// addobj is the address of a pointer to an object of class classname.
/// IMPORTANT: classname must derive from TObject.
/// The class dictionary must be available (ClassDef in class header).
///
/// This option requires access to the library where the corresponding class
/// is defined. Accessing one single data member in the object implies
/// reading the full object.
/// See the next Branch constructor for a more efficient storage
/// in case the entry consists of arrays of identical objects.
///
/// By default the branch buffers are stored in the same file as the Tree.
/// use TBranch::SetFile to specify a different file
///
/// IMPORTANT NOTE about branch names:
///
/// And in general, in case two or more master branches contain subbranches
/// with identical names, one must add a "." (dot) character at the end
/// of the master branch name. This will force the name of the subbranches
/// to be of the form `master.subbranch` instead of simply `subbranch`.
/// This situation happens when the top level object
/// has two or more members referencing the same class.
/// For example, if a Tree has two branches B1 and B2 corresponding
/// to objects of the same class MyClass, one can do:
/// ~~~ {.cpp}
/// tree.Branch("B1.","MyClass",&b1,8000,1);
/// tree.Branch("B2.","MyClass",&b2,8000,1);
/// ~~~
/// if MyClass has 3 members a,b,c, the two instructions above will generate
/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
///
/// bufsize is the buffer size in bytes for this branch
/// The default value is 32000 bytes and should be ok for most cases.
/// You can specify a larger value (e.g. 256000) if your Tree is not split
/// and each entry is large (Megabytes)
/// A small value for bufsize is optimum if you intend to access
/// the entries in the Tree randomly and your Tree is in split mode.
TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
{
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("BranchOld", "Cannot find class: '%s'", classname);
return 0;
}
if (!cl->IsTObject()) {
if (fgBranchStyle == 0) {
Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
"\tfgBranchStyle is set to zero requesting by default to use BranchOld.\n"
"\tIf this is intentional use Bronch instead of Branch or BranchOld.", classname);
} else {
Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
"\tYou can not use BranchOld to store objects of this type.",classname);
}
return 0;
}
TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
fBranches.Add(branch);
if (!splitlevel) {
return branch;
}
// We are going to fully split the class now.
TObjArray* blist = branch->GetListOfBranches();
const char* rdname = 0;
const char* dname = 0;
TString branchname;
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
Bool_t delobj = kFALSE;
if (!obj) {
obj = (TObject*) cl->New();
delobj = kTRUE;
}
// Build the StreamerInfo if first time for the class.
BuildStreamerInfo(cl, obj);
// Loop on all public data members of the class and its base classes.
Int_t lenName = strlen(name);
Int_t isDot = 0;
if (name[lenName-1] == '.') {
isDot = 1;
}
TBranch* branch1 = 0;
TRealData* rd = 0;
TRealData* rdi = 0;
TIter nexti(cl->GetListOfRealData());
TIter next(cl->GetListOfRealData());
// Note: This loop results in a full split because the
// real data list includes all data members of
// data members.
while ((rd = (TRealData*) next())) {
if (rd->TestBit(TRealData::kTransient)) continue;
// Loop over all data members creating branches for each one.
TDataMember* dm = rd->GetDataMember();
if (!dm->IsPersistent()) {
// Do not process members with an "!" as the first character in the comment field.
continue;
}
if (rd->IsObject()) {
// We skip data members of class type.
// But we do build their real data, their
// streamer info, and write their streamer
// info to the current directory's file.
// Oh yes, and we also do this for all of
// their base classes.
TClass* clm = TClass::GetClass(dm->GetFullTypeName());
if (clm) {
BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
}
continue;
}
rdname = rd->GetName();
dname = dm->GetName();
if (cl->CanIgnoreTObjectStreamer()) {
// Skip the TObject base class data members.
// FIXME: This prevents a user from ever
// using these names themself!
if (!strcmp(dname, "fBits")) {
continue;
}
if (!strcmp(dname, "fUniqueID")) {
continue;
}
}
TDataType* dtype = dm->GetDataType();
Int_t code = 0;
if (dtype) {
code = dm->GetDataType()->GetType();
}
// Encode branch name. Use real data member name
branchname = rdname;
if (isDot) {
if (dm->IsaPointer()) {
// FIXME: This is wrong! The asterisk is not usually in the front!
branchname.Form("%s%s", name, &rdname[1]);
} else {
branchname.Form("%s%s", name, &rdname[0]);
}
}
// FIXME: Change this to a string stream.
TString leaflist;
Int_t offset = rd->GetThisOffset();
char* pointer = ((char*) obj) + offset;
if (dm->IsaPointer()) {
// We have a pointer to an object or a pointer to an array of basic types.
TClass* clobj = 0;
if (!dm->IsBasic()) {
clobj = TClass::GetClass(dm->GetTypeName());
}
if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
// We have a pointer to a clones array.
char* cpointer = (char*) pointer;
char** ppointer = (char**) cpointer;
TClonesArray* li = (TClonesArray*) *ppointer;
if (splitlevel != 2) {
if (isDot) {
branch1 = new TBranchClones(branch,branchname, pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
}
blist->Add(branch1);
} else {
if (isDot) {
branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
}
blist->Add(branch1);
}
} else if (clobj) {
// We have a pointer to an object.
//
// It must be a TObject object.
if (!clobj->IsTObject()) {
continue;
}
branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
if (isDot) {
branch1->SetName(branchname);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
// Do not use the first character (*).
branch1->SetName(&branchname.Data()[1]);
}
blist->Add(branch1);
} else {
// We have a pointer to an array of basic types.
//
// Check the comments in the text of the code for an index specification.
const char* index = dm->GetArrayIndex();
if (index[0]) {
// We are a pointer to a varying length array of basic types.
//check that index is a valid data member name
//if member is part of an object (e.g. fA and index=fN)
//index must be changed from fN to fA.fN
TString aindex (rd->GetName());
Ssiz_t rdot = aindex.Last('.');
if (rdot>=0) {
aindex.Remove(rdot+1);
aindex.Append(index);
}
nexti.Reset();
while ((rdi = (TRealData*) nexti())) {
if (rdi->TestBit(TRealData::kTransient)) continue;
if (!strcmp(rdi->GetName(), index)) {
break;
}
if (!strcmp(rdi->GetName(), aindex)) {
index = rdi->GetName();
break;
}
}
char vcode = DataTypeToChar((EDataType)code);
// Note that we differentiate between strings and
// char array by the fact that there is NO specified
// size for a string (see next if (code == 1)
if (vcode) {
leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
} else {
// We are possibly a character string.
if (code == 1) {
// We are a character string.
leaflist.Form("%s/%s", dname, "C");
} else {
// Invalid array specification.
// FIXME: We need an error message here.
continue;
}
}
// There are '*' in both the branchname and leaflist, remove them.
TString bname( branchname );
bname.ReplaceAll("*","");
leaflist.ReplaceAll("*","");
// Add the branch to the tree and indicate that the address
// is that of a pointer to be dereferenced before using.
branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
leaf->SetBit(TLeaf::kIndirectAddress);
leaf->SetAddress((void**) pointer);
blist->Add(branch1);
}
} else if (dm->IsBasic()) {
// We have a basic type.
char vcode = DataTypeToChar((EDataType)code);
if (vcode) {
leaflist.Form("%s/%c", rdname, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
branch1->SetTitle(rdname);
blist->Add(branch1);
} else {
// We have a class type.
// Note: This cannot happen due to the rd->IsObject() test above.
// FIXME: Put an error message here just in case.
}
if (branch1) {
branch1->SetOffset(offset);
} else {
Warning("BranchOld", "Cannot process member: '%s'", rdname);
}
}
if (delobj) {
delete obj;
obj = 0;
}
return branch;
}
////////////////////////////////////////////////////////////////////////////////
/// Build the optional branch supporting the TRefTable.
/// This branch will keep all the information to find the branches
/// containing referenced objects.
///
/// At each Tree::Fill, the branch numbers containing the
/// referenced objects are saved to the TBranchRef basket.
/// When the Tree header is saved (via TTree::Write), the branch
/// is saved keeping the information with the pointers to the branches
/// having referenced objects.
TBranch* TTree::BranchRef()
{
if (!fBranchRef) {
fBranchRef = new TBranchRef(this);
}
return fBranchRef;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new TTree BranchElement.
///
/// ## WARNING about this new function
///
/// This function is designed to replace the internal
/// implementation of the old TTree::Branch (whose implementation
/// has been moved to BranchOld).
///
/// NOTE: The 'Bronch' method supports only one possible calls
/// signature (where the object type has to be specified
/// explicitly and the address must be the address of a pointer).
/// For more flexibility use 'Branch'. Use Bronch only in (rare)
/// cases (likely to be legacy cases) where both the new and old
/// implementation of Branch needs to be used at the same time.
///
/// This function is far more powerful than the old Branch
/// function. It supports the full C++, including STL and has
/// the same behaviour in split or non-split mode. classname does
/// not have to derive from TObject. The function is based on
/// the new TStreamerInfo.
///
/// Build a TBranchElement for an object of class classname.
///
/// addr is the address of a pointer to an object of class
/// classname. The class dictionary must be available (ClassDef
/// in class header).
///
/// Note: See the comments in TBranchElement::SetAddress() for a more
/// detailed discussion of the meaning of the addr parameter.
///
/// This option requires access to the library where the
/// corresponding class is defined. Accessing one single data
/// member in the object implies reading the full object.
///
/// By default the branch buffers are stored in the same file as the Tree.
/// use TBranch::SetFile to specify a different file
///
/// IMPORTANT NOTE about branch names:
///
/// And in general, in case two or more master branches contain subbranches
/// with identical names, one must add a "." (dot) character at the end
/// of the master branch name. This will force the name of the subbranches
/// to be of the form `master.subbranch` instead of simply `subbranch`.
/// This situation happens when the top level object
/// has two or more members referencing the same class.
/// For example, if a Tree has two branches B1 and B2 corresponding
/// to objects of the same class MyClass, one can do:
/// ~~~ {.cpp}
/// tree.Branch("B1.","MyClass",&b1,8000,1);
/// tree.Branch("B2.","MyClass",&b2,8000,1);
/// ~~~
/// if MyClass has 3 members a,b,c, the two instructions above will generate
/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
///
/// bufsize is the buffer size in bytes for this branch
/// The default value is 32000 bytes and should be ok for most cases.
/// You can specify a larger value (e.g. 256000) if your Tree is not split
/// and each entry is large (Megabytes)
/// A small value for bufsize is optimum if you intend to access
/// the entries in the Tree randomly and your Tree is in split mode.
///
/// Use splitlevel < 0 instead of splitlevel=0 when the class
/// has a custom Streamer
///
/// Note: if the split level is set to the default (99), TTree::Branch will
/// not issue a warning if the class can not be split.
TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
return BronchExec(name, classname, addr, kTRUE, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, Bool_t isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("Bronch", "Cannot find class:%s", classname);
return 0;
}
//if splitlevel <= 0 and class has a custom Streamer, we must create
//a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
//with the custom Streamer. The penalty is that one cannot process
//this Tree without the class library containing the class.
char* objptr = 0;
if (!isptrptr) {
objptr = (char*)addr;
} else if (addr) {
objptr = *((char**) addr);
}
if (cl == TClonesArray::Class()) {
TClonesArray* clones = (TClonesArray*) objptr;
if (!clones) {
Error("Bronch", "Pointer to TClonesArray is null");
return 0;
}
if (!clones->GetClass()) {
Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
return 0;
}
if (!clones->GetClass()->HasDataMemberInfo()) {
Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
return 0;
}
bool hasCustomStreamer = clones->GetClass()->TestBit(TClass::kHasCustomStreamerMember);
if (splitlevel > 0) {
if (hasCustomStreamer)
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
} else {
if (hasCustomStreamer) clones->BypassStreamer(kFALSE);
TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,/*compress=*/ -1,isptrptr);
fBranches.Add(branch);
return branch;
}
}
if (cl->GetCollectionProxy()) {
TVirtualCollectionProxy* collProxy = cl->GetCollectionProxy();
//if (!collProxy) {
// Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
//}
TClass* inklass = collProxy->GetValueClass();
if (!inklass && (collProxy->GetType() == 0)) {
Error("Bronch", "%s with no class defined in branch: %s", classname, name);
return 0;
}
if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == 0)) {
ROOT::ESTLType stl = cl->GetCollectionType();
if ((stl != ROOT::kSTLmap) && (stl != ROOT::kSTLmultimap)) {
if (!inklass->HasDataMemberInfo()) {
Error("Bronch", "Container with no dictionary defined in branch: %s", name);
return 0;
}
if (inklass->TestBit(TClass::kHasCustomStreamerMember)) {
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
}
}
}
//-------------------------------------------------------------------------
// If the splitting switch is enabled, the split level is big enough and
// the collection contains pointers we can split it
//////////////////////////////////////////////////////////////////////////
TBranch *branch;
if( splitlevel > kSplitCollectionOfPointers && collProxy->HasPointers() )
branch = new TBranchSTL( this, name, collProxy, bufsize, splitlevel );
else
branch = new TBranchElement(this, name, collProxy, bufsize, splitlevel);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
Bool_t hasCustomStreamer = kFALSE;
if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
Error("Bronch", "Cannot find dictionary for class: %s", classname);
return 0;
}
if (!cl->GetCollectionProxy() && cl->TestBit(TClass::kHasCustomStreamerMember)) {
// Not an STL container and the linkdef file had a "-" after the class name.
hasCustomStreamer = kTRUE;
}
if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->IsTObject())) {
TBranchObject* branch = new TBranchObject(this, name, classname, addr, bufsize, 0, /*compress=*/ ROOT::RCompressionSetting::EAlgorithm::kInherit, isptrptr);
fBranches.Add(branch);
return branch;
}
if (cl == TClonesArray::Class()) {
// Special case of TClonesArray.
// No dummy object is created.
// The streamer info is not rebuilt unoptimized.
// No dummy top-level branch is created.
// No splitting is attempted.
TBranchElement* branch = new TBranchElement(this, name, (TClonesArray*) objptr, bufsize, splitlevel%kSplitCollectionOfPointers);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
//
// If we are not given an object to use as an i/o buffer
// then create a temporary one which we will delete just
// before returning.
//
Bool_t delobj = kFALSE;
if (!objptr) {
objptr = (char*) cl->New();
delobj = kTRUE;
}
//
// Avoid splitting unsplittable classes.
//
if ((splitlevel > 0) && !cl->CanSplit()) {
if (splitlevel != 99) {
Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
}
splitlevel = 0;
}
//
// Make sure the streamer info is built and fetch it.
//
// If we are splitting, then make sure the streamer info
// is built unoptimized (data members are not combined).
//
TStreamerInfo* sinfo = BuildStreamerInfo(cl, objptr, splitlevel==0);
if (!sinfo) {
Error("Bronch", "Cannot build the StreamerInfo for class: %s", cl->GetName());
return 0;
}
//
// Create a dummy top level branch object.
//
Int_t id = -1;
if (splitlevel > 0) {
id = -2;
}
TBranchElement* branch = new TBranchElement(this, name, sinfo, id, objptr, bufsize, splitlevel);
fBranches.Add(branch);
//
// Do splitting, if requested.
//
if (splitlevel%kSplitCollectionOfPointers > 0) {
branch->Unroll(name, cl, sinfo, objptr, bufsize, splitlevel);
}
//
// Setup our offsets into the user's i/o buffer.
//
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
if (delobj) {
cl->Destructor(objptr);
objptr = 0;
}
return branch;
}
////////////////////////////////////////////////////////////////////////////////
/// Browse content of the TTree.
void TTree::Browse(TBrowser* b)
{
fBranches.Browse(b);
if (fUserInfo) {
if (strcmp("TList",fUserInfo->GetName())==0) {
fUserInfo->SetName("UserInfo");
b->Add(fUserInfo);
fUserInfo->SetName("TList");
} else {
b->Add(fUserInfo);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Build a Tree Index (default is TTreeIndex).
/// See a description of the parameters and functionality in
/// TTreeIndex::TTreeIndex().
///
/// The return value is the number of entries in the Index (< 0 indicates failure).
///
/// A TTreeIndex object pointed by fTreeIndex is created.
/// This object will be automatically deleted by the TTree destructor.
/// If an index is already existing, this is replaced by the new one without being
/// deleted. This behaviour prevents the deletion of a previously external index
/// assigned to the TTree via the TTree::SetTreeIndex() method.
/// See also comments in TTree::SetTreeIndex().
Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
{
fTreeIndex = GetPlayer()->BuildIndex(this, majorname, minorname);
if (fTreeIndex->IsZombie()) {
delete fTreeIndex;
fTreeIndex = 0;
return 0;
}
return fTreeIndex->GetN();
}
////////////////////////////////////////////////////////////////////////////////
/// Build StreamerInfo for class cl.
/// pointer is an optional argument that may contain a pointer to an object of cl.
TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, Bool_t canOptimize /* = kTRUE */ )
{
if (!cl) {
return 0;
}
cl->BuildRealData(pointer);
TStreamerInfo* sinfo = (TStreamerInfo*)cl->GetStreamerInfo(cl->GetClassVersion());
// Create StreamerInfo for all base classes.
TBaseClass* base = 0;
TIter nextb(cl->GetListOfBases());
while((base = (TBaseClass*) nextb())) {
if (base->IsSTLContainer()) {
continue;
}
TClass* clm = TClass::GetClass(base->GetName());
BuildStreamerInfo(clm, pointer, canOptimize);
}
if (sinfo && fDirectory) {
sinfo->ForceWriteInfo(fDirectory->GetFile());
}
return sinfo;
}
////////////////////////////////////////////////////////////////////////////////
/// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
/// Create a new file. If the original file is named "myfile.root",
/// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
///
/// Returns a pointer to the new file.
///
/// Currently, the automatic change of file is restricted
/// to the case where the tree is in the top level directory.
/// The file should not contain sub-directories.
///
/// Before switching to a new file, the tree header is written
/// to the current file, then the current file is closed.
///
/// To process the multiple files created by ChangeFile, one must use
/// a TChain.
///
/// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
/// By default a Root session starts with fFileNumber=0. One can set
/// fFileNumber to a different value via TTree::SetFileNumber.
/// In case a file named "_N" already exists, the function will try
/// a file named "__N", then "___N", etc.
///
/// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
/// The default value of fgMaxTreeSize is 100 Gigabytes.
///
/// If the current file contains other objects like TH1 and TTree,
/// these objects are automatically moved to the new file.
///
/// IMPORTANT NOTE:
///
/// Be careful when writing the final Tree header to the file!
///
/// Don't do:
/// ~~~ {.cpp}
/// TFile *file = new TFile("myfile.root","recreate");
/// TTree *T = new TTree("T","title");
/// T->Fill(); //loop
/// file->Write();
/// file->Close();
/// ~~~
/// but do the following:
/// ~~~ {.cpp}
/// TFile *file = new TFile("myfile.root","recreate");
/// TTree *T = new TTree("T","title");
/// T->Fill(); //loop
/// file = T->GetCurrentFile(); //to get the pointer to the current file
/// file->Write();
/// file->Close();
/// ~~~
TFile* TTree::ChangeFile(TFile* file)
{
file->cd();
Write();
Reset();
constexpr auto kBufSize = 2000;
char* fname = new char[kBufSize];
++fFileNumber;
char uscore[10];
for (Int_t i = 0; i < 10; ++i) {
uscore[i] = 0;
}
Int_t nus = 0;
// Try to find a suitable file name that does not already exist.
while (nus < 10) {
uscore[nus] = '_';
fname[0] = 0;
strlcpy(fname, file->GetName(), kBufSize);
if (fFileNumber > 1) {
char* cunder = strrchr(fname, '_');
if (cunder) {
snprintf(cunder, kBufSize - Int_t(cunder - fname), "%s%d", uscore, fFileNumber);
const char* cdot = strrchr(file->GetName(), '.');
if (cdot) {
strlcat(fname, cdot, kBufSize);
}
} else {
char fcount[21];
snprintf(fcount,21, "%s%d", uscore, fFileNumber);
strlcat(fname, fcount, kBufSize);
}
} else {
char* cdot = strrchr(fname, '.');
if (cdot) {
snprintf(cdot, kBufSize - Int_t(fname-cdot), "%s%d", uscore, fFileNumber);
strlcat(fname, strrchr(file->GetName(), '.'), kBufSize);
} else {
char fcount[21];
snprintf(fcount,21, "%s%d", uscore, fFileNumber);
strlcat(fname, fcount, kBufSize);
}
}
if (gSystem->AccessPathName(fname)) {
break;
}
++nus;
Warning("ChangeFile", "file %s already exist, trying with %d underscores", fname, nus+1);
}
Int_t compress = file->GetCompressionSettings();
TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
if (newfile == 0) {
Error("Fill","Failed to open new file %s, continuing as a memory tree.",fname);
} else {
Printf("Fill: Switching to new file: %s", fname);
}
// The current directory may contain histograms and trees.
// These objects must be moved to the new file.
TBranch* branch = 0;
TObject* obj = 0;
while ((obj = file->GetList()->First())) {
file->Remove(obj);
// Histogram: just change the directory.
if (obj->InheritsFrom("TH1")) {
gROOT->ProcessLine(TString::Format("((%s*)0x%lx)->SetDirectory((TDirectory*)0x%lx);", obj->ClassName(), (Long_t) obj, (Long_t) newfile));
continue;
}
// Tree: must save all trees in the old file, reset them.
if (obj->InheritsFrom(TTree::Class())) {
TTree* t = (TTree*) obj;
if (t != this) {
t->AutoSave();
t->Reset();
t->fFileNumber = fFileNumber;
}
t->SetDirectory(newfile);
TIter nextb(t->GetListOfBranches());
while ((branch = (TBranch*)nextb())) {
branch->SetFile(newfile);
}
if (t->GetBranchRef()) {
t->GetBranchRef()->SetFile(newfile);
}
continue;
}
// Not a TH1 or a TTree, move object to new file.
if (newfile) newfile->Append(obj);
file->Remove(obj);
}
delete file;
file = 0;
delete[] fname;
fname = 0;
return newfile;
}
////////////////////////////////////////////////////////////////////////////////
/// Check whether or not the address described by the last 3 parameters
/// matches the content of the branch. If a Data Model Evolution conversion
/// is involved, reset the fInfo of the branch.
/// The return values are:
//
/// - kMissingBranch (-5) : Missing branch
/// - kInternalError (-4) : Internal error (could not find the type corresponding to a data type number)
/// - kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
/// - kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
/// - kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
/// - kMatch (0) : perfect match
/// - kMatchConversion (1) : match with (I/O) conversion
/// - kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
/// - kMakeClass (3) : MakeClass mode so we can not check.
/// - kVoidPtr (4) : void* passed so no check was made.
/// - kNoCheck (5) : Underlying TBranch not yet available so no check was made.
Int_t TTree::CheckBranchAddressType(TBranch* branch, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
if (GetMakeClass()) {
// If we are in MakeClass mode so we do not really use classes.
return kMakeClass;
}
// Let's determine what we need!
TClass* expectedClass = 0;
EDataType expectedType = kOther_t;
if (0 != branch->GetExpectedType(expectedClass,expectedType) ) {
// Something went wrong, the warning message has already be issued.
return kInternalError;
}
if (expectedClass && datatype == kOther_t && ptrClass == 0) {
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
"The class expected (%s) refers to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
return kMissingCompiledCollectionProxy;
}
if (!expectedClass->IsLoaded()) {
// The originally expected class does not have a dictionary, it is then plausible that the pointer being passed is the right type
// (we really don't know). So let's express that.
Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
"The class expected (%s) does not have a dictionary and needs to be emulated for I/O purposes but is being passed a compiled object."
"Please generate the dictionary for this class (%s)",
branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
} else {
Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
"This is probably due to a missing dictionary, the original data class for this branch is %s.", branch->GetName(), expectedClass->GetName());
}
return kClassMismatch;
}
if (expectedClass && ptrClass && (branch->GetMother() == branch)) {
// Top Level branch
if (!isptr) {
Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
}
}
if (expectedType == kFloat16_t) {
expectedType = kFloat_t;
}
if (expectedType == kDouble32_t) {
expectedType = kDouble_t;
}
if (datatype == kFloat16_t) {
datatype = kFloat_t;
}
if (datatype == kDouble32_t) {
datatype = kDouble_t;
}
/////////////////////////////////////////////////////////////////////////////
// Deal with the class renaming
/////////////////////////////////////////////////////////////////////////////
if( expectedClass && ptrClass &&
expectedClass != ptrClass &&
branch->InheritsFrom( TBranchElement::Class() ) &&
ptrClass->GetSchemaRules() &&
ptrClass->GetSchemaRules()->HasRuleWithSourceClass( expectedClass->GetName() ) ) {
TBranchElement* bEl = (TBranchElement*)branch;
if ( ptrClass->GetCollectionProxy() && expectedClass->GetCollectionProxy() ) {
if (gDebug > 7)
Info("SetBranchAddress", "Matching STL collection (at least according to the SchemaRuleSet when "
"reading a %s into a %s",expectedClass->GetName(),ptrClass->GetName());
bEl->SetTargetClass( ptrClass->GetName() );
return kMatchConversion;
} else if ( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
!ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" by the branch: %s", ptrClass->GetName(), bEl->GetClassName(), branch->GetName());
bEl->SetTargetClass( expectedClass->GetName() );
return kClassMismatch;
}
else {
bEl->SetTargetClass( ptrClass->GetName() );
return kMatchConversion;
}
} else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
branch->InheritsFrom( TBranchElement::Class() ) &&
expectedClass->GetCollectionProxy()->GetValueClass() &&
ptrClass->GetCollectionProxy()->GetValueClass() )
{
// In case of collection, we know how to convert them, if we know how to convert their content.
// NOTE: we need to extend this to std::pair ...
TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
if (inmemValueClass->GetSchemaRules() &&
inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
{
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( ptrClass->GetName() );
return kMatchConversionCollection;
}
}
Error("SetBranchAddress", "The pointer type given (%s) does not correspond to the class needed (%s) by the branch: %s", ptrClass->GetName(), expectedClass->GetName(), branch->GetName());
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
return kClassMismatch;
} else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
if (datatype != kChar_t) {
// For backward compatibility we assume that (char*) was just a cast and/or a generic address
Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s",
TDataType::GetTypeName(datatype), datatype, TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
return kMismatch;
}
} else if ((expectedClass && (datatype != kOther_t && datatype != kNoType_t && datatype != kInt_t)) ||
(ptrClass && (expectedType != kOther_t && expectedType != kNoType_t && datatype != kInt_t)) ) {
// Sometime a null pointer can look an int, avoid complaining in that case.
if (expectedClass) {
Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" by the branch: %s",
TDataType::GetTypeName(datatype), datatype, expectedClass->GetName(), branch->GetName());
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
} else {
// In this case, it is okay if the first data member is of the right type (to support the case where we are being passed
// a struct).
bool found = false;
if (ptrClass->IsLoaded()) {
TIter next(ptrClass->GetListOfRealData());
TRealData *rdm;
while ((rdm = (TRealData*)next())) {
if (rdm->GetThisOffset() == 0) {
TDataType *dmtype = rdm->GetDataMember()->GetDataType();
if (dmtype) {
EDataType etype = (EDataType)dmtype->GetType();
if (etype == expectedType) {
found = true;
}
}
break;
}
}
} else {
TIter next(ptrClass->GetListOfDataMembers());
TDataMember *dm;
while ((dm = (TDataMember*)next())) {
if (dm->GetOffset() == 0) {
TDataType *dmtype = dm->GetDataType();
if (dmtype) {
EDataType etype = (EDataType)dmtype->GetType();
if (etype == expectedType) {
found = true;
}
}
break;
}
}
}
if (found) {
// let's check the size.
TLeaf *last = (TLeaf*)branch->GetListOfLeaves()->Last();
long len = last->GetOffset() + last->GetLenType() * last->GetLen();
if (len <= ptrClass->Size()) {
return kMatch;
}
}
Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" (%d) by the branch: %s",
ptrClass->GetName(), TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
}
return kMismatch;
}
if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
Error("SetBranchAddress", writeStlWithoutProxyMsg,
expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
return kMissingCompiledCollectionProxy;
}
if (expectedClass && branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
return kMatch;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a clone of this tree and copy nentries.
///
/// By default copy all entries.
/// The compression level of the cloned tree is set to the destination
/// file's compression level.
///
/// NOTE: Only active branches are copied.
/// NOTE: If the TTree is a TChain, the structure of the first TTree
/// is used for the copy.
///
/// IMPORTANT: The cloned tree stays connected with this tree until
/// this tree is deleted. In particular, any changes in
/// branch addresses in this tree are forwarded to the
/// clone trees, unless a branch in a clone tree has had
/// its address changed, in which case that change stays in
/// effect. When this tree is deleted, all the addresses of
/// the cloned tree are reset to their default values.
///
/// If 'option' contains the word 'fast' and nentries is -1, the
/// cloning will be done without unzipping or unstreaming the baskets
/// (i.e., a direct copy of the raw bytes on disk).
///
/// When 'fast' is specified, 'option' can also contain a sorting
/// order for the baskets in the output file.
///
/// There are currently 3 supported sorting order:
///
/// - SortBasketsByOffset (the default)
/// - SortBasketsByBranch
/// - SortBasketsByEntry
///
/// When using SortBasketsByOffset the baskets are written in the
/// output file in the same order as in the original file (i.e. the
/// baskets are sorted by their offset in the original file; Usually
/// this also means that the baskets are sorted by the index/number of
/// the _last_ entry they contain)
///
/// When using SortBasketsByBranch all the baskets of each individual
/// branches are stored contiguously. This tends to optimize reading
/// speed when reading a small number (1->5) of branches, since all
/// their baskets will be clustered together instead of being spread
/// across the file. However it might decrease the performance when
/// reading more branches (or the full entry).
///
/// When using SortBasketsByEntry the baskets with the lowest starting
/// entry are written first. (i.e. the baskets are sorted by the
/// index/number of the first entry they contain). This means that on
/// the file the baskets will be in the order in which they will be
/// needed when reading the whole tree sequentially.
///
/// For examples of CloneTree, see tutorials:
///
/// - copytree.C:
/// A macro to copy a subset of a TTree to a new TTree.
/// The input file has been generated by the program in
/// $ROOTSYS/test/Event with: Event 1000 1 1 1
///
/// - copytree2.C:
/// A macro to copy a subset of a TTree to a new TTree.
/// One branch of the new Tree is written to a separate file.
/// The input file has been generated by the program in
/// $ROOTSYS/test/Event with: Event 1000 1 1 1
TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
// Options
Bool_t fastClone = kFALSE;
TString opt = option;
opt.ToLower();
if (opt.Contains("fast")) {
fastClone = kTRUE;
}
// If we are a chain, switch to the first tree.
if ((fEntries > 0) && (LoadTree(0) < 0)) {
// FIXME: We need an error message here.
return 0;
}
// Note: For a tree we get the this pointer, for
// a chain we get the chain's current tree.
TTree* thistree = GetTree();
// We will use this to override the IO features on the cloned branches.
ROOT::TIOFeatures features = this->GetIOFeatures();
;
// Note: For a chain, the returned clone will be
// a clone of the chain's first tree.
TTree* newtree = (TTree*) thistree->Clone();
if (!newtree) {
return 0;
}
// The clone should not delete any objects allocated by SetAddress().
TObjArray* branches = newtree->GetListOfBranches();
Int_t nb = branches->GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
}
// Add the new tree to the list of clones so that
// we can later inform it of changes to branch addresses.
thistree->AddClone(newtree);
if (thistree != this) {
// In case this object is a TChain, add the clone
// also to the TChain's list of clones.
AddClone(newtree);
}
newtree->Reset();
TDirectory* ndir = newtree->GetDirectory();
TFile* nfile = 0;
if (ndir) {
nfile = ndir->GetFile();
}
Int_t newcomp = -1;
if (nfile) {
newcomp = nfile->GetCompressionSettings();
}
//
// Delete non-active branches from the clone.
//
// Note: If we are a chain, this does nothing
// since chains have no leaves.
TObjArray* leaves = newtree->GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
if (!leaf) {
continue;
}
TBranch* branch = leaf->GetBranch();
if (branch && (newcomp > -1)) {
branch->SetCompressionSettings(newcomp);
}
if (branch) branch->SetIOFeatures(features);
if (!branch || !branch->TestBit(kDoNotProcess)) {
continue;
}
// size might change at each iteration of the loop over the leaves.
nb = branches->GetEntriesFast();
for (Long64_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br == branch) {
branches->RemoveAt(i);
delete br;
br = 0;
branches->Compress();
break;
}
TObjArray* lb = br->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; ++j) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!b1) {
continue;
}
if (b1 == branch) {
lb->RemoveAt(j);
delete b1;
b1 = 0;
lb->Compress();
break;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; ++k) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!b2) {
continue;
}
if (b2 == branch) {
lb1->RemoveAt(k);
delete b2;
b2 = 0;
lb1->Compress();
break;
}
}
}
}
}
leaves->Compress();
// Copy MakeClass status.
newtree->SetMakeClass(fMakeClass);
// Copy branch addresses.
CopyAddresses(newtree);
//
// Copy entries if requested.
//
if (nentries != 0) {
if (fastClone && (nentries < 0)) {
if ( newtree->CopyEntries( this, -1, option ) < 0 ) {
// There was a problem!
Error("CloneTTree", "TTree has not been cloned\n");
delete newtree;
newtree = 0;
return 0;
}
} else {
newtree->CopyEntries( this, nentries, option );
}
}
return newtree;
}
////////////////////////////////////////////////////////////////////////////////
/// Set branch addresses of passed tree equal to ours.
/// If undo is true, reset the branch address instead of copying them.
/// This insures 'separation' of a cloned tree from its original
void TTree::CopyAddresses(TTree* tree, Bool_t undo)
{
// Copy branch addresses starting from branches.
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
TBranch* br = tree->GetBranch(branch->GetName());
tree->ResetBranchAddress(br);
} else {
char* addr = branch->GetAddress();
if (!addr) {
if (branch->IsA() == TBranch::Class()) {
// If the branch was created using a leaflist, the branch itself may not have
// an address but the leaf might already.
TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
if (!firstleaf || firstleaf->GetValuePointer()) {
// Either there is no leaf (and thus no point in copying the address)
// or the leaf has an address but we can not copy it via the branche
// this will be copied via the next loop (over the leaf).
continue;
}
}
// Note: This may cause an object to be allocated.
branch->SetAddress(0);
addr = branch->GetAddress();
}
// FIXME: The GetBranch() function is braindead and may
// not find the branch!
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
br->SetAddress(addr);
// The copy does not own any object allocated by SetAddress().
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
}
}
// Copy branch addresses starting from leaves.
TObjArray* tleaves = tree->GetListOfLeaves();
Int_t ntleaves = tleaves->GetEntriesFast();
for (Int_t i = 0; i < ntleaves; ++i) {
TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
TBranch* tbranch = tleaf->GetBranch();
TBranch* branch = GetBranch(tbranch->GetName());
if (!branch) {
continue;
}
TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
if (!leaf) {
continue;
}
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
// Now we know whether the address has been transfered
tree->ResetBranchAddress(tbranch);
} else {
TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
{
// If it is an array and it was allocated by the leaf itself,
// let's make sure it is large enough for the incoming data.
if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
if (leaf->GetValuePointer()) {
if (leaf->IsA() == TLeafElement::Class() && mother)
mother->ResetAddress();
else
leaf->SetAddress(nullptr);
}
}
}
if (!branch->GetAddress() && !leaf->GetValuePointer()) {
// We should attempts to set the address of the branch.
// something like:
//(TBranchElement*)branch->GetMother()->SetAddress(0)
//plus a few more subtilities (see TBranchElement::GetEntry).
//but for now we go the simplest route:
//
// Note: This may result in the allocation of an object.
branch->SetupAddresses();
}
if (branch->GetAddress()) {
tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
// The copy does not own any object allocated by SetAddress().
// FIXME: We do too much here, br may not be a top-level branch.
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
} else {
tleaf->SetAddress(leaf->GetValuePointer());
}
}
}
if (undo &&
( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
) {
tree->ResetBranchAddresses();
}
}
namespace {
enum EOnIndexError { kDrop, kKeep, kBuild };
static Bool_t R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
{
// Return true if we should continue to handle indices, false otherwise.
Bool_t withIndex = kTRUE;
if ( newtree->GetTreeIndex() ) {
if ( oldtree->GetTree()->GetTreeIndex() == 0 ) {
switch (onIndexError) {
case kDrop:
delete newtree->GetTreeIndex();
newtree->SetTreeIndex(0);
withIndex = kFALSE;
break;
case kKeep:
// Nothing to do really.
break;
case kBuild:
// Build the index then copy it
if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
// Clean up
delete oldtree->GetTree()->GetTreeIndex();
oldtree->GetTree()->SetTreeIndex(0);
}
break;
}
} else {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
} else if ( oldtree->GetTree()->GetTreeIndex() != 0 ) {
// We discover the first index in the middle of the chain.
switch (onIndexError) {
case kDrop:
// Nothing to do really.
break;
case kKeep: {
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
break;
}
case kBuild:
if (newtree->GetEntries() == 0) {
// Start an index.
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
} else {
// Build the index so far.
if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
}
break;
}
} else if ( onIndexError == kDrop ) {
// There is no index on this or on tree->GetTree(), we know we have to ignore any further
// index
withIndex = kFALSE;
}
return withIndex;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Copy nentries from given tree to this tree.
/// This routines assumes that the branches that intended to be copied are
/// already connected. The typical case is that this tree was created using
/// tree->CloneTree(0).
///
/// By default copy all entries.
///
/// Returns number of bytes copied to this tree.
///
/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
/// raw bytes on disk).
///
/// When 'fast' is specified, 'option' can also contains a sorting order for the
/// baskets in the output file.
///
/// There are currently 3 supported sorting order:
///
/// - SortBasketsByOffset (the default)
/// - SortBasketsByBranch
/// - SortBasketsByEntry
///
/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
///
/// If the tree or any of the underlying tree of the chain has an index, that index and any
/// index in the subsequent underlying TTree objects will be merged.
///
/// There are currently three 'options' to control this merging:
/// - NoIndex : all the TTreeIndex object are dropped.
/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
/// they are all dropped.
/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
if (!tree) {
return 0;
}
// Options
TString opt = option;
opt.ToLower();
Bool_t fastClone = opt.Contains("fast");
Bool_t withIndex = !opt.Contains("noindex");
EOnIndexError onIndexError;
if (opt.Contains("asisindex")) {
onIndexError = kKeep;
} else if (opt.Contains("buildindex")) {
onIndexError = kBuild;
} else if (opt.Contains("dropindex")) {
onIndexError = kDrop;
} else {
onIndexError = kBuild;
}
Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
Int_t cacheSize = -1;
if (cacheSizeLoc != TString::kNPOS) {
// If the parse faile, cacheSize stays at -1.
Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
TSubString cacheSizeStr( opt(cacheSizeLoc+10,cacheSizeEnd) );
auto parseResult = ROOT::FromHumanReadableSize(cacheSizeStr,cacheSize);
if (parseResult == ROOT::EFromHumanReadableSize::kParseFail) {
Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
} else if (parseResult == ROOT::EFromHumanReadableSize::kOverflow) {
double m;
const char *munit = nullptr;
ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
}
}
if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %d\n",cacheSize);
Long64_t nbytes = 0;
Long64_t treeEntries = tree->GetEntriesFast();
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
// Quickly copy the basket without decompression and streaming.
Long64_t totbytes = GetTotBytes();
for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
if (tree->LoadTree(i) < 0) {
break;
}
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
if (this->GetDirectory()) {
TFile* file2 = this->GetDirectory()->GetFile();
if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
if (this->GetDirectory() == (TDirectory*) file2) {
this->ChangeFile(file2);
}
}
}
TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
if (cloner.IsValid()) {
this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
cloner.Exec();
} else {
if (i == 0) {
Warning("CopyEntries","%s",cloner.GetWarning());
// If the first cloning does not work, something is really wrong
// (since apriori the source and target are exactly the same structure!)
return -1;
} else {
if (cloner.NeedConversion()) {
TTree *localtree = tree->GetTree();
Long64_t tentries = localtree->GetEntries();
for (Long64_t ii = 0; ii < tentries; ii++) {
if (localtree->GetEntry(ii) <= 0) {
break;
}
this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), kTRUE);
}
} else {
Warning("CopyEntries","%s",cloner.GetWarning());
if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
} else {
Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
}
}
}
}
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
nbytes = GetTotBytes() - totbytes;
} else {
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
Int_t treenumber = -1;
for (Long64_t i = 0; i < nentries; i++) {
if (tree->LoadTree(i) < 0) {
break;
}
if (treenumber != tree->GetTreeNumber()) {
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
treenumber = tree->GetTreeNumber();
}
if (tree->GetEntry(i) <= 0) {
break;
}
nbytes += this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
}
return nbytes;
}
////////////////////////////////////////////////////////////////////////////////
/// Copy a tree with selection.
///
/// ### Important:
///
/// The returned copied tree stays connected with the original tree
/// until the original tree is deleted. In particular, any changes
/// to the branch addresses in the original tree are also made to
/// the copied tree. Any changes made to the branch addresses of the
/// copied tree are overridden anytime the original tree changes its
/// branch addresses. When the original tree is deleted, all the
/// branch addresses of the copied tree are set to zero.
///
/// For examples of CopyTree, see the tutorials:
///
/// - copytree.C:
/// Example macro to copy a subset of a tree to a new tree.
/// The input file was generated by running the program in
/// $ROOTSYS/test/Event in this way:
/// ~~~ {.cpp}
/// ./Event 1000 1 1 1
/// ~~~
/// - copytree2.C
/// Example macro to copy a subset of a tree to a new tree.
/// One branch of the new tree is written to a separate file.
/// The input file was generated by running the program in
/// $ROOTSYS/test/Event in this way:
/// ~~~ {.cpp}
/// ./Event 1000 1 1 1
/// ~~~
/// - copytree3.C
/// Example macro to copy a subset of a tree to a new tree.
/// Only selected entries are copied to the new tree.
/// NOTE that only the active branches are copied.
TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
{
GetPlayer();
if (fPlayer) {
return fPlayer->CopyTree(selection, option, nentries, firstentry);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a basket for this tree and given branch.
TBasket* TTree::CreateBasket(TBranch* branch)
{
if (!branch) {
return 0;
}
return new TBasket(branch->GetName(), GetName(), branch);
}
////////////////////////////////////////////////////////////////////////////////
/// Delete this tree from memory or/and disk.
///
/// - if option == "all" delete Tree object from memory AND from disk
/// all baskets on disk are deleted. All keys with same name
/// are deleted.
/// - if option =="" only Tree object in memory is deleted.
void TTree::Delete(Option_t* option /* = "" */)
{
TFile *file = GetCurrentFile();
// delete all baskets and header from file
if (file && !strcmp(option,"all")) {
if (!file->IsWritable()) {
Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
return;
}
//find key and import Tree header in memory
TKey *key = fDirectory->GetKey(GetName());
if (!key) return;
TDirectory *dirsav = gDirectory;
file->cd();
//get list of leaves and loop on all the branches baskets
TIter next(GetListOfLeaves());
TLeaf *leaf;
char header[16];
Int_t ntot = 0;
Int_t nbask = 0;
Int_t nbytes,objlen,keylen;
while ((leaf = (TLeaf*)next())) {
TBranch *branch = leaf->GetBranch();
Int_t nbaskets = branch->GetMaxBaskets();
for (Int_t i=0;i<nbaskets;i++) {
Long64_t pos = branch->GetBasketSeek(i);
if (!pos) continue;
TFile *branchFile = branch->GetFile();
if (!branchFile) continue;
branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
if (nbytes <= 0) continue;
branchFile->MakeFree(pos,pos+nbytes-1);
ntot += nbytes;
nbask++;
}
}
// delete Tree header key and all keys with the same name
// A Tree may have been saved many times. Previous cycles are invalid.
while (key) {
ntot += key->GetNbytes();
key->Delete();
delete key;
key = fDirectory->GetKey(GetName());
}
if (dirsav) dirsav->cd();
if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
}
if (fDirectory) {
fDirectory->Remove(this);
//delete the file cache if it points to this Tree
MoveReadCache(file,0);
fDirectory = 0;
ResetBit(kMustCleanup);
}
// Delete object from CINT symbol table so it can not be used anymore.
gCling->DeleteGlobal(this);
// Warning: We have intentional invalidated this object while inside a member function!
delete this;
}
///////////////////////////////////////////////////////////////////////////////
/// Called by TKey and TObject::Clone to automatically add us to a directory
/// when we are read from a file.
void TTree::DirectoryAutoAdd(TDirectory* dir)
{
if (fDirectory == dir) return;
if (fDirectory) {
fDirectory->Remove(this);
// Delete or move the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,dir);
}
fDirectory = dir;
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->UpdateFile();
}
if (fBranchRef) {
fBranchRef->UpdateFile();
}
if (fDirectory) fDirectory->Append(this);
}
////////////////////////////////////////////////////////////////////////////////
/// Draw expression varexp for specified entries.
///
/// \return -1 in case of error or number of selected events in case of success.
///
/// This function accepts TCut objects as arguments.
/// Useful to use the string operator +
///
/// Example:
///
/// ~~~ {.cpp}
/// ntuple.Draw("x",cut1+cut2+cut3);
/// ~~~
Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
}
////////////////////////////////////////////////////////////////////////////////
/// Draw expression varexp for specified entries.
///
/// \return -1 in case of error or number of selected events in case of success.
///
/// \param [in] varexp is an expression of the general form
/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
/// on the y-axis versus "e2" on the x-axis
/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
/// vs "e2" vs "e3" on the x-, y-, z-axis, respectively.
/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
/// (to create histograms in the 2, 3, and 4 dimensional case,
/// see section "Saving the result of Draw to an histogram")
///
/// Example:
/// - varexp = x simplest case: draw a 1-Dim distribution of column named x
/// - varexp = sqrt(x) : draw distribution of sqrt(x)
/// - varexp = x*y/z
/// - varexp = y:sqrt(x) 2-Dim distribution of y versus sqrt(x)
/// - varexp = px:py:pz:2.5*E produces a 3-d scatter-plot of px vs py ps pz
/// and the color number of each marker will be 2.5*E.
/// If the color number is negative it is set to 0.
/// If the color number is greater than the current number of colors
/// it is set to the highest color number.The default number of
/// colors is 50. see TStyle::SetPalette for setting a new color palette.
///
/// Note that the variables e1, e2 or e3 may contain a selection.
/// example, if e1= x*(y<0), the value histogrammed will be x if y<0
/// and will be 0 otherwise.
///
/// The expressions can use all the operations and build-in functions
/// supported by TFormula (See TFormula::Analyze), including free
/// standing function taking numerical arguments (TMath::Bessel).
/// In addition, you can call member functions taking numerical
/// arguments. For example:
/// ~~~ {.cpp}
/// TMath::BreitWigner(fPx,3,2)
/// event.GetHistogram().GetXaxis().GetXmax()
/// ~~~
/// Note: You can only pass expression that depend on the TTree's data
/// to static functions and you can only call non-static member function
/// with 'fixed' parameters.
///
/// \param [in] selection is an expression with a combination of the columns.
/// In a selection all the C++ operators are authorized.
/// The value corresponding to the selection expression is used as a weight
/// to fill the histogram.
/// If the expression includes only boolean operations, the result
/// is 0 or 1. If the result is 0, the histogram is not filled.
/// In general, the expression may be of the form:
/// ~~~ {.cpp}
/// value*(boolean expression)
/// ~~~
/// if boolean expression is true, the histogram is filled with
/// a `weight = value`.
/// Examples:
/// - selection1 = "x<y && sqrt(z)>3.2"
/// - selection2 = "(x+y)*(sqrt(z)>3.2)"
/// - selection1 returns a weight = 0 or 1
/// - selection2 returns a weight = x+y if sqrt(z)>3.2
/// returns a weight = 0 otherwise.
///
/// \param [in] option is the drawing option.
/// - When an histogram is produced it can be any histogram drawing option
/// listed in THistPainter.
/// - when no option is specified:
/// - the default histogram drawing option is used
/// if the expression is of the form "e1".
/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
/// unbinned 2D or 3D points is drawn respectively.
/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
/// palette.
/// - If option COL is specified when varexp has three fields:
/// ~~~ {.cpp}
/// tree.Draw("e1:e2:e3","","col");
/// ~~~
/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
/// color palette. The colors for e3 are evaluated once in linear scale before
/// painting. Therefore changing the pad to log scale along Z as no effect
/// on the colors.
/// - if expression has more than four fields the option "PARA"or "CANDLE"
/// can be used.
/// - If option contains the string "goff", no graphics is generated.
///
/// \param [in] nentries is the number of entries to process (default is all)
///
/// \param [in] firstentry is the first entry to process (default is 0)
///
/// ### Drawing expressions using arrays and array elements
///
/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
/// or a TClonesArray.
/// In a TTree::Draw expression you can now access fMatrix using the following
/// syntaxes:
///
/// | String passed | What is used for each entry of the tree
/// |-----------------|--------------------------------------------------------|
/// | `fMatrix` | the 9 elements of fMatrix |
/// | `fMatrix[][]` | the 9 elements of fMatrix |
/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
///
/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
///
/// In summary, if a specific index is not specified for a dimension, TTree::Draw
/// will loop through all the indices along this dimension. Leaving off the
/// last (right most) dimension of specifying then with the two characters '[]'
/// is equivalent. For variable size arrays (and TClonesArray) the range
/// of the first dimension is recalculated for each entry of the tree.
/// You can also specify the index as an expression of any other variables from the
/// tree.
///
/// TTree::Draw also now properly handling operations involving 2 or more arrays.
///
/// Let assume a second matrix fResults[5][2], here are a sample of some
/// of the possible combinations, the number of elements they produce and
/// the loop used:
///
/// | expression | element(s) | Loop |
/// |----------------------------------|------------|--------------------------|
/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
/// | `fMatrix[][fResult[][]]` | 30 | on 1st dim of fMatrix then on both dimensions of fResults. The value if fResults[j][k] is used as the second index of fMatrix.|
///
///
/// In summary, TTree::Draw loops through all unspecified dimensions. To
/// figure out the range of each loop, we match each unspecified dimension
/// from left to right (ignoring ALL dimensions for which an index has been
/// specified), in the equivalent loop matched dimensions use the same index
/// and are restricted to the smallest range (of only the matched dimensions).
/// When involving variable arrays, the range can of course be different
/// for each entry of the tree.
///
/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i < min(3,2); i++) {
/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
/// }
/// ~~~
/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i < min(3,5); i++) {
/// for (Int_t i1; i1 < 2; i1++) {
/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
/// }
/// }
/// ~~~
/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i < min(3,5); i++) {
/// for (Int_t i1; i1 < min(3,2); i1++) {
/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
/// }
/// }
/// ~~~
/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i0 < 3; i0++) {
/// for (Int_t j2; j2 < 5; j2++) {
/// for (Int_t j3; j3 < 2; j3++) {
/// i1 = fResults[j2][j3];
/// use the value of fMatrix[i0][i1]
/// }
/// }
/// ~~~
/// ### Retrieving the result of Draw
///
/// By default the temporary histogram created is called "htemp", but only in
/// the one dimensional Draw("e1") it contains the TTree's data points. For
/// a two dimensional Draw, the data is filled into a TGraph which is named
/// "Graph". They can be retrieved by calling
/// ~~~ {.cpp}
/// TH1F *htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
/// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
/// ~~~
/// For a three and four dimensional Draw the TPolyMarker3D is unnamed, and
/// cannot be retrieved.
///
/// gPad always contains a TH1 derived object called "htemp" which allows to
/// access the axes:
/// ~~~ {.cpp}
/// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
/// TH2F *htemp = (TH2F*)gPad->GetPrimitive("htemp"); // empty, but has axes
/// TAxis *xaxis = htemp->GetXaxis();
/// ~~~
/// ### Saving the result of Draw to an histogram
///
/// If varexp0 contains >>hnew (following the variable(s) name(s),
/// the new histogram created is called hnew and it is kept in the current
/// directory (and also the current pad). This works for all dimensions.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw("sqrt(x)>>hsqrt","y>0")
/// ~~~
/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
/// directory. To retrieve it do:
/// ~~~ {.cpp}
/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
/// ~~~
/// The binning information is taken from the environment variables
/// ~~~ {.cpp}
/// Hist.Binning.?D.?
/// ~~~
/// In addition, the name of the histogram can be followed by up to 9
/// numbers between '(' and ')', where the numbers describe the
/// following:
///
/// - 1 - bins in x-direction
/// - 2 - lower limit in x-direction
/// - 3 - upper limit in x-direction
/// - 4-6 same for y-direction
/// - 7-9 same for z-direction
///
/// When a new binning is used the new value will become the default.
/// Values can be skipped.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
/// // plot sqrt(x) between 10 and 20 using 500 bins
/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
/// // plot sqrt(x) against sin(y)
/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
/// ~~~
/// By default, the specified histogram is reset.
/// To continue to append data to an existing histogram, use "+" in front
/// of the histogram name.
///
/// A '+' in front of the histogram name is ignored, when the name is followed by
/// binning information as described in the previous paragraph.
/// ~~~ {.cpp}
/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
/// ~~~
/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
/// and 3-D histograms.
///
/// ### Accessing collection objects
///
/// TTree::Draw default's handling of collections is to assume that any
/// request on a collection pertain to it content. For example, if fTracks
/// is a collection of Track objects, the following:
/// ~~~ {.cpp}
/// tree->Draw("event.fTracks.fPx");
/// ~~~
/// will plot the value of fPx for each Track objects inside the collection.
/// Also
/// ~~~ {.cpp}
/// tree->Draw("event.fTracks.size()");
/// ~~~
/// would plot the result of the member function Track::size() for each
/// Track object inside the collection.
/// To access information about the collection itself, TTree::Draw support
/// the '@' notation. If a variable which points to a collection is prefixed
/// or postfixed with '@', the next part of the expression will pertain to
/// the collection object. For example:
/// ~~~ {.cpp}
/// tree->Draw("event.@fTracks.size()");
/// ~~~
/// will plot the size of the collection referred to by `fTracks` (i.e the number
/// of Track objects).
///
/// ### Drawing 'objects'
///
/// When a class has a member function named AsDouble or AsString, requesting
/// to directly draw the object will imply a call to one of the 2 functions.
/// If both AsDouble and AsString are present, AsDouble will be used.
/// AsString can return either a char*, a std::string or a TString.s
/// For example, the following
/// ~~~ {.cpp}
/// tree->Draw("event.myTTimeStamp");
/// ~~~
/// will draw the same histogram as
/// ~~~ {.cpp}
/// tree->Draw("event.myTTimeStamp.AsDouble()");
/// ~~~
/// In addition, when the object is a type TString or std::string, TTree::Draw
/// will call respectively `TString::Data` and `std::string::c_str()`
///
/// If the object is a TBits, the histogram will contain the index of the bit
/// that are turned on.
///
/// ### Retrieving information about the tree itself.
///
/// You can refer to the tree (or chain) containing the data by using the
/// string 'This'.
/// You can then could any TTree methods. For example:
/// ~~~ {.cpp}
/// tree->Draw("This->GetReadEntry()");
/// ~~~
/// will display the local entry numbers be read.
/// ~~~ {.cpp}
/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
/// ~~~
/// will display the name of the first 'user info' object.
///
/// ### Special functions and variables
///
/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
/// to access the entry number being read. For example to draw every
/// other entry use:
/// ~~~ {.cpp}
/// tree.Draw("myvar","Entry$%2==0");
/// ~~~
/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
/// - `LocalEntry$` : return the current entry number in the current tree of a
/// chain (`== GetTree()->GetReadEntry()`)
/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
/// - `LocalEntries$` : return the total number of entries in the current tree
/// of a chain (== GetTree()->TTree::GetEntries())
/// - `Length$` : return the total number of element of this formula for this
/// entry (`==TTreeFormula::GetNdata()`)
/// - `Iteration$` : return the current iteration over this formula for this
/// entry (i.e. varies from 0 to `Length$`).
/// - `Length$(formula )` : return the total number of element of the formula
/// given as a parameter.
/// - `Sum$(formula )` : return the sum of the value of the elements of the
/// formula given as a parameter. For example the mean for all the elements in
/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
/// - `Min$(formula )` : return the minimun (within one TTree entry) of the value of the
/// elements of the formula given as a parameter.
/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
/// elements of the formula given as a parameter.
/// - `MinIf$(formula,condition)`
/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
/// of the value of the elements of the formula given as a parameter
/// if they match the condition. If no element matches the condition,
/// the result is zero. To avoid the resulting peak at zero, use the
/// pattern:
/// ~~~ {.cpp}
/// tree->Draw("MinIf$(formula,condition)","condition");
/// ~~~
/// which will avoid calculation `MinIf$` for the entries that have no match
/// for the condition.
/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
/// for the current iteration otherwise return the value of "alternate".
/// For example, with arr1[3] and arr2[2]
/// ~~~ {.cpp}
/// tree->Draw("arr1+Alt$(arr2,0)");
/// ~~~
/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
/// Or with a variable size array arr3
/// ~~~ {.cpp}
/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
/// ~~~
/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
/// As a comparison
/// ~~~ {.cpp}
/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
/// ~~~
/// will draw the sum arr3 for the index 0 to 2 only if the
/// actual_size_of_arr3 is greater or equal to 3.
/// Note that the array in 'primary' is flattened/linearized thus using
/// `Alt$` with multi-dimensional arrays of different dimensions in unlikely
/// to yield the expected results. To visualize a bit more what elements
/// would be matched by TTree::Draw, TTree::Scan can be used:
/// ~~~ {.cpp}
/// tree->Scan("arr1:Alt$(arr2,0)");
/// ~~~
/// will print on one line the value of arr1 and (arr2,0) that will be
/// matched by
/// ~~~ {.cpp}
/// tree->Draw("arr1-Alt$(arr2,0)");
/// ~~~
/// The ternary operator is not directly supported in TTree::Draw however, to plot the
/// equivalent of `var2<20 ? -99 : var1`, you can use:
/// ~~~ {.cpp}
/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
/// ~~~
///
/// ### Drawing a user function accessing the TTree data directly
///
/// If the formula contains a file name, TTree::MakeProxy will be used
/// to load and execute this file. In particular it will draw the
/// result of a function with the same name as the file. The function
/// will be executed in a context where the name of the branches can
/// be used as a C++ variable.
///
/// For example draw px using the file hsimple.root (generated by the
/// hsimple.C tutorial), we need a file named hsimple.cxx:
/// ~~~ {.cpp}
/// double hsimple() {
/// return px;
/// }
/// ~~~
/// MakeProxy can then be used indirectly via the TTree::Draw interface
/// as follow:
/// ~~~ {.cpp}
/// new TFile("hsimple.root")
/// ntuple->Draw("hsimple.cxx");
/// ~~~
/// A more complete example is available in the tutorials directory:
/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
/// which reimplement the selector found in `h1analysis.C`
///
/// The main features of this facility are:
///
/// * on-demand loading of branches
/// * ability to use the 'branchname' as if it was a data member
/// * protection against array out-of-bound
/// * ability to use the branch data as object (when the user code is available)
///
/// See TTree::MakeProxy for more details.
///
/// ### Making a Profile histogram
///
/// In case of a 2-Dim expression, one can generate a TProfile histogram
/// instead of a TH2F histogram by specifying option=prof or option=profs
/// or option=profi or option=profg ; the trailing letter select the way
/// the bin error are computed, See TProfile2D::SetErrorOption for
/// details on the differences.
/// The option=prof is automatically selected in case of y:x>>pf
/// where pf is an existing TProfile histogram.
///
/// ### Making a 2D Profile histogram
///
/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
/// instead of a TH3F histogram by specifying option=prof or option=profs.
/// or option=profi or option=profg ; the trailing letter select the way
/// the bin error are computed, See TProfile2D::SetErrorOption for
/// details on the differences.
/// The option=prof is automatically selected in case of z:y:x>>pf
/// where pf is an existing TProfile2D histogram.
///
/// ### Making a 5D plot using GL
///
/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
/// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
///
/// ### Making a parallel coordinates plot
///
/// In case of a 2-Dim or more expression with the option=para, one can generate
/// a parallel coordinates plot. With that option, the number of dimensions is
/// arbitrary. Giving more than 4 variables without the option=para or
/// option=candle or option=goff will produce an error.
///
/// ### Making a candle sticks chart
///
/// In case of a 2-Dim or more expression with the option=candle, one can generate
/// a candle sticks chart. With that option, the number of dimensions is
/// arbitrary. Giving more than 4 variables without the option=para or
/// option=candle or option=goff will produce an error.
///
/// ### Normalizing the output histogram to 1
///
/// When option contains "norm" the output histogram is normalized to 1.
///
/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
///
/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
/// instead of histogramming one variable.
/// If varexp0 has the form >>elist , a TEventList object named "elist"
/// is created in the current directory. elist will contain the list
/// of entry numbers satisfying the current selection.
/// If option "entrylist" is used, a TEntryList object is created
/// If the selection contains arrays, vectors or any container class and option
/// "entrylistarray" is used, a TEntryListArray object is created
/// containing also the subentries satisfying the selection, i.e. the indices of
/// the branches which hold containers classes.
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>yplus","y>0")
/// ~~~
/// will create a TEventList object named "yplus" in the current directory.
/// In an interactive session, one can type (after TTree::Draw)
/// ~~~ {.cpp}
/// yplus.Print("all")
/// ~~~
/// to print the list of entry numbers in the list.
/// ~~~ {.cpp}
/// tree.Draw(">>yplus", "y>0", "entrylist")
/// ~~~
/// will create a TEntryList object names "yplus" in the current directory
/// ~~~ {.cpp}
/// tree.Draw(">>yplus", "y>0", "entrylistarray")
/// ~~~
/// will create a TEntryListArray object names "yplus" in the current directory
///
/// By default, the specified entry list is reset.
/// To continue to append data to an existing list, use "+" in front
/// of the list name;
/// ~~~ {.cpp}
/// tree.Draw(">>+yplus","y>0")
/// ~~~
/// will not reset yplus, but will enter the selected entries at the end
/// of the existing list.
///
/// ### Using a TEventList, TEntryList or TEntryListArray as Input
///
/// Once a TEventList or a TEntryList object has been generated, it can be used as input
/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
/// current event list
///
/// Example 1:
/// ~~~ {.cpp}
/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
/// tree->SetEventList(elist);
/// tree->Draw("py");
/// ~~~
/// Example 2:
/// ~~~ {.cpp}
/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
/// tree->SetEntryList(elist);
/// tree->Draw("py");
/// ~~~
/// If a TEventList object is used as input, a new TEntryList object is created
/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
/// for this transformation. This new object is owned by the chain and is deleted
/// with it, unless the user extracts it by calling GetEntryList() function.
/// See also comments to SetEventList() function of TTree and TChain.
///
/// If arrays are used in the selection criteria and TEntryListArray is not used,
/// all the entries that have at least one element of the array that satisfy the selection
/// are entered in the list.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>pyplus","fTracks.fPy>0");
/// tree->SetEventList(pyplus);
/// tree->Draw("fTracks.fPy");
/// ~~~
/// will draw the fPy of ALL tracks in event with at least one track with
/// a positive fPy.
///
/// To select only the elements that did match the original selection
/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>pyplus","fTracks.fPy>0");
/// pyplus->SetReapplyCut(kTRUE);
/// tree->SetEventList(pyplus);
/// tree->Draw("fTracks.fPy");
/// ~~~
/// will draw the fPy of only the tracks that have a positive fPy.
///
/// To draw only the elements that match a selection in case of arrays,
/// you can also use TEntryListArray (faster in case of a more general selection).
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
/// tree->SetEntryList(pyplus);
/// tree->Draw("fTracks.fPy");
/// ~~~
/// will draw the fPy of only the tracks that have a positive fPy,
/// but without redoing the selection.
///
/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
///
/// ### How to obtain more info from TTree::Draw
///
/// Once TTree::Draw has been called, it is possible to access useful
/// information still stored in the TTree object via the following functions:
///
/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
/// - GetV1() // returns a pointer to the double array of V1
/// - GetV2() // returns a pointer to the double array of V2
/// - GetV3() // returns a pointer to the double array of V3
/// - GetV4() // returns a pointer to the double array of V4
/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
///
/// where V1,V2,V3 correspond to the expressions in
/// ~~~ {.cpp}
/// TTree::Draw("V1:V2:V3:V4",selection);
/// ~~~
/// If the expression has more than 4 component use GetVal(index)
///
/// Example:
/// ~~~ {.cpp}
/// Root > ntuple->Draw("py:px","pz>4");
/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
/// ntuple->GetV2(), ntuple->GetV1());
/// Root > gr->Draw("ap"); //draw graph in current pad
/// ~~~
///
/// A more complete complete tutorial (treegetval.C) shows how to use the
/// GetVal() method.
///
/// creates a TGraph object with a number of points corresponding to the
/// number of entries selected by the expression "pz>4", the x points of the graph
/// being the px values of the Tree and the y points the py values.
///
/// Important note: By default TTree::Draw creates the arrays obtained
/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
/// values calculated.
/// By default fEstimate=1000000 and can be modified
/// via TTree::SetEstimate. To keep in memory all the results (in case
/// where there is only one result per entry), use
/// ~~~ {.cpp}
/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
/// ~~~
/// You must call SetEstimate if the expected number of selected rows
/// you need to look at is greater than 1000000.
///
/// You can use the option "goff" to turn off the graphics output
/// of TTree::Draw in the above example.
///
/// ### Automatic interface to TTree::Draw via the TTreeViewer
///
/// A complete graphical interface to this function is implemented
/// in the class TTreeViewer.
/// To start the TTreeViewer, three possibilities:
/// - select TTree context menu item "StartViewer"
/// - type the command "TTreeViewer TV(treeName)"
/// - execute statement "tree->StartViewer();"
Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer)
return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Remove some baskets from memory.
void TTree::DropBaskets()
{
TBranch* branch = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
branch = (TBranch*) fBranches.UncheckedAt(i);
branch->DropBaskets("all");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
void TTree::DropBuffers(Int_t)
{
// Be careful not to remove current read/write buffers.
Int_t ndrop = 0;
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; ++i) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
for (Int_t j = 0; j < nbaskets - 1; ++j) {
if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
continue;
}
TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
if (basket) {
ndrop += basket->DropBuffers();
if (fTotalBuffers < fMaxVirtualSize) {
return;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Fill all branches.
///
/// This function loops on all the branches of this tree. For
/// each branch, it copies to the branch buffer (basket) the current
/// values of the leaves data types. If a leaf is a simple data type,
/// a simple conversion to a machine independent format has to be done.
///
/// This machine independent version of the data is copied into a
/// basket (each branch has its own basket). When a basket is full
/// (32k worth of data by default), it is then optionally compressed
/// and written to disk (this operation is also called committing or
/// 'flushing' the basket). The committed baskets are then
/// immediately removed from memory.
///
/// The function returns the number of bytes committed to the
/// individual branches.
///
/// If a write error occurs, the number of bytes returned is -1.
///
/// If no data are written, because, e.g., the branch is disabled,
/// the number of bytes returned is 0.
///
/// __The baskets are flushed and the Tree header saved at regular intervals__
///
/// At regular intervals, when the amount of data written so far is
/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
/// This makes future reading faster as it guarantees that baskets belonging to nearby
/// entries will be on the same disk region.
/// When the first call to flush the baskets happen, we also take this opportunity
/// to optimize the baskets buffers.
/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
/// in case the program writing the Tree crashes.
/// The decisions to FlushBaskets and Auto Save can be made based either on the number
/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
/// written (fAutoFlush and fAutoSave positive).
/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
/// base on the number of events written instead of the number of bytes written.
///
/// Note that calling FlushBaskets too often increases the IO time.
///
/// Note that calling AutoSave too often increases the IO time and also the file size.
Int_t TTree::Fill()
{
Int_t nbytes = 0;
Int_t nwrite = 0;
Int_t nerror = 0;
Int_t nbranches = fBranches.GetEntriesFast();
// Case of one single super branch. Automatically update
// all the branch addresses if a new object was created.
if (nbranches == 1)
((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
if (fBranchRef)
fBranchRef->Clear();
#ifdef R__USE_IMT
const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
ROOT::Internal::TBranchIMTHelper imtHelper;
if (useIMT) {
fIMTFlush = true;
fIMTZipBytes.store(0);
fIMTTotBytes.store(0);
}
#endif
for (Int_t i = 0; i < nbranches; ++i) {
// Loop over all branches, filling and accumulating bytes written and error counts.
TBranch *branch = (TBranch *)fBranches.UncheckedAt(i);
if (branch->TestBit(kDoNotProcess))
continue;
#ifndef R__USE_IMT
nwrite = branch->FillImpl(nullptr);
#else
nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
#endif
if (nwrite < 0) {
if (nerror < 2) {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
" This error is symptomatic of a Tree created as a memory-resident Tree\n"
" Instead of doing:\n"
" TTree *T = new TTree(...)\n"
" TFile *f = new TFile(...)\n"
" you should do:\n"
" TFile *f = new TFile(...)\n"
" TTree *T = new TTree(...)\n\n",
GetName(), branch->GetName(), nwrite, fEntries + 1);
} else {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
fEntries + 1);
}
++nerror;
} else {
nbytes += nwrite;
}
}
#ifdef R__USE_IMT
if (fIMTFlush) {
imtHelper.Wait();
fIMTFlush = false;
const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
nbytes += imtHelper.GetNbytes();
nerror += imtHelper.GetNerrors();
}
#endif
if (fBranchRef)
fBranchRef->Fill();
++fEntries;
if (fEntries > fMaxEntries)
KeepCircular();
if (gDebug > 0)
Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
GetZipBytes(), fFlushedBytes, fSavedBytes);
bool autoFlush = false;
bool autoSave = false;
if (fAutoFlush != 0 || fAutoSave != 0) {
// Is it time to flush or autosave baskets?
if (fFlushedBytes == 0) {
// If fFlushedBytes == 0, it means we never flushed or saved, so
// we need to check if it's time to do it and recompute the values
// of fAutoFlush and fAutoSave in terms of the number of entries.
// Decision can be based initially either on the number of bytes
// or the number of entries written.
Long64_t zipBytes = GetZipBytes();
if (fAutoFlush)
autoFlush = fAutoFlush < 0 ? (zipBytes > -fAutoFlush) : fEntries % fAutoFlush == 0;
if (fAutoSave)
autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
if (autoFlush || autoSave) {
// First call FlushBasket to make sure that fTotBytes is up to date.
FlushBasketsImpl();
autoFlush = false; // avoid auto flushing again later
// When we are in one-basket-per-cluster mode, there is no need to optimize basket:
// they will automatically grow to the size needed for an event cluster (with the basket
// shrinking preventing them from growing too much larger than the actually-used space).
if (!TestBit(TTree::kOnlyFlushAtCluster)) {
OptimizeBaskets(GetTotBytes(), 1, "");
if (gDebug > 0)
Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
fEntries, GetZipBytes(), fFlushedBytes);
}
fFlushedBytes = GetZipBytes();
fAutoFlush = fEntries; // Use test on entries rather than bytes
// subsequently in run
if (fAutoSave < 0) {
// Set fAutoSave to the largest integer multiple of
// fAutoFlush events such that fAutoSave*fFlushedBytes
// < (minus the input value of fAutoSave)
Long64_t totBytes = GetTotBytes();
if (zipBytes != 0) {
fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / zipBytes) / fEntries));
} else if (totBytes != 0) {
fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / totBytes) / fEntries));
} else {
TBufferFile b(TBuffer::kWrite, 10000);
TTree::Class()->WriteBuffer(b, (TTree *)this);
Long64_t total = b.Length();
fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / total) / fEntries));
}
} else if (fAutoSave > 0) {
fAutoSave = fAutoFlush * (fAutoSave / fAutoFlush);
}
if (fAutoSave != 0 && fEntries >= fAutoSave)
autoSave = true;
if (gDebug > 0)
Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
}
} else {
// Check if we need to auto flush
if (fAutoFlush) {
if (fNClusterRange == 0)
autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
else
autoFlush = (fEntries - (fClusterRangeEnd[fNClusterRange - 1] + 1)) % fAutoFlush == 0;
}
// Check if we need to auto save
if (fAutoSave)
autoSave = fEntries % fAutoSave == 0;
}
}
if (autoFlush) {
FlushBasketsImpl();
if (gDebug > 0)
Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
GetZipBytes(), fFlushedBytes);
fFlushedBytes = GetZipBytes();
}
if (autoSave) {
AutoSave(); // does not call FlushBasketsImpl() again
if (gDebug > 0)
Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
GetZipBytes(), fSavedBytes);
}
// Check that output file is still below the maximum size.
// If above, close the current file and continue on a new file.
// Currently, the automatic change of file is restricted
// to the case where the tree is in the top level directory.
if (fDirectory)
if (TFile *file = fDirectory->GetFile())
if ((TDirectory *)file == fDirectory && (file->GetEND() > fgMaxTreeSize))
ChangeFile(file);
return nerror == 0 ? nbytes : -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Search in the array for a branch matching the branch name,
/// with the branch possibly expressed as a 'full' path name (with dots).
static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
if (list==0 || branchname == 0 || branchname[0] == '\0') return 0;
Int_t nbranches = list->GetEntries();
UInt_t brlen = strlen(branchname);
for(Int_t index = 0; index < nbranches; ++index) {
TBranch *where = (TBranch*)list->UncheckedAt(index);
const char *name = where->GetName();
UInt_t len = strlen(name);
if (len && name[len-1]==']') {
const char *dim = strchr(name,'[');
if (dim) {
len = dim - name;
}
}
if (brlen == len && strncmp(branchname,name,len)==0) {
return where;
}
TBranch *next = 0;
if ((brlen >= len) && (branchname[len] == '.')
&& strncmp(name, branchname, len) == 0) {
// The prefix subbranch name match the branch name.
next = where->FindBranch(branchname);
if (!next) {
next = where->FindBranch(branchname+len+1);
}
if (next) return next;
}
const char *dot = strchr((char*)branchname,'.');
if (dot) {
if (len==(size_t)(dot-branchname) &&
strncmp(branchname,name,dot-branchname)==0 ) {
return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
}
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return the branch that correspond to the path 'branchname', which can
/// include the name of the tree or the omitted name of the parent branches.
/// In case of ambiguity, returns the first match.
TBranch* TTree::FindBranch(const char* branchname)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kFindBranch & fFriendLockStatus) {
return 0;
}
TBranch* branch = 0;
// If the first part of the name match the TTree name, look for the right part in the
// list of branches.
// This will allow the branchname to be preceded by
// the name of this tree.
if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
if (branch) return branch;
}
// If we did not find it, let's try to find the full name in the list of branches.
branch = R__FindBranchHelper(GetListOfBranches(), branchname);
if (branch) return branch;
// If we still did not find, let's try to find it within each branch assuming it does not the branch name.
TIter next(GetListOfBranches());
while ((branch = (TBranch*) next())) {
TBranch* nestedbranch = branch->FindBranch(branchname);
if (nestedbranch) {
return nestedbranch;
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindBranch);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
const char *subbranch = strstr(branchname, fe->GetName());
if (subbranch != branchname) {
subbranch = 0;
}
if (subbranch) {
subbranch += strlen(fe->GetName());
if (*subbranch != '.') {
subbranch = 0;
} else {
++subbranch;
}
}
std::ostringstream name;
if (subbranch) {
name << t->GetName() << "." << subbranch;
} else {
name << branchname;
}
branch = t->FindBranch(name.str().c_str());
if (branch) {
return branch;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Find leaf..
TLeaf* TTree::FindLeaf(const char* searchname)
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kFindLeaf & fFriendLockStatus) {
return 0;
}
// This will allow the branchname to be preceded by
// the name of this tree.
char* subsearchname = (char*) strstr(searchname, GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
if (subsearchname[0]==0) {
subsearchname = 0;
}
}
}
TString leafname;
TString leaftitle;
TString longname;
TString longtitle;
const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
// For leaves we allow for one level up to be prefixed to the name.
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leafname = leaf->GetName();
Ssiz_t dim = leafname.First('[');
if (dim >= 0) leafname.Remove(dim);
if (leafname == searchname) {
return leaf;
}
if (subsearchname && leafname == subsearchname) {
return leaf;
}
// The TLeafElement contains the branch name
// in its name, let's use the title.
leaftitle = leaf->GetTitle();
dim = leaftitle.First('[');
if (dim >= 0) leaftitle.Remove(dim);
if (leaftitle == searchname) {
return leaf;
}
if (subsearchname && leaftitle == subsearchname) {
return leaf;
}
if (!searchnameHasDot)
continue;
TBranch* branch = leaf->GetBranch();
if (branch) {
longname.Form("%s.%s",branch->GetName(),leafname.Data());
dim = longname.First('[');
if (dim>=0) longname.Remove(dim);
if (longname == searchname) {
return leaf;
}
if (subsearchname && longname == subsearchname) {
return leaf;
}
longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
dim = longtitle.First('[');
if (dim>=0) longtitle.Remove(dim);
if (longtitle == searchname) {
return leaf;
}
if (subsearchname && longtitle == subsearchname) {
return leaf;
}
// The following is for the case where the branch is only
// a sub-branch. Since we do not see it through
// TTree::GetListOfBranches, we need to see it indirectly.
// This is the less sturdy part of this search ... it may
// need refining ...
if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
return leaf;
}
if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
return leaf;
}
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindLeaf);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
subsearchname = (char*) strstr(searchname, fe->GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(fe->GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
}
}
if (subsearchname) {
leafname.Form("%s.%s",t->GetName(),subsearchname);
} else {
leafname = searchname;
}
leaf = t->FindLeaf(leafname);
if (leaf) {
return leaf;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Fit a projected item(s) from a tree.
///
/// funcname is a TF1 function.
///
/// See TTree::Draw() for explanations of the other parameters.
///
/// By default the temporary histogram created is called htemp.
/// If varexp contains >>hnew , the new histogram created is called hnew
/// and it is kept in the current directory.
///
/// The function returns the number of selected entries.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
/// ~~~
/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
/// directory.
///
/// See also TTree::UnbinnedFit
///
/// ## Return status
///
/// The function returns the status of the histogram fit (see TH1::Fit)
/// If no entries were selected, the function returns -1;
/// (i.e. fitResult is null if the fit is OK)
Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
}
return -1;
}
namespace {
struct BoolRAIIToggle {
Bool_t &m_val;
BoolRAIIToggle(Bool_t &val) : m_val(val) { m_val = true; }
~BoolRAIIToggle() { m_val = false; }
};
}
////////////////////////////////////////////////////////////////////////////////
/// Write to disk all the basket that have not yet been individually written and
/// create an event cluster boundary (by default).
///
/// If the caller wishes to flush the baskets but not create an event cluster,
/// then set create_cluster to false.
///
/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
/// via TThreadExecutor to do this operation; one per basket compression. If the
/// caller utilizes TBB also, care must be taken to prevent deadlocks.
///
/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
/// run another one of the user's tasks in this thread. If the second user task
/// tries to acquire A, then a deadlock will occur. The example call sequence
/// looks like this:
///
/// - User acquires mutex A
/// - User calls FlushBaskets.
/// - ROOT launches N tasks and calls wait.
/// - TBB schedules another user task, T2.
/// - T2 tries to acquire mutex A.
///
/// At this point, the thread will deadlock: the code may function with IMT-mode
/// disabled if the user assumed the legacy code never would run their own TBB
/// tasks.
///
/// SO: users of TBB who want to enable IMT-mode should carefully review their
/// locking patterns and make sure they hold no coarse-grained application
/// locks when they invoke ROOT.
///
/// Return the number of bytes written or -1 in case of write error.
Int_t TTree::FlushBaskets(Bool_t create_cluster) const
{
Int_t retval = FlushBasketsImpl();
if (retval == -1) return retval;
if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
return retval;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal implementation of the FlushBaskets algorithm.
/// Unlike the public interface, this does NOT create an explicit event cluster
/// boundary; it is up to the (internal) caller to determine whether that should
/// done.
///
/// Otherwise, the comments for FlushBaskets applies.
///
Int_t TTree::FlushBasketsImpl() const
{
if (!fDirectory) return 0;
Int_t nbytes = 0;
Int_t nerror = 0;
TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
Int_t nb = lb->GetEntriesFast();
#ifdef R__USE_IMT
const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
if (useIMT) {
// ROOT-9668: here we need to check if the size of fSortedBranches is different from the
// size of the list of branches before triggering the initialisation of the fSortedBranches
// container to cover two cases:
// 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
// 2. We flushed at least once already but a branch has been be added to the tree since then
if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
BoolRAIIToggle sentry(fIMTFlush);
fIMTZipBytes.store(0);
fIMTTotBytes.store(0);
std::atomic<Int_t> nerrpar(0);
std::atomic<Int_t> nbpar(0);
std::atomic<Int_t> pos(0);
auto mapFunction = [&]() {
// The branch to process is obtained when the task starts to run.
// This way, since branches are sorted, we make sure that branches
// leading to big tasks are processed first. If we assigned the
// branch at task creation time, the scheduler would not necessarily
// respect our sorting.
Int_t j = pos.fetch_add(1);
auto branch = fSortedBranches[j].second;
if (R__unlikely(!branch)) { return; }
if (R__unlikely(gDebug > 0)) {
std::stringstream ss;
ss << std::this_thread::get_id();
Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
}
Int_t nbtask = branch->FlushBaskets();
if (nbtask < 0) { nerrpar++; }
else { nbpar += nbtask; }
};
ROOT::TThreadExecutor pool;
pool.Foreach(mapFunction, nb);
fIMTFlush = false;
const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
return nerrpar ? -1 : nbpar.load();
}
#endif
for (Int_t j = 0; j < nb; j++) {
TBranch* branch = (TBranch*) lb->UncheckedAt(j);
if (branch) {
Int_t nwrite = branch->FlushBaskets();
if (nwrite<0) {
++nerror;
} else {
nbytes += nwrite;
}
}
}
if (nerror) {
return -1;
} else {
return nbytes;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the expanded value of the alias. Search in the friends if any.
const char* TTree::GetAlias(const char* aliasName) const
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetAlias & fFriendLockStatus) {
return 0;
}
if (fAliases) {
TObject* alias = fAliases->FindObject(aliasName);
if (alias) {
return alias->GetTitle();
}
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t) {
const char* alias = t->GetAlias(aliasName);
if (alias) {
return alias;
}
const char* subAliasName = strstr(aliasName, fe->GetName());
if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
if (alias) {
return alias;
}
}
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the branch with the given name in this tree or its friends.
TBranch* TTree::GetBranch(const char* name)
{
if (name == 0) return 0;
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetBranch & fFriendLockStatus) {
return 0;
}
// Search using branches.
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
if (!branch) {
continue;
}
if (!strcmp(branch->GetName(), name)) {
return branch;
}
TObjArray* lb = branch->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; j++) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!strcmp(b1->GetName(), name)) {
return b1;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; k++) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!strcmp(b2->GetName(), name)) {
return b2;
}
}
}
}
// Search using leaves.
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (!strcmp(branch->GetName(), name)) {
return branch;
}
}
if (!fFriends) {
return 0;
}
// Search in list of friends.
TFriendLock lock(this, kGetBranch);
TIter next(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (t) {
TBranch* branch = t->GetBranch(name);
if (branch) {
return branch;
}
}
}
// Second pass in the list of friends when
// the branch name is prefixed by the tree name.
next.Reset();
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
char* subname = (char*) strstr(name, fe->GetName());
if (subname != name) {
continue;
}
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') {
continue;
}
subname++;
TBranch* branch = t->GetBranch(subname);
if (branch) {
return branch;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return status of branch with name branchname.
///
/// - 0 if branch is not activated
/// - 1 if branch is activated
Bool_t TTree::GetBranchStatus(const char* branchname) const
{
TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
if (br) {
return br->TestBit(kDoNotProcess) == 0;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Static function returning the current branch style.
///
/// - style = 0 old Branch
/// - style = 1 new Bronch
Int_t TTree::GetBranchStyle()
{
return fgBranchStyle;
}
////////////////////////////////////////////////////////////////////////////////
/// Used for automatic sizing of the cache.
///
/// Estimates a suitable size for the tree cache based on AutoFlush.
/// A cache sizing factor is taken from the configuration. If this yields zero
/// and withDefault is true the historical algorithm for default size is used.
Long64_t TTree::GetCacheAutoSize(Bool_t withDefault /* = kFALSE */ ) const
{
const char *stcs;
Double_t cacheFactor = 0.0;
if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
} else {
cacheFactor = TString(stcs).Atof();
}
if (cacheFactor < 0.0) {
// ignore negative factors
cacheFactor = 0.0;
}
Long64_t cacheSize = 0;
if (fAutoFlush < 0) cacheSize = Long64_t(-cacheFactor*fAutoFlush);
else if (fAutoFlush == 0) cacheSize = 0;
else cacheSize = Long64_t(cacheFactor*1.5*fAutoFlush*GetZipBytes()/(fEntries+1));
if (cacheSize >= (INT_MAX / 4)) {
cacheSize = INT_MAX / 4;
}
if (cacheSize < 0) {
cacheSize = 0;
}
if (cacheSize == 0 && withDefault) {
if (fAutoFlush < 0) cacheSize = -fAutoFlush;
else if (fAutoFlush == 0) cacheSize = 0;
else cacheSize = Long64_t(1.5*fAutoFlush*GetZipBytes()/(fEntries+1));
}
return cacheSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Return an iterator over the cluster of baskets starting at firstentry.
///
/// This iterator is not yet supported for TChain object.
/// ~~~ {.cpp}
/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
/// Long64_t clusterStart;
/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
/// }
/// ~~~
TTree::TClusterIterator TTree::GetClusterIterator(Long64_t firstentry)
{
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
return TClusterIterator(this,firstentry);
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the current file.
TFile* TTree::GetCurrentFile() const
{
if (!fDirectory || fDirectory==gROOT) {
return 0;
}
return fDirectory->GetFile();
}
////////////////////////////////////////////////////////////////////////////////
/// Return the number of entries matching the selection.
/// Return -1 in case of errors.
///
/// If the selection uses any arrays or containers, we return the number
/// of entries where at least one element match the selection.
/// GetEntries is implemented using the selector class TSelectorEntries,
/// which can be used directly (see code in TTreePlayer::GetEntries) for
/// additional option.
/// If SetEventList was used on the TTree or TChain, only that subset
/// of entries will be considered.
Long64_t TTree::GetEntries(const char *selection)
{
GetPlayer();
if (fPlayer) {
return fPlayer->GetEntries(selection);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the 1st Leaf named name in any Branch of this Tree or
/// any branch in the list of friend trees.
Long64_t TTree::GetEntriesFriend() const
{
if (fEntries) return fEntries;
if (!fFriends) return 0;
TFriendElement *fr = (TFriendElement*)fFriends->At(0);
if (!fr) return 0;
TTree *t = fr->GetTree();
if (t==0) return 0;
return t->GetEntriesFriend();
}
////////////////////////////////////////////////////////////////////////////////
/// Read all branches of entry and return total number of bytes read.
///
/// - `getall = 0` : get only active branches
/// - `getall = 1` : get all branches
///
/// The function returns the number of bytes read from the input buffer.
/// If entry does not exist the function returns 0.
/// If an I/O error occurs, the function returns -1.
///
/// If the Tree has friends, also read the friends entry.
///
/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
/// For example, if you have a Tree with several hundred branches, and you
/// are interested only by branches named "a" and "b", do
/// ~~~ {.cpp}
/// mytree.SetBranchStatus("*",0); //disable all branches
/// mytree.SetBranchStatus("a",1);
/// mytree.SetBranchStatus("b",1);
/// ~~~
/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
///
/// __WARNING!!__
/// If your Tree has been created in split mode with a parent branch "parent.",
/// ~~~ {.cpp}
/// mytree.SetBranchStatus("parent",1);
/// ~~~
/// will not activate the sub-branches of "parent". You should do:
/// ~~~ {.cpp}
/// mytree.SetBranchStatus("parent*",1);
/// ~~~
/// Without the trailing dot in the branch creation you have no choice but to
/// call SetBranchStatus explicitly for each of the sub branches.
///
/// An alternative is to call directly
/// ~~~ {.cpp}
/// brancha.GetEntry(i)
/// branchb.GetEntry(i);
/// ~~~
/// ## IMPORTANT NOTE
///
/// By default, GetEntry reuses the space allocated by the previous object
/// for each branch. You can force the previous object to be automatically
/// deleted if you call mybranch.SetAutoDelete(kTRUE) (default is kFALSE).
///
/// Example:
///
/// Consider the example in $ROOTSYS/test/Event.h
/// The top level branch in the tree T is declared with:
/// ~~~ {.cpp}
/// Event *event = 0; //event must be null or point to a valid object
/// //it must be initialized
/// T.SetBranchAddress("event",&event);
/// ~~~
/// When reading the Tree, one can choose one of these 3 options:
///
/// ## OPTION 1
///
/// ~~~ {.cpp}
/// for (Long64_t i=0;i<nentries;i++) {
/// T.GetEntry(i);
/// // the object event has been filled at this point
/// }
/// ~~~
/// The default (recommended). At the first entry an object of the class
/// Event will be created and pointed by event. At the following entries,
/// event will be overwritten by the new data. All internal members that are
/// TObject* are automatically deleted. It is important that these members
/// be in a valid state when GetEntry is called. Pointers must be correctly
/// initialized. However these internal members will not be deleted if the
/// characters "->" are specified as the first characters in the comment
/// field of the data member declaration.
///
/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
/// In this case, it is assumed that the pointer is never null (case of
/// pointer TClonesArray *fTracks in the Event example). If "->" is not
/// specified, the pointer member is read via buf >> pointer. In this case
/// the pointer may be null. Note that the option with "->" is faster to
/// read or write and it also consumes less space in the file.
///
/// ## OPTION 2
///
/// The option AutoDelete is set
/// ~~~ {.cpp}
/// TBranch *branch = T.GetBranch("event");
/// branch->SetAddress(&event);
/// branch->SetAutoDelete(kTRUE);
/// for (Long64_t i=0;i<nentries;i++) {
/// T.GetEntry(i);
/// // the object event has been filled at this point
/// }
/// ~~~
/// In this case, at each iteration, the object event is deleted by GetEntry
/// and a new instance of Event is created and filled.
///
/// ## OPTION 3
///
/// ~~~ {.cpp}
/// Same as option 1, but you delete yourself the event.
///
/// for (Long64_t i=0;i<nentries;i++) {
/// delete event;
/// event = 0; // EXTREMELY IMPORTANT
/// T.GetEntry(i);
/// // the object event has been filled at this point
/// }
/// ~~~
/// It is strongly recommended to use the default option 1. It has the
/// additional advantage that functions like TTree::Draw (internally calling
/// TTree::GetEntry) will be functional even when the classes in the file are
/// not available.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// object ownership policy of the underlying (user) data.
Int_t TTree::GetEntry(Long64_t entry, Int_t getall)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetEntry & fFriendLockStatus) return 0;
if (entry < 0 || entry >= fEntries) return 0;
Int_t i;
Int_t nbytes = 0;
fReadEntry = entry;
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
Int_t nbranches = fBranches.GetEntriesUnsafe();
Int_t nb=0;
auto seqprocessing = [&]() {
TBranch *branch;
for (i=0;i<nbranches;i++) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(entry, getall);
if (nb < 0) break;
nbytes += nb;
}
};
#ifdef R__USE_IMT
if (nbranches > 1 && ROOT::IsImplicitMTEnabled() && fIMTEnabled && !TTreeCacheUnzip::IsParallelUnzip()) {
if (fSortedBranches.empty())
InitializeBranchLists(true);
// Count branches are processed first and sequentially
for (auto branch : fSeqBranches) {
nb = branch->GetEntry(entry, getall);
if (nb < 0) break;
nbytes += nb;
}
if (nb < 0) return nb;
// Enable this IMT use case (activate its locks)
ROOT::Internal::TParBranchProcessingRAII pbpRAII;
Int_t errnb = 0;
std::atomic<Int_t> pos(0);
std::atomic<Int_t> nbpar(0);
auto mapFunction = [&]() {
// The branch to process is obtained when the task starts to run.
// This way, since branches are sorted, we make sure that branches
// leading to big tasks are processed first. If we assigned the
// branch at task creation time, the scheduler would not necessarily
// respect our sorting.
Int_t j = pos.fetch_add(1);
Int_t nbtask = 0;
auto branch = fSortedBranches[j].second;
if (gDebug > 0) {
std::stringstream ss;
ss << std::this_thread::get_id();
Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
}
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
nbtask = branch->GetEntry(entry, getall);
end = std::chrono::system_clock::now();
Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
fSortedBranches[j].first += tasktime;
if (nbtask < 0) errnb = nbtask;
else nbpar += nbtask;
};
ROOT::TThreadExecutor pool;
pool.Foreach(mapFunction, fSortedBranches.size());
if (errnb < 0) {
nb = errnb;
}
else {
// Save the number of bytes read by the tasks
nbytes += nbpar;
// Re-sort branches if necessary
if (++fNEntriesSinceSorting == kNEntriesResort) {
SortBranchesByTime();
fNEntriesSinceSorting = 0;
}
}
}
else {
seqprocessing();
}
#else
seqprocessing();
#endif
if (nb < 0) return nb;
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntry);
TIter nextf(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t) {
if (fe->TestBit(TFriendElement::kFromChain)) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else {
if ( t->LoadTreeFriend(entry,this) >= 0 ) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else nb = 0;
}
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
////////////////////////////////////////////////////////////////////////////////
/// Divides the top-level branches into two vectors: (i) branches to be
/// processed sequentially and (ii) branches to be processed in parallel.
/// Even if IMT is on, some branches might need to be processed first and in a
/// sequential fashion: in the parallelization of GetEntry, those are the
/// branches that store the size of another branch for every entry
/// (e.g. the size of an array branch). If such branches were processed
/// in parallel with the rest, there could be two threads invoking
/// TBranch::GetEntry on one of them at the same time, since a branch that
/// depends on a size (or count) branch will also invoke GetEntry on the latter.
/// This method can be invoked several times during the event loop if the TTree
/// is being written, for example when adding new branches. In these cases, the
/// `checkLeafCount` parameter is false.
/// \param[in] checkLeafCount True if we need to check whether some branches are
/// count leaves.
void TTree::InitializeBranchLists(bool checkLeafCount)
{
Int_t nbranches = fBranches.GetEntriesFast();
// The special branch fBranchRef needs to be processed sequentially:
// we add it once only.
if (fBranchRef && fBranchRef != fSeqBranches[0]) {
fSeqBranches.push_back(fBranchRef);
}
// The branches to be processed sequentially are those that are the leaf count of another branch
if (checkLeafCount) {
for (Int_t i = 0; i < nbranches; i++) {
TBranch* branch = (TBranch*)fBranches.UncheckedAt(i);
auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
if (leafCount) {
auto countBranch = leafCount->GetBranch();
if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
fSeqBranches.push_back(countBranch);
}
}
}
}
// Any branch that is not a leaf count can be safely processed in parallel when reading
// We need to reset the vector to make sure we do not re-add several times the same branch.
if (!checkLeafCount) {
fSortedBranches.clear();
}
for (Int_t i = 0; i < nbranches; i++) {
Long64_t bbytes = 0;
TBranch* branch = (TBranch*)fBranches.UncheckedAt(i);
if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
bbytes = branch->GetTotBytes("*");
fSortedBranches.emplace_back(bbytes, branch);
}
}
// Initially sort parallel branches by size
std::sort(fSortedBranches.begin(),
fSortedBranches.end(),
[](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
return a.first > b.first;
});
for (size_t i = 0; i < fSortedBranches.size(); i++) {
fSortedBranches[i].first = 0LL;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Sorts top-level branches by the last average task time recorded per branch.
void TTree::SortBranchesByTime()
{
for (size_t i = 0; i < fSortedBranches.size(); i++) {
fSortedBranches[i].first *= kNEntriesResortInv;
}
std::sort(fSortedBranches.begin(),
fSortedBranches.end(),
[](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
return a.first > b.first;
});
for (size_t i = 0; i < fSortedBranches.size(); i++) {
fSortedBranches[i].first = 0LL;
}
}
////////////////////////////////////////////////////////////////////////////////
///Returns the entry list assigned to this tree
TEntryList* TTree::GetEntryList()
{
return fEntryList;
}
////////////////////////////////////////////////////////////////////////////////
/// Return entry number corresponding to entry.
///
/// if no TEntryList set returns entry
/// else returns the entry number corresponding to the list index=entry
Long64_t TTree::GetEntryNumber(Long64_t entry) const
{
if (!fEntryList) {
return entry;
}
return fEntryList->GetEntry(entry);
}
////////////////////////////////////////////////////////////////////////////////
/// Return entry number corresponding to major and minor number.
/// Note that this function returns only the entry number, not the data
/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
/// the BuildIndex function has created a table of Long64_t* of sorted values
/// corresponding to val = major<<31 + minor;
/// The function performs binary search in this sorted table.
/// If it finds a pair that matches val, it returns directly the
/// index in the table.
/// If an entry corresponding to major and minor is not found, the function
/// returns the index of the major,minor pair immediately lower than the
/// requested value, ie it will return -1 if the pair is lower than
/// the first entry in the index.
///
/// See also GetEntryNumberWithIndex
Long64_t TTree::GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor) const
{
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithBestIndex(major, minor);
}
////////////////////////////////////////////////////////////////////////////////
/// Return entry number corresponding to major and minor number.
/// Note that this function returns only the entry number, not the data
/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
/// the BuildIndex function has created a table of Long64_t* of sorted values
/// corresponding to val = major<<31 + minor;
/// The function performs binary search in this sorted table.
/// If it finds a pair that matches val, it returns directly the
/// index in the table, otherwise it returns -1.
///
/// See also GetEntryNumberWithBestIndex
Long64_t TTree::GetEntryNumberWithIndex(Long64_t major, Long64_t minor) const
{
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithIndex(major, minor);
}
////////////////////////////////////////////////////////////////////////////////
/// Read entry corresponding to major and minor number.
///
/// The function returns the total number of bytes read.
/// If the Tree has friend trees, the corresponding entry with
/// the index values (major,minor) is read. Note that the master Tree
/// and its friend may have different entry serial numbers corresponding
/// to (major,minor).
Int_t TTree::GetEntryWithIndex(Int_t major, Int_t minor)
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetEntryWithIndex & fFriendLockStatus) {
return 0;
}
Long64_t serial = GetEntryNumberWithIndex(major, minor);
if (serial < 0) {
return -1;
}
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
Int_t i;
Int_t nbytes = 0;
fReadEntry = serial;
TBranch *branch;
Int_t nbranches = fBranches.GetEntriesFast();
Int_t nb;
for (i = 0; i < nbranches; ++i) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntryWithIndex);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *t = fe->GetTree();
if (t) {
serial = t->GetEntryNumberWithIndex(major,minor);
if (serial <0) return -nbytes;
nb = t->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the TTree friend whose name or alias is 'friendname.
TTree* TTree::GetFriend(const char *friendname) const
{
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriend & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (strcmp(friendname,fe->GetName())==0
|| strcmp(friendname,fe->GetTreeName())==0) {
return fe->GetTree();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *res = fe->GetTree()->GetFriend(friendname);
if (res) {
return res;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// If the 'tree' is a friend, this method returns its alias name.
///
/// This alias is an alternate name for the tree.
///
/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
/// to specify in which particular tree the branch or leaf can be found if
/// the friend trees have branches or leaves with the same name as the master
/// tree.
///
/// It can also be used in conjunction with an alias created using
/// TTree::SetAlias in a TTreeFormula, e.g.:
/// ~~~ {.cpp}
/// maintree->Draw("treealias.fPx - treealias.myAlias");
/// ~~~
/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
/// was created using TTree::SetAlias on the friend tree.
///
/// However, note that 'treealias.myAlias' will be expanded literally,
/// without remembering that it comes from the aliased friend and thus
/// the branch name might not be disambiguated properly, which means
/// that you may not be able to take advantage of this feature.
///
const char* TTree::GetFriendAlias(TTree* tree) const
{
if ((tree == this) || (tree == GetTree())) {
return 0;
}
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriendAlias & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t == tree) {
return fe->GetName();
}
// Case of a chain:
if (t && t->GetTree() == tree) {
return fe->GetName();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
const char* res = fe->GetTree()->GetFriendAlias(tree);
if (res) {
return res;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the current set of IO settings
ROOT::TIOFeatures TTree::GetIOFeatures() const
{
return fIOFeatures;
}
////////////////////////////////////////////////////////////////////////////////
/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
TIterator* TTree::GetIteratorOnAllLeaves(Bool_t dir)
{
return new TTreeFriendLeafIter(this, dir);
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the 1st Leaf named name in any Branch of this
/// Tree or any branch in the list of friend trees.
///
/// The leaf name can contain the name of a friend tree with the
/// syntax: friend_dir_and_tree.full_leaf_name
/// the friend_dir_and_tree can be of the form:
/// ~~~ {.cpp}
/// TDirectoryName/TreeName
/// ~~~
TLeaf* TTree::GetLeafImpl(const char* branchname, const char *leafname)
{
TLeaf *leaf = 0;
if (branchname) {
TBranch *branch = FindBranch(branchname);
if (branch) {
leaf = branch->GetLeaf(leafname);
if (leaf) {
return leaf;
}
}
}
TIter nextl(GetListOfLeaves());
while ((leaf = (TLeaf*)nextl())) {
if (strcmp(leaf->GetName(),leafname)) continue;
if (branchname) {
UInt_t nbch = strlen(branchname);
TBranch *br = leaf->GetBranch();
const char* brname = br->GetName();
TBranch *mother = br->GetMother();
if (strncmp(brname,branchname,nbch)) {
if (mother != br) {
const char *mothername = mother->GetName();
UInt_t motherlen = strlen(mothername);
if (nbch > motherlen && strncmp(mothername,branchname,motherlen)==0 && (mothername[motherlen-1]=='.' || branchname[motherlen]=='.')) {
// The left part of the requested name match the name of the mother, let's see if the right part match the name of the branch.
if (strncmp(brname,branchname+motherlen+1,nbch-motherlen-1)) {
// No it does not
continue;
} // else we have match so we can proceed.
} else {
// no match
continue;
}
} else {
continue;
}
}
// The start of the branch name is identical to the content
// of 'aname' before the first '/'.
// Let's make sure that it is not longer (we are trying
// to avoid having jet2/value match the branch jet23
if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
continue;
}
}
return leaf;
}
if (!fFriends) return 0;
TFriendLock lock(this,kGetLeaf);
TIter next(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t) {
leaf = t->GetLeaf(leafname);
if (leaf) return leaf;
}
}
//second pass in the list of friends when the leaf name
//is prefixed by the tree name
TString strippedArg;
next.Reset();
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t==0) continue;
char *subname = (char*)strstr(leafname,fe->GetName());
if (subname != leafname) continue;
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') continue;
subname++;
strippedArg += subname;
leaf = t->GetLeaf(branchname,subname);
if (leaf) return leaf;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the 1st Leaf named name in any Branch of this
/// Tree or any branch in the list of friend trees.
///
/// The leaf name can contain the name of a friend tree with the
/// syntax: friend_dir_and_tree.full_leaf_name
/// the friend_dir_and_tree can be of the form:
///
/// TDirectoryName/TreeName
TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
{
if (leafname == 0) return 0;
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetLeaf & fFriendLockStatus) {
return 0;
}
return GetLeafImpl(branchname,leafname);
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to first leaf named \param[name] in any branch of this
/// tree or its friend trees.
///
/// \param[name] may be in the form 'branch/leaf'
///
TLeaf* TTree::GetLeaf(const char *name)
{
// Return nullptr if name is invalid or if we have
// already been visited while searching friend trees
if (!name || (kGetLeaf & fFriendLockStatus))
return nullptr;
std::string path(name);
const auto sep = path.find_last_of("/");
if (sep != std::string::npos)
return GetLeafImpl(path.substr(0, sep).c_str(), name+sep+1);
return GetLeafImpl(nullptr, name);
}
////////////////////////////////////////////////////////////////////////////////
/// Return maximum of column with name columname.
/// if the Tree has an associated TEventList or TEntryList, the maximum
/// is computed for the entries in this list.
Double_t TTree::GetMaximum(const char* columname)
{
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
TBranch* branch = leaf->GetBranch();
Double_t cmax = -DBL_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0; j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val > cmax) {
cmax = val;
}
}
}
return cmax;
}
////////////////////////////////////////////////////////////////////////////////
/// Static function which returns the tree file size limit in bytes.
Long64_t TTree::GetMaxTreeSize()
{
return fgMaxTreeSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Return minimum of column with name columname.
/// if the Tree has an associated TEventList or TEntryList, the minimum
/// is computed for the entries in this list.
Double_t TTree::GetMinimum(const char* columname)
{
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
TBranch* branch = leaf->GetBranch();
Double_t cmin = DBL_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0;j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val < cmin) {
cmin = val;
}
}
}
return cmin;
}
////////////////////////////////////////////////////////////////////////////////
/// Load the TTreePlayer (if not already done).
TVirtualTreePlayer* TTree::GetPlayer()
{
if (fPlayer) {
return fPlayer;
}
fPlayer = TVirtualTreePlayer::TreePlayer(this);
return fPlayer;
}
////////////////////////////////////////////////////////////////////////////////
/// Find and return the TTreeCache registered with the file and which may
/// contain branches for us.
TTreeCache *TTree::GetReadCache(TFile *file) const
{
TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(this));
if (pe && pe->GetTree() != this)
pe = nullptr;
return pe;
}
////////////////////////////////////////////////////////////////////////////////
/// Find and return the TTreeCache registered with the file and which may
/// contain branches for us. If create is true and there is no cache
/// a new cache is created with default size.
TTreeCache *TTree::GetReadCache(TFile *file, Bool_t create)
{
TTreeCache *pe = GetReadCache(file);
if (create && !pe) {
if (fCacheDoAutoInit)
SetCacheSizeAux(kTRUE, -1);
pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(this));
if (pe && pe->GetTree() != this) pe = 0;
}
return pe;
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the list containing user objects associated to this tree.
///
/// The list is automatically created if it does not exist.
///
/// WARNING: By default the TTree destructor will delete all objects added
/// to this list. If you do not want these objects to be deleted,
/// call:
///
/// mytree->GetUserInfo()->Clear();
///
/// before deleting the tree.
TList* TTree::GetUserInfo()
{
if (!fUserInfo) {
fUserInfo = new TList();
fUserInfo->SetName("UserInfo");
}
return fUserInfo;
}
////////////////////////////////////////////////////////////////////////////////
/// Appends the cluster range information stored in 'fromtree' to this tree,
/// including the value of fAutoFlush.
///
/// This is used when doing a fast cloning (by TTreeCloner).
/// See also fAutoFlush and fAutoSave if needed.
void TTree::ImportClusterRanges(TTree *fromtree)
{
Long64_t autoflush = fromtree->GetAutoFlush();
if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
// nothing to do
} else if (fNClusterRange || fromtree->fNClusterRange) {
Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
if (newsize > fMaxClusterRange) {
if (fMaxClusterRange) {
fClusterRangeEnd = (Long64_t*)TStorage::ReAlloc(fClusterRangeEnd,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fClusterSize = (Long64_t*)TStorage::ReAlloc(fClusterSize,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fMaxClusterRange = newsize;
} else {
fMaxClusterRange = newsize;
fClusterRangeEnd = new Long64_t[fMaxClusterRange];
fClusterSize = new Long64_t[fMaxClusterRange];
}
}
if (fEntries) {
fClusterRangeEnd[fNClusterRange] = fEntries - 1;
fClusterSize[fNClusterRange] = fAutoFlush<0 ? 0 : fAutoFlush;
++fNClusterRange;
}
for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
fClusterRangeEnd[fNClusterRange] = fEntries + fromtree->fClusterRangeEnd[i];
fClusterSize[fNClusterRange] = fromtree->fClusterSize[i];
++fNClusterRange;
}
fAutoFlush = autoflush;
} else {
SetAutoFlush( autoflush );
}
Long64_t autosave = GetAutoSave();
if (autoflush > 0 && autosave > 0) {
SetAutoSave( autoflush*(autosave/autoflush) );
}
}
////////////////////////////////////////////////////////////////////////////////
/// Keep a maximum of fMaxEntries in memory.
void TTree::KeepCircular()
{
Int_t nb = fBranches.GetEntriesFast();
Long64_t maxEntries = fMaxEntries - (fMaxEntries / 10);
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->KeepCircular(maxEntries);
}
if (fNClusterRange) {
Long64_t entriesOffset = fEntries - maxEntries;
Int_t oldsize = fNClusterRange;
for(Int_t i = 0, j = 0; j < oldsize; ++j) {
if (fClusterRangeEnd[j] > entriesOffset) {
fClusterRangeEnd[i] = fClusterRangeEnd[j] - entriesOffset;
++i;
} else {
--fNClusterRange;
}
}
}
fEntries = maxEntries;
fReadEntry = -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
///
/// If maxmemory is non null and positive SetMaxVirtualSize is called
/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
/// The function returns the total number of baskets read into memory
/// if negative an error occurred while loading the branches.
/// This method may be called to force branch baskets in memory
/// when random access to branch entries is required.
/// If random access to only a few branches is required, you should
/// call directly TBranch::LoadBaskets.
Int_t TTree::LoadBaskets(Long64_t maxmemory)
{
if (maxmemory > 0) SetMaxVirtualSize(maxmemory);
TIter next(GetListOfLeaves());
TLeaf *leaf;
Int_t nimported = 0;
while ((leaf=(TLeaf*)next())) {
nimported += leaf->GetBranch()->LoadBaskets();//break;
}
return nimported;
}
////////////////////////////////////////////////////////////////////////////////
/// Set current entry.
///
/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
/// Returns -6 if an error occours in the notification callback (just as TChain::LoadTree()).
///
/// Note: This function is overloaded in TChain.
///
Long64_t TTree::LoadTree(Long64_t entry)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kLoadTree & fFriendLockStatus) {
// We need to return a negative value to avoid a circular list of friend
// to think that there is always an entry somewhere in the list.
return -1;
}
// create cache if wanted
if (fCacheDoAutoInit && entry >=0)
SetCacheSizeAux();
if (fNotify) {
if (fReadEntry < 0) {
fNotify->Notify();
}
}
fReadEntry = entry;
Bool_t friendHasEntry = kFALSE;
if (fFriends) {
// Set current entry in friends as well.
//
// An alternative would move this code to each of the
// functions calling LoadTree (and to overload a few more).
Bool_t needUpdate = kFALSE;
{
// This scope is need to insure the lock is released at the right time
TIter nextf(fFriends);
TFriendLock lock(this, kLoadTree);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (fe->TestBit(TFriendElement::kFromChain)) {
// This friend element was added by the chain that owns this
// tree, the chain will deal with loading the correct entry.
continue;
}
TTree* friendTree = fe->GetTree();
if (friendTree == 0) {
// Somehow we failed to retrieve the friend TTree.
} else if (friendTree->IsA() == TTree::Class()) {
// Friend is actually a tree.
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
} else {
// Friend is actually a chain.
// FIXME: This logic should be in the TChain override.
Int_t oldNumber = friendTree->GetTreeNumber();
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
Int_t newNumber = friendTree->GetTreeNumber();
if (oldNumber != newNumber) {
// We can not just compare the tree pointers because they could be reused.
// So we compare the tree number instead.
needUpdate = kTRUE;
}
}
} // for each friend
}
if (needUpdate) {
//update list of leaves in all TTreeFormula of the TTreePlayer (if any)
if (fPlayer) {
fPlayer->UpdateFormulaLeaves();
}
//Notify user if requested
if (fNotify) {
if(!fNotify->Notify()) return -6;
}
}
}
if ((fReadEntry >= fEntries) && !friendHasEntry) {
fReadEntry = -1;
return -2;
}
return fReadEntry;
}
////////////////////////////////////////////////////////////////////////////////
/// Load entry on behalf of our master tree, we may use an index.
///
/// Called by LoadTree() when the masterTree looks for the entry
/// number in a friend tree (us) corresponding to the passed entry
/// number in the masterTree.
///
/// If we have no index, our entry number and the masterTree entry
/// number are the same.
///
/// If we *do* have an index, we must find the (major, minor) value pair
/// in masterTree to locate our corresponding entry.
///
Long64_t TTree::LoadTreeFriend(Long64_t entry, TTree* masterTree)
{
if (!fTreeIndex) {
return LoadTree(entry);
}
return LoadTree(fTreeIndex->GetEntryNumberFriend(masterTree));
}
////////////////////////////////////////////////////////////////////////////////
/// Generate a skeleton analysis class for this tree.
///
/// The following files are produced: classname.h and classname.C.
/// If classname is 0, classname will be called "nameoftree".
///
/// The generated code in classname.h includes the following:
///
/// - Identification of the original tree and the input file name.
/// - Definition of an analysis class (data members and member functions).
/// - The following member functions:
/// - constructor (by default opening the tree file),
/// - GetEntry(Long64_t entry),
/// - Init(TTree* tree) to initialize a new TTree,
/// - Show(Long64_t entry) to read and dump entry.
///
/// The generated code in classname.C includes only the main
/// analysis function Loop.
///
/// To use this function:
///
/// - Open your tree file (eg: TFile f("myfile.root");)
/// - T->MakeClass("MyClass");
///
/// where T is the name of the TTree in file myfile.root,
/// and MyClass.h, MyClass.C the name of the files created by this function.
/// In a ROOT session, you can do:
/// ~~~ {.cpp}
/// root > .L MyClass.C
/// root > MyClass* t = new MyClass;
/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
/// root > t->Show(); // Show values of entry 12.
/// root > t->Show(16); // Read and show values of entry 16.
/// root > t->Loop(); // Loop on all entries.
/// ~~~
/// NOTE: Do not use the code generated for a single TTree which is part
/// of a TChain to process that entire TChain. The maximum dimensions
/// calculated for arrays on the basis of a single TTree from the TChain
/// might be (will be!) too small when processing all of the TTrees in
/// the TChain. You must use myChain.MakeClass() to generate the code,
/// not myTree.MakeClass(...).
Int_t TTree::MakeClass(const char* classname, Option_t* option)
{
GetPlayer();
if (!fPlayer) {
return 0;
}
return fPlayer->MakeClass(classname, option);
}
////////////////////////////////////////////////////////////////////////////////
/// Generate a skeleton function for this tree.
///
/// The function code is written on filename.
/// If filename is 0, filename will be called nameoftree.C
///
/// The generated code includes the following:
/// - Identification of the original Tree and Input file name,
/// - Opening the Tree file,
/// - Declaration of Tree variables,
/// - Setting of branches addresses,
/// - A skeleton for the entry loop.
///
/// To use this function:
///
/// - Open your Tree file (eg: TFile f("myfile.root");)
/// - T->MakeCode("MyAnalysis.C");
///
/// where T is the name of the TTree in file myfile.root
/// and MyAnalysis.C the name of the file created by this function.
///
/// NOTE: Since the implementation of this function, a new and better
/// function TTree::MakeClass() has been developed.
Int_t TTree::MakeCode(const char* filename)
{
Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeCode(filename);
}
////////////////////////////////////////////////////////////////////////////////
/// Generate a skeleton analysis class for this Tree using TBranchProxy.
///
/// TBranchProxy is the base of a class hierarchy implementing an
/// indirect access to the content of the branches of a TTree.
///
/// "proxyClassname" is expected to be of the form:
/// ~~~ {.cpp}
/// [path/]fileprefix
/// ~~~
/// The skeleton will then be generated in the file:
/// ~~~ {.cpp}
/// fileprefix.h
/// ~~~
/// located in the current directory or in 'path/' if it is specified.
/// The class generated will be named 'fileprefix'
///
/// "macrofilename" and optionally "cutfilename" are expected to point
/// to source files which will be included by the generated skeleton.
/// Method of the same name as the file(minus the extension and path)
/// will be called by the generated skeleton's Process method as follow:
/// ~~~ {.cpp}
/// [if (cutfilename())] htemp->Fill(macrofilename());
/// ~~~
/// "option" can be used select some of the optional features during
/// the code generation. The possible options are:
///
/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
///
/// 'maxUnrolling' controls how deep in the class hierarchy does the
/// system 'unroll' classes that are not split. Unrolling a class
/// allows direct access to its data members (this emulates the behavior
/// of TTreeFormula).
///
/// The main features of this skeleton are:
///
/// * on-demand loading of branches
/// * ability to use the 'branchname' as if it was a data member
/// * protection against array out-of-bounds errors
/// * ability to use the branch data as an object (when the user code is available)
///
/// For example with Event.root, if
/// ~~~ {.cpp}
/// Double_t somePx = fTracks.fPx[2];
/// ~~~
/// is executed by one of the method of the skeleton,
/// somePx will updated with the current value of fPx of the 3rd track.
///
/// Both macrofilename and the optional cutfilename are expected to be
/// the name of source files which contain at least a free standing
/// function with the signature:
/// ~~~ {.cpp}
/// x_t macrofilename(); // i.e function with the same name as the file
/// ~~~
/// and
/// ~~~ {.cpp}
/// y_t cutfilename(); // i.e function with the same name as the file
/// ~~~
/// x_t and y_t needs to be types that can convert respectively to a double
/// and a bool (because the skeleton uses:
///
/// if (cutfilename()) htemp->Fill(macrofilename());
///
/// These two functions are run in a context such that the branch names are
/// available as local variables of the correct (read-only) type.
///
/// Note that if you use the same 'variable' twice, it is more efficient
/// to 'cache' the value. For example:
/// ~~~ {.cpp}
/// Int_t n = fEventNumber; // Read fEventNumber
/// if (n<10 || n>10) { ... }
/// ~~~
/// is more efficient than
/// ~~~ {.cpp}
/// if (fEventNumber<10 || fEventNumber>10)
/// ~~~
/// Also, optionally, the generated selector will also call methods named
/// macrofilename_methodname in each of 6 main selector methods if the method
/// macrofilename_methodname exist (Where macrofilename is stripped of its
/// extension).
///
/// Concretely, with the script named h1analysisProxy.C,
///
/// - The method calls the method (if it exist)
/// - Begin -> void h1analysisProxy_Begin(TTree*);
/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
/// - Notify -> Bool_t h1analysisProxy_Notify();
/// - Process -> Bool_t h1analysisProxy_Process(Long64_t);
/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
/// - Terminate -> void h1analysisProxy_Terminate();
///
/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
/// it is included before the declaration of the proxy class. This can
/// be used in particular to insure that the include files needed by
/// the macro file are properly loaded.
///
/// The default histogram is accessible via the variable named 'htemp'.
///
/// If the library of the classes describing the data in the branch is
/// loaded, the skeleton will add the needed `include` statements and
/// give the ability to access the object stored in the branches.
///
/// To draw px using the file hsimple.root (generated by the
/// hsimple.C tutorial), we need a file named hsimple.cxx:
/// ~~~ {.cpp}
/// double hsimple() {
/// return px;
/// }
/// ~~~
/// MakeProxy can then be used indirectly via the TTree::Draw interface
/// as follow:
/// ~~~ {.cpp}
/// new TFile("hsimple.root")
/// ntuple->Draw("hsimple.cxx");
/// ~~~
/// A more complete example is available in the tutorials directory:
/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
/// which reimplement the selector found in h1analysis.C
Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
{
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeProxy(proxyClassname,macrofilename,cutfilename,option,maxUnrolling);
}
////////////////////////////////////////////////////////////////////////////////
/// Generate skeleton selector class for this tree.
///
/// The following files are produced: selector.h and selector.C.
/// If selector is 0, the selector will be called "nameoftree".
/// The option can be used to specify the branches that will have a data member.
/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
/// members and branch pointers instead of TTreeReaders).
/// - If option is empty, readers will be generated for each leaf.
/// - If option is "@", readers will be generated for the topmost branches.
/// - Individual branches can also be picked by their name:
/// - "X" generates readers for leaves of X.
/// - "@X" generates a reader for X as a whole.
/// - "@X;Y" generates a reader for X as a whole and also readers for the
/// leaves of Y.
/// - For further examples see the figure below.
///
/// \image html ttree_makeselector_option_examples.png
///
/// The generated code in selector.h includes the following:
/// - Identification of the original Tree and Input file name
/// - Definition of selector class (data and functions)
/// - The following class functions:
/// - constructor and destructor
/// - void Begin(TTree *tree)
/// - void SlaveBegin(TTree *tree)
/// - void Init(TTree *tree)
/// - Bool_t Notify()
/// - Bool_t Process(Long64_t entry)
/// - void Terminate()
/// - void SlaveTerminate()
///
/// The class selector derives from TSelector.
/// The generated code in selector.C includes empty functions defined above.
///
/// To use this function:
///
/// - connect your Tree file (eg: `TFile f("myfile.root");`)
/// - `T->MakeSelector("myselect");`
///
/// where T is the name of the Tree in file myfile.root
/// and myselect.h, myselect.C the name of the files created by this function.
/// In a ROOT session, you can do:
/// ~~~ {.cpp}
/// root > T->Process("myselect.C")
/// ~~~
Int_t TTree::MakeSelector(const char* selector, Option_t* option)
{
TString opt(option);
if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
return MakeClass(selector, "selector");
} else {
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeReader(selector, option);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Check if adding nbytes to memory we are still below MaxVirtualsize.
Bool_t TTree::MemoryFull(Int_t nbytes)
{
if ((fTotalBuffers + nbytes) < fMaxVirtualSize) {
return kFALSE;
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Static function merging the trees in the TList into a new tree.
///
/// Trees in the list can be memory or disk-resident trees.
/// The new tree is created in the current directory (memory if gROOT).
TTree* TTree::MergeTrees(TList* li, Option_t* options)
{
if (!li) return 0;
TIter next(li);
TTree *newtree = 0;
TObject *obj;
while ((obj=next())) {
if (!obj->InheritsFrom(TTree::Class())) continue;
TTree *tree = (TTree*)obj;
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
if (!newtree) {
newtree = (TTree*)tree->CloneTree();
if (!newtree) continue;
// Once the cloning is done, separate the trees,
// to avoid as many side-effects as possible
// The list of clones is guaranteed to exist since we
// just cloned the tree.
tree->GetListOfClones()->Remove(newtree);
tree->ResetBranchAddresses();
newtree->ResetBranchAddresses();
continue;
}
newtree->CopyAddresses(tree);
newtree->CopyEntries(tree,-1,options);
tree->ResetBranchAddresses(); // Disconnect from new tree.
}
if (newtree && newtree->GetTreeIndex()) {
newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
return newtree;
}
////////////////////////////////////////////////////////////////////////////////
/// Merge the trees in the TList into this tree.
///
/// Returns the total number of entries in the merged tree.
Long64_t TTree::Merge(TCollection* li, Option_t *options)
{
if (!li) return 0;
Long64_t storeAutoSave = fAutoSave;
// Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
// key would invalidate its iteration (or require costly measure to not use the deleted keys).
// Also since this is part of a merging operation, the output file is not as precious as in
// the general case since the input file should still be around.
fAutoSave = 0;
TIter next(li);
TTree *tree;
while ((tree = (TTree*)next())) {
if (tree==this) continue;
if (!tree->InheritsFrom(TTree::Class())) {
Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
fAutoSave = storeAutoSave;
return -1;
}
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
CopyAddresses(tree);
CopyEntries(tree,-1,options);
tree->ResetBranchAddresses();
}
fAutoSave = storeAutoSave;
return GetEntries();
}
////////////////////////////////////////////////////////////////////////////////
/// Merge the trees in the TList into this tree.
/// If info->fIsFirst is true, first we clone this TTree info the directory
/// info->fOutputDirectory and then overlay the new TTree information onto
/// this TTree object (so that this TTree object is now the appropriate to
/// use for further merging).
///
/// Returns the total number of entries in the merged tree.
Long64_t TTree::Merge(TCollection* li, TFileMergeInfo *info)
{
const char *options = info ? info->fOptions.Data() : "";
if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
TDirectory::TContext ctxt(info->fOutputDirectory);
TIOFeatures saved_features = fIOFeatures;
if (info->fIOFeatures) {
fIOFeatures = *(info->fIOFeatures);
}
TTree *newtree = CloneTree(-1, options);
fIOFeatures = saved_features;
if (newtree) {
newtree->Write();
delete newtree;
}
// Make sure things are really written out to disk before attempting any reading.
info->fOutputDirectory->GetFile()->Flush();
info->fOutputDirectory->ReadTObject(this,this->GetName());
}
if (!li) return 0;
Long64_t storeAutoSave = fAutoSave;
// Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
// key would invalidate its iteration (or require costly measure to not use the deleted keys).
// Also since this is part of a merging operation, the output file is not as precious as in
// the general case since the input file should still be around.
fAutoSave = 0;
TIter next(li);
TTree *tree;
while ((tree = (TTree*)next())) {
if (tree==this) continue;
if (!tree->InheritsFrom(TTree::Class())) {
Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
fAutoSave = storeAutoSave;
return -1;
}
// Copy MakeClass status.
tree->SetMakeClass(fMakeClass);
// Copy branch addresses.
CopyAddresses(tree);
CopyEntries(tree,-1,options);
tree->ResetBranchAddresses();
}
fAutoSave = storeAutoSave;
return GetEntries();
}
////////////////////////////////////////////////////////////////////////////////
/// Move a cache from a file to the current file in dir.
/// if src is null no operation is done, if dir is null or there is no
/// current file the cache is deleted.
void TTree::MoveReadCache(TFile *src, TDirectory *dir)
{
if (!src) return;
TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : 0;
if (src == dst) return;
TTreeCache *pf = GetReadCache(src);
if (dst) {
src->SetCacheRead(0,this);
dst->SetCacheRead(pf, this);
} else {
if (pf) {
pf->WaitFinishPrefetch();
}
src->SetCacheRead(0,this);
delete pf;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Function called when loading a new class library.
Bool_t TTree::Notify()
{
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leaf->Notify();
leaf->GetBranch()->Notify();
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// This function may be called after having filled some entries in a Tree.
/// Using the information in the existing branch buffers, it will reassign
/// new branch buffer sizes to optimize time and memory.
///
/// The function computes the best values for branch buffer sizes such that
/// the total buffer sizes is less than maxMemory and nearby entries written
/// at the same time.
/// In case the branch compression factor for the data written so far is less
/// than compMin, the compression is disabled.
///
/// if option ="d" an analysis report is printed.
void TTree::OptimizeBaskets(ULong64_t maxMemory, Float_t minComp, Option_t *option)
{
//Flush existing baskets if the file is writable
if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
TString opt( option );
opt.ToLower();
Bool_t pDebug = opt.Contains("d");
TObjArray *leaves = this->GetListOfLeaves();
Int_t nleaves = leaves->GetEntries();
Double_t treeSize = (Double_t)this->GetTotBytes();
if (nleaves == 0 || treeSize == 0) {
// We're being called too early, we really have nothing to do ...
return;
}
Double_t aveSize = treeSize/nleaves;
UInt_t bmin = 512;
UInt_t bmax = 256000;
Double_t memFactor = 1;
Int_t i, oldMemsize,newMemsize,oldBaskets,newBaskets;
i = oldMemsize = newMemsize = oldBaskets = newBaskets = 0;
//we make two passes
//one pass to compute the relative branch buffer sizes
//a second pass to compute the absolute values
for (Int_t pass =0;pass<2;pass++) {
oldMemsize = 0; //to count size of baskets in memory with old buffer size
newMemsize = 0; //to count size of baskets in memory with new buffer size
oldBaskets = 0; //to count number of baskets with old buffer size
newBaskets = 0; //to count number of baskets with new buffer size
for (i=0;i<nleaves;i++) {
TLeaf *leaf = (TLeaf*)leaves->At(i);
TBranch *branch = leaf->GetBranch();
Double_t totBytes = (Double_t)branch->GetTotBytes();
Double_t idealFactor = totBytes/aveSize;
UInt_t sizeOfOneEntry;
if (branch->GetEntries() == 0) {
// There is no data, so let's make a guess ...
sizeOfOneEntry = aveSize;
} else {
sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
}
Int_t oldBsize = branch->GetBasketSize();
oldMemsize += oldBsize;
oldBaskets += 1+Int_t(totBytes/oldBsize);
Int_t nb = branch->GetListOfBranches()->GetEntries();
if (nb > 0) {
newBaskets += 1+Int_t(totBytes/oldBsize);
continue;
}
Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
if (bsize < 0) bsize = bmax;
if (bsize > bmax) bsize = bmax;
UInt_t newBsize = UInt_t(bsize);
if (pass) { // only on the second pass so that it doesn't interfere with scaling
// If there is an entry offset, it will be stored in the same buffer as the object data; hence,
// we must bump up the size of the branch to account for this extra footprint.
// If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
// the value of GetEntries().
Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
if (branch->GetEntryOffsetLen()) {
newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
}
// We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
// with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
// resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
// at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
// stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
// structures we found a factor of 2 fewer baskets needed in the new scheme.
// rounds up, increases basket size to ensure all entries fit into single basket as intended
newBsize = newBsize - newBsize%512 + 512;
}
if (newBsize < sizeOfOneEntry) newBsize = sizeOfOneEntry;
if (newBsize < bmin) newBsize = bmin;
if (newBsize > 10000000) newBsize = bmax;
if (pass) {
if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
branch->SetBasketSize(newBsize);
}
newMemsize += newBsize;
// For this number to be somewhat accurate when newBsize is 'low'
// we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
// not let it be lower than 100+TBranch::fEntryOffsetLen.
newBaskets += 1+Int_t(totBytes/newBsize);
if (pass == 0) continue;
//Reset the compression level in case the compression factor is small
Double_t comp = 1;
if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
if (comp > 1 && comp < minComp) {
if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
branch->SetCompressionSettings(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal);
}
}
// coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
memFactor = Double_t(maxMemory)/Double_t(newMemsize);
if (memFactor > 100) memFactor = 100;
Double_t bmin_new = bmin*memFactor;
Double_t bmax_new = bmax*memFactor;
static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
// Really, really never go lower than 8 bytes (we use this number
// so that the calculation of the number of basket is consistent
// but in fact SetBasketSize will not let the size go below
// TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
// (The 2nd part being a slight over estimate of the key length.
static const UInt_t hardmin = 8;
bmin = (bmin_new > hardmax) ? hardmax : ( bmin_new < hardmin ? hardmin : (UInt_t)bmin_new );
bmax = (bmax_new > hardmax) ? bmin : (UInt_t)bmax_new;
}
if (pDebug) {
Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Interface to the Principal Components Analysis class.
///
/// Create an instance of TPrincipal
///
/// Fill it with the selected variables
///
/// - if option "n" is specified, the TPrincipal object is filled with
/// normalized variables.
/// - If option "p" is specified, compute the principal components
/// - If option "p" and "d" print results of analysis
/// - If option "p" and "h" generate standard histograms
/// - If option "p" and "c" generate code of conversion functions
/// - return a pointer to the TPrincipal object. It is the user responsibility
/// - to delete this object.
/// - The option default value is "np"
///
/// see TTree::Draw for explanation of the other parameters.
///
/// The created object is named "principal" and a reference to it
/// is added to the list of specials Root objects.
/// you can retrieve a pointer to the created object via:
/// ~~~ {.cpp}
/// TPrincipal *principal =
/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
/// ~~~
TPrincipal* TTree::Principal(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Principal(varexp, selection, option, nentries, firstentry);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Print a summary of the tree contents.
///
/// - If option contains "all" friend trees are also printed.
/// - If option contains "toponly" only the top level branches are printed.
/// - If option contains "clusters" information about the cluster of baskets is printed.
///
/// Wildcarding can be used to print only a subset of the branches, e.g.,
/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
void TTree::Print(Option_t* option) const
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kPrint & fFriendLockStatus) {
return;
}
Int_t s = 0;
Int_t skey = 0;
if (fDirectory) {
TKey* key = fDirectory->GetKey(GetName());
if (key) {
skey = key->GetKeylen();
s = key->GetNbytes();
}
}
Long64_t total = skey;
Long64_t zipBytes = GetZipBytes();
if (zipBytes > 0) {
total += GetTotBytes();
}
TBufferFile b(TBuffer::kWrite, 10000);
TTree::Class()->WriteBuffer(b, (TTree*) this);
total += b.Length();
Long64_t file = zipBytes + s;
Float_t cx = 1;
if (zipBytes) {
cx = (GetTotBytes() + 0.00001) / zipBytes;
}
Printf("******************************************************************************");
Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
Printf("* : : Tree compression factor = %6.2f *", cx);
Printf("******************************************************************************");
// Avoid many check of option validity
if (option == nullptr)
option = "";
if (strncmp(option,"clusters",strlen("clusters"))==0) {
Printf("%-16s %-16s %-16s %5s",
"Cluster Range #", "Entry Start", "Last Entry", "Size");
Int_t index= 0;
Long64_t clusterRangeStart = 0;
if (fNClusterRange) {
for( ; index < fNClusterRange; ++index) {
Printf("%-16d %-16lld %-16lld %5lld",
index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
clusterRangeStart = fClusterRangeEnd[index] + 1;
}
}
Printf("%-16d %-16lld %-16lld %5lld",
index, clusterRangeStart, fEntries - 1, fAutoFlush);
return;
}
Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
Int_t l;
TBranch* br = 0;
TLeaf* leaf = 0;
if (strstr(option, "toponly")) {
Long64_t *count = new Long64_t[nl];
Int_t keep =0;
for (l=0;l<nl;l++) {
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
if (strchr(br->GetName(),'.')) {
count[l] = -1;
count[keep] += br->GetZipBytes();
} else {
keep = l;
count[keep] = br->GetZipBytes();
}
}
for (l=0;l<nl;l++) {
if (count[l] < 0) continue;
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
Printf("branch: %-20s %9lld\n",br->GetName(),count[l]);
}
delete [] count;
} else {
TString reg = "*";
if (strlen(option) && strchr(option,'*')) reg = option;
TRegexp re(reg,kTRUE);
TIter next(const_cast<TTree*>(this)->GetListOfBranches());
TBranch::ResetCount();
while ((br= (TBranch*)next())) {
TString st = br->GetName();
st.ReplaceAll("/","_");
if (st.Index(re) == kNPOS) continue;
br->Print(option);
}
}
//print TRefTable (if one)
if (fBranchRef) fBranchRef->Print(option);
//print friends if option "all"
if (!fFriends || !strstr(option,"all")) return;
TIter nextf(fFriends);
TFriendLock lock(const_cast<TTree*>(this),kPrint);
TFriendElement *fr;
while ((fr = (TFriendElement*)nextf())) {
TTree * t = fr->GetTree();
if (t) t->Print(option);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Print statistics about the TreeCache for this tree.
/// Like:
/// ~~~ {.cpp}
/// ******TreeCache statistics for file: cms2.root ******
/// Reading 73921562 bytes in 716 transactions
/// Average transaction = 103.242405 Kbytes
/// Number of blocks in current cache: 202, total size : 6001193
/// ~~~
/// if option = "a" the list of blocks in the cache is printed
void TTree::PrintCacheStats(Option_t* option) const
{
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = GetReadCache(f);
if (tc) tc->Print(option);
}
////////////////////////////////////////////////////////////////////////////////
/// Process this tree executing the TSelector code in the specified filename.
/// The return value is -1 in case of error and TSelector::GetStatus() in
/// in case of success.
///
/// The code in filename is loaded (interpreted or compiled, see below),
/// filename must contain a valid class implementation derived from TSelector,
/// where TSelector has the following member functions:
///
/// - `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.
///
/// If filename is of the form file.C, the file will be interpreted.
///
/// If filename is of the form file.C++, the file file.C will be compiled
/// and dynamically loaded.
///
/// If filename is of the form file.C+, the file file.C will be compiled
/// and dynamically loaded. At next call, if file.C is older than file.o
/// and file.so, the file.C is not compiled, only file.so is loaded.
///
/// ## NOTE1
///
/// It may be more interesting to invoke directly the other Process function
/// accepting a TSelector* as argument.eg
/// ~~~ {.cpp}
/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
/// selector->CallSomeFunction(..);
/// mytree.Process(selector,..);
/// ~~~
/// ## NOTE2
//
/// One should not call this function twice with the same selector file
/// in the same script. If this is required, proceed as indicated in NOTE1,
/// by getting a pointer to the corresponding TSelector,eg
///
/// ### Workaround 1
///
/// ~~~ {.cpp}
/// void stubs1() {
/// TSelector *selector = TSelector::GetSelector("h1test.C");
/// TFile *f1 = new TFile("stubs_nood_le1.root");
/// TTree *h1 = (TTree*)f1->Get("h1");
/// h1->Process(selector);
/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
/// TTree *h2 = (TTree*)f2->Get("h1");
/// h2->Process(selector);
/// }
/// ~~~
/// or use ACLIC to compile the selector
///
/// ### Workaround 2
///
/// ~~~ {.cpp}
/// void stubs2() {
/// TFile *f1 = new TFile("stubs_nood_le1.root");
/// TTree *h1 = (TTree*)f1->Get("h1");
/// h1->Process("h1test.C+");
/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
/// TTree *h2 = (TTree*)f2->Get("h1");
/// h2->Process("h1test.C+");
/// }
/// ~~~
Long64_t TTree::Process(const char* filename, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Process(filename, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Process this tree executing the code in the specified selector.
/// The return value is -1 in case of error and TSelector::GetStatus() in
/// in case of success.
///
/// The TSelector class has the following member functions:
///
/// - `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.
///
/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
/// of the EventList, starting at firstentry, otherwise the loop is on the
/// specified Tree entries.
Long64_t TTree::Process(TSelector* selector, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Process(selector, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Make a projection of a tree using selections.
///
/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
/// projection of the tree will be filled in histogram hname.
/// Note that the dimension of hname must match with the dimension of varexp.
///
Long64_t TTree::Project(const char* hname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
TString var;
var.Form("%s>>%s", varexp, hname);
TString opt("goff");
if (option) {
opt.Form("%sgoff", option);
}
Long64_t nsel = Draw(var, selection, opt, nentries, firstentry);
return nsel;
}
////////////////////////////////////////////////////////////////////////////////
/// Loop over entries and return a TSQLResult object containing entries following selection.
TSQLResult* TTree::Query(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Query(varexp, selection, option, nentries, firstentry);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create or simply read branches from filename.
///
/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
/// is given in the first line of the file with a syntax like
/// ~~~ {.cpp}
/// A/D:Table[2]/F:Ntracks/I:astring/C
/// ~~~
/// otherwise branchDescriptor must be specified with the above syntax.
///
/// - If the type of the first variable is not specified, it is assumed to be "/F"
/// - If the type of any other variable is not specified, the type of the previous
/// variable is assumed. eg
/// - `x:y:z` (all variables are assumed of type "F"
/// - `x/D:y:z` (all variables are of type "D"
/// - `x:y/D:z` (x is type "F", y and z of type "D"
///
/// delimiter allows for the use of another delimiter besides whitespace.
/// This provides support for direct import of common data file formats
/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
/// branch description is taken from the first line in the file, but
/// delimiter is used for the branch names tokenization rather than ':'.
/// Note however that if the values in the first line do not use the
/// /[type] syntax, all variables are assumed to be of type "F".
/// If the filename ends with extensions .csv or .CSV and a delimiter is
/// not specified (besides ' '), the delimiter is automatically set to ','.
///
/// Lines in the input file starting with "#" are ignored. Leading whitespace
/// for each column data is skipped. Empty lines are skipped.
///
/// A TBranch object is created for each variable in the expression.
/// The total number of rows read from the file is returned.
///
/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
///
/// To fill a TTree with multiple input text files, proceed as indicated above
/// for the first input file and omit the second argument for subsequent calls
/// ~~~ {.cpp}
/// T.ReadFile("file1.dat","branch descriptor");
/// T.ReadFile("file2.dat");
/// ~~~
Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
{
std::ifstream in;
in.open(filename);
if (!in.good()) {
Error("ReadFile","Cannot open file: %s",filename);
return 0;
}
const char* ext = strrchr(filename, '.');
if(ext != NULL && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
delimiter = ',';
}
return ReadStream(in, branchDescriptor, delimiter);
}
////////////////////////////////////////////////////////////////////////////////
/// Determine which newline this file is using.
/// Return '\\r' for Windows '\\r\\n' as that already terminates.
char TTree::GetNewlineValue(std::istream &inputStream)
{
Long_t inPos = inputStream.tellg();
char newline = '\n';
while(1) {
char c = 0;
inputStream.get(c);
if(!inputStream.good()) {
Error("ReadStream","Error reading stream: no newline found.");
return 0;
}
if(c == newline) break;
if(c == '\r') {
newline = '\r';
break;
}
}
inputStream.clear();
inputStream.seekg(inPos);
return newline;
}
////////////////////////////////////////////////////////////////////////////////
/// Create or simply read branches from an input stream.
///
/// See reference information for TTree::ReadFile
Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
{
char newline = 0;
std::stringstream ss;
std::istream *inTemp;
Long_t inPos = inputStream.tellg();
if (!inputStream.good()) {
Error("ReadStream","Error reading stream");
return 0;
}
if (inPos == -1) {
ss << std::cin.rdbuf();
newline = GetNewlineValue(ss);
inTemp = &ss;
} else {
newline = GetNewlineValue(inputStream);
inTemp = &inputStream;
}
std::istream& in = *inTemp;
Long64_t nlines = 0;
TBranch *branch = 0;
Int_t nbranches = fBranches.GetEntries();
if (nbranches == 0) {
char *bdname = new char[4000];
char *bd = new char[100000];
Int_t nch = 0;
if (branchDescriptor) nch = strlen(branchDescriptor);
// branch Descriptor is null, read its definition from the first line in the file
if (!nch) {
do {
in.getline(bd, 100000, newline);
if (!in.good()) {
delete [] bdname;
delete [] bd;
Error("ReadStream","Error reading stream");
return 0;
}
char *cursor = bd;
while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
++cursor;
}
if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
break;
}
} while (true);
++nlines;
nch = strlen(bd);
} else {
strlcpy(bd,branchDescriptor,100000);
}
//parse the branch descriptor and create a branch for each element
//separated by ":"
void *address = &bd[90000];
char *bdcur = bd;
TString desc="", olddesc="F";
char bdelim = ':';
if(delimiter != ' ') {
bdelim = delimiter;
if (strchr(bdcur,bdelim)==0 && strchr(bdcur,':') != 0) {
// revert to the default
bdelim = ':';
}
}
while (bdcur) {
char *colon = strchr(bdcur,bdelim);
if (colon) *colon = 0;
strlcpy(bdname,bdcur,4000);
char *slash = strchr(bdname,'/');
if (slash) {
*slash = 0;
desc = bdcur;
olddesc = slash+1;
} else {
desc.Form("%s/%s",bdname,olddesc.Data());
}
char *bracket = strchr(bdname,'[');
if (bracket) {
*bracket = 0;
}
branch = new TBranch(this,bdname,address,desc.Data(),32000);
if (branch->IsZombie()) {
delete branch;
Warning("ReadStream","Illegal branch definition: %s",bdcur);
} else {
fBranches.Add(branch);
branch->SetAddress(0);
}
if (!colon)break;
bdcur = colon+1;
}
delete [] bdname;
delete [] bd;
}
nbranches = fBranches.GetEntries();
if (gDebug > 1) {
Info("ReadStream", "Will use branches:");
for (int i = 0 ; i < nbranches; ++i) {
TBranch* br = (TBranch*) fBranches.At(i);
Info("ReadStream", " %s: %s [%s]", br->GetName(),
br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
}
if (gDebug > 3) {
Info("ReadStream", "Dumping read tokens, format:");
Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
Info("ReadStream", " L: line number");
Info("ReadStream", " B: branch number");
Info("ReadStream", " gfbe: good / fail / bad / eof of token");
Info("ReadStream", " GFBE: good / fail / bad / eof of file");
Info("ReadStream", " T: Token being read");
}
}
//loop on all lines in the file
Long64_t nGoodLines = 0;
std::string line;
const char sDelimBuf[2] = { delimiter, 0 };
const char* sDelim = sDelimBuf;
if (delimiter == ' ') {
// ' ' really means whitespace
sDelim = "[ \t]";
}
while(in.good()) {
if (newline == '\r' && in.peek() == '\n') {
// Windows, skip '\n':
in.get();
}
std::getline(in, line, newline);
++nlines;
TString sLine(line);
sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
if (sLine.IsNull()) {
if (gDebug > 2) {
Info("ReadStream", "Skipping empty line number %lld", nlines);
}
continue; // silently skip empty lines
}
if (sLine[0] == '#') {
if (gDebug > 2) {
Info("ReadStream", "Skipping comment line number %lld: '%s'",
nlines, line.c_str());
}
continue;
}
if (gDebug > 2) {
Info("ReadStream", "Parsing line number %lld: '%s'",
nlines, line.c_str());
}
// Loop on branches and read the branch values into their buffer
branch = 0;
TString tok; // one column's data
TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
std::stringstream sToken; // string stream feeding leafData into leaves
Ssiz_t pos = 0;
Int_t iBranch = 0;
Bool_t goodLine = kTRUE; // whether the row can be filled into the tree
Int_t remainingLeafLen = 0; // remaining columns for the current leaf
while (goodLine && iBranch < nbranches
&& sLine.Tokenize(tok, pos, sDelim)) {
tok = tok.Strip(TString::kLeading); // skip leading whitespace
if (tok.IsNull() && delimiter == ' ') {
// 1 2 should not be interpreted as 1,,,2 but 1, 2.
// Thus continue until we have a non-empty token.
continue;
}
if (!remainingLeafLen) {
// next branch!
branch = (TBranch*)fBranches.At(iBranch);
}
TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
if (!remainingLeafLen) {
remainingLeafLen = leaf->GetLen();
if (leaf->GetMaximum() > 0) {
// This is a dynamic leaf length, i.e. most likely a TLeafC's
// string size. This still translates into one token:
remainingLeafLen = 1;
}
leafData = tok;
} else {
// append token to laf data:
leafData += " ";
leafData += tok;
}
--remainingLeafLen;
if (remainingLeafLen) {
// need more columns for this branch:
continue;
}
++iBranch;
// initialize stringstream with token
sToken.clear();
sToken.seekp(0, std::ios_base::beg);
sToken.str(leafData.Data());
sToken.seekg(0, std::ios_base::beg);
leaf->ReadValue(sToken, 0 /* 0 = "all" */);
if (gDebug > 3) {
Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
nlines, iBranch,
(int)sToken.good(), (int)sToken.fail(),
(int)sToken.bad(), (int)sToken.eof(),
(int)in.good(), (int)in.fail(),
(int)in.bad(), (int)in.eof(),
sToken.str().c_str());
}
// Error handling
if (sToken.bad()) {
// How could that happen for a stringstream?
Warning("ReadStream",
"Buffer error while reading data for branch %s on line %lld",
branch->GetName(), nlines);
} else if (!sToken.eof()) {
if (sToken.fail()) {
Warning("ReadStream",
"Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
tok.Data(), branch->GetName(), nlines);
goodLine = kFALSE;
} else {
std::string remainder;
std::getline(sToken, remainder, newline);
if (!remainder.empty()) {
Warning("ReadStream",
"Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
remainder.c_str(), branch->GetName(), nlines);
}
}
}
} // tokenizer loop
if (iBranch < nbranches) {
Warning("ReadStream",
"Read too few columns (%d < %d) in line %lld; ignoring line",
iBranch, nbranches, nlines);
goodLine = kFALSE;
} else if (pos != kNPOS) {
sLine = sLine.Strip(TString::kTrailing);
if (pos < sLine.Length()) {
Warning("ReadStream",
"Ignoring trailing \"%s\" while reading line %lld",
sLine.Data() + pos - 1 /* also print delimiter */,
nlines);
}
}
//we are now ready to fill the tree
if (goodLine) {
Fill();
++nGoodLines;
}
}
return nGoodLines;
}
////////////////////////////////////////////////////////////////////////////////
/// Make sure that obj (which is being deleted or will soon be) is no
/// longer referenced by this TTree.
void TTree::RecursiveRemove(TObject *obj)
{
if (obj == fEventList) {
fEventList = 0;
}
if (obj == fEntryList) {
fEntryList = 0;
}
if (fUserInfo) {
fUserInfo->RecursiveRemove(obj);
}
if (fPlayer == obj) {
fPlayer = 0;
}
if (fTreeIndex == obj) {
fTreeIndex = 0;
}
if (fAliases) {
fAliases->RecursiveRemove(obj);
}
if (fFriends) {
fFriends->RecursiveRemove(obj);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Refresh contents of this tree and its branches from the current status on disk.
///
/// One can call this function in case the tree file is being
/// updated by another process.
void TTree::Refresh()
{
if (!fDirectory->GetFile()) {
return;
}
fDirectory->ReadKeys();
fDirectory->Remove(this);
TTree* tree; fDirectory->GetObject(GetName(),tree);
if (!tree) {
return;
}
//copy info from tree header into this Tree
fEntries = 0;
fNClusterRange = 0;
ImportClusterRanges(tree);
fAutoSave = tree->fAutoSave;
fEntries = tree->fEntries;
fTotBytes = tree->GetTotBytes();
fZipBytes = tree->GetZipBytes();
fSavedBytes = tree->fSavedBytes;
fTotalBuffers = tree->fTotalBuffers.load();
//loop on all branches and update them
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
branch->Refresh(tree->GetBranch(branch->GetName()));
}
fDirectory->Remove(tree);
fDirectory->Append(this);
delete tree;
tree = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Remove a friend from the list of friends.
void TTree::RemoveFriend(TTree* oldFriend)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kRemoveFriend & fFriendLockStatus) {
return;
}
if (!fFriends) {
return;
}
TFriendLock lock(this, kRemoveFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* friend_t = fe->GetTree();
if (friend_t == oldFriend) {
fFriends->Remove(fe);
delete fe;
fe = 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Reset baskets, buffers and entries count in all branches and leaves.
void TTree::Reset(Option_t* option)
{
fNotify = 0;
fEntries = 0;
fNClusterRange = 0;
fTotBytes = 0;
fZipBytes = 0;
fFlushedBytes = 0;
fSavedBytes = 0;
fTotalBuffers = 0;
fChainOffset = 0;
fReadEntry = -1;
delete fTreeIndex;
fTreeIndex = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->Reset(option);
}
if (fBranchRef) {
fBranchRef->Reset();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Resets the state of this TTree after a merge (keep the customization but
/// forget the data).
void TTree::ResetAfterMerge(TFileMergeInfo *info)
{
fEntries = 0;
fNClusterRange = 0;
fTotBytes = 0;
fZipBytes = 0;
fSavedBytes = 0;
fFlushedBytes = 0;
fTotalBuffers = 0;
fChainOffset = 0;
fReadEntry = -1;
delete fTreeIndex;
fTreeIndex = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->ResetAfterMerge(info);
}
if (fBranchRef) {
fBranchRef->ResetAfterMerge(info);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Tell all of our branches to set their addresses to zero.
///
/// Note: If any of our branches own any objects, they are deleted.
void TTree::ResetBranchAddress(TBranch *br)
{
if (br && br->GetTree()) {
br->ResetAddress();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Tell all of our branches to drop their current objects and allocate new ones.
void TTree::ResetBranchAddresses()
{
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
branch->ResetAddress();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Loop over tree entries and print entries passing selection.
///
/// - If varexp is 0 (or "") then print only first 8 columns.
/// - If varexp = "*" print all columns.
///
/// Otherwise a columns selection can be made using "var1:var2:var3".
/// See TTreePlayer::Scan for more information
Long64_t TTree::Scan(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Scan(varexp, selection, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Set a tree variable alias.
///
/// Set an alias for an expression/formula based on the tree 'variables'.
///
/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
/// 'aliasFormula'.
///
/// If the content of 'aliasFormula' only contains symbol names, periods and
/// array index specification (for example event.fTracks[3]), then
/// the content of 'aliasName' can be used as the start of symbol.
///
/// If the alias 'aliasName' already existed, it is replaced by the new
/// value.
///
/// When being used, the alias can be preceded by an eventual 'Friend Alias'
/// (see TTree::GetFriendAlias)
///
/// Return true if it was added properly.
///
/// For example:
/// ~~~ {.cpp}
/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
/// tree->Draw("y2-y1:x2-x1");
///
/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
/// ~~~
Bool_t TTree::SetAlias(const char* aliasName, const char* aliasFormula)
{
if (!aliasName || !aliasFormula) {
return kFALSE;
}
if (!aliasName[0] || !aliasFormula[0]) {
return kFALSE;
}
if (!fAliases) {
fAliases = new TList;
} else {
TNamed* oldHolder = (TNamed*) fAliases->FindObject(aliasName);
if (oldHolder) {
oldHolder->SetTitle(aliasFormula);
return kTRUE;
}
}
TNamed* holder = new TNamed(aliasName, aliasFormula);
fAliases->Add(holder);
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// This function may be called at the start of a program to change
/// the default value for fAutoFlush.
///
/// ### CASE 1 : autof > 0
///
/// autof is the number of consecutive entries after which TTree::Fill will
/// flush all branch buffers to disk.
///
/// ### CASE 2 : autof < 0
///
/// When filling the Tree the branch buffers will be flushed to disk when
/// more than autof bytes have been written to the file. At the first FlushBaskets
/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
///
/// Calling this function with autof<0 is interesting when it is hard to estimate
/// the size of one entry. This value is also independent of the Tree.
///
/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
///
/// ### CASE 3 : autof = 0
///
/// The AutoFlush mechanism is disabled.
///
/// Flushing the buffers at regular intervals optimize the location of
/// consecutive entries on the disk by creating clusters of baskets.
///
/// A cluster of baskets is a set of baskets that contains all
/// the data for a (consecutive) set of entries and that is stored
/// consecutively on the disk. When reading all the branches, this
/// is the minimum set of baskets that the TTreeCache will read.
void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
{
// Implementation note:
//
// A positive value of autoflush determines the size (in number of entries) of
// a cluster of baskets.
//
// If the value of autoflush is changed over time (this happens in
// particular when the TTree results from fast merging many trees),
// we record the values of fAutoFlush in the data members:
// fClusterRangeEnd and fClusterSize.
// In the code we refer to a range of entries where the size of the
// cluster of baskets is the same (i.e the value of AutoFlush was
// constant) is called a ClusterRange.
//
// The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
// active (used) values and have fMaxClusterRange allocated entries.
//
// fClusterRangeEnd contains the last entries number of a cluster range.
// In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
// fClusterSize contains the size in number of entries of all the cluster
// within the given range.
// The last range (and the only one if fNClusterRange is zero) start at
// fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
// size of the cluster in this range is given by the value of fAutoFlush.
//
// For example printing the beginning and end of each the ranges can be done by:
//
// Printf("%-16s %-16s %-16s %5s",
// "Cluster Range #", "Entry Start", "Last Entry", "Size");
// Int_t index= 0;
// Long64_t clusterRangeStart = 0;
// if (fNClusterRange) {
// for( ; index < fNClusterRange; ++index) {
// Printf("%-16d %-16lld %-16lld %5lld",
// index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
// clusterRangeStart = fClusterRangeEnd[index] + 1;
// }
// }
// Printf("%-16d %-16lld %-16lld %5lld",
// index, prevEntry, fEntries - 1, fAutoFlush);
//
// Note: We store the entry number corresponding to the end of the cluster
// rather than its start in order to avoid using the array if the cluster
// size never varies (If there is only one value of AutoFlush for the whole TTree).
if( fAutoFlush != autof) {
if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
// The mechanism was already enabled, let's record the previous
// cluster if needed.
MarkEventCluster();
}
fAutoFlush = autof;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Mark the previous event as being at the end of the event cluster.
///
/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
/// is called, then the first cluster has 9 events.
void TTree::MarkEventCluster()
{
if (!fEntries) return;
if ( (fNClusterRange+1) > fMaxClusterRange ) {
if (fMaxClusterRange) {
// Resize arrays to hold a larger event cluster.
Int_t newsize = TMath::Max(10,Int_t(2*fMaxClusterRange));
fClusterRangeEnd = (Long64_t*)TStorage::ReAlloc(fClusterRangeEnd,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fClusterSize = (Long64_t*)TStorage::ReAlloc(fClusterSize,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fMaxClusterRange = newsize;
} else {
// Cluster ranges have never been initialized; create them now.
fMaxClusterRange = 2;
fClusterRangeEnd = new Long64_t[fMaxClusterRange];
fClusterSize = new Long64_t[fMaxClusterRange];
}
}
fClusterRangeEnd[fNClusterRange] = fEntries - 1;
// If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
if (fAutoFlush > 0) {
// Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
// will appropriately go to the next event range.
fClusterSize[fNClusterRange] = fAutoFlush;
// Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
} else if (fNClusterRange == 0) {
fClusterSize[fNClusterRange] = fEntries;
} else {
fClusterSize[fNClusterRange] = fClusterRangeEnd[fNClusterRange] - fClusterRangeEnd[fNClusterRange-1];
}
++fNClusterRange;
}
////////////////////////////////////////////////////////////////////////////////
/// This function may be called at the start of a program to change
/// the default value for fAutoSave (and for SetAutoSave) is -300000000, ie 300 MBytes.
/// When filling the Tree the branch buffers as well as the Tree header
/// will be flushed to disk when the watermark is reached.
/// If fAutoSave is positive the watermark is reached when a multiple of fAutoSave
/// entries have been written.
/// If fAutoSave is negative the watermark is reached when -fAutoSave bytes
/// have been written to the file.
/// In case of a program crash, it will be possible to recover the data in the Tree
/// up to the last AutoSave point.
void TTree::SetAutoSave(Long64_t autos)
{
fAutoSave = autos;
}
////////////////////////////////////////////////////////////////////////////////
/// Set a branch's basket size.
///
/// bname is the name of a branch.
///
/// - if bname="*", apply to all branches.
/// - if bname="xxx*", apply to all branches with name starting with xxx
///
/// see TRegexp for wildcarding options
/// buffsize = branc basket size
void TTree::SetBasketSize(const char* bname, Int_t buffsize)
{
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname, kTRUE);
Int_t nb = 0;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
continue;
}
nb++;
branch->SetBasketSize(buffsize);
}
if (!nb) {
Error("SetBasketSize", "unknown branch -> '%s'", bname);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change branch address, dealing with clone trees properly.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
{
TBranch* branch = GetBranch(bname);
if (!branch) {
if (ptr) *ptr = 0;
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kMissingBranch;
}
return SetBranchAddressImp(branch,addr,ptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Verify the validity of the type of addr before calling SetBranchAddress.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
return SetBranchAddress(bname, addr, 0, ptrClass, datatype, isptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Verify the validity of the type of addr before calling SetBranchAddress.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
TBranch* branch = GetBranch(bname);
if (!branch) {
if (ptr) *ptr = 0;
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kMissingBranch;
}
Int_t res = CheckBranchAddressType(branch, ptrClass, datatype, isptr);
// This will set the value of *ptr to branch.
if (res >= 0) {
// The check succeeded.
SetBranchAddressImp(branch,addr,ptr);
} else {
if (ptr) *ptr = 0;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// Change branch address, dealing with clone trees properly.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddressImp(TBranch *branch, void* addr, TBranch** ptr)
{
if (ptr) {
*ptr = branch;
}
if (fClones) {
void* oldAddr = branch->GetAddress();
TIter next(fClones);
TTree* clone = 0;
const char *bname = branch->GetName();
while ((clone = (TTree*) next())) {
TBranch* cloneBr = clone->GetBranch(bname);
if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
cloneBr->SetAddress(addr);
}
}
}
branch->SetAddress(addr);
return kVoidPtr;
}
////////////////////////////////////////////////////////////////////////////////
/// Set branch status to Process or DoNotProcess.
///
/// When reading a Tree, by default, all branches are read.
/// One can speed up considerably the analysis phase by activating
/// only the branches that hold variables involved in a query.
///
/// bname is the name of a branch.
///
/// - if bname="*", apply to all branches.
/// - if bname="xxx*", apply to all branches with name starting with xxx
///
/// see TRegexp for wildcarding options
///
/// - status = 1 branch will be processed
/// - = 0 branch will not be processed
///
/// Example:
///
/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
/// when doing T.GetEntry(i) all branches are read for entry i.
/// to read only the branches c and e, one can do
/// ~~~ {.cpp}
/// T.SetBranchStatus("*",0); //disable all branches
/// T.SetBranchStatus("c",1);
/// T.setBranchStatus("e",1);
/// T.GetEntry(i);
/// ~~~
/// bname is interpreted as a wildcarded TRegexp (see TRegexp::MakeWildcard).
/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
/// "b", but not any other branch with an "a" followed at some point by a
/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
/// support '|', and so you cannot select, e.g. track and shower branches
/// with "track|shower".
///
/// __WARNING! WARNING! WARNING!__
///
/// SetBranchStatus is matching the branch based on match of the branch
/// 'name' and not on the branch hierarchy! In order to be able to
/// selectively enable a top level object that is 'split' you need to make
/// sure the name of the top level branch is prefixed to the sub-branches'
/// name (by adding a dot ('.') at the end of the Branch creation and use the
/// corresponding bname.
///
/// I.e If your Tree has been created in split mode with a parent branch "parent."
/// (note the trailing dot).
/// ~~~ {.cpp}
/// T.SetBranchStatus("parent",1);
/// ~~~
/// will not activate the sub-branches of "parent". You should do:
/// ~~~ {.cpp}
/// T.SetBranchStatus("parent*",1);
/// ~~~
/// Without the trailing dot in the branch creation you have no choice but to
/// call SetBranchStatus explicitly for each of the sub branches.
///
/// An alternative to this function is to read directly and only
/// the interesting branches. Example:
/// ~~~ {.cpp}
/// TBranch *brc = T.GetBranch("c");
/// TBranch *bre = T.GetBranch("e");
/// brc->GetEntry(i);
/// bre->GetEntry(i);
/// ~~~
/// If found is not 0, the number of branch(es) found matching the regular
/// expression is returned in *found AND the error message 'unknown branch'
/// is suppressed.
void TTree::SetBranchStatus(const char* bname, Bool_t status, UInt_t* found)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kSetBranchStatus & fFriendLockStatus) {
return;
}
if (0 == strcmp(bname, "")) {
Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
return;
}
TBranch *branch, *bcount, *bson;
TLeaf *leaf, *leafcount;
Int_t i,j;
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname,kTRUE);
Int_t nb = 0;
// first pass, loop on all branches
// for leafcount branches activate/deactivate in function of status
for (i=0;i<nleaves;i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
TString longname;
longname.Form("%s.%s",GetName(),branch->GetName());
if (strcmp(bname,branch->GetName())
&& longname != bname
&& s.Index(re) == kNPOS) continue;
}
nb++;
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
if (status) bcount->ResetBit(kDoNotProcess);
else bcount->SetBit(kDoNotProcess);
}
}
if (nb==0 && strchr(bname,'*')==0) {
branch = GetBranch(bname);
if (branch) {
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
++nb;
}
}
//search in list of friends
UInt_t foundInFriend = 0;
if (fFriends) {
TFriendLock lock(this,kSetBranchStatus);
TIter nextf(fFriends);
TFriendElement *fe;
TString name;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t==0) continue;
// If the alias is present replace it with the real name.
char *subbranch = (char*)strstr(bname,fe->GetName());
if (subbranch!=bname) subbranch = 0;
if (subbranch) {
subbranch += strlen(fe->GetName());
if ( *subbranch != '.' ) subbranch = 0;
else subbranch ++;
}
if (subbranch) {
name.Form("%s.%s",t->GetName(),subbranch);
} else {
name = bname;
}
t->SetBranchStatus(name,status, &foundInFriend);
}
}
if (!nb && !foundInFriend) {
if (found==0) {
if (status) {
if (strchr(bname,'*') != 0)
Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
else
Error("SetBranchStatus", "unknown branch -> %s", bname);
} else {
if (strchr(bname,'*') != 0)
Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
else
Warning("SetBranchStatus", "unknown branch -> %s", bname);
}
}
return;
}
if (found) *found = nb + foundInFriend;
// second pass, loop again on all branches
// activate leafcount branches for active branches only
for (i = 0; i < nleaves; i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
if (!branch->TestBit(kDoNotProcess)) {
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
bcount->ResetBit(kDoNotProcess);
}
} else {
//Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
Int_t nbranches = branch->GetListOfBranches()->GetEntries();
for (j=0;j<nbranches;j++) {
bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
if (!bson) continue;
if (!bson->TestBit(kDoNotProcess)) {
if (bson->GetNleaves() <= 0) continue;
branch->ResetBit(kDoNotProcess);
break;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the current branch style. (static function)
///
/// - style = 0 old Branch
/// - style = 1 new Bronch
void TTree::SetBranchStyle(Int_t style)
{
fgBranchStyle = style;
}
////////////////////////////////////////////////////////////////////////////////
/// Set maximum size of the file cache .
//
/// - if cachesize = 0 the existing cache (if any) is deleted.
/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
/// the Tree (default is 30 MBytes).
///
/// Returns:
/// - 0 size set, cache was created if possible
/// - -1 on error
Int_t TTree::SetCacheSize(Long64_t cacheSize)
{
// remember that the user has requested an explicit cache setup
fCacheUserSet = kTRUE;
return SetCacheSizeAux(kFALSE, cacheSize);
}
////////////////////////////////////////////////////////////////////////////////
/// Set the size of the file cache and create it if possible.
///
/// If autocache is true:
/// this may be an autocreated cache, possibly enlarging an existing
/// autocreated cache. The size is calculated. The value passed in cacheSize:
/// - cacheSize = 0 make cache if default cache creation is enabled
/// - cacheSize = -1 make a default sized cache in any case
///
/// If autocache is false:
/// this is a user requested cache. cacheSize is used to size the cache.
/// This cache should never be automatically adjusted.
///
/// Returns:
/// - 0 size set, or existing autosized cache almost large enough.
/// (cache was created if possible)
/// - -1 on error
Int_t TTree::SetCacheSizeAux(Bool_t autocache /* = kTRUE */, Long64_t cacheSize /* = 0 */ )
{
if (autocache) {
// used as a once only control for automatic cache setup
fCacheDoAutoInit = kFALSE;
}
if (!autocache) {
// negative size means the user requests the default
if (cacheSize < 0) {
cacheSize = GetCacheAutoSize(kTRUE);
}
} else {
if (cacheSize == 0) {
cacheSize = GetCacheAutoSize();
} else if (cacheSize < 0) {
cacheSize = GetCacheAutoSize(kTRUE);
}
}
TFile* file = GetCurrentFile();
if (!file || GetTree() != this) {
// if there's no file or we are not a plain tree (e.g. if we're a TChain)
// do not create a cache, only record the size if one was given
if (!autocache) {
fCacheSize = cacheSize;
}
if (GetTree() != this) {
return 0;
}
if (!autocache && cacheSize>0) {
Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
}
return 0;
}
// Check for an existing cache
TTreeCache* pf = GetReadCache(file);
if (pf) {
if (autocache) {
// reset our cache status tracking in case existing cache was added
// by the user without using one of the TTree methods
fCacheSize = pf->GetBufferSize();
fCacheUserSet = !pf->IsAutoCreated();
if (fCacheUserSet) {
// existing cache was created by the user, don't change it
return 0;
}
} else {
// update the cache to ensure it records the user has explicitly
// requested it
pf->SetAutoCreated(kFALSE);
}
// if we're using an automatically calculated size and the existing
// cache is already almost large enough don't resize
if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
// already large enough
return 0;
}
if (cacheSize == fCacheSize) {
return 0;
}
if (cacheSize == 0) {
// delete existing cache
pf->WaitFinishPrefetch();
file->SetCacheRead(0,this);
delete pf;
pf = 0;
} else {
// resize
Int_t res = pf->SetBufferSize(cacheSize);
if (res < 0) {
return -1;
}
}
} else {
// no existing cache
if (autocache) {
if (fCacheUserSet) {
// value was already set manually.
if (fCacheSize == 0) return 0;
// Expected a cache should exist; perhaps the user moved it
// Do nothing more here.
if (cacheSize) {
Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
}
return -1;
}
}
}
fCacheSize = cacheSize;
if (cacheSize == 0 || pf) {
return 0;
}
#ifdef R__USE_IMT
if(TTreeCacheUnzip::IsParallelUnzip() && file->GetCompressionLevel() > 0)
pf = new TTreeCacheUnzip(this, cacheSize);
else
#endif
pf = new TTreeCache(this, cacheSize);
pf->SetAutoCreated(autocache);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
///interface to TTreeCache to set the cache entry range
///
/// Returns:
/// - 0 entry range set
/// - -1 on error
Int_t TTree::SetCacheEntryRange(Long64_t first, Long64_t last)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("SetCacheEntryRange","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->SetCacheEntryRange(first, last);
}
} else {
Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
return -1;
}
tc->SetEntryRange(first,last);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Interface to TTreeCache to set the number of entries for the learning phase
void TTree::SetCacheLearnEntries(Int_t n)
{
TTreeCache::SetLearnEntries(n);
}
////////////////////////////////////////////////////////////////////////////////
/// Enable/Disable circularity for this tree.
///
/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
/// per branch in memory.
/// Note that when this function is called (maxEntries>0) the Tree
/// must be empty or having only one basket per branch.
/// if maxEntries <= 0 the tree circularity is disabled.
///
/// #### NOTE 1:
/// Circular Trees are interesting in online real time environments
/// to store the results of the last maxEntries events.
/// #### NOTE 2:
/// Calling SetCircular with maxEntries <= 0 is necessary before
/// merging circular Trees that have been saved on files.
/// #### NOTE 3:
/// SetCircular with maxEntries <= 0 is automatically called
/// by TChain::Merge
/// #### NOTE 4:
/// A circular Tree can still be saved in a file. When read back,
/// it is still a circular Tree and can be filled again.
void TTree::SetCircular(Long64_t maxEntries)
{
if (maxEntries <= 0) {
// Disable circularity.
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
ResetBit(kCircular);
//in case the Tree was originally created in gROOT, the branch
//compression level was set to -1. If the Tree is now associated to
//a file, reset the compression level to the file compression level
if (fDirectory) {
TFile* bfile = fDirectory->GetFile();
Int_t compress = ROOT::RCompressionSetting::EDefaults::kUseGeneralPurpose;
if (bfile) {
compress = bfile->GetCompressionSettings();
}
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->SetCompressionSettings(compress);
}
}
} else {
// Enable circularity.
fMaxEntries = maxEntries;
SetBit(kCircular);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the debug level and the debug range.
///
/// For entries in the debug range, the functions TBranchElement::Fill
/// and TBranchElement::GetEntry will print the number of bytes filled
/// or read for each branch.
void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
{
fDebug = level;
fDebugMin = min;
fDebugMax = max;
}
////////////////////////////////////////////////////////////////////////////////
/// Update the default value for the branch's fEntryOffsetLen.
/// If updateExisting is true, also update all the existing branches.
/// If newdefault is less than 10, the new default value will be 10.
void TTree::SetDefaultEntryOffsetLen(Int_t newdefault, Bool_t updateExisting)
{
if (newdefault < 10) {
newdefault = 10;
}
fDefaultEntryOffsetLen = newdefault;
if (updateExisting) {
TIter next( GetListOfBranches() );
TBranch *b;
while ( ( b = (TBranch*)next() ) ) {
b->SetEntryOffsetLen( newdefault, kTRUE );
}
if (fBranchRef) {
fBranchRef->SetEntryOffsetLen( newdefault, kTRUE );
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change the tree's directory.
///
/// Remove reference to this tree from current directory and
/// add reference to new directory dir. The dir parameter can
/// be 0 in which case the tree does not belong to any directory.
///
void TTree::SetDirectory(TDirectory* dir)
{
if (fDirectory == dir) {
return;
}
if (fDirectory) {
fDirectory->Remove(this);
// Delete or move the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,dir);
}
fDirectory = dir;
if (fDirectory) {
fDirectory->Append(this);
}
TFile* file = 0;
if (fDirectory) {
file = fDirectory->GetFile();
}
if (fBranchRef) {
fBranchRef->SetFile(file);
}
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->SetFile(file);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change number of entries in the tree.
///
/// If n >= 0, set number of entries in the tree = n.
///
/// If n < 0, set number of entries in the tree to match the
/// number of entries in each branch. (default for n is -1)
///
/// This function should be called only when one fills each branch
/// independently via TBranch::Fill without calling TTree::Fill.
/// Calling TTree::SetEntries() make sense only if the number of entries
/// in each branch is identical, a warning is issued otherwise.
/// The function returns the number of entries.
///
Long64_t TTree::SetEntries(Long64_t n)
{
// case 1 : force number of entries to n
if (n >= 0) {
fEntries = n;
return n;
}
// case 2; compute the number of entries from the number of entries in the branches
TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
Long64_t nMin = kMaxEntries;
Long64_t nMax = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())){
Long64_t n2 = b->GetEntries();
if (!bMin || n2 < nMin) {
nMin = n2;
bMin = b;
}
if (!bMax || n2 > nMax) {
nMax = n2;
bMax = b;
}
}
if (bMin && nMin != nMax) {
Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
bMin->GetName(), nMin, bMax->GetName(), nMax);
}
fEntries = nMax;
return fEntries;
}
////////////////////////////////////////////////////////////////////////////////
/// Set an EntryList
void TTree::SetEntryList(TEntryList *enlist, Option_t * /*opt*/)
{
if (fEntryList) {
//check if the previous entry list is owned by the tree
if (fEntryList->TestBit(kCanDelete)){
delete fEntryList;
}
}
fEventList = 0;
if (!enlist) {
fEntryList = 0;
return;
}
fEntryList = enlist;
fEntryList->SetTree(this);
}
////////////////////////////////////////////////////////////////////////////////
/// This function transfroms the given TEventList into a TEntryList
/// The new TEntryList is owned by the TTree and gets deleted when the tree
/// is deleted. This TEntryList can be returned by GetEntryList() function.
void TTree::SetEventList(TEventList *evlist)
{
fEventList = evlist;
if (fEntryList){
if (fEntryList->TestBit(kCanDelete)) {
TEntryList *tmp = fEntryList;
fEntryList = 0; // Avoid problem with RecursiveRemove.
delete tmp;
} else {
fEntryList = 0;
}
}
if (!evlist) {
fEntryList = 0;
fEventList = 0;
return;
}
fEventList = evlist;
char enlistname[100];
snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
fEntryList = new TEntryList(enlistname, evlist->GetTitle());
fEntryList->SetDirectory(0); // We own this.
Int_t nsel = evlist->GetN();
fEntryList->SetTree(this);
Long64_t entry;
for (Int_t i=0; i<nsel; i++){
entry = evlist->GetEntry(i);
fEntryList->Enter(entry);
}
fEntryList->SetReapplyCut(evlist->GetReapplyCut());
fEntryList->SetBit(kCanDelete, kTRUE);
}
////////////////////////////////////////////////////////////////////////////////
/// Set number of entries to estimate variable limits.
/// If n is -1, the estimate is set to be the current maximum
/// for the tree (i.e. GetEntries() + 1)
/// If n is less than -1, the behavior is undefined.
void TTree::SetEstimate(Long64_t n /* = 1000000 */)
{
if (n == 0) {
n = 10000;
} else if (n < 0) {
n = fEntries - n;
}
fEstimate = n;
GetPlayer();
if (fPlayer) {
fPlayer->SetEstimate(n);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Provide the end-user with the ability to enable/disable various experimental
/// IO features for this TTree.
///
/// Returns all the newly-set IO settings.
ROOT::TIOFeatures TTree::SetIOFeatures(const ROOT::TIOFeatures &features)
{
// Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
// error of their ways; this is just a safety check.
UChar_t featuresRequested = features.GetFeatures() & static_cast<UChar_t>(TBasket::EIOBits::kSupported);
UChar_t curFeatures = fIOFeatures.GetFeatures();
UChar_t newFeatures = ~curFeatures & featuresRequested;
curFeatures |= newFeatures;
fIOFeatures.Set(curFeatures);
ROOT::TIOFeatures newSettings(newFeatures);
return newSettings;
}
////////////////////////////////////////////////////////////////////////////////
/// Set fFileNumber to number.
/// fFileNumber is used by TTree::Fill to set the file name
/// for a new file to be created when the current file exceeds fgTreeMaxSize.
/// (see TTree::ChangeFile)
/// if fFileNumber=10, the new file name will have a suffix "_11",
/// ie, fFileNumber is incremented before setting the file name
void TTree::SetFileNumber(Int_t number)
{
if (fFileNumber < 0) {
Warning("SetFileNumber", "file number must be positive. Set to 0");
fFileNumber = 0;
return;
}
fFileNumber = number;
}
////////////////////////////////////////////////////////////////////////////////
/// Set all the branches in this TTree to be in decomposed object mode
/// (also known as MakeClass mode).
///
/// For MakeClass mode 0, the TTree expects the address where the data is stored
/// to be set by either the user or the TTree to the address of a full object
/// through the top level branch.
/// For MakeClass mode 1, this address is expected to point to a numerical type
/// or C-style array (variable or not) of numerical type, representing the
/// primitive data members.
/// The function's primary purpose is to allow the user to access the data
/// directly with numerical type variable rather than having to have the original
/// set of classes (or a reproduction thereof).
void TTree::SetMakeClass(Int_t make)
{
fMakeClass = make;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->SetMakeClass(make);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the maximum size in bytes of a Tree file (static function).
/// The default size is 100000000000LL, ie 100 Gigabytes.
///
/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
/// the function closes the current file and starts writing into
/// a new file with a name of the style "file_1.root" if the original
/// requested file name was "file.root".
void TTree::SetMaxTreeSize(Long64_t maxsize)
{
fgMaxTreeSize = maxsize;
}
////////////////////////////////////////////////////////////////////////////////
/// Change the name of this tree.
void TTree::SetName(const char* name)
{
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update hashlists if we change the name.
TFile *file = 0;
TTreeCache *pf = 0;
if (fDirectory) {
fDirectory->Remove(this);
if ((file = GetCurrentFile())) {
pf = GetReadCache(file);
file->SetCacheRead(0,this,TFile::kDoNotDisconnect);
}
}
// This changes our hash value.
fName = name;
if (fDirectory) {
fDirectory->Append(this);
if (pf) {
file->SetCacheRead(pf,this,TFile::kDoNotDisconnect);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change the name and title of this tree.
void TTree::SetObject(const char* name, const char* title)
{
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update hashlists if we change the name
TFile *file = 0;
TTreeCache *pf = 0;
if (fDirectory) {
fDirectory->Remove(this);
if ((file = GetCurrentFile())) {
pf = GetReadCache(file);
file->SetCacheRead(0,this,TFile::kDoNotDisconnect);
}
}
// This changes our hash value.
fName = name;
fTitle = title;
if (fDirectory) {
fDirectory->Append(this);
if (pf) {
file->SetCacheRead(pf,this,TFile::kDoNotDisconnect);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Enable or disable parallel unzipping of Tree buffers.
void TTree::SetParallelUnzip(Bool_t opt, Float_t RelSize)
{
if (opt) TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);
else TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kDisable);
if (RelSize > 0) {
TTreeCacheUnzip::SetUnzipRelBufferSize(RelSize);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set perf stats
void TTree::SetPerfStats(TVirtualPerfStats *perf)
{
fPerfStats = perf;
}
////////////////////////////////////////////////////////////////////////////////
/// The current TreeIndex is replaced by the new index.
/// Note that this function does not delete the previous index.
/// This gives the possibility to play with more than one index, e.g.,
/// ~~~ {.cpp}
/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
/// tree.SetTreeIndex(newIndex);
/// tree.Draw();
/// tree.SetTreeIndex(oldIndex);
/// tree.Draw(); etc
/// ~~~
void TTree::SetTreeIndex(TVirtualIndex* index)
{
if (fTreeIndex) {
fTreeIndex->SetTree(0);
}
fTreeIndex = index;
}
////////////////////////////////////////////////////////////////////////////////
/// Set tree weight.
///
/// The weight is used by TTree::Draw to automatically weight each
/// selected entry in the resulting histogram.
///
/// For example the equivalent of:
/// ~~~ {.cpp}
/// T.Draw("x", "w")
/// ~~~
/// is:
/// ~~~ {.cpp}
/// T.SetWeight(w);
/// T.Draw("x");
/// ~~~
/// This function is redefined by TChain::SetWeight. In case of a
/// TChain, an option "global" may be specified to set the same weight
/// for all trees in the TChain instead of the default behaviour
/// using the weights of each tree in the chain (see TChain::SetWeight).
void TTree::SetWeight(Double_t w, Option_t*)
{
fWeight = w;
}
////////////////////////////////////////////////////////////////////////////////
/// Print values of all active leaves for entry.
///
/// - if entry==-1, print current entry (default)
/// - if a leaf is an array, a maximum of lenmax elements is printed.
void TTree::Show(Long64_t entry, Int_t lenmax)
{
if (entry != -1) {
Int_t ret = LoadTree(entry);
if (ret == -2) {
Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
return;
} else if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
}
ret = GetEntry(entry);
if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
} else if (ret == 0) {
Error("Show()", "Cannot read entry %lld (no data read)", entry);
return;
}
}
printf("======> EVENT:%lld\n", fReadEntry);
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
Int_t ltype;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (branch->TestBit(kDoNotProcess)) {
continue;
}
Int_t len = leaf->GetLen();
if (len <= 0) {
continue;
}
len = TMath::Min(len, lenmax);
if (leaf->IsA() == TLeafElement::Class()) {
leaf->PrintValue(lenmax);
continue;
}
if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
continue;
}
ltype = 10;
if (leaf->IsA() == TLeafF::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafD::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafC::Class()) {
len = 1;
ltype = 5;
};
printf(" %-15s = ", leaf->GetName());
for (Int_t l = 0; l < len; l++) {
leaf->PrintValue(l);
if (l == (len - 1)) {
printf("\n");
continue;
}
printf(", ");
if ((l % ltype) == 0) {
printf("\n ");
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Start the TTreeViewer on this tree.
///
/// - ww is the width of the canvas in pixels
/// - wh is the height of the canvas in pixels
void TTree::StartViewer()
{
GetPlayer();
if (fPlayer) {
fPlayer->StartViewer(600, 400);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Stop the cache learning phase
///
/// Returns:
/// - 0 learning phase stopped or not active
/// - -1 on error
Int_t TTree::StopCacheLearningPhase()
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("StopCacheLearningPhase","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->StopCacheLearningPhase();
}
} else {
Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
return -1;
}
tc->StopLearningPhase();
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Set the fTree member for all branches and sub branches.
static void TBranch__SetTree(TTree *tree, TObjArray &branches)
{
Int_t nb = branches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches.UncheckedAt(i);
br->SetTree(tree);
Int_t nBaskets = br->GetListOfBaskets()->GetEntries();
Int_t writeBasket = br->GetWriteBasket();
for (Int_t j=writeBasket,n=0;j>=0 && n<nBaskets;--j) {
TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
if (bk) {
tree->IncrementTotalBuffers(bk->GetBufferSize());
++n;
}
}
TBranch__SetTree(tree,*br->GetListOfBranches());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the fTree member for all friend elements.
void TFriendElement__SetTree(TTree *tree, TList *frlist)
{
if (frlist) {
TObjLink *lnk = frlist->FirstLink();
while (lnk) {
TFriendElement *elem = (TFriendElement*)lnk->GetObject();
elem->fParentTree = tree;
lnk = lnk->Next();
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Stream a class object.
void TTree::Streamer(TBuffer& b)
{
if (b.IsReading()) {
UInt_t R__s, R__c;
if (fDirectory) {
fDirectory->Remove(this);
//delete the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,0);
}
fDirectory = 0;
fCacheDoAutoInit = kTRUE;
fCacheUserSet = kFALSE;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 4) {
b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
fBranches.SetOwner(kTRUE); // True needed only for R__v < 19 and most R__v == 19
if (fBranchRef) fBranchRef->SetTree(this);
TBranch__SetTree(this,fBranches);
TFriendElement__SetTree(this,fFriends);
if (fTreeIndex) {
fTreeIndex->SetTree(this);
}
if (fIndex.fN) {
Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
fIndex.Set(0);
fIndexValues.Set(0);
}
if (fEstimate <= 10000) {
fEstimate = 1000000;
}
if (fNClusterRange) {
// The I/O allocated just enough memory to hold the
// current set of ranges.
fMaxClusterRange = fNClusterRange;
}
if (GetCacheAutoSize() != 0) {
// a cache will be automatically created.
// No need for TTreePlayer::Process to enable the cache
fCacheSize = 0;
} else if (fAutoFlush < 0) {
// If there is no autoflush set, let's keep the cache completely
// disable by default for now.
fCacheSize = fAutoFlush;
} else if (fAutoFlush != 0) {
// Estimate the cluster size.
// This will allow TTree::Process to enable the cache.
Long64_t zipBytes = GetZipBytes();
Long64_t totBytes = GetTotBytes();
if (zipBytes != 0) {
fCacheSize = fAutoFlush*(zipBytes/fEntries);
} else if (totBytes != 0) {
fCacheSize = fAutoFlush*(totBytes/fEntries);
} else {
fCacheSize = 30000000;
}
if (fCacheSize >= (INT_MAX / 4)) {
fCacheSize = INT_MAX / 4;
} else if (fCacheSize == 0) {
fCacheSize = 30000000;
}
} else {
fCacheSize = 0;
}
ResetBit(kMustCleanup);
return;
}
//====process old versions before automatic schema evolution
Stat_t djunk;
Int_t ijunk;
TNamed::Streamer(b);
TAttLine::Streamer(b);
TAttFill::Streamer(b);
TAttMarker::Streamer(b);
b >> fScanField;
b >> ijunk; fMaxEntryLoop = (Long64_t)ijunk;
b >> ijunk; fMaxVirtualSize = (Long64_t)ijunk;
b >> djunk; fEntries = (Long64_t)djunk;
b >> djunk; fTotBytes = (Long64_t)djunk;
b >> djunk; fZipBytes = (Long64_t)djunk;
b >> ijunk; fAutoSave = (Long64_t)ijunk;
b >> ijunk; fEstimate = (Long64_t)ijunk;
if (fEstimate <= 10000) fEstimate = 1000000;
fBranches.Streamer(b);
if (fBranchRef) fBranchRef->SetTree(this);
TBranch__SetTree(this,fBranches);
fLeaves.Streamer(b);
fSavedBytes = fTotBytes;
if (R__v > 1) fIndexValues.Streamer(b);
if (R__v > 2) fIndex.Streamer(b);
if (R__v > 3) {
TList OldInfoList;
OldInfoList.Streamer(b);
OldInfoList.Delete();
}
fNClusterRange = 0;
fDefaultEntryOffsetLen = 1000;
ResetBit(kMustCleanup);
b.CheckByteCount(R__s, R__c, TTree::IsA());
//====end of old versions
} else {
if (fBranchRef) {
fBranchRef->Clear();
}
TRefTable *table = TRefTable::GetRefTable();
if (table) TRefTable::SetRefTable(0);
b.WriteClassBuffer(TTree::Class(), this);
if (table) TRefTable::SetRefTable(table);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Unbinned fit of one or more variable(s) from a tree.
///
/// funcname is a TF1 function.
///
/// See TTree::Draw for explanations of the other parameters.
///
/// Fit the variable varexp using the function funcname using the
/// selection cuts given by selection.
///
/// The list of fit options is given in parameter option.
///
/// - option = "Q" Quiet mode (minimum printing)
/// - option = "V" Verbose mode (default is between Q and V)
/// - option = "E" Perform better Errors estimation using Minos technique
/// - option = "M" More. Improve fit results
///
/// You can specify boundary limits for some or all parameters via
/// ~~~ {.cpp}
/// func->SetParLimits(p_number, parmin, parmax);
/// ~~~
/// if parmin>=parmax, the parameter is fixed
///
/// Note that you are not forced to fix the limits for all parameters.
/// For example, if you fit a function with 6 parameters, you can do:
/// ~~~ {.cpp}
/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
/// func->SetParLimits(4,-10,-4);
/// func->SetParLimits(5, 1,1);
/// ~~~
/// With this setup:
///
/// - Parameters 0->3 can vary freely
/// - Parameter 4 has boundaries [-10,-4] with initial value -8
/// - Parameter 5 is fixed to 100.
///
/// For the fit to be meaningful, the function must be self-normalized.
///
/// i.e. It must have the same integral regardless of the parameter
/// settings. Otherwise the fit will effectively just maximize the
/// area.
///
/// It is mandatory to have a normalization variable
/// which is fixed for the fit. e.g.
/// ~~~ {.cpp}
/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
/// f1->SetParameters(1, 3.1, 0.01);
/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
/// ~~~
/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
///
/// Return status:
///
/// - The function return the status of the fit in the following form
/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
/// - The fitResult is 0 is the fit is OK.
/// - The fitResult is negative in case of an error not connected with the fit.
/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
/// - If the number of selected entries is null the function returns -1
Int_t TTree::UnbinnedFit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->UnbinnedFit(funcname, varexp, selection, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Replace current attributes by current style.
void TTree::UseCurrentStyle()
{
if (gStyle->IsReading()) {
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
} else {
gStyle->SetHistFillColor(GetFillColor());
gStyle->SetHistFillStyle(GetFillStyle());
gStyle->SetHistLineColor(GetLineColor());
gStyle->SetHistLineStyle(GetLineStyle());
gStyle->SetHistLineWidth(GetLineWidth());
gStyle->SetMarkerColor(GetMarkerColor());
gStyle->SetMarkerStyle(GetMarkerStyle());
gStyle->SetMarkerSize(GetMarkerSize());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Write this object to the current directory. For more see TObject::Write
/// If option & kFlushBasket, call FlushBasket before writing the tree.
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
{
FlushBasketsImpl();
return TObject::Write(name, option, bufsize);
}
////////////////////////////////////////////////////////////////////////////////
/// Write this object to the current directory. For more see TObject::Write
/// If option & kFlushBasket, call FlushBasket before writing the tree.
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize)
{
return ((const TTree*)this)->Write(name, option, bufsize);
}
////////////////////////////////////////////////////////////////////////////////
/// \class TTreeFriendLeafIter
///
/// Iterator on all the leaves in a TTree and its friend
ClassImp(TTreeFriendLeafIter);
////////////////////////////////////////////////////////////////////////////////
/// Create a new iterator. By default the iteration direction
/// is kIterForward. To go backward use kIterBackward.
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTree* tree, Bool_t dir)
: fTree(const_cast<TTree*>(tree))
, fLeafIter(0)
, fTreeIter(0)
, fDirection(dir)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor. Does NOT copy the 'cursor' location!
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTreeFriendLeafIter& iter)
: TIterator(iter)
, fTree(iter.fTree)
, fLeafIter(0)
, fTreeIter(0)
, fDirection(iter.fDirection)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Overridden assignment operator. Does NOT copy the 'cursor' location!
TIterator& TTreeFriendLeafIter::operator=(const TIterator& rhs)
{
if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
const TTreeFriendLeafIter &rhs1 = (const TTreeFriendLeafIter &)rhs;
fDirection = rhs1.fDirection;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Overridden assignment operator. Does NOT copy the 'cursor' location!
TTreeFriendLeafIter& TTreeFriendLeafIter::operator=(const TTreeFriendLeafIter& rhs)
{
if (this != &rhs) {
fDirection = rhs.fDirection;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Go the next friend element
TObject* TTreeFriendLeafIter::Next()
{
if (!fTree) return 0;
TObject * next;
TTree * nextTree;
if (!fLeafIter) {
TObjArray *list = fTree->GetListOfLeaves();
if (!list) return 0; // Can happen with an empty chain.
fLeafIter = list->MakeIterator(fDirection);
if (!fLeafIter) return 0;
}
next = fLeafIter->Next();
if (!next) {
if (!fTreeIter) {
TCollection * list = fTree->GetListOfFriends();
if (!list) return next;
fTreeIter = list->MakeIterator(fDirection);
if (!fTreeIter) return 0;
}
TFriendElement * nextFriend = (TFriendElement*) fTreeIter->Next();
///nextTree = (TTree*)fTreeIter->Next();
if (nextFriend) {
nextTree = const_cast<TTree*>(nextFriend->GetTree());
if (!nextTree) return Next();
SafeDelete(fLeafIter);
fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
if (!fLeafIter) return 0;
next = fLeafIter->Next();
}
}
return next;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the object option stored in the list.
Option_t* TTreeFriendLeafIter::GetOption() const
{
if (fLeafIter) return fLeafIter->GetOption();
return "";
}
Make TTree::SetParallelUnzip behavior non-static.
Previously it was 'just' updating the global state and not affecting (directly) the current TTree,
which is ... surprising ... for a non-static function.
// @(#)root/tree:$Id$
// Author: Rene Brun 12/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
\defgroup tree Tree Library
In order to store columnar datasets, ROOT provides the TTree, TChain,
TNtuple and TNtupleD classes.
The TTree class represents a columnar dataset. Any C++ type can be stored in the
columns. The TTree has allowed to store about **1 EB** of data coming from the LHC alone:
it is demonstrated to scale and it's battle tested. It has been optimized during the years
to reduce dataset sizes on disk and to deliver excellent runtime performance.
It allows to access only part of the columns of the datasets, too.
The TNtuple and TNtupleD classes are specialisations of the TTree class which can
only hold single precision and double precision floating-point numbers respectively;
The TChain is a collection of TTrees, which can be located also in different files.
*/
/** \class TTree
\ingroup tree
A TTree represents a columnar dataset. Any C++ type can be stored in its columns.
A TTree, often called in jargon *tree*, consists of a list of independent columns or *branches*,
represented by the TBranch class.
Behind each branch, buffers are allocated automatically by ROOT.
Such buffers are automatically written to disk or kept in memory until the size stored in the
attribute fMaxVirtualSize is reached.
Variables of one branch are written to the same buffer. A branch buffer is
automatically compressed if the file compression attribute is set (default).
Branches may be written to different files (see TBranch::SetFile).
The ROOT user can decide to make one single branch and serialize one object into
one single I/O buffer or to make several branches.
Making several branches is particularly interesting in the data analysis phase,
when it is desirable to have a high reading rate and not all columns are equally interesting
## Table of contents:
- [Creating a TTree](#creatingattree)
- [Add a Column of Fundamental Types and Arrays thereof](#addcolumnoffundamentaltypes)
- [Add a Column of a STL Collection instances](#addingacolumnofstl)
- [Add a column holding an object](#addingacolumnofobjs)
- [Add a column holding a TObjectArray](#addingacolumnofobjs)
- [Fill the tree](#fillthetree)
- [Add a column to an already existing Tree](#addcoltoexistingtree)
- [An Example](#fullexample)
## <a name="creatingattree"></a>Creating a TTree
~~~ {.cpp}
TTree tree(name, title)
~~~
Creates a Tree with name and title.
Various kinds of branches can be added to a tree:
- Variables representing fundamental types, simple classes/structures or list of variables: for example for C or Fortran
structures.
- Any C++ object or collection, provided by the STL or ROOT.
In the following, the details about the creation of different types of branches are given.
## <a name="addcolumnoffundamentaltypes"></a>Add a column (`branch`) of fundamental types and arrays thereof
This strategy works also for lists of variables, e.g. to describe simple structures.
It is strongly reccomended to persistify those as objects rather than lists of leaves.
~~~ {.cpp}
auto branch = tree.Branch(branchname, address, leaflist, bufsize)
~~~
- address is the address of the first item of a structure
- leaflist is the concatenation of all the variable names and types
separated by a colon character :
The variable name and the variable type are separated by a
slash (/). The variable type must be 1 character. (Characters
after the first are legal and will be appended to the visible
name of the leaf, but have no effect.) If no type is given, the
type of the variable is assumed to be the same as the previous
variable. If the first variable does not have a type, it is
assumed of type F by default. The list of currently supported
types is given below:
- `C` : a character string terminated by the 0 character
- `B` : an 8 bit signed integer (`Char_t`)
- `b` : an 8 bit unsigned integer (`UChar_t`)
- `S` : a 16 bit signed integer (`Short_t`)
- `s` : a 16 bit unsigned integer (`UShort_t`)
- `I` : a 32 bit signed integer (`Int_t`)
- `i` : a 32 bit unsigned integer (`UInt_t`)
- `F` : a 32 bit floating point (`Float_t`)
- `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
- `D` : a 64 bit floating point (`Double_t`)
- `d` : a 24 bit truncated floating point (`Double32_t`)
- `L` : a 64 bit signed integer (`Long64_t`)
- `l` : a 64 bit unsigned integer (`ULong64_t`)
- `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
Examples:
- A int: "myVar/I"
- A float array with fixed size: "myArrfloat[42]/F"
- An double array with variable size, held by the `myvar` column: "myArrdouble[myvar]/D"
- An Double32_t array with variable size, held by the `myvar` column , with values between 0 and 16: "myArr[myvar]/d[0,10]"
- If the address points to a single numerical variable, the leaflist is optional:
~~~ {.cpp}
int value;
`tree->Branch(branchname, &value);`
~~~
- If the address points to more than one numerical variable, we strongly recommend
that the variable be sorted in decreasing order of size. Any other order will
result in a non-portable TTree (i.e. you will not be able to read it back on a
platform with a different padding strategy).
We recommend to persistify objects rather than composite leaflists.
- In case of the truncated floating point types (Float16_t and Double32_t) you can
furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
the type character. For example, for storing a variable size array `myArr` of
`Double32_t` with values within a range of `[0, 2*pi]` and the size of which is
stored in a branch called `myArrSize`, the syntax for the `leaflist` string would
be: `myArr[myArrSize]/d[0,twopi]`. Of course the number of bits could be specified,
the standard rules of opaque typedefs annotation are valid. For example, if only
18 bits were sufficient, the syntax would become: `myArr[myArrSize]/d[0,twopi,18]`
## <a name="addingacolumnofstl"></a>Adding a column of STL collection instances (e.g. std::vector, std::list, std::unordered_map)
~~~ {.cpp}
auto branch = tree.Branch( branchname, STLcollection, buffsize, splitlevel);
~~~
STLcollection is the address of a pointer to std::vector, std::list,
std::deque, std::set or std::multiset containing pointers to objects.
If the splitlevel is a value bigger than 100 (TTree::kSplitCollectionOfPointers)
then the collection will be written in split mode, e.g. if it contains objects of
any types deriving from TTrack this function will sort the objects
based on their type and store them in separate branches in split
mode.
~~~ {.cpp}
branch->SetAddress(void *address)
~~~
In case of dynamic structures changing with each entry for example, one must
redefine the branch address before filling the branch again.
This is done via the TBranch::SetAddress member function.
## <a name="addingacolumnofobjs">Add a column of objects
~~~ {.cpp}
MyClass object;
auto branch = tree.Branch(branchname, &object, bufsize, splitlevel)
~~~
Note: The 2nd parameter must be the address of a valid object.
The object must not be destroyed (i.e. be deleted) until the TTree
is deleted or TTree::ResetBranchAddress is called.
- if splitlevel=0, the object is serialized in the branch buffer.
- if splitlevel=1 (default), this branch will automatically be split
into subbranches, with one subbranch for each data member or object
of the object itself. In case the object member is a TClonesArray,
the mechanism described in case C is applied to this array.
- if splitlevel=2 ,this branch will automatically be split
into subbranches, with one subbranch for each data member or object
of the object itself. In case the object member is a TClonesArray,
it is processed as a TObject*, only one branch.
Another available syntax is the following:
~~~ {.cpp}
auto branch = tree.Branch(branchname, &p_object, bufsize, splitlevel)
auto branch = tree.Branch(branchname, className, &p_object, bufsize, splitlevel)
~~~
- p_object is a pointer to an object.
- If className is not specified, Branch uses the type of p_object to determine the
type of the object.
- If className is used to specify explicitly the object type, the className must
be of a type related to the one pointed to by the pointer. It should be either
a parent or derived class.
Note: The pointer whose address is passed to TTree::Branch must not
be destroyed (i.e. go out of scope) until the TTree is deleted or
TTree::ResetBranchAddress is called.
Note: The pointer p_object must be initialized before calling TTree::Branch
- Do either:
~~~ {.cpp}
MyDataClass* p_object = nullptr;
tree.Branch(branchname, &p_object);
~~~
- Or:
~~~ {.cpp}
auto p_object = new MyDataClass;
tree.Branch(branchname, &p_object);
~~~
Whether the pointer is set to zero or not, the ownership of the object
is not taken over by the TTree. I.e. even though an object will be allocated
by TTree::Branch if the pointer p_object is zero, the object will <b>not</b>
be deleted when the TTree is deleted.
## <a name="addingacolumnoftclonesarray">Add a column of TClonesArray instances
*It is recommended to use STL containers instead of TClonesArrays*.
~~~ {.cpp}
// clonesarray is the address of a pointer to a TClonesArray.
auto branch = tree.Branch(branchname,clonesarray, bufsize, splitlevel)
~~~
The TClonesArray is a direct access list of objects of the same class.
For example, if the TClonesArray is an array of TTrack objects,
this function will create one subbranch for each data member of
the object TTrack.
## <a name="fillthetree">Fill the Tree:
A TTree instance is filled with the invocation of the TTree::Fill method:
~~~ {.cpp}
tree.Fill()
~~~
Upon its invocation, a loop on all defined branches takes place that for each branch invokes
the TBranch::Fill method.
## <a name="addcoltoexistingtree">Add a column to an already existing Tree
You may want to add a branch to an existing tree. For example,
if one variable in the tree was computed with a certain algorithm,
you may want to try another algorithm and compare the results.
One solution is to add a new branch, fill it, and save the tree.
The code below adds a simple branch to an existing tree.
Note the kOverwrite option in the Write method, it overwrites the
existing tree. If it is not specified, two copies of the tree headers
are saved.
~~~ {.cpp}
void tree3AddBranch() {
TFile f("tree3.root", "update");
Float_t new_v;
auto t3 = f->Get<TTree>("t3");
auto newBranch = t3->Branch("new_v", &new_v, "new_v/F");
Long64_t nentries = t3->GetEntries(); // read the number of entries in the t3
for (Long64_t i = 0; i < nentries; i++) {
new_v = gRandom->Gaus(0, 1);
newBranch->Fill();
}
t3->Write("", TObject::kOverwrite); // save only the new version of the tree
}
~~~
It is not always possible to add branches to existing datasets stored in TFiles: for example,
these files might not be writeable, just readable. In addition, modifying in place a TTree
causes a new TTree instance to be written and the previous one to be deleted.
For this reasons, ROOT offers the concept of friends for TTree and TChain:
if is good practice to rely on friend trees rather than adding a branch manually.
## <a name="fullexample">An Example
Begin_Macro
../../../tutorials/tree/tree.C
End_Macro
~~~ {.cpp}
// A simple example with histograms and a tree
//
// This program creates :
// - a one dimensional histogram
// - a two dimensional histogram
// - a profile histogram
// - a tree
//
// These objects are filled with some random numbers and saved on a file.
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TProfile.h"
#include "TRandom.h"
#include "TTree.h"
//__________________________________________________________________________
main(int argc, char **argv)
{
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,trees
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
TFile hfile("htree.root","RECREATE","Demo ROOT file with histograms & trees");
// Create some histograms and a profile histogram
TH1F hpx("hpx","This is the px distribution",100,-4,4);
TH2F hpxpy("hpxpy","py ps px",40,-4,4,40,-4,4);
TProfile hprof("hprof","Profile of pz versus px",100,-4,4,0,20);
// Define some simple structures
typedef struct {Float_t x,y,z;} POINT;
typedef struct {
Int_t ntrack,nseg,nvertex;
UInt_t flag;
Float_t temperature;
} EVENTN;
POINT point;
EVENTN eventn;
// Create a ROOT Tree
TTree tree("T","An example of ROOT tree with a few branches");
tree.Branch("point",&point,"x:y:z");
tree.Branch("eventn",&eventn,"ntrack/I:nseg:nvertex:flag/i:temperature/F");
tree.Branch("hpx","TH1F",&hpx,128000,0);
Float_t px,py,pz;
// Here we start a loop on 1000 events
for ( Int_t i=0; i<1000; i++) {
gRandom->Rannor(px,py);
pz = px*px + py*py;
const auto random = gRandom->::Rndm(1);
// Fill histograms
hpx.Fill(px);
hpxpy.Fill(px,py,1);
hprof.Fill(px,pz,1);
// Fill structures
point.x = 10*(random-1);
point.y = 5*random;
point.z = 20*random;
eventn.ntrack = Int_t(100*random);
eventn.nseg = Int_t(2*eventn.ntrack);
eventn.nvertex = 1;
eventn.flag = Int_t(random+0.5);
eventn.temperature = 20+random;
// Fill the tree. For each event, save the 2 structures and 3 objects
// In this simple example, the objects hpx, hprof and hpxpy are slightly
// different from event to event. We expect a big compression factor!
tree->Fill();
}
// End of the loop
tree.Print();
// Save all objects in this file
hfile.Write();
// Close the file. Note that this is automatically done when you leave
// the application upon file destruction.
hfile.Close();
return 0;
}
~~~
*/
#include <ROOT/RConfig.hxx>
#include "TTree.h"
#include "ROOT/TIOFeatures.hxx"
#include "TArrayC.h"
#include "TBufferFile.h"
#include "TBaseClass.h"
#include "TBasket.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TBranchRef.h"
#include "TBrowser.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TClonesArray.h"
#include "TCut.h"
#include "TDataMember.h"
#include "TDataType.h"
#include "TDirectory.h"
#include "TError.h"
#include "TEntryList.h"
#include "TEnv.h"
#include "TEventList.h"
#include "TFile.h"
#include "TFolder.h"
#include "TFriendElement.h"
#include "TInterpreter.h"
#include "TLeaf.h"
#include "TLeafB.h"
#include "TLeafC.h"
#include "TLeafD.h"
#include "TLeafElement.h"
#include "TLeafF.h"
#include "TLeafI.h"
#include "TLeafL.h"
#include "TLeafObject.h"
#include "TLeafS.h"
#include "TList.h"
#include "TMath.h"
#include "TROOT.h"
#include "TRealData.h"
#include "TRegexp.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
#include "TStyle.h"
#include "TSystem.h"
#include "TTreeCloner.h"
#include "TTreeCache.h"
#include "TTreeCacheUnzip.h"
#include "TVirtualCollectionProxy.h"
#include "TEmulatedCollectionProxy.h"
#include "TVirtualIndex.h"
#include "TVirtualPerfStats.h"
#include "TVirtualPad.h"
#include "TBranchSTL.h"
#include "TSchemaRuleSet.h"
#include "TFileMergeInfo.h"
#include "ROOT/StringConv.hxx"
#include "TVirtualMutex.h"
#include "TBranchIMTHelper.h"
#include "TNotifyLink.h"
#include <chrono>
#include <cstddef>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <limits.h>
#include <algorithm>
#ifdef R__USE_IMT
#include "ROOT/TThreadExecutor.hxx"
#include <thread>
#include <string>
#include <sstream>
#endif
constexpr Int_t kNEntriesResort = 100;
constexpr Float_t kNEntriesResortInv = 1.f/kNEntriesResort;
Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
Long64_t TTree::fgMaxTreeSize = 100000000000LL;
ClassImp(TTree);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static char DataTypeToChar(EDataType datatype)
{
// Return the leaflist 'char' for a given datatype.
switch(datatype) {
case kChar_t: return 'B';
case kUChar_t: return 'b';
case kBool_t: return 'O';
case kShort_t: return 'S';
case kUShort_t: return 's';
case kCounter:
case kInt_t: return 'I';
case kUInt_t: return 'i';
case kDouble_t: return 'D';
case kDouble32_t: return 'd';
case kFloat_t: return 'F';
case kFloat16_t: return 'f';
case kLong_t: return 0; // unsupported
case kULong_t: return 0; // unsupported?
case kchar: return 0; // unsupported
case kLong64_t: return 'L';
case kULong64_t: return 'l';
case kCharStar: return 'C';
case kBits: return 0; //unsupported
case kOther_t:
case kNoType_t:
default:
return 0;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// \class TTree::TFriendLock
/// Helper class to prevent infinite recursion in the usage of TTree Friends.
////////////////////////////////////////////////////////////////////////////////
/// Record in tree that it has been used while recursively looks through the friends.
TTree::TFriendLock::TFriendLock(TTree* tree, UInt_t methodbit)
: fTree(tree)
{
// We could also add some code to acquire an actual
// lock to prevent multi-thread issues
fMethodBit = methodbit;
if (fTree) {
fPrevious = fTree->fFriendLockStatus & fMethodBit;
fTree->fFriendLockStatus |= fMethodBit;
} else {
fPrevious = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor.
TTree::TFriendLock::TFriendLock(const TFriendLock& tfl) :
fTree(tfl.fTree),
fMethodBit(tfl.fMethodBit),
fPrevious(tfl.fPrevious)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment operator.
TTree::TFriendLock& TTree::TFriendLock::operator=(const TTree::TFriendLock& tfl)
{
if(this!=&tfl) {
fTree=tfl.fTree;
fMethodBit=tfl.fMethodBit;
fPrevious=tfl.fPrevious;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Restore the state of tree the same as before we set the lock.
TTree::TFriendLock::~TFriendLock()
{
if (fTree) {
if (!fPrevious) {
fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// \class TTree::TClusterIterator
/// Helper class to iterate over cluster of baskets.
////////////////////////////////////////////////////////////////////////////////
/// Regular constructor.
/// TTree is not set as const, since we might modify if it is a TChain.
TTree::TClusterIterator::TClusterIterator(TTree *tree, Long64_t firstEntry) : fTree(tree), fClusterRange(0), fStartEntry(0), fNextEntry(0), fEstimatedSize(-1)
{
if (fTree->fNClusterRange) {
// Find the correct cluster range.
//
// Since fClusterRangeEnd contains the inclusive upper end of the range, we need to search for the
// range that was containing the previous entry and add 1 (because BinarySearch consider the values
// to be the inclusive start of the bucket).
fClusterRange = TMath::BinarySearch(fTree->fNClusterRange, fTree->fClusterRangeEnd, firstEntry - 1) + 1;
Long64_t entryInRange;
Long64_t pedestal;
if (fClusterRange == 0) {
pedestal = 0;
entryInRange = firstEntry;
} else {
pedestal = fTree->fClusterRangeEnd[fClusterRange-1] + 1;
entryInRange = firstEntry - pedestal;
}
Long64_t autoflush;
if (fClusterRange == fTree->fNClusterRange) {
autoflush = fTree->fAutoFlush;
} else {
autoflush = fTree->fClusterSize[fClusterRange];
}
if (autoflush <= 0) {
autoflush = GetEstimatedClusterSize();
}
fStartEntry = pedestal + entryInRange - entryInRange%autoflush;
} else if ( fTree->GetAutoFlush() <= 0 ) {
// Case of old files before November 9 2009 *or* small tree where AutoFlush was never set.
fStartEntry = firstEntry;
} else {
fStartEntry = firstEntry - firstEntry%fTree->GetAutoFlush();
}
fNextEntry = fStartEntry; // Position correctly for the first call to Next()
}
////////////////////////////////////////////////////////////////////////////////
/// Estimate the cluster size.
///
/// In almost all cases, this quickly returns the size of the auto-flush
/// in the TTree.
///
/// However, in the case where the cluster size was not fixed (old files and
/// case where autoflush was explicitly set to zero), we need estimate
/// a cluster size in relation to the size of the cache.
///
/// After this value is calculated once for the TClusterIterator, it is
/// cached and reused in future calls.
Long64_t TTree::TClusterIterator::GetEstimatedClusterSize()
{
auto autoFlush = fTree->GetAutoFlush();
if (autoFlush > 0) return autoFlush;
if (fEstimatedSize > 0) return fEstimatedSize;
Long64_t zipBytes = fTree->GetZipBytes();
if (zipBytes == 0) {
fEstimatedSize = fTree->GetEntries() - 1;
} else {
Long64_t clusterEstimate = 1;
Long64_t cacheSize = fTree->GetCacheSize();
if (cacheSize == 0) {
// Humm ... let's double check on the file.
TFile *file = fTree->GetCurrentFile();
if (file) {
TFileCacheRead *cache = fTree->GetReadCache(file);
if (cache) {
cacheSize = cache->GetBufferSize();
}
}
}
// If neither file nor tree has a cache, use the current default.
if (cacheSize <= 0) {
cacheSize = 30000000;
}
clusterEstimate = fTree->GetEntries() * cacheSize / zipBytes;
// If there are no entries, then just default to 1.
fEstimatedSize = clusterEstimate ? clusterEstimate : 1;
}
return fEstimatedSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Move on to the next cluster and return the starting entry
/// of this next cluster
Long64_t TTree::TClusterIterator::Next()
{
fStartEntry = fNextEntry;
if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
if (fClusterRange == fTree->fNClusterRange) {
// We are looking at a range which size
// is defined by AutoFlush itself and goes to the GetEntries.
fNextEntry += GetEstimatedClusterSize();
} else {
if (fStartEntry > fTree->fClusterRangeEnd[fClusterRange]) {
++fClusterRange;
}
if (fClusterRange == fTree->fNClusterRange) {
// We are looking at the last range which size
// is defined by AutoFlush itself and goes to the GetEntries.
fNextEntry += GetEstimatedClusterSize();
} else {
Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
if (clusterSize == 0) {
clusterSize = GetEstimatedClusterSize();
}
fNextEntry += clusterSize;
if (fNextEntry > fTree->fClusterRangeEnd[fClusterRange]) {
// The last cluster of the range was a partial cluster,
// so the next cluster starts at the beginning of the
// next range.
fNextEntry = fTree->fClusterRangeEnd[fClusterRange] + 1;
}
}
}
} else {
// Case of old files before November 9 2009
fNextEntry = fStartEntry + GetEstimatedClusterSize();
}
if (fNextEntry > fTree->GetEntries()) {
fNextEntry = fTree->GetEntries();
}
return fStartEntry;
}
////////////////////////////////////////////////////////////////////////////////
/// Move on to the previous cluster and return the starting entry
/// of this previous cluster
Long64_t TTree::TClusterIterator::Previous()
{
fNextEntry = fStartEntry;
if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
if (fClusterRange == 0 || fTree->fNClusterRange == 0) {
// We are looking at a range which size
// is defined by AutoFlush itself.
fStartEntry -= GetEstimatedClusterSize();
} else {
if (fNextEntry <= fTree->fClusterRangeEnd[fClusterRange]) {
--fClusterRange;
}
if (fClusterRange == 0) {
// We are looking at the first range.
fStartEntry = 0;
} else {
Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
if (clusterSize == 0) {
clusterSize = GetEstimatedClusterSize();
}
fStartEntry -= clusterSize;
}
}
} else {
// Case of old files before November 9 2009 or trees that never auto-flushed.
fStartEntry = fNextEntry - GetEstimatedClusterSize();
}
if (fStartEntry < 0) {
fStartEntry = 0;
}
return fStartEntry;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// Default constructor and I/O constructor.
///
/// Note: We do *not* insert ourself into the current directory.
///
TTree::TTree()
: TNamed()
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fNClusterRange(0)
, fMaxClusterRange(0)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fClusterRangeEnd(0)
, fClusterSize(0)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(0)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fPerfStats(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
, fTransientBuffer(0)
, fCacheDoAutoInit(kTRUE)
, fCacheDoClusterPrefetch(kFALSE)
, fCacheUserSet(kFALSE)
, fIMTEnabled(ROOT::IsImplicitMTEnabled())
, fNEntriesSinceSorting(0)
{
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
fBranches.SetOwner(kTRUE);
}
////////////////////////////////////////////////////////////////////////////////
/// Normal tree constructor.
///
/// The tree is created in the current directory.
/// Use the various functions Branch below to add branches to this tree.
///
/// If the first character of title is a "/", the function assumes a folder name.
/// In this case, it creates automatically branches following the folder hierarchy.
/// splitlevel may be used in this case to control the split level.
TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */,
TDirectory* dir /* = gDirectory*/)
: TNamed(name, title)
, TAttLine()
, TAttFill()
, TAttMarker()
, fEntries(0)
, fTotBytes(0)
, fZipBytes(0)
, fSavedBytes(0)
, fFlushedBytes(0)
, fWeight(1)
, fTimerInterval(0)
, fScanField(25)
, fUpdate(0)
, fDefaultEntryOffsetLen(1000)
, fNClusterRange(0)
, fMaxClusterRange(0)
, fMaxEntries(0)
, fMaxEntryLoop(0)
, fMaxVirtualSize(0)
, fAutoSave( -300000000)
, fAutoFlush(-30000000)
, fEstimate(1000000)
, fClusterRangeEnd(0)
, fClusterSize(0)
, fCacheSize(0)
, fChainOffset(0)
, fReadEntry(-1)
, fTotalBuffers(0)
, fPacketSize(100)
, fNfill(0)
, fDebug(0)
, fDebugMin(0)
, fDebugMax(9999999)
, fMakeClass(0)
, fFileNumber(0)
, fNotify(0)
, fDirectory(dir)
, fBranches()
, fLeaves()
, fAliases(0)
, fEventList(0)
, fEntryList(0)
, fIndexValues()
, fIndex()
, fTreeIndex(0)
, fFriends(0)
, fPerfStats(0)
, fUserInfo(0)
, fPlayer(0)
, fClones(0)
, fBranchRef(0)
, fFriendLockStatus(0)
, fTransientBuffer(0)
, fCacheDoAutoInit(kTRUE)
, fCacheDoClusterPrefetch(kFALSE)
, fCacheUserSet(kFALSE)
, fIMTEnabled(ROOT::IsImplicitMTEnabled())
, fNEntriesSinceSorting(0)
{
// TAttLine state.
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
// TAttFill state.
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
// TAttMarkerState.
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
fMaxEntryLoop = 1000000000;
fMaxEntryLoop *= 1000;
// Insert ourself into the current directory.
// FIXME: This is very annoying behaviour, we should
// be able to choose to not do this like we
// can with a histogram.
if (fDirectory) fDirectory->Append(this);
fBranches.SetOwner(kTRUE);
// If title starts with "/" and is a valid folder name, a superbranch
// is created.
// FIXME: Why?
if (strlen(title) > 2) {
if (title[0] == '/') {
Branch(title+1,32000,splitlevel);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor.
TTree::~TTree()
{
if (auto link = dynamic_cast<TNotifyLinkBase*>(fNotify)) {
link->Clear();
}
if (fAllocationCount && (gDebug > 0)) {
Info("TTree::~TTree", "For tree %s, allocation count is %u.", GetName(), fAllocationCount.load());
#ifdef R__TRACK_BASKET_ALLOC_TIME
Info("TTree::~TTree", "For tree %s, allocation time is %lluus.", GetName(), fAllocationTime.load());
#endif
}
if (fDirectory) {
// We are in a directory, which may possibly be a file.
if (fDirectory->GetList()) {
// Remove us from the directory listing.
fDirectory->Remove(this);
}
//delete the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,0);
}
// We don't own the leaves in fLeaves, the branches do.
fLeaves.Clear();
// I'm ready to destroy any objects allocated by
// SetAddress() by my branches. If I have clones,
// tell them to zero their pointers to this shared
// memory.
if (fClones && fClones->GetEntries()) {
// I have clones.
// I am about to delete the objects created by
// SetAddress() which we are sharing, so tell
// the clones to release their pointers to them.
for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
TTree* clone = (TTree*) lnk->GetObject();
// clone->ResetBranchAddresses();
// Reset only the branch we have set the address of.
CopyAddresses(clone,kTRUE);
}
}
// Get rid of our branches, note that this will also release
// any memory allocated by TBranchElement::SetAddress().
fBranches.Delete();
// FIXME: We must consider what to do with the reset of these if we are a clone.
delete fPlayer;
fPlayer = 0;
if (fFriends) {
fFriends->Delete();
delete fFriends;
fFriends = 0;
}
if (fAliases) {
fAliases->Delete();
delete fAliases;
fAliases = 0;
}
if (fUserInfo) {
fUserInfo->Delete();
delete fUserInfo;
fUserInfo = 0;
}
if (fClones) {
// Clone trees should no longer be removed from fClones when they are deleted.
{
R__LOCKGUARD(gROOTMutex);
gROOT->GetListOfCleanups()->Remove(fClones);
}
// Note: fClones does not own its content.
delete fClones;
fClones = 0;
}
if (fEntryList) {
if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==0) {
// Delete the entry list if it is marked to be deleted and it is not also
// owned by a directory. (Otherwise we would need to make sure that a
// TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
delete fEntryList;
fEntryList=0;
}
}
delete fTreeIndex;
fTreeIndex = 0;
delete fBranchRef;
fBranchRef = 0;
delete [] fClusterRangeEnd;
fClusterRangeEnd = 0;
delete [] fClusterSize;
fClusterSize = 0;
// Must be done after the destruction of friends.
// Note: We do *not* own our directory.
fDirectory = 0;
if (fTransientBuffer) {
delete fTransientBuffer;
fTransientBuffer = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the transient buffer currently used by this TTree for reading/writing baskets.
TBuffer* TTree::GetTransientBuffer(Int_t size)
{
if (fTransientBuffer) {
if (fTransientBuffer->BufferSize() < size) {
fTransientBuffer->Expand(size);
}
return fTransientBuffer;
}
fTransientBuffer = new TBufferFile(TBuffer::kRead, size);
return fTransientBuffer;
}
////////////////////////////////////////////////////////////////////////////////
/// Add branch with name bname to the Tree cache.
/// If bname="*" all branches are added to the cache.
/// if subbranches is true all the branches of the subbranches are
/// also put to the cache.
///
/// Returns:
/// - 0 branch added or already included
/// - -1 on error
Int_t TTree::AddBranchToCache(const char*bname, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("AddBranchToCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->AddBranchToCache(bname, subbranches);
}
} else {
Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("AddBranchToCache", "No cache is available, branch not added");
return -1;
}
return tc->AddBranch(bname,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Add branch b to the Tree cache.
/// if subbranches is true all the branches of the subbranches are
/// also put to the cache.
///
/// Returns:
/// - 0 branch added or already included
/// - -1 on error
Int_t TTree::AddBranchToCache(TBranch *b, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("AddBranchToCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
Int_t res = GetTree()->AddBranchToCache(b, subbranches);
if (res<0) {
Error("AddBranchToCache", "Error adding branch");
}
return res;
}
} else {
Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("AddBranchToCache", "No cache is available, branch not added");
return -1;
}
return tc->AddBranch(b,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Remove the branch with name 'bname' from the Tree cache.
/// If bname="*" all branches are removed from the cache.
/// if subbranches is true all the branches of the subbranches are
/// also removed from the cache.
///
/// Returns:
/// - 0 branch dropped or not in cache
/// - -1 on error
Int_t TTree::DropBranchFromCache(const char*bname, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("DropBranchFromCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->DropBranchFromCache(bname, subbranches);
}
} else {
Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("DropBranchFromCache", "No cache is available, branch not dropped");
return -1;
}
return tc->DropBranch(bname,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Remove the branch b from the Tree cache.
/// if subbranches is true all the branches of the subbranches are
/// also removed from the cache.
///
/// Returns:
/// - 0 branch dropped or not in cache
/// - -1 on error
Int_t TTree::DropBranchFromCache(TBranch *b, Bool_t subbranches)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("DropBranchFromCache","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
Int_t res = GetTree()->DropBranchFromCache(b, subbranches);
if (res<0) {
Error("DropBranchFromCache", "Error dropping branch");
}
return res;
}
} else {
Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("DropBranchFromCache", "No cache is available, branch not dropped");
return -1;
}
return tc->DropBranch(b,subbranches);
}
////////////////////////////////////////////////////////////////////////////////
/// Add a cloned tree to our list of trees to be notified whenever we change
/// our branch addresses or when we are deleted.
void TTree::AddClone(TTree* clone)
{
if (!fClones) {
fClones = new TList();
fClones->SetOwner(false);
// So that the clones are automatically removed from the list when
// they are deleted.
{
R__LOCKGUARD(gROOTMutex);
gROOT->GetListOfCleanups()->Add(fClones);
}
}
if (!fClones->FindObject(clone)) {
fClones->Add(clone);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TFriendElement to the list of friends.
///
/// This function:
/// - opens a file if filename is specified
/// - reads a Tree with name treename from the file (current directory)
/// - adds the Tree to the list of friends
/// see other AddFriend functions
///
/// A TFriendElement TF describes a TTree object TF in a file.
/// When a TFriendElement TF is added to the the list of friends of an
/// existing TTree T, any variable from TF can be referenced in a query
/// to T.
///
/// A tree keeps a list of friends. In the context of a tree (or a chain),
/// friendship means unrestricted access to the friends data. In this way
/// it is much like adding another branch to the tree without taking the risk
/// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
/// method. The tree in the diagram below has two friends (friend_tree1 and
/// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
///
/// \image html ttree_friend1.png
///
/// The AddFriend method has two parameters, the first is the tree name and the
/// second is the name of the ROOT file where the friend tree is saved.
/// AddFriend automatically opens the friend file. If no file name is given,
/// the tree called ft1 is assumed to be in the same file as the original tree.
///
/// tree.AddFriend("ft1","friendfile1.root");
/// If the friend tree has the same name as the original tree, you can give it
/// an alias in the context of the friendship:
///
/// tree.AddFriend("tree1 = tree","friendfile1.root");
/// Once the tree has friends, we can use TTree::Draw as if the friend's
/// variables were in the original tree. To specify which tree to use in
/// the Draw method, use the syntax:
/// ~~~ {.cpp}
/// <treeName>.<branchname>.<varname>
/// ~~~
/// If the variablename is enough to uniquely identify the variable, you can
/// leave out the tree and/or branch name.
/// For example, these commands generate a 3-d scatter plot of variable "var"
/// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
/// TTree ft2.
/// ~~~ {.cpp}
/// tree.AddFriend("ft1","friendfile1.root");
/// tree.AddFriend("ft2","friendfile2.root");
/// tree.Draw("var:ft1.v1:ft2.v2");
/// ~~~
/// \image html ttree_friend2.png
///
/// The picture illustrates the access of the tree and its friends with a
/// Draw command.
/// When AddFriend is called, the ROOT file is automatically opened and the
/// friend tree (ft1) is read into memory. The new friend (ft1) is added to
/// the list of friends of tree.
/// The number of entries in the friend must be equal or greater to the number
/// of entries of the original tree. If the friend tree has fewer entries a
/// warning is given and the missing entries are not included in the histogram.
/// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
/// When the tree is written to file (TTree::Write), the friends list is saved
/// with it. And when the tree is retrieved, the trees on the friends list are
/// also retrieved and the friendship restored.
/// When a tree is deleted, the elements of the friend list are also deleted.
/// It is possible to declare a friend tree that has the same internal
/// structure (same branches and leaves) as the original tree, and compare the
/// same values by specifying the tree.
/// ~~~ {.cpp}
/// tree.Draw("var:ft1.var:ft2.var")
/// ~~~
TFriendElement* TTree::AddFriend(const char* treename, const char* filename)
{
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, treename, filename);
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename, filename, t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "Cannot add FriendElement %s in file %s", treename, filename);
}
return fe;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TFriendElement to the list of friends.
///
/// The TFile is managed by the user (e.g. the user must delete the file).
/// For complete description see AddFriend(const char *, const char *).
/// This function:
/// - reads a Tree with name treename from the file
/// - adds the Tree to the list of friends
TFriendElement* TTree::AddFriend(const char* treename, TFile* file)
{
if (!fFriends) {
fFriends = new TList();
}
TFriendElement *fe = new TFriendElement(this, treename, file);
R__ASSERT(fe);
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename, file->GetName(), t->GetEntries(), fEntries);
}
} else {
Warning("AddFriend", "unknown tree '%s' in file '%s'", treename, file->GetName());
}
return fe;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TFriendElement to the list of friends.
///
/// The TTree is managed by the user (e.g., the user must delete the file).
/// For a complete description see AddFriend(const char *, const char *).
TFriendElement* TTree::AddFriend(TTree* tree, const char* alias, Bool_t warn)
{
if (!tree) {
return 0;
}
if (!fFriends) {
fFriends = new TList();
}
TFriendElement* fe = new TFriendElement(this, tree, alias);
R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
fFriends->Add(fe);
TTree* t = fe->GetTree();
if (warn && (t->GetEntries() < fEntries)) {
Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld",
tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(), fEntries);
}
return fe;
}
////////////////////////////////////////////////////////////////////////////////
/// AutoSave tree header every fAutoSave bytes.
///
/// When large Trees are produced, it is safe to activate the AutoSave
/// procedure. Some branches may have buffers holding many entries.
/// If fAutoSave is negative, AutoSave is automatically called by
/// TTree::Fill when the number of bytes generated since the previous
/// AutoSave is greater than -fAutoSave bytes.
/// If fAutoSave is positive, AutoSave is automatically called by
/// TTree::Fill every N entries.
/// This function may also be invoked by the user.
/// Each AutoSave generates a new key on the file.
/// Once the key with the tree header has been written, the previous cycle
/// (if any) is deleted.
///
/// Note that calling TTree::AutoSave too frequently (or similarly calling
/// TTree::SetAutoSave with a small value) is an expensive operation.
/// You should make tests for your own application to find a compromise
/// between speed and the quantity of information you may loose in case of
/// a job crash.
///
/// In case your program crashes before closing the file holding this tree,
/// the file will be automatically recovered when you will connect the file
/// in UPDATE mode.
/// The Tree will be recovered at the status corresponding to the last AutoSave.
///
/// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
/// This allows another process to analyze the Tree while the Tree is being filled.
///
/// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
/// the current basket are closed-out and written to disk individually.
///
/// By default the previous header is deleted after having written the new header.
/// if option contains "Overwrite", the previous Tree header is deleted
/// before written the new header. This option is slightly faster, but
/// the default option is safer in case of a problem (disk quota exceeded)
/// when writing the new header.
///
/// The function returns the number of bytes written to the file.
/// if the number of bytes is null, an error has occurred while writing
/// the header to the file.
///
/// ## How to write a Tree in one process and view it from another process
///
/// The following two scripts illustrate how to do this.
/// The script treew.C is executed by process1, treer.C by process2
///
/// script treew.C:
/// ~~~ {.cpp}
/// void treew() {
/// TFile f("test.root","recreate");
/// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
/// Float_t px, py, pz;
/// for ( Int_t i=0; i<10000000; i++) {
/// gRandom->Rannor(px,py);
/// pz = px*px + py*py;
/// Float_t random = gRandom->Rndm(1);
/// ntuple->Fill(px,py,pz,random,i);
/// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
/// }
/// }
/// ~~~
/// script treer.C:
/// ~~~ {.cpp}
/// void treer() {
/// TFile f("test.root");
/// TTree *ntuple = (TTree*)f.Get("ntuple");
/// TCanvas c1;
/// Int_t first = 0;
/// while(1) {
/// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
/// else ntuple->Draw("px>>+hpx","","",10000000,first);
/// first = (Int_t)ntuple->GetEntries();
/// c1.Update();
/// gSystem->Sleep(1000); //sleep 1 second
/// ntuple->Refresh();
/// }
/// }
/// ~~~
Long64_t TTree::AutoSave(Option_t* option)
{
if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
if (gDebug > 0) {
Info("AutoSave", "Tree:%s after %lld bytes written\n",GetName(),GetTotBytes());
}
TString opt = option;
opt.ToLower();
if (opt.Contains("flushbaskets")) {
if (gDebug > 0) Info("AutoSave", "calling FlushBaskets \n");
FlushBasketsImpl();
}
fSavedBytes = GetZipBytes();
TKey *key = (TKey*)fDirectory->GetListOfKeys()->FindObject(GetName());
Long64_t nbytes;
if (opt.Contains("overwrite")) {
nbytes = fDirectory->WriteTObject(this,"","overwrite");
} else {
nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
if (nbytes && key) {
key->Delete();
delete key;
}
}
// save StreamerInfo
TFile *file = fDirectory->GetFile();
if (file) file->WriteStreamerInfo();
if (opt.Contains("saveself")) {
fDirectory->SaveSelf();
//the following line is required in case GetUserInfo contains a user class
//for which the StreamerInfo must be written. One could probably be a bit faster (Rene)
if (file) file->WriteHeader();
}
return nbytes;
}
namespace {
// This error message is repeated several times in the code. We write it once.
const char* writeStlWithoutProxyMsg = "The class requested (%s) for the branch \"%s\""
" is an instance of an stl collection and does not have a compiled CollectionProxy."
" Please generate the dictionary for this collection (%s) to avoid to write corrupted data.";
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch() with added check that addobj matches className.
///
/// See TTree::Branch() for other details.
///
TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
TClass* claim = TClass::GetClass(classname);
if (!ptrClass) {
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr) {
actualClass = ptrClass->GetActualClass(*addr);
}
if (ptrClass && claim) {
if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
// Note we currently do not warn in case of splicing or over-expectation).
if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
claim->GetName(), branchname, ptrClass->GetName());
}
} else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
actualClass->GetName(), branchname, claim->GetName());
}
}
}
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
claim->GetName(), branchname, claim->GetName());
return 0;
}
return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch but automatic detection of the class name.
/// See TTree::Branch for other details.
TBranch* TTree::BranchImp(const char* branchname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
{
if (!ptrClass) {
Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
return 0;
}
TClass* actualClass = 0;
void** addr = (void**) addobj;
if (addr && *addr) {
actualClass = ptrClass->GetActualClass(*addr);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
} else {
actualClass = ptrClass;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch but automatic detection of the class name.
/// See TTree::Branch for other details.
TBranch* TTree::BranchImpRef(const char* branchname, const char *classname, TClass* ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
{
TClass* claim = TClass::GetClass(classname);
if (!ptrClass) {
if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
claim->GetName(), branchname, claim->GetName());
return 0;
} else if (claim == 0) {
Error("Branch", "The pointer specified for %s is not of a class known to ROOT and %s is not a known class", branchname, classname);
return 0;
}
ptrClass = claim;
}
TClass* actualClass = 0;
if (!addobj) {
Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
return 0;
}
actualClass = ptrClass->GetActualClass(addobj);
if (ptrClass && claim) {
if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
// Note we currently do not warn in case of splicing or over-expectation).
if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the object passed (%s)",
claim->GetName(), branchname, ptrClass->GetName());
}
} else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
// The type is the same according to the C++ type_info, we must be in the case of
// a template of Double32_t. This is actually a correct case.
} else {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
actualClass->GetName(), branchname, claim->GetName());
}
}
}
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Same as TTree::Branch but automatic detection of the class name.
/// See TTree::Branch for other details.
TBranch* TTree::BranchImpRef(const char* branchname, TClass* ptrClass, EDataType datatype, void* addobj, Int_t bufsize, Int_t splitlevel)
{
if (!ptrClass) {
if (datatype == kOther_t || datatype == kNoType_t) {
Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
} else {
TString varname; varname.Form("%s/%c",branchname,DataTypeToChar(datatype));
return Branch(branchname,addobj,varname.Data(),bufsize);
}
return 0;
}
TClass* actualClass = 0;
if (!addobj) {
Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
return 0;
}
actualClass = ptrClass->GetActualClass(addobj);
if (!actualClass) {
Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
branchname, ptrClass->GetName());
actualClass = ptrClass;
} else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
return 0;
}
if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
Error("Branch", writeStlWithoutProxyMsg,
actualClass->GetName(), branchname, actualClass->GetName());
return 0;
}
return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
// Wrapper to turn Branch call with an std::array into the relevant leaf list
// call
TBranch *TTree::BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize,
Int_t /* splitlevel */)
{
if (datatype == kOther_t || datatype == kNoType_t) {
Error("Branch",
"The inner type of the std::array passed specified for %s is not of a class or type known to ROOT",
branchname);
} else {
TString varname;
varname.Form("%s[%d]/%c", branchname, (int)N, DataTypeToChar(datatype));
return Branch(branchname, addobj, varname.Data(), bufsize);
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Deprecated function. Use next function instead.
Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
{
return Branch((TCollection*) li, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Create one branch for each element in the collection.
///
/// Each entry in the collection becomes a top level branch if the
/// corresponding class is not a collection. If it is a collection, the entry
/// in the collection becomes in turn top level branches, etc.
/// The splitlevel is decreased by 1 every time a new collection is found.
/// For example if list is a TObjArray*
/// - if splitlevel = 1, one top level branch is created for each element
/// of the TObjArray.
/// - if splitlevel = 2, one top level branch is created for each array element.
/// if, in turn, one of the array elements is a TCollection, one top level
/// branch will be created for each element of this collection.
///
/// In case a collection element is a TClonesArray, the special Tree constructor
/// for TClonesArray is called.
/// The collection itself cannot be a TClonesArray.
///
/// The function returns the total number of branches created.
///
/// If name is given, all branch names will be prefixed with name_.
///
/// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
///
/// IMPORTANT NOTE2: The branches created by this function will have names
/// corresponding to the collection or object names. It is important
/// to give names to collections to avoid misleading branch names or
/// identical branch names. By default collections have a name equal to
/// the corresponding class name, e.g. the default name for a TList is "TList".
///
/// And in general, in case two or more master branches contain subbranches
/// with identical names, one must add a "." (dot) character at the end
/// of the master branch name. This will force the name of the subbranches
/// to be of the form `master.subbranch` instead of simply `subbranch`.
/// This situation happens when the top level object
/// has two or more members referencing the same class.
/// For example, if a Tree has two branches B1 and B2 corresponding
/// to objects of the same class MyClass, one can do:
/// ~~~ {.cpp}
/// tree.Branch("B1.","MyClass",&b1,8000,1);
/// tree.Branch("B2.","MyClass",&b2,8000,1);
/// ~~~
/// if MyClass has 3 members a,b,c, the two instructions above will generate
/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
///
/// Example:
/// ~~~ {.cpp}
/// {
/// TTree T("T","test list");
/// TList *list = new TList();
///
/// TObjArray *a1 = new TObjArray();
/// a1->SetName("a1");
/// list->Add(a1);
/// TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
/// TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
/// a1->Add(ha1a);
/// a1->Add(ha1b);
/// TObjArray *b1 = new TObjArray();
/// b1->SetName("b1");
/// list->Add(b1);
/// TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
/// TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
/// b1->Add(hb1a);
/// b1->Add(hb1b);
///
/// TObjArray *a2 = new TObjArray();
/// a2->SetName("a2");
/// list->Add(a2);
/// TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
/// TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
/// a2->Add(ha2a);
/// a2->Add(ha2b);
///
/// T.Branch(list,16000,2);
/// T.Print();
/// }
/// ~~~
Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
{
if (!li) {
return 0;
}
TObject* obj = 0;
Int_t nbranches = GetListOfBranches()->GetEntries();
if (li->InheritsFrom(TClonesArray::Class())) {
Error("Branch", "Cannot call this constructor for a TClonesArray");
return 0;
}
Int_t nch = strlen(name);
TString branchname;
TIter next(li);
while ((obj = next())) {
if ((splitlevel > 1) && obj->InheritsFrom(TCollection::Class()) && !obj->InheritsFrom(TClonesArray::Class())) {
TCollection* col = (TCollection*) obj;
if (nch) {
branchname.Form("%s_%s_", name, col->GetName());
} else {
branchname.Form("%s_", col->GetName());
}
Branch(col, bufsize, splitlevel - 1, branchname);
} else {
if (nch && (name[nch-1] == '_')) {
branchname.Form("%s%s", name, obj->GetName());
} else {
if (nch) {
branchname.Form("%s_%s", name, obj->GetName());
} else {
branchname.Form("%s", obj->GetName());
}
}
if (splitlevel > 99) {
branchname += ".";
}
Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
}
}
return GetListOfBranches()->GetEntries() - nbranches;
}
////////////////////////////////////////////////////////////////////////////////
/// Create one branch for each element in the folder.
/// Returns the total number of branches created.
Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
TObject* ob = gROOT->FindObjectAny(foldername);
if (!ob) {
return 0;
}
if (ob->IsA() != TFolder::Class()) {
return 0;
}
Int_t nbranches = GetListOfBranches()->GetEntries();
TFolder* folder = (TFolder*) ob;
TIter next(folder->GetListOfFolders());
TObject* obj = 0;
char* curname = new char[1000];
char occur[20];
while ((obj = next())) {
snprintf(curname,1000, "%s/%s", foldername, obj->GetName());
if (obj->IsA() == TFolder::Class()) {
Branch(curname, bufsize, splitlevel - 1);
} else {
void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
for (Int_t i = 0; i < 1000; ++i) {
if (curname[i] == 0) {
break;
}
if (curname[i] == '/') {
curname[i] = '.';
}
}
Int_t noccur = folder->Occurence(obj);
if (noccur > 0) {
snprintf(occur,20, "_%d", noccur);
strlcat(curname, occur,1000);
}
TBranchElement* br = (TBranchElement*) Bronch(curname, obj->ClassName(), add, bufsize, splitlevel - 1);
if (br) br->SetBranchFolder();
}
}
delete[] curname;
return GetListOfBranches()->GetEntries() - nbranches;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new TTree Branch.
///
/// This Branch constructor is provided to support non-objects in
/// a Tree. The variables described in leaflist may be simple
/// variables or structures. // See the two following
/// constructors for writing objects in a Tree.
///
/// By default the branch buffers are stored in the same file as the Tree.
/// use TBranch::SetFile to specify a different file
///
/// * address is the address of the first item of a structure.
/// * leaflist is the concatenation of all the variable names and types
/// separated by a colon character :
/// The variable name and the variable type are separated by a slash (/).
/// The variable type may be 0,1 or 2 characters. If no type is given,
/// the type of the variable is assumed to be the same as the previous
/// variable. If the first variable does not have a type, it is assumed
/// of type F by default. The list of currently supported types is given below:
/// - `C` : a character string terminated by the 0 character
/// - `B` : an 8 bit signed integer (`Char_t`)
/// - `b` : an 8 bit unsigned integer (`UChar_t`)
/// - `S` : a 16 bit signed integer (`Short_t`)
/// - `s` : a 16 bit unsigned integer (`UShort_t`)
/// - `I` : a 32 bit signed integer (`Int_t`)
/// - `i` : a 32 bit unsigned integer (`UInt_t`)
/// - `F` : a 32 bit floating point (`Float_t`)
/// - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
/// - `D` : a 64 bit floating point (`Double_t`)
/// - `d` : a 24 bit truncated floating point (`Double32_t`)
/// - `L` : a 64 bit signed integer (`Long64_t`)
/// - `l` : a 64 bit unsigned integer (`ULong64_t`)
/// - `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
///
/// Arrays of values are supported with the following syntax:
/// - If leaf name has the form var[nelem], where nelem is alphanumeric, then
/// if nelem is a leaf name, it is used as the variable size of the array,
/// otherwise return 0.
/// - If leaf name has the form var[nelem], where nelem is a non-negative integer, then
/// it is used as the fixed size of the array.
/// - If leaf name has the form of a multi-dimensional array (e.g. var[nelem][nelem2])
/// where nelem and nelem2 are non-negative integer) then
/// it is used as a 2 dimensional array of fixed size.
/// - In case of the truncated floating point types (Float16_t and Double32_t) you can
/// furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
/// the type character. See `TStreamerElement::GetRange()` for further information.
///
/// Any of other form is not supported.
///
/// Note that the TTree will assume that all the item are contiguous in memory.
/// On some platform, this is not always true of the member of a struct or a class,
/// due to padding and alignment. Sorting your data member in order of decreasing
/// sizeof usually leads to their being contiguous in memory.
///
/// * bufsize is the buffer size in bytes for this branch
/// The default value is 32000 bytes and should be ok for most cases.
/// You can specify a larger value (e.g. 256000) if your Tree is not split
/// and each entry is large (Megabytes)
/// A small value for bufsize is optimum if you intend to access
/// the entries in the Tree randomly and your Tree is in split mode.
TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
{
TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
if (branch->IsZombie()) {
delete branch;
branch = 0;
return 0;
}
fBranches.Add(branch);
return branch;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new branch with the object of class classname at address addobj.
///
/// WARNING:
///
/// Starting with Root version 3.01, the Branch function uses the new style
/// branches (TBranchElement). To get the old behaviour, you can:
/// - call BranchOld or
/// - call TTree::SetBranchStyle(0)
///
/// Note that with the new style, classname does not need to derive from TObject.
/// It must derived from TObject if the branch style has been set to 0 (old)
///
/// Note: See the comments in TBranchElement::SetAddress() for a more
/// detailed discussion of the meaning of the addobj parameter in
/// the case of new-style branches.
///
/// Use splitlevel < 0 instead of splitlevel=0 when the class
/// has a custom Streamer
///
/// Note: if the split level is set to the default (99), TTree::Branch will
/// not issue a warning if the class can not be split.
TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
if (fgBranchStyle == 1) {
return Bronch(name, classname, addobj, bufsize, splitlevel);
} else {
if (splitlevel < 0) {
splitlevel = 0;
}
return BranchOld(name, classname, addobj, bufsize, splitlevel);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new TTree BranchObject.
///
/// Build a TBranchObject for an object of class classname.
/// addobj is the address of a pointer to an object of class classname.
/// IMPORTANT: classname must derive from TObject.
/// The class dictionary must be available (ClassDef in class header).
///
/// This option requires access to the library where the corresponding class
/// is defined. Accessing one single data member in the object implies
/// reading the full object.
/// See the next Branch constructor for a more efficient storage
/// in case the entry consists of arrays of identical objects.
///
/// By default the branch buffers are stored in the same file as the Tree.
/// use TBranch::SetFile to specify a different file
///
/// IMPORTANT NOTE about branch names:
///
/// And in general, in case two or more master branches contain subbranches
/// with identical names, one must add a "." (dot) character at the end
/// of the master branch name. This will force the name of the subbranches
/// to be of the form `master.subbranch` instead of simply `subbranch`.
/// This situation happens when the top level object
/// has two or more members referencing the same class.
/// For example, if a Tree has two branches B1 and B2 corresponding
/// to objects of the same class MyClass, one can do:
/// ~~~ {.cpp}
/// tree.Branch("B1.","MyClass",&b1,8000,1);
/// tree.Branch("B2.","MyClass",&b2,8000,1);
/// ~~~
/// if MyClass has 3 members a,b,c, the two instructions above will generate
/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
///
/// bufsize is the buffer size in bytes for this branch
/// The default value is 32000 bytes and should be ok for most cases.
/// You can specify a larger value (e.g. 256000) if your Tree is not split
/// and each entry is large (Megabytes)
/// A small value for bufsize is optimum if you intend to access
/// the entries in the Tree randomly and your Tree is in split mode.
TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
{
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("BranchOld", "Cannot find class: '%s'", classname);
return 0;
}
if (!cl->IsTObject()) {
if (fgBranchStyle == 0) {
Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
"\tfgBranchStyle is set to zero requesting by default to use BranchOld.\n"
"\tIf this is intentional use Bronch instead of Branch or BranchOld.", classname);
} else {
Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
"\tYou can not use BranchOld to store objects of this type.",classname);
}
return 0;
}
TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
fBranches.Add(branch);
if (!splitlevel) {
return branch;
}
// We are going to fully split the class now.
TObjArray* blist = branch->GetListOfBranches();
const char* rdname = 0;
const char* dname = 0;
TString branchname;
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
Bool_t delobj = kFALSE;
if (!obj) {
obj = (TObject*) cl->New();
delobj = kTRUE;
}
// Build the StreamerInfo if first time for the class.
BuildStreamerInfo(cl, obj);
// Loop on all public data members of the class and its base classes.
Int_t lenName = strlen(name);
Int_t isDot = 0;
if (name[lenName-1] == '.') {
isDot = 1;
}
TBranch* branch1 = 0;
TRealData* rd = 0;
TRealData* rdi = 0;
TIter nexti(cl->GetListOfRealData());
TIter next(cl->GetListOfRealData());
// Note: This loop results in a full split because the
// real data list includes all data members of
// data members.
while ((rd = (TRealData*) next())) {
if (rd->TestBit(TRealData::kTransient)) continue;
// Loop over all data members creating branches for each one.
TDataMember* dm = rd->GetDataMember();
if (!dm->IsPersistent()) {
// Do not process members with an "!" as the first character in the comment field.
continue;
}
if (rd->IsObject()) {
// We skip data members of class type.
// But we do build their real data, their
// streamer info, and write their streamer
// info to the current directory's file.
// Oh yes, and we also do this for all of
// their base classes.
TClass* clm = TClass::GetClass(dm->GetFullTypeName());
if (clm) {
BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
}
continue;
}
rdname = rd->GetName();
dname = dm->GetName();
if (cl->CanIgnoreTObjectStreamer()) {
// Skip the TObject base class data members.
// FIXME: This prevents a user from ever
// using these names themself!
if (!strcmp(dname, "fBits")) {
continue;
}
if (!strcmp(dname, "fUniqueID")) {
continue;
}
}
TDataType* dtype = dm->GetDataType();
Int_t code = 0;
if (dtype) {
code = dm->GetDataType()->GetType();
}
// Encode branch name. Use real data member name
branchname = rdname;
if (isDot) {
if (dm->IsaPointer()) {
// FIXME: This is wrong! The asterisk is not usually in the front!
branchname.Form("%s%s", name, &rdname[1]);
} else {
branchname.Form("%s%s", name, &rdname[0]);
}
}
// FIXME: Change this to a string stream.
TString leaflist;
Int_t offset = rd->GetThisOffset();
char* pointer = ((char*) obj) + offset;
if (dm->IsaPointer()) {
// We have a pointer to an object or a pointer to an array of basic types.
TClass* clobj = 0;
if (!dm->IsBasic()) {
clobj = TClass::GetClass(dm->GetTypeName());
}
if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
// We have a pointer to a clones array.
char* cpointer = (char*) pointer;
char** ppointer = (char**) cpointer;
TClonesArray* li = (TClonesArray*) *ppointer;
if (splitlevel != 2) {
if (isDot) {
branch1 = new TBranchClones(branch,branchname, pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
}
blist->Add(branch1);
} else {
if (isDot) {
branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
}
blist->Add(branch1);
}
} else if (clobj) {
// We have a pointer to an object.
//
// It must be a TObject object.
if (!clobj->IsTObject()) {
continue;
}
branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
if (isDot) {
branch1->SetName(branchname);
} else {
// FIXME: This is wrong! The asterisk is not usually in the front!
// Do not use the first character (*).
branch1->SetName(&branchname.Data()[1]);
}
blist->Add(branch1);
} else {
// We have a pointer to an array of basic types.
//
// Check the comments in the text of the code for an index specification.
const char* index = dm->GetArrayIndex();
if (index[0]) {
// We are a pointer to a varying length array of basic types.
//check that index is a valid data member name
//if member is part of an object (e.g. fA and index=fN)
//index must be changed from fN to fA.fN
TString aindex (rd->GetName());
Ssiz_t rdot = aindex.Last('.');
if (rdot>=0) {
aindex.Remove(rdot+1);
aindex.Append(index);
}
nexti.Reset();
while ((rdi = (TRealData*) nexti())) {
if (rdi->TestBit(TRealData::kTransient)) continue;
if (!strcmp(rdi->GetName(), index)) {
break;
}
if (!strcmp(rdi->GetName(), aindex)) {
index = rdi->GetName();
break;
}
}
char vcode = DataTypeToChar((EDataType)code);
// Note that we differentiate between strings and
// char array by the fact that there is NO specified
// size for a string (see next if (code == 1)
if (vcode) {
leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
} else {
// We are possibly a character string.
if (code == 1) {
// We are a character string.
leaflist.Form("%s/%s", dname, "C");
} else {
// Invalid array specification.
// FIXME: We need an error message here.
continue;
}
}
// There are '*' in both the branchname and leaflist, remove them.
TString bname( branchname );
bname.ReplaceAll("*","");
leaflist.ReplaceAll("*","");
// Add the branch to the tree and indicate that the address
// is that of a pointer to be dereferenced before using.
branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
leaf->SetBit(TLeaf::kIndirectAddress);
leaf->SetAddress((void**) pointer);
blist->Add(branch1);
}
} else if (dm->IsBasic()) {
// We have a basic type.
char vcode = DataTypeToChar((EDataType)code);
if (vcode) {
leaflist.Form("%s/%c", rdname, vcode);
} else {
Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
leaflist = "";
}
branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
branch1->SetTitle(rdname);
blist->Add(branch1);
} else {
// We have a class type.
// Note: This cannot happen due to the rd->IsObject() test above.
// FIXME: Put an error message here just in case.
}
if (branch1) {
branch1->SetOffset(offset);
} else {
Warning("BranchOld", "Cannot process member: '%s'", rdname);
}
}
if (delobj) {
delete obj;
obj = 0;
}
return branch;
}
////////////////////////////////////////////////////////////////////////////////
/// Build the optional branch supporting the TRefTable.
/// This branch will keep all the information to find the branches
/// containing referenced objects.
///
/// At each Tree::Fill, the branch numbers containing the
/// referenced objects are saved to the TBranchRef basket.
/// When the Tree header is saved (via TTree::Write), the branch
/// is saved keeping the information with the pointers to the branches
/// having referenced objects.
TBranch* TTree::BranchRef()
{
if (!fBranchRef) {
fBranchRef = new TBranchRef(this);
}
return fBranchRef;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new TTree BranchElement.
///
/// ## WARNING about this new function
///
/// This function is designed to replace the internal
/// implementation of the old TTree::Branch (whose implementation
/// has been moved to BranchOld).
///
/// NOTE: The 'Bronch' method supports only one possible calls
/// signature (where the object type has to be specified
/// explicitly and the address must be the address of a pointer).
/// For more flexibility use 'Branch'. Use Bronch only in (rare)
/// cases (likely to be legacy cases) where both the new and old
/// implementation of Branch needs to be used at the same time.
///
/// This function is far more powerful than the old Branch
/// function. It supports the full C++, including STL and has
/// the same behaviour in split or non-split mode. classname does
/// not have to derive from TObject. The function is based on
/// the new TStreamerInfo.
///
/// Build a TBranchElement for an object of class classname.
///
/// addr is the address of a pointer to an object of class
/// classname. The class dictionary must be available (ClassDef
/// in class header).
///
/// Note: See the comments in TBranchElement::SetAddress() for a more
/// detailed discussion of the meaning of the addr parameter.
///
/// This option requires access to the library where the
/// corresponding class is defined. Accessing one single data
/// member in the object implies reading the full object.
///
/// By default the branch buffers are stored in the same file as the Tree.
/// use TBranch::SetFile to specify a different file
///
/// IMPORTANT NOTE about branch names:
///
/// And in general, in case two or more master branches contain subbranches
/// with identical names, one must add a "." (dot) character at the end
/// of the master branch name. This will force the name of the subbranches
/// to be of the form `master.subbranch` instead of simply `subbranch`.
/// This situation happens when the top level object
/// has two or more members referencing the same class.
/// For example, if a Tree has two branches B1 and B2 corresponding
/// to objects of the same class MyClass, one can do:
/// ~~~ {.cpp}
/// tree.Branch("B1.","MyClass",&b1,8000,1);
/// tree.Branch("B2.","MyClass",&b2,8000,1);
/// ~~~
/// if MyClass has 3 members a,b,c, the two instructions above will generate
/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
///
/// bufsize is the buffer size in bytes for this branch
/// The default value is 32000 bytes and should be ok for most cases.
/// You can specify a larger value (e.g. 256000) if your Tree is not split
/// and each entry is large (Megabytes)
/// A small value for bufsize is optimum if you intend to access
/// the entries in the Tree randomly and your Tree is in split mode.
///
/// Use splitlevel < 0 instead of splitlevel=0 when the class
/// has a custom Streamer
///
/// Note: if the split level is set to the default (99), TTree::Branch will
/// not issue a warning if the class can not be split.
TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
return BronchExec(name, classname, addr, kTRUE, bufsize, splitlevel);
}
////////////////////////////////////////////////////////////////////////////////
/// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, Bool_t isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
{
TClass* cl = TClass::GetClass(classname);
if (!cl) {
Error("Bronch", "Cannot find class:%s", classname);
return 0;
}
//if splitlevel <= 0 and class has a custom Streamer, we must create
//a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
//with the custom Streamer. The penalty is that one cannot process
//this Tree without the class library containing the class.
char* objptr = 0;
if (!isptrptr) {
objptr = (char*)addr;
} else if (addr) {
objptr = *((char**) addr);
}
if (cl == TClonesArray::Class()) {
TClonesArray* clones = (TClonesArray*) objptr;
if (!clones) {
Error("Bronch", "Pointer to TClonesArray is null");
return 0;
}
if (!clones->GetClass()) {
Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
return 0;
}
if (!clones->GetClass()->HasDataMemberInfo()) {
Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
return 0;
}
bool hasCustomStreamer = clones->GetClass()->TestBit(TClass::kHasCustomStreamerMember);
if (splitlevel > 0) {
if (hasCustomStreamer)
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
} else {
if (hasCustomStreamer) clones->BypassStreamer(kFALSE);
TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,/*compress=*/ -1,isptrptr);
fBranches.Add(branch);
return branch;
}
}
if (cl->GetCollectionProxy()) {
TVirtualCollectionProxy* collProxy = cl->GetCollectionProxy();
//if (!collProxy) {
// Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
//}
TClass* inklass = collProxy->GetValueClass();
if (!inklass && (collProxy->GetType() == 0)) {
Error("Bronch", "%s with no class defined in branch: %s", classname, name);
return 0;
}
if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == 0)) {
ROOT::ESTLType stl = cl->GetCollectionType();
if ((stl != ROOT::kSTLmap) && (stl != ROOT::kSTLmultimap)) {
if (!inklass->HasDataMemberInfo()) {
Error("Bronch", "Container with no dictionary defined in branch: %s", name);
return 0;
}
if (inklass->TestBit(TClass::kHasCustomStreamerMember)) {
Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
}
}
}
//-------------------------------------------------------------------------
// If the splitting switch is enabled, the split level is big enough and
// the collection contains pointers we can split it
//////////////////////////////////////////////////////////////////////////
TBranch *branch;
if( splitlevel > kSplitCollectionOfPointers && collProxy->HasPointers() )
branch = new TBranchSTL( this, name, collProxy, bufsize, splitlevel );
else
branch = new TBranchElement(this, name, collProxy, bufsize, splitlevel);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
Bool_t hasCustomStreamer = kFALSE;
if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
Error("Bronch", "Cannot find dictionary for class: %s", classname);
return 0;
}
if (!cl->GetCollectionProxy() && cl->TestBit(TClass::kHasCustomStreamerMember)) {
// Not an STL container and the linkdef file had a "-" after the class name.
hasCustomStreamer = kTRUE;
}
if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->IsTObject())) {
TBranchObject* branch = new TBranchObject(this, name, classname, addr, bufsize, 0, /*compress=*/ ROOT::RCompressionSetting::EAlgorithm::kInherit, isptrptr);
fBranches.Add(branch);
return branch;
}
if (cl == TClonesArray::Class()) {
// Special case of TClonesArray.
// No dummy object is created.
// The streamer info is not rebuilt unoptimized.
// No dummy top-level branch is created.
// No splitting is attempted.
TBranchElement* branch = new TBranchElement(this, name, (TClonesArray*) objptr, bufsize, splitlevel%kSplitCollectionOfPointers);
fBranches.Add(branch);
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
return branch;
}
//
// If we are not given an object to use as an i/o buffer
// then create a temporary one which we will delete just
// before returning.
//
Bool_t delobj = kFALSE;
if (!objptr) {
objptr = (char*) cl->New();
delobj = kTRUE;
}
//
// Avoid splitting unsplittable classes.
//
if ((splitlevel > 0) && !cl->CanSplit()) {
if (splitlevel != 99) {
Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
}
splitlevel = 0;
}
//
// Make sure the streamer info is built and fetch it.
//
// If we are splitting, then make sure the streamer info
// is built unoptimized (data members are not combined).
//
TStreamerInfo* sinfo = BuildStreamerInfo(cl, objptr, splitlevel==0);
if (!sinfo) {
Error("Bronch", "Cannot build the StreamerInfo for class: %s", cl->GetName());
return 0;
}
//
// Create a dummy top level branch object.
//
Int_t id = -1;
if (splitlevel > 0) {
id = -2;
}
TBranchElement* branch = new TBranchElement(this, name, sinfo, id, objptr, bufsize, splitlevel);
fBranches.Add(branch);
//
// Do splitting, if requested.
//
if (splitlevel%kSplitCollectionOfPointers > 0) {
branch->Unroll(name, cl, sinfo, objptr, bufsize, splitlevel);
}
//
// Setup our offsets into the user's i/o buffer.
//
if (isptrptr) {
branch->SetAddress(addr);
} else {
branch->SetObject(addr);
}
if (delobj) {
cl->Destructor(objptr);
objptr = 0;
}
return branch;
}
////////////////////////////////////////////////////////////////////////////////
/// Browse content of the TTree.
void TTree::Browse(TBrowser* b)
{
fBranches.Browse(b);
if (fUserInfo) {
if (strcmp("TList",fUserInfo->GetName())==0) {
fUserInfo->SetName("UserInfo");
b->Add(fUserInfo);
fUserInfo->SetName("TList");
} else {
b->Add(fUserInfo);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Build a Tree Index (default is TTreeIndex).
/// See a description of the parameters and functionality in
/// TTreeIndex::TTreeIndex().
///
/// The return value is the number of entries in the Index (< 0 indicates failure).
///
/// A TTreeIndex object pointed by fTreeIndex is created.
/// This object will be automatically deleted by the TTree destructor.
/// If an index is already existing, this is replaced by the new one without being
/// deleted. This behaviour prevents the deletion of a previously external index
/// assigned to the TTree via the TTree::SetTreeIndex() method.
/// See also comments in TTree::SetTreeIndex().
Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
{
fTreeIndex = GetPlayer()->BuildIndex(this, majorname, minorname);
if (fTreeIndex->IsZombie()) {
delete fTreeIndex;
fTreeIndex = 0;
return 0;
}
return fTreeIndex->GetN();
}
////////////////////////////////////////////////////////////////////////////////
/// Build StreamerInfo for class cl.
/// pointer is an optional argument that may contain a pointer to an object of cl.
TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, Bool_t canOptimize /* = kTRUE */ )
{
if (!cl) {
return 0;
}
cl->BuildRealData(pointer);
TStreamerInfo* sinfo = (TStreamerInfo*)cl->GetStreamerInfo(cl->GetClassVersion());
// Create StreamerInfo for all base classes.
TBaseClass* base = 0;
TIter nextb(cl->GetListOfBases());
while((base = (TBaseClass*) nextb())) {
if (base->IsSTLContainer()) {
continue;
}
TClass* clm = TClass::GetClass(base->GetName());
BuildStreamerInfo(clm, pointer, canOptimize);
}
if (sinfo && fDirectory) {
sinfo->ForceWriteInfo(fDirectory->GetFile());
}
return sinfo;
}
////////////////////////////////////////////////////////////////////////////////
/// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
/// Create a new file. If the original file is named "myfile.root",
/// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
///
/// Returns a pointer to the new file.
///
/// Currently, the automatic change of file is restricted
/// to the case where the tree is in the top level directory.
/// The file should not contain sub-directories.
///
/// Before switching to a new file, the tree header is written
/// to the current file, then the current file is closed.
///
/// To process the multiple files created by ChangeFile, one must use
/// a TChain.
///
/// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
/// By default a Root session starts with fFileNumber=0. One can set
/// fFileNumber to a different value via TTree::SetFileNumber.
/// In case a file named "_N" already exists, the function will try
/// a file named "__N", then "___N", etc.
///
/// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
/// The default value of fgMaxTreeSize is 100 Gigabytes.
///
/// If the current file contains other objects like TH1 and TTree,
/// these objects are automatically moved to the new file.
///
/// IMPORTANT NOTE:
///
/// Be careful when writing the final Tree header to the file!
///
/// Don't do:
/// ~~~ {.cpp}
/// TFile *file = new TFile("myfile.root","recreate");
/// TTree *T = new TTree("T","title");
/// T->Fill(); //loop
/// file->Write();
/// file->Close();
/// ~~~
/// but do the following:
/// ~~~ {.cpp}
/// TFile *file = new TFile("myfile.root","recreate");
/// TTree *T = new TTree("T","title");
/// T->Fill(); //loop
/// file = T->GetCurrentFile(); //to get the pointer to the current file
/// file->Write();
/// file->Close();
/// ~~~
TFile* TTree::ChangeFile(TFile* file)
{
file->cd();
Write();
Reset();
constexpr auto kBufSize = 2000;
char* fname = new char[kBufSize];
++fFileNumber;
char uscore[10];
for (Int_t i = 0; i < 10; ++i) {
uscore[i] = 0;
}
Int_t nus = 0;
// Try to find a suitable file name that does not already exist.
while (nus < 10) {
uscore[nus] = '_';
fname[0] = 0;
strlcpy(fname, file->GetName(), kBufSize);
if (fFileNumber > 1) {
char* cunder = strrchr(fname, '_');
if (cunder) {
snprintf(cunder, kBufSize - Int_t(cunder - fname), "%s%d", uscore, fFileNumber);
const char* cdot = strrchr(file->GetName(), '.');
if (cdot) {
strlcat(fname, cdot, kBufSize);
}
} else {
char fcount[21];
snprintf(fcount,21, "%s%d", uscore, fFileNumber);
strlcat(fname, fcount, kBufSize);
}
} else {
char* cdot = strrchr(fname, '.');
if (cdot) {
snprintf(cdot, kBufSize - Int_t(fname-cdot), "%s%d", uscore, fFileNumber);
strlcat(fname, strrchr(file->GetName(), '.'), kBufSize);
} else {
char fcount[21];
snprintf(fcount,21, "%s%d", uscore, fFileNumber);
strlcat(fname, fcount, kBufSize);
}
}
if (gSystem->AccessPathName(fname)) {
break;
}
++nus;
Warning("ChangeFile", "file %s already exist, trying with %d underscores", fname, nus+1);
}
Int_t compress = file->GetCompressionSettings();
TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
if (newfile == 0) {
Error("Fill","Failed to open new file %s, continuing as a memory tree.",fname);
} else {
Printf("Fill: Switching to new file: %s", fname);
}
// The current directory may contain histograms and trees.
// These objects must be moved to the new file.
TBranch* branch = 0;
TObject* obj = 0;
while ((obj = file->GetList()->First())) {
file->Remove(obj);
// Histogram: just change the directory.
if (obj->InheritsFrom("TH1")) {
gROOT->ProcessLine(TString::Format("((%s*)0x%lx)->SetDirectory((TDirectory*)0x%lx);", obj->ClassName(), (Long_t) obj, (Long_t) newfile));
continue;
}
// Tree: must save all trees in the old file, reset them.
if (obj->InheritsFrom(TTree::Class())) {
TTree* t = (TTree*) obj;
if (t != this) {
t->AutoSave();
t->Reset();
t->fFileNumber = fFileNumber;
}
t->SetDirectory(newfile);
TIter nextb(t->GetListOfBranches());
while ((branch = (TBranch*)nextb())) {
branch->SetFile(newfile);
}
if (t->GetBranchRef()) {
t->GetBranchRef()->SetFile(newfile);
}
continue;
}
// Not a TH1 or a TTree, move object to new file.
if (newfile) newfile->Append(obj);
file->Remove(obj);
}
delete file;
file = 0;
delete[] fname;
fname = 0;
return newfile;
}
////////////////////////////////////////////////////////////////////////////////
/// Check whether or not the address described by the last 3 parameters
/// matches the content of the branch. If a Data Model Evolution conversion
/// is involved, reset the fInfo of the branch.
/// The return values are:
//
/// - kMissingBranch (-5) : Missing branch
/// - kInternalError (-4) : Internal error (could not find the type corresponding to a data type number)
/// - kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
/// - kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
/// - kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
/// - kMatch (0) : perfect match
/// - kMatchConversion (1) : match with (I/O) conversion
/// - kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
/// - kMakeClass (3) : MakeClass mode so we can not check.
/// - kVoidPtr (4) : void* passed so no check was made.
/// - kNoCheck (5) : Underlying TBranch not yet available so no check was made.
Int_t TTree::CheckBranchAddressType(TBranch* branch, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
if (GetMakeClass()) {
// If we are in MakeClass mode so we do not really use classes.
return kMakeClass;
}
// Let's determine what we need!
TClass* expectedClass = 0;
EDataType expectedType = kOther_t;
if (0 != branch->GetExpectedType(expectedClass,expectedType) ) {
// Something went wrong, the warning message has already be issued.
return kInternalError;
}
if (expectedClass && datatype == kOther_t && ptrClass == 0) {
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
"The class expected (%s) refers to an stl collection and do not have a compiled CollectionProxy. "
"Please generate the dictionary for this class (%s)",
branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
return kMissingCompiledCollectionProxy;
}
if (!expectedClass->IsLoaded()) {
// The originally expected class does not have a dictionary, it is then plausible that the pointer being passed is the right type
// (we really don't know). So let's express that.
Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
"The class expected (%s) does not have a dictionary and needs to be emulated for I/O purposes but is being passed a compiled object."
"Please generate the dictionary for this class (%s)",
branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
} else {
Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
"This is probably due to a missing dictionary, the original data class for this branch is %s.", branch->GetName(), expectedClass->GetName());
}
return kClassMismatch;
}
if (expectedClass && ptrClass && (branch->GetMother() == branch)) {
// Top Level branch
if (!isptr) {
Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
}
}
if (expectedType == kFloat16_t) {
expectedType = kFloat_t;
}
if (expectedType == kDouble32_t) {
expectedType = kDouble_t;
}
if (datatype == kFloat16_t) {
datatype = kFloat_t;
}
if (datatype == kDouble32_t) {
datatype = kDouble_t;
}
/////////////////////////////////////////////////////////////////////////////
// Deal with the class renaming
/////////////////////////////////////////////////////////////////////////////
if( expectedClass && ptrClass &&
expectedClass != ptrClass &&
branch->InheritsFrom( TBranchElement::Class() ) &&
ptrClass->GetSchemaRules() &&
ptrClass->GetSchemaRules()->HasRuleWithSourceClass( expectedClass->GetName() ) ) {
TBranchElement* bEl = (TBranchElement*)branch;
if ( ptrClass->GetCollectionProxy() && expectedClass->GetCollectionProxy() ) {
if (gDebug > 7)
Info("SetBranchAddress", "Matching STL collection (at least according to the SchemaRuleSet when "
"reading a %s into a %s",expectedClass->GetName(),ptrClass->GetName());
bEl->SetTargetClass( ptrClass->GetName() );
return kMatchConversion;
} else if ( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
!ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" by the branch: %s", ptrClass->GetName(), bEl->GetClassName(), branch->GetName());
bEl->SetTargetClass( expectedClass->GetName() );
return kClassMismatch;
}
else {
bEl->SetTargetClass( ptrClass->GetName() );
return kMatchConversion;
}
} else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
branch->InheritsFrom( TBranchElement::Class() ) &&
expectedClass->GetCollectionProxy()->GetValueClass() &&
ptrClass->GetCollectionProxy()->GetValueClass() )
{
// In case of collection, we know how to convert them, if we know how to convert their content.
// NOTE: we need to extend this to std::pair ...
TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
if (inmemValueClass->GetSchemaRules() &&
inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
{
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( ptrClass->GetName() );
return kMatchConversionCollection;
}
}
Error("SetBranchAddress", "The pointer type given (%s) does not correspond to the class needed (%s) by the branch: %s", ptrClass->GetName(), expectedClass->GetName(), branch->GetName());
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
return kClassMismatch;
} else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
if (datatype != kChar_t) {
// For backward compatibility we assume that (char*) was just a cast and/or a generic address
Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s",
TDataType::GetTypeName(datatype), datatype, TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
return kMismatch;
}
} else if ((expectedClass && (datatype != kOther_t && datatype != kNoType_t && datatype != kInt_t)) ||
(ptrClass && (expectedType != kOther_t && expectedType != kNoType_t && datatype != kInt_t)) ) {
// Sometime a null pointer can look an int, avoid complaining in that case.
if (expectedClass) {
Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" by the branch: %s",
TDataType::GetTypeName(datatype), datatype, expectedClass->GetName(), branch->GetName());
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
} else {
// In this case, it is okay if the first data member is of the right type (to support the case where we are being passed
// a struct).
bool found = false;
if (ptrClass->IsLoaded()) {
TIter next(ptrClass->GetListOfRealData());
TRealData *rdm;
while ((rdm = (TRealData*)next())) {
if (rdm->GetThisOffset() == 0) {
TDataType *dmtype = rdm->GetDataMember()->GetDataType();
if (dmtype) {
EDataType etype = (EDataType)dmtype->GetType();
if (etype == expectedType) {
found = true;
}
}
break;
}
}
} else {
TIter next(ptrClass->GetListOfDataMembers());
TDataMember *dm;
while ((dm = (TDataMember*)next())) {
if (dm->GetOffset() == 0) {
TDataType *dmtype = dm->GetDataType();
if (dmtype) {
EDataType etype = (EDataType)dmtype->GetType();
if (etype == expectedType) {
found = true;
}
}
break;
}
}
}
if (found) {
// let's check the size.
TLeaf *last = (TLeaf*)branch->GetListOfLeaves()->Last();
long len = last->GetOffset() + last->GetLenType() * last->GetLen();
if (len <= ptrClass->Size()) {
return kMatch;
}
}
Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" (%d) by the branch: %s",
ptrClass->GetName(), TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
}
return kMismatch;
}
if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
Error("SetBranchAddress", writeStlWithoutProxyMsg,
expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
if (branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
return kMissingCompiledCollectionProxy;
}
if (expectedClass && branch->InheritsFrom( TBranchElement::Class() )) {
TBranchElement* bEl = (TBranchElement*)branch;
bEl->SetTargetClass( expectedClass->GetName() );
}
return kMatch;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a clone of this tree and copy nentries.
///
/// By default copy all entries.
/// The compression level of the cloned tree is set to the destination
/// file's compression level.
///
/// NOTE: Only active branches are copied.
/// NOTE: If the TTree is a TChain, the structure of the first TTree
/// is used for the copy.
///
/// IMPORTANT: The cloned tree stays connected with this tree until
/// this tree is deleted. In particular, any changes in
/// branch addresses in this tree are forwarded to the
/// clone trees, unless a branch in a clone tree has had
/// its address changed, in which case that change stays in
/// effect. When this tree is deleted, all the addresses of
/// the cloned tree are reset to their default values.
///
/// If 'option' contains the word 'fast' and nentries is -1, the
/// cloning will be done without unzipping or unstreaming the baskets
/// (i.e., a direct copy of the raw bytes on disk).
///
/// When 'fast' is specified, 'option' can also contain a sorting
/// order for the baskets in the output file.
///
/// There are currently 3 supported sorting order:
///
/// - SortBasketsByOffset (the default)
/// - SortBasketsByBranch
/// - SortBasketsByEntry
///
/// When using SortBasketsByOffset the baskets are written in the
/// output file in the same order as in the original file (i.e. the
/// baskets are sorted by their offset in the original file; Usually
/// this also means that the baskets are sorted by the index/number of
/// the _last_ entry they contain)
///
/// When using SortBasketsByBranch all the baskets of each individual
/// branches are stored contiguously. This tends to optimize reading
/// speed when reading a small number (1->5) of branches, since all
/// their baskets will be clustered together instead of being spread
/// across the file. However it might decrease the performance when
/// reading more branches (or the full entry).
///
/// When using SortBasketsByEntry the baskets with the lowest starting
/// entry are written first. (i.e. the baskets are sorted by the
/// index/number of the first entry they contain). This means that on
/// the file the baskets will be in the order in which they will be
/// needed when reading the whole tree sequentially.
///
/// For examples of CloneTree, see tutorials:
///
/// - copytree.C:
/// A macro to copy a subset of a TTree to a new TTree.
/// The input file has been generated by the program in
/// $ROOTSYS/test/Event with: Event 1000 1 1 1
///
/// - copytree2.C:
/// A macro to copy a subset of a TTree to a new TTree.
/// One branch of the new Tree is written to a separate file.
/// The input file has been generated by the program in
/// $ROOTSYS/test/Event with: Event 1000 1 1 1
TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
// Options
Bool_t fastClone = kFALSE;
TString opt = option;
opt.ToLower();
if (opt.Contains("fast")) {
fastClone = kTRUE;
}
// If we are a chain, switch to the first tree.
if ((fEntries > 0) && (LoadTree(0) < 0)) {
// FIXME: We need an error message here.
return 0;
}
// Note: For a tree we get the this pointer, for
// a chain we get the chain's current tree.
TTree* thistree = GetTree();
// We will use this to override the IO features on the cloned branches.
ROOT::TIOFeatures features = this->GetIOFeatures();
;
// Note: For a chain, the returned clone will be
// a clone of the chain's first tree.
TTree* newtree = (TTree*) thistree->Clone();
if (!newtree) {
return 0;
}
// The clone should not delete any objects allocated by SetAddress().
TObjArray* branches = newtree->GetListOfBranches();
Int_t nb = branches->GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
}
// Add the new tree to the list of clones so that
// we can later inform it of changes to branch addresses.
thistree->AddClone(newtree);
if (thistree != this) {
// In case this object is a TChain, add the clone
// also to the TChain's list of clones.
AddClone(newtree);
}
newtree->Reset();
TDirectory* ndir = newtree->GetDirectory();
TFile* nfile = 0;
if (ndir) {
nfile = ndir->GetFile();
}
Int_t newcomp = -1;
if (nfile) {
newcomp = nfile->GetCompressionSettings();
}
//
// Delete non-active branches from the clone.
//
// Note: If we are a chain, this does nothing
// since chains have no leaves.
TObjArray* leaves = newtree->GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
if (!leaf) {
continue;
}
TBranch* branch = leaf->GetBranch();
if (branch && (newcomp > -1)) {
branch->SetCompressionSettings(newcomp);
}
if (branch) branch->SetIOFeatures(features);
if (!branch || !branch->TestBit(kDoNotProcess)) {
continue;
}
// size might change at each iteration of the loop over the leaves.
nb = branches->GetEntriesFast();
for (Long64_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches->UncheckedAt(i);
if (br == branch) {
branches->RemoveAt(i);
delete br;
br = 0;
branches->Compress();
break;
}
TObjArray* lb = br->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; ++j) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!b1) {
continue;
}
if (b1 == branch) {
lb->RemoveAt(j);
delete b1;
b1 = 0;
lb->Compress();
break;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; ++k) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!b2) {
continue;
}
if (b2 == branch) {
lb1->RemoveAt(k);
delete b2;
b2 = 0;
lb1->Compress();
break;
}
}
}
}
}
leaves->Compress();
// Copy MakeClass status.
newtree->SetMakeClass(fMakeClass);
// Copy branch addresses.
CopyAddresses(newtree);
//
// Copy entries if requested.
//
if (nentries != 0) {
if (fastClone && (nentries < 0)) {
if ( newtree->CopyEntries( this, -1, option ) < 0 ) {
// There was a problem!
Error("CloneTTree", "TTree has not been cloned\n");
delete newtree;
newtree = 0;
return 0;
}
} else {
newtree->CopyEntries( this, nentries, option );
}
}
return newtree;
}
////////////////////////////////////////////////////////////////////////////////
/// Set branch addresses of passed tree equal to ours.
/// If undo is true, reset the branch address instead of copying them.
/// This insures 'separation' of a cloned tree from its original
void TTree::CopyAddresses(TTree* tree, Bool_t undo)
{
// Copy branch addresses starting from branches.
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
TBranch* br = tree->GetBranch(branch->GetName());
tree->ResetBranchAddress(br);
} else {
char* addr = branch->GetAddress();
if (!addr) {
if (branch->IsA() == TBranch::Class()) {
// If the branch was created using a leaflist, the branch itself may not have
// an address but the leaf might already.
TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
if (!firstleaf || firstleaf->GetValuePointer()) {
// Either there is no leaf (and thus no point in copying the address)
// or the leaf has an address but we can not copy it via the branche
// this will be copied via the next loop (over the leaf).
continue;
}
}
// Note: This may cause an object to be allocated.
branch->SetAddress(0);
addr = branch->GetAddress();
}
// FIXME: The GetBranch() function is braindead and may
// not find the branch!
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
br->SetAddress(addr);
// The copy does not own any object allocated by SetAddress().
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
}
}
// Copy branch addresses starting from leaves.
TObjArray* tleaves = tree->GetListOfLeaves();
Int_t ntleaves = tleaves->GetEntriesFast();
for (Int_t i = 0; i < ntleaves; ++i) {
TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
TBranch* tbranch = tleaf->GetBranch();
TBranch* branch = GetBranch(tbranch->GetName());
if (!branch) {
continue;
}
TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
if (!leaf) {
continue;
}
if (branch->TestBit(kDoNotProcess)) {
continue;
}
if (undo) {
// Now we know whether the address has been transfered
tree->ResetBranchAddress(tbranch);
} else {
TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
{
// If it is an array and it was allocated by the leaf itself,
// let's make sure it is large enough for the incoming data.
if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
if (leaf->GetValuePointer()) {
if (leaf->IsA() == TLeafElement::Class() && mother)
mother->ResetAddress();
else
leaf->SetAddress(nullptr);
}
}
}
if (!branch->GetAddress() && !leaf->GetValuePointer()) {
// We should attempts to set the address of the branch.
// something like:
//(TBranchElement*)branch->GetMother()->SetAddress(0)
//plus a few more subtilities (see TBranchElement::GetEntry).
//but for now we go the simplest route:
//
// Note: This may result in the allocation of an object.
branch->SetupAddresses();
}
if (branch->GetAddress()) {
tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
TBranch* br = tree->GetBranch(branch->GetName());
if (br) {
// The copy does not own any object allocated by SetAddress().
// FIXME: We do too much here, br may not be a top-level branch.
if (br->InheritsFrom(TBranchElement::Class())) {
((TBranchElement*) br)->ResetDeleteObject();
}
} else {
Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
}
} else {
tleaf->SetAddress(leaf->GetValuePointer());
}
}
}
if (undo &&
( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
) {
tree->ResetBranchAddresses();
}
}
namespace {
enum EOnIndexError { kDrop, kKeep, kBuild };
static Bool_t R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
{
// Return true if we should continue to handle indices, false otherwise.
Bool_t withIndex = kTRUE;
if ( newtree->GetTreeIndex() ) {
if ( oldtree->GetTree()->GetTreeIndex() == 0 ) {
switch (onIndexError) {
case kDrop:
delete newtree->GetTreeIndex();
newtree->SetTreeIndex(0);
withIndex = kFALSE;
break;
case kKeep:
// Nothing to do really.
break;
case kBuild:
// Build the index then copy it
if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
// Clean up
delete oldtree->GetTree()->GetTreeIndex();
oldtree->GetTree()->SetTreeIndex(0);
}
break;
}
} else {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
} else if ( oldtree->GetTree()->GetTreeIndex() != 0 ) {
// We discover the first index in the middle of the chain.
switch (onIndexError) {
case kDrop:
// Nothing to do really.
break;
case kKeep: {
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
break;
}
case kBuild:
if (newtree->GetEntries() == 0) {
// Start an index.
TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
index->SetTree(newtree);
newtree->SetTreeIndex(index);
} else {
// Build the index so far.
if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
}
}
break;
}
} else if ( onIndexError == kDrop ) {
// There is no index on this or on tree->GetTree(), we know we have to ignore any further
// index
withIndex = kFALSE;
}
return withIndex;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Copy nentries from given tree to this tree.
/// This routines assumes that the branches that intended to be copied are
/// already connected. The typical case is that this tree was created using
/// tree->CloneTree(0).
///
/// By default copy all entries.
///
/// Returns number of bytes copied to this tree.
///
/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
/// raw bytes on disk).
///
/// When 'fast' is specified, 'option' can also contains a sorting order for the
/// baskets in the output file.
///
/// There are currently 3 supported sorting order:
///
/// - SortBasketsByOffset (the default)
/// - SortBasketsByBranch
/// - SortBasketsByEntry
///
/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
///
/// If the tree or any of the underlying tree of the chain has an index, that index and any
/// index in the subsequent underlying TTree objects will be merged.
///
/// There are currently three 'options' to control this merging:
/// - NoIndex : all the TTreeIndex object are dropped.
/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
/// they are all dropped.
/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
{
if (!tree) {
return 0;
}
// Options
TString opt = option;
opt.ToLower();
Bool_t fastClone = opt.Contains("fast");
Bool_t withIndex = !opt.Contains("noindex");
EOnIndexError onIndexError;
if (opt.Contains("asisindex")) {
onIndexError = kKeep;
} else if (opt.Contains("buildindex")) {
onIndexError = kBuild;
} else if (opt.Contains("dropindex")) {
onIndexError = kDrop;
} else {
onIndexError = kBuild;
}
Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
Int_t cacheSize = -1;
if (cacheSizeLoc != TString::kNPOS) {
// If the parse faile, cacheSize stays at -1.
Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
TSubString cacheSizeStr( opt(cacheSizeLoc+10,cacheSizeEnd) );
auto parseResult = ROOT::FromHumanReadableSize(cacheSizeStr,cacheSize);
if (parseResult == ROOT::EFromHumanReadableSize::kParseFail) {
Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
} else if (parseResult == ROOT::EFromHumanReadableSize::kOverflow) {
double m;
const char *munit = nullptr;
ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
}
}
if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %d\n",cacheSize);
Long64_t nbytes = 0;
Long64_t treeEntries = tree->GetEntriesFast();
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
// Quickly copy the basket without decompression and streaming.
Long64_t totbytes = GetTotBytes();
for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
if (tree->LoadTree(i) < 0) {
break;
}
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
if (this->GetDirectory()) {
TFile* file2 = this->GetDirectory()->GetFile();
if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
if (this->GetDirectory() == (TDirectory*) file2) {
this->ChangeFile(file2);
}
}
}
TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
if (cloner.IsValid()) {
this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
cloner.Exec();
} else {
if (i == 0) {
Warning("CopyEntries","%s",cloner.GetWarning());
// If the first cloning does not work, something is really wrong
// (since apriori the source and target are exactly the same structure!)
return -1;
} else {
if (cloner.NeedConversion()) {
TTree *localtree = tree->GetTree();
Long64_t tentries = localtree->GetEntries();
for (Long64_t ii = 0; ii < tentries; ii++) {
if (localtree->GetEntry(ii) <= 0) {
break;
}
this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), kTRUE);
}
} else {
Warning("CopyEntries","%s",cloner.GetWarning());
if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
} else {
Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
}
}
}
}
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
nbytes = GetTotBytes() - totbytes;
} else {
if (nentries < 0) {
nentries = treeEntries;
} else if (nentries > treeEntries) {
nentries = treeEntries;
}
Int_t treenumber = -1;
for (Long64_t i = 0; i < nentries; i++) {
if (tree->LoadTree(i) < 0) {
break;
}
if (treenumber != tree->GetTreeNumber()) {
if ( withIndex ) {
withIndex = R__HandleIndex( onIndexError, this, tree );
}
treenumber = tree->GetTreeNumber();
}
if (tree->GetEntry(i) <= 0) {
break;
}
nbytes += this->Fill();
}
if (this->GetTreeIndex()) {
this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
}
return nbytes;
}
////////////////////////////////////////////////////////////////////////////////
/// Copy a tree with selection.
///
/// ### Important:
///
/// The returned copied tree stays connected with the original tree
/// until the original tree is deleted. In particular, any changes
/// to the branch addresses in the original tree are also made to
/// the copied tree. Any changes made to the branch addresses of the
/// copied tree are overridden anytime the original tree changes its
/// branch addresses. When the original tree is deleted, all the
/// branch addresses of the copied tree are set to zero.
///
/// For examples of CopyTree, see the tutorials:
///
/// - copytree.C:
/// Example macro to copy a subset of a tree to a new tree.
/// The input file was generated by running the program in
/// $ROOTSYS/test/Event in this way:
/// ~~~ {.cpp}
/// ./Event 1000 1 1 1
/// ~~~
/// - copytree2.C
/// Example macro to copy a subset of a tree to a new tree.
/// One branch of the new tree is written to a separate file.
/// The input file was generated by running the program in
/// $ROOTSYS/test/Event in this way:
/// ~~~ {.cpp}
/// ./Event 1000 1 1 1
/// ~~~
/// - copytree3.C
/// Example macro to copy a subset of a tree to a new tree.
/// Only selected entries are copied to the new tree.
/// NOTE that only the active branches are copied.
TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
{
GetPlayer();
if (fPlayer) {
return fPlayer->CopyTree(selection, option, nentries, firstentry);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a basket for this tree and given branch.
TBasket* TTree::CreateBasket(TBranch* branch)
{
if (!branch) {
return 0;
}
return new TBasket(branch->GetName(), GetName(), branch);
}
////////////////////////////////////////////////////////////////////////////////
/// Delete this tree from memory or/and disk.
///
/// - if option == "all" delete Tree object from memory AND from disk
/// all baskets on disk are deleted. All keys with same name
/// are deleted.
/// - if option =="" only Tree object in memory is deleted.
void TTree::Delete(Option_t* option /* = "" */)
{
TFile *file = GetCurrentFile();
// delete all baskets and header from file
if (file && !strcmp(option,"all")) {
if (!file->IsWritable()) {
Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
return;
}
//find key and import Tree header in memory
TKey *key = fDirectory->GetKey(GetName());
if (!key) return;
TDirectory *dirsav = gDirectory;
file->cd();
//get list of leaves and loop on all the branches baskets
TIter next(GetListOfLeaves());
TLeaf *leaf;
char header[16];
Int_t ntot = 0;
Int_t nbask = 0;
Int_t nbytes,objlen,keylen;
while ((leaf = (TLeaf*)next())) {
TBranch *branch = leaf->GetBranch();
Int_t nbaskets = branch->GetMaxBaskets();
for (Int_t i=0;i<nbaskets;i++) {
Long64_t pos = branch->GetBasketSeek(i);
if (!pos) continue;
TFile *branchFile = branch->GetFile();
if (!branchFile) continue;
branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
if (nbytes <= 0) continue;
branchFile->MakeFree(pos,pos+nbytes-1);
ntot += nbytes;
nbask++;
}
}
// delete Tree header key and all keys with the same name
// A Tree may have been saved many times. Previous cycles are invalid.
while (key) {
ntot += key->GetNbytes();
key->Delete();
delete key;
key = fDirectory->GetKey(GetName());
}
if (dirsav) dirsav->cd();
if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
}
if (fDirectory) {
fDirectory->Remove(this);
//delete the file cache if it points to this Tree
MoveReadCache(file,0);
fDirectory = 0;
ResetBit(kMustCleanup);
}
// Delete object from CINT symbol table so it can not be used anymore.
gCling->DeleteGlobal(this);
// Warning: We have intentional invalidated this object while inside a member function!
delete this;
}
///////////////////////////////////////////////////////////////////////////////
/// Called by TKey and TObject::Clone to automatically add us to a directory
/// when we are read from a file.
void TTree::DirectoryAutoAdd(TDirectory* dir)
{
if (fDirectory == dir) return;
if (fDirectory) {
fDirectory->Remove(this);
// Delete or move the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,dir);
}
fDirectory = dir;
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->UpdateFile();
}
if (fBranchRef) {
fBranchRef->UpdateFile();
}
if (fDirectory) fDirectory->Append(this);
}
////////////////////////////////////////////////////////////////////////////////
/// Draw expression varexp for specified entries.
///
/// \return -1 in case of error or number of selected events in case of success.
///
/// This function accepts TCut objects as arguments.
/// Useful to use the string operator +
///
/// Example:
///
/// ~~~ {.cpp}
/// ntuple.Draw("x",cut1+cut2+cut3);
/// ~~~
Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
}
////////////////////////////////////////////////////////////////////////////////
/// Draw expression varexp for specified entries.
///
/// \return -1 in case of error or number of selected events in case of success.
///
/// \param [in] varexp is an expression of the general form
/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
/// on the y-axis versus "e2" on the x-axis
/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
/// vs "e2" vs "e3" on the x-, y-, z-axis, respectively.
/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
/// (to create histograms in the 2, 3, and 4 dimensional case,
/// see section "Saving the result of Draw to an histogram")
///
/// Example:
/// - varexp = x simplest case: draw a 1-Dim distribution of column named x
/// - varexp = sqrt(x) : draw distribution of sqrt(x)
/// - varexp = x*y/z
/// - varexp = y:sqrt(x) 2-Dim distribution of y versus sqrt(x)
/// - varexp = px:py:pz:2.5*E produces a 3-d scatter-plot of px vs py ps pz
/// and the color number of each marker will be 2.5*E.
/// If the color number is negative it is set to 0.
/// If the color number is greater than the current number of colors
/// it is set to the highest color number.The default number of
/// colors is 50. see TStyle::SetPalette for setting a new color palette.
///
/// Note that the variables e1, e2 or e3 may contain a selection.
/// example, if e1= x*(y<0), the value histogrammed will be x if y<0
/// and will be 0 otherwise.
///
/// The expressions can use all the operations and build-in functions
/// supported by TFormula (See TFormula::Analyze), including free
/// standing function taking numerical arguments (TMath::Bessel).
/// In addition, you can call member functions taking numerical
/// arguments. For example:
/// ~~~ {.cpp}
/// TMath::BreitWigner(fPx,3,2)
/// event.GetHistogram().GetXaxis().GetXmax()
/// ~~~
/// Note: You can only pass expression that depend on the TTree's data
/// to static functions and you can only call non-static member function
/// with 'fixed' parameters.
///
/// \param [in] selection is an expression with a combination of the columns.
/// In a selection all the C++ operators are authorized.
/// The value corresponding to the selection expression is used as a weight
/// to fill the histogram.
/// If the expression includes only boolean operations, the result
/// is 0 or 1. If the result is 0, the histogram is not filled.
/// In general, the expression may be of the form:
/// ~~~ {.cpp}
/// value*(boolean expression)
/// ~~~
/// if boolean expression is true, the histogram is filled with
/// a `weight = value`.
/// Examples:
/// - selection1 = "x<y && sqrt(z)>3.2"
/// - selection2 = "(x+y)*(sqrt(z)>3.2)"
/// - selection1 returns a weight = 0 or 1
/// - selection2 returns a weight = x+y if sqrt(z)>3.2
/// returns a weight = 0 otherwise.
///
/// \param [in] option is the drawing option.
/// - When an histogram is produced it can be any histogram drawing option
/// listed in THistPainter.
/// - when no option is specified:
/// - the default histogram drawing option is used
/// if the expression is of the form "e1".
/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
/// unbinned 2D or 3D points is drawn respectively.
/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
/// palette.
/// - If option COL is specified when varexp has three fields:
/// ~~~ {.cpp}
/// tree.Draw("e1:e2:e3","","col");
/// ~~~
/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
/// color palette. The colors for e3 are evaluated once in linear scale before
/// painting. Therefore changing the pad to log scale along Z as no effect
/// on the colors.
/// - if expression has more than four fields the option "PARA"or "CANDLE"
/// can be used.
/// - If option contains the string "goff", no graphics is generated.
///
/// \param [in] nentries is the number of entries to process (default is all)
///
/// \param [in] firstentry is the first entry to process (default is 0)
///
/// ### Drawing expressions using arrays and array elements
///
/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
/// or a TClonesArray.
/// In a TTree::Draw expression you can now access fMatrix using the following
/// syntaxes:
///
/// | String passed | What is used for each entry of the tree
/// |-----------------|--------------------------------------------------------|
/// | `fMatrix` | the 9 elements of fMatrix |
/// | `fMatrix[][]` | the 9 elements of fMatrix |
/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
///
/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
///
/// In summary, if a specific index is not specified for a dimension, TTree::Draw
/// will loop through all the indices along this dimension. Leaving off the
/// last (right most) dimension of specifying then with the two characters '[]'
/// is equivalent. For variable size arrays (and TClonesArray) the range
/// of the first dimension is recalculated for each entry of the tree.
/// You can also specify the index as an expression of any other variables from the
/// tree.
///
/// TTree::Draw also now properly handling operations involving 2 or more arrays.
///
/// Let assume a second matrix fResults[5][2], here are a sample of some
/// of the possible combinations, the number of elements they produce and
/// the loop used:
///
/// | expression | element(s) | Loop |
/// |----------------------------------|------------|--------------------------|
/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
/// | `fMatrix[][fResult[][]]` | 30 | on 1st dim of fMatrix then on both dimensions of fResults. The value if fResults[j][k] is used as the second index of fMatrix.|
///
///
/// In summary, TTree::Draw loops through all unspecified dimensions. To
/// figure out the range of each loop, we match each unspecified dimension
/// from left to right (ignoring ALL dimensions for which an index has been
/// specified), in the equivalent loop matched dimensions use the same index
/// and are restricted to the smallest range (of only the matched dimensions).
/// When involving variable arrays, the range can of course be different
/// for each entry of the tree.
///
/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i < min(3,2); i++) {
/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
/// }
/// ~~~
/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i < min(3,5); i++) {
/// for (Int_t i1; i1 < 2; i1++) {
/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
/// }
/// }
/// ~~~
/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i < min(3,5); i++) {
/// for (Int_t i1; i1 < min(3,2); i1++) {
/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
/// }
/// }
/// ~~~
/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
/// ~~~ {.cpp}
/// for (Int_t i0; i0 < 3; i0++) {
/// for (Int_t j2; j2 < 5; j2++) {
/// for (Int_t j3; j3 < 2; j3++) {
/// i1 = fResults[j2][j3];
/// use the value of fMatrix[i0][i1]
/// }
/// }
/// ~~~
/// ### Retrieving the result of Draw
///
/// By default the temporary histogram created is called "htemp", but only in
/// the one dimensional Draw("e1") it contains the TTree's data points. For
/// a two dimensional Draw, the data is filled into a TGraph which is named
/// "Graph". They can be retrieved by calling
/// ~~~ {.cpp}
/// TH1F *htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
/// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
/// ~~~
/// For a three and four dimensional Draw the TPolyMarker3D is unnamed, and
/// cannot be retrieved.
///
/// gPad always contains a TH1 derived object called "htemp" which allows to
/// access the axes:
/// ~~~ {.cpp}
/// TGraph *graph = (TGraph*)gPad->GetPrimitive("Graph"); // 2D
/// TH2F *htemp = (TH2F*)gPad->GetPrimitive("htemp"); // empty, but has axes
/// TAxis *xaxis = htemp->GetXaxis();
/// ~~~
/// ### Saving the result of Draw to an histogram
///
/// If varexp0 contains >>hnew (following the variable(s) name(s),
/// the new histogram created is called hnew and it is kept in the current
/// directory (and also the current pad). This works for all dimensions.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw("sqrt(x)>>hsqrt","y>0")
/// ~~~
/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
/// directory. To retrieve it do:
/// ~~~ {.cpp}
/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
/// ~~~
/// The binning information is taken from the environment variables
/// ~~~ {.cpp}
/// Hist.Binning.?D.?
/// ~~~
/// In addition, the name of the histogram can be followed by up to 9
/// numbers between '(' and ')', where the numbers describe the
/// following:
///
/// - 1 - bins in x-direction
/// - 2 - lower limit in x-direction
/// - 3 - upper limit in x-direction
/// - 4-6 same for y-direction
/// - 7-9 same for z-direction
///
/// When a new binning is used the new value will become the default.
/// Values can be skipped.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
/// // plot sqrt(x) between 10 and 20 using 500 bins
/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
/// // plot sqrt(x) against sin(y)
/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
/// ~~~
/// By default, the specified histogram is reset.
/// To continue to append data to an existing histogram, use "+" in front
/// of the histogram name.
///
/// A '+' in front of the histogram name is ignored, when the name is followed by
/// binning information as described in the previous paragraph.
/// ~~~ {.cpp}
/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
/// ~~~
/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
/// and 3-D histograms.
///
/// ### Accessing collection objects
///
/// TTree::Draw default's handling of collections is to assume that any
/// request on a collection pertain to it content. For example, if fTracks
/// is a collection of Track objects, the following:
/// ~~~ {.cpp}
/// tree->Draw("event.fTracks.fPx");
/// ~~~
/// will plot the value of fPx for each Track objects inside the collection.
/// Also
/// ~~~ {.cpp}
/// tree->Draw("event.fTracks.size()");
/// ~~~
/// would plot the result of the member function Track::size() for each
/// Track object inside the collection.
/// To access information about the collection itself, TTree::Draw support
/// the '@' notation. If a variable which points to a collection is prefixed
/// or postfixed with '@', the next part of the expression will pertain to
/// the collection object. For example:
/// ~~~ {.cpp}
/// tree->Draw("event.@fTracks.size()");
/// ~~~
/// will plot the size of the collection referred to by `fTracks` (i.e the number
/// of Track objects).
///
/// ### Drawing 'objects'
///
/// When a class has a member function named AsDouble or AsString, requesting
/// to directly draw the object will imply a call to one of the 2 functions.
/// If both AsDouble and AsString are present, AsDouble will be used.
/// AsString can return either a char*, a std::string or a TString.s
/// For example, the following
/// ~~~ {.cpp}
/// tree->Draw("event.myTTimeStamp");
/// ~~~
/// will draw the same histogram as
/// ~~~ {.cpp}
/// tree->Draw("event.myTTimeStamp.AsDouble()");
/// ~~~
/// In addition, when the object is a type TString or std::string, TTree::Draw
/// will call respectively `TString::Data` and `std::string::c_str()`
///
/// If the object is a TBits, the histogram will contain the index of the bit
/// that are turned on.
///
/// ### Retrieving information about the tree itself.
///
/// You can refer to the tree (or chain) containing the data by using the
/// string 'This'.
/// You can then could any TTree methods. For example:
/// ~~~ {.cpp}
/// tree->Draw("This->GetReadEntry()");
/// ~~~
/// will display the local entry numbers be read.
/// ~~~ {.cpp}
/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
/// ~~~
/// will display the name of the first 'user info' object.
///
/// ### Special functions and variables
///
/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
/// to access the entry number being read. For example to draw every
/// other entry use:
/// ~~~ {.cpp}
/// tree.Draw("myvar","Entry$%2==0");
/// ~~~
/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
/// - `LocalEntry$` : return the current entry number in the current tree of a
/// chain (`== GetTree()->GetReadEntry()`)
/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
/// - `LocalEntries$` : return the total number of entries in the current tree
/// of a chain (== GetTree()->TTree::GetEntries())
/// - `Length$` : return the total number of element of this formula for this
/// entry (`==TTreeFormula::GetNdata()`)
/// - `Iteration$` : return the current iteration over this formula for this
/// entry (i.e. varies from 0 to `Length$`).
/// - `Length$(formula )` : return the total number of element of the formula
/// given as a parameter.
/// - `Sum$(formula )` : return the sum of the value of the elements of the
/// formula given as a parameter. For example the mean for all the elements in
/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
/// - `Min$(formula )` : return the minimun (within one TTree entry) of the value of the
/// elements of the formula given as a parameter.
/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
/// elements of the formula given as a parameter.
/// - `MinIf$(formula,condition)`
/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
/// of the value of the elements of the formula given as a parameter
/// if they match the condition. If no element matches the condition,
/// the result is zero. To avoid the resulting peak at zero, use the
/// pattern:
/// ~~~ {.cpp}
/// tree->Draw("MinIf$(formula,condition)","condition");
/// ~~~
/// which will avoid calculation `MinIf$` for the entries that have no match
/// for the condition.
/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
/// for the current iteration otherwise return the value of "alternate".
/// For example, with arr1[3] and arr2[2]
/// ~~~ {.cpp}
/// tree->Draw("arr1+Alt$(arr2,0)");
/// ~~~
/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
/// Or with a variable size array arr3
/// ~~~ {.cpp}
/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
/// ~~~
/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
/// As a comparison
/// ~~~ {.cpp}
/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
/// ~~~
/// will draw the sum arr3 for the index 0 to 2 only if the
/// actual_size_of_arr3 is greater or equal to 3.
/// Note that the array in 'primary' is flattened/linearized thus using
/// `Alt$` with multi-dimensional arrays of different dimensions in unlikely
/// to yield the expected results. To visualize a bit more what elements
/// would be matched by TTree::Draw, TTree::Scan can be used:
/// ~~~ {.cpp}
/// tree->Scan("arr1:Alt$(arr2,0)");
/// ~~~
/// will print on one line the value of arr1 and (arr2,0) that will be
/// matched by
/// ~~~ {.cpp}
/// tree->Draw("arr1-Alt$(arr2,0)");
/// ~~~
/// The ternary operator is not directly supported in TTree::Draw however, to plot the
/// equivalent of `var2<20 ? -99 : var1`, you can use:
/// ~~~ {.cpp}
/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
/// ~~~
///
/// ### Drawing a user function accessing the TTree data directly
///
/// If the formula contains a file name, TTree::MakeProxy will be used
/// to load and execute this file. In particular it will draw the
/// result of a function with the same name as the file. The function
/// will be executed in a context where the name of the branches can
/// be used as a C++ variable.
///
/// For example draw px using the file hsimple.root (generated by the
/// hsimple.C tutorial), we need a file named hsimple.cxx:
/// ~~~ {.cpp}
/// double hsimple() {
/// return px;
/// }
/// ~~~
/// MakeProxy can then be used indirectly via the TTree::Draw interface
/// as follow:
/// ~~~ {.cpp}
/// new TFile("hsimple.root")
/// ntuple->Draw("hsimple.cxx");
/// ~~~
/// A more complete example is available in the tutorials directory:
/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
/// which reimplement the selector found in `h1analysis.C`
///
/// The main features of this facility are:
///
/// * on-demand loading of branches
/// * ability to use the 'branchname' as if it was a data member
/// * protection against array out-of-bound
/// * ability to use the branch data as object (when the user code is available)
///
/// See TTree::MakeProxy for more details.
///
/// ### Making a Profile histogram
///
/// In case of a 2-Dim expression, one can generate a TProfile histogram
/// instead of a TH2F histogram by specifying option=prof or option=profs
/// or option=profi or option=profg ; the trailing letter select the way
/// the bin error are computed, See TProfile2D::SetErrorOption for
/// details on the differences.
/// The option=prof is automatically selected in case of y:x>>pf
/// where pf is an existing TProfile histogram.
///
/// ### Making a 2D Profile histogram
///
/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
/// instead of a TH3F histogram by specifying option=prof or option=profs.
/// or option=profi or option=profg ; the trailing letter select the way
/// the bin error are computed, See TProfile2D::SetErrorOption for
/// details on the differences.
/// The option=prof is automatically selected in case of z:y:x>>pf
/// where pf is an existing TProfile2D histogram.
///
/// ### Making a 5D plot using GL
///
/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
/// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
///
/// ### Making a parallel coordinates plot
///
/// In case of a 2-Dim or more expression with the option=para, one can generate
/// a parallel coordinates plot. With that option, the number of dimensions is
/// arbitrary. Giving more than 4 variables without the option=para or
/// option=candle or option=goff will produce an error.
///
/// ### Making a candle sticks chart
///
/// In case of a 2-Dim or more expression with the option=candle, one can generate
/// a candle sticks chart. With that option, the number of dimensions is
/// arbitrary. Giving more than 4 variables without the option=para or
/// option=candle or option=goff will produce an error.
///
/// ### Normalizing the output histogram to 1
///
/// When option contains "norm" the output histogram is normalized to 1.
///
/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
///
/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
/// instead of histogramming one variable.
/// If varexp0 has the form >>elist , a TEventList object named "elist"
/// is created in the current directory. elist will contain the list
/// of entry numbers satisfying the current selection.
/// If option "entrylist" is used, a TEntryList object is created
/// If the selection contains arrays, vectors or any container class and option
/// "entrylistarray" is used, a TEntryListArray object is created
/// containing also the subentries satisfying the selection, i.e. the indices of
/// the branches which hold containers classes.
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>yplus","y>0")
/// ~~~
/// will create a TEventList object named "yplus" in the current directory.
/// In an interactive session, one can type (after TTree::Draw)
/// ~~~ {.cpp}
/// yplus.Print("all")
/// ~~~
/// to print the list of entry numbers in the list.
/// ~~~ {.cpp}
/// tree.Draw(">>yplus", "y>0", "entrylist")
/// ~~~
/// will create a TEntryList object names "yplus" in the current directory
/// ~~~ {.cpp}
/// tree.Draw(">>yplus", "y>0", "entrylistarray")
/// ~~~
/// will create a TEntryListArray object names "yplus" in the current directory
///
/// By default, the specified entry list is reset.
/// To continue to append data to an existing list, use "+" in front
/// of the list name;
/// ~~~ {.cpp}
/// tree.Draw(">>+yplus","y>0")
/// ~~~
/// will not reset yplus, but will enter the selected entries at the end
/// of the existing list.
///
/// ### Using a TEventList, TEntryList or TEntryListArray as Input
///
/// Once a TEventList or a TEntryList object has been generated, it can be used as input
/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
/// current event list
///
/// Example 1:
/// ~~~ {.cpp}
/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
/// tree->SetEventList(elist);
/// tree->Draw("py");
/// ~~~
/// Example 2:
/// ~~~ {.cpp}
/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
/// tree->SetEntryList(elist);
/// tree->Draw("py");
/// ~~~
/// If a TEventList object is used as input, a new TEntryList object is created
/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
/// for this transformation. This new object is owned by the chain and is deleted
/// with it, unless the user extracts it by calling GetEntryList() function.
/// See also comments to SetEventList() function of TTree and TChain.
///
/// If arrays are used in the selection criteria and TEntryListArray is not used,
/// all the entries that have at least one element of the array that satisfy the selection
/// are entered in the list.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>pyplus","fTracks.fPy>0");
/// tree->SetEventList(pyplus);
/// tree->Draw("fTracks.fPy");
/// ~~~
/// will draw the fPy of ALL tracks in event with at least one track with
/// a positive fPy.
///
/// To select only the elements that did match the original selection
/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>pyplus","fTracks.fPy>0");
/// pyplus->SetReapplyCut(kTRUE);
/// tree->SetEventList(pyplus);
/// tree->Draw("fTracks.fPy");
/// ~~~
/// will draw the fPy of only the tracks that have a positive fPy.
///
/// To draw only the elements that match a selection in case of arrays,
/// you can also use TEntryListArray (faster in case of a more general selection).
///
/// Example:
/// ~~~ {.cpp}
/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
/// tree->SetEntryList(pyplus);
/// tree->Draw("fTracks.fPy");
/// ~~~
/// will draw the fPy of only the tracks that have a positive fPy,
/// but without redoing the selection.
///
/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
///
/// ### How to obtain more info from TTree::Draw
///
/// Once TTree::Draw has been called, it is possible to access useful
/// information still stored in the TTree object via the following functions:
///
/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
/// - GetV1() // returns a pointer to the double array of V1
/// - GetV2() // returns a pointer to the double array of V2
/// - GetV3() // returns a pointer to the double array of V3
/// - GetV4() // returns a pointer to the double array of V4
/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
///
/// where V1,V2,V3 correspond to the expressions in
/// ~~~ {.cpp}
/// TTree::Draw("V1:V2:V3:V4",selection);
/// ~~~
/// If the expression has more than 4 component use GetVal(index)
///
/// Example:
/// ~~~ {.cpp}
/// Root > ntuple->Draw("py:px","pz>4");
/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
/// ntuple->GetV2(), ntuple->GetV1());
/// Root > gr->Draw("ap"); //draw graph in current pad
/// ~~~
///
/// A more complete complete tutorial (treegetval.C) shows how to use the
/// GetVal() method.
///
/// creates a TGraph object with a number of points corresponding to the
/// number of entries selected by the expression "pz>4", the x points of the graph
/// being the px values of the Tree and the y points the py values.
///
/// Important note: By default TTree::Draw creates the arrays obtained
/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
/// values calculated.
/// By default fEstimate=1000000 and can be modified
/// via TTree::SetEstimate. To keep in memory all the results (in case
/// where there is only one result per entry), use
/// ~~~ {.cpp}
/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
/// ~~~
/// You must call SetEstimate if the expected number of selected rows
/// you need to look at is greater than 1000000.
///
/// You can use the option "goff" to turn off the graphics output
/// of TTree::Draw in the above example.
///
/// ### Automatic interface to TTree::Draw via the TTreeViewer
///
/// A complete graphical interface to this function is implemented
/// in the class TTreeViewer.
/// To start the TTreeViewer, three possibilities:
/// - select TTree context menu item "StartViewer"
/// - type the command "TTreeViewer TV(treeName)"
/// - execute statement "tree->StartViewer();"
Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer)
return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Remove some baskets from memory.
void TTree::DropBaskets()
{
TBranch* branch = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
branch = (TBranch*) fBranches.UncheckedAt(i);
branch->DropBaskets("all");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
void TTree::DropBuffers(Int_t)
{
// Be careful not to remove current read/write buffers.
Int_t ndrop = 0;
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; ++i) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
for (Int_t j = 0; j < nbaskets - 1; ++j) {
if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
continue;
}
TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
if (basket) {
ndrop += basket->DropBuffers();
if (fTotalBuffers < fMaxVirtualSize) {
return;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Fill all branches.
///
/// This function loops on all the branches of this tree. For
/// each branch, it copies to the branch buffer (basket) the current
/// values of the leaves data types. If a leaf is a simple data type,
/// a simple conversion to a machine independent format has to be done.
///
/// This machine independent version of the data is copied into a
/// basket (each branch has its own basket). When a basket is full
/// (32k worth of data by default), it is then optionally compressed
/// and written to disk (this operation is also called committing or
/// 'flushing' the basket). The committed baskets are then
/// immediately removed from memory.
///
/// The function returns the number of bytes committed to the
/// individual branches.
///
/// If a write error occurs, the number of bytes returned is -1.
///
/// If no data are written, because, e.g., the branch is disabled,
/// the number of bytes returned is 0.
///
/// __The baskets are flushed and the Tree header saved at regular intervals__
///
/// At regular intervals, when the amount of data written so far is
/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
/// This makes future reading faster as it guarantees that baskets belonging to nearby
/// entries will be on the same disk region.
/// When the first call to flush the baskets happen, we also take this opportunity
/// to optimize the baskets buffers.
/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
/// in case the program writing the Tree crashes.
/// The decisions to FlushBaskets and Auto Save can be made based either on the number
/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
/// written (fAutoFlush and fAutoSave positive).
/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
/// base on the number of events written instead of the number of bytes written.
///
/// Note that calling FlushBaskets too often increases the IO time.
///
/// Note that calling AutoSave too often increases the IO time and also the file size.
Int_t TTree::Fill()
{
Int_t nbytes = 0;
Int_t nwrite = 0;
Int_t nerror = 0;
Int_t nbranches = fBranches.GetEntriesFast();
// Case of one single super branch. Automatically update
// all the branch addresses if a new object was created.
if (nbranches == 1)
((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
if (fBranchRef)
fBranchRef->Clear();
#ifdef R__USE_IMT
const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
ROOT::Internal::TBranchIMTHelper imtHelper;
if (useIMT) {
fIMTFlush = true;
fIMTZipBytes.store(0);
fIMTTotBytes.store(0);
}
#endif
for (Int_t i = 0; i < nbranches; ++i) {
// Loop over all branches, filling and accumulating bytes written and error counts.
TBranch *branch = (TBranch *)fBranches.UncheckedAt(i);
if (branch->TestBit(kDoNotProcess))
continue;
#ifndef R__USE_IMT
nwrite = branch->FillImpl(nullptr);
#else
nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
#endif
if (nwrite < 0) {
if (nerror < 2) {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
" This error is symptomatic of a Tree created as a memory-resident Tree\n"
" Instead of doing:\n"
" TTree *T = new TTree(...)\n"
" TFile *f = new TFile(...)\n"
" you should do:\n"
" TFile *f = new TFile(...)\n"
" TTree *T = new TTree(...)\n\n",
GetName(), branch->GetName(), nwrite, fEntries + 1);
} else {
Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
fEntries + 1);
}
++nerror;
} else {
nbytes += nwrite;
}
}
#ifdef R__USE_IMT
if (fIMTFlush) {
imtHelper.Wait();
fIMTFlush = false;
const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
nbytes += imtHelper.GetNbytes();
nerror += imtHelper.GetNerrors();
}
#endif
if (fBranchRef)
fBranchRef->Fill();
++fEntries;
if (fEntries > fMaxEntries)
KeepCircular();
if (gDebug > 0)
Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
GetZipBytes(), fFlushedBytes, fSavedBytes);
bool autoFlush = false;
bool autoSave = false;
if (fAutoFlush != 0 || fAutoSave != 0) {
// Is it time to flush or autosave baskets?
if (fFlushedBytes == 0) {
// If fFlushedBytes == 0, it means we never flushed or saved, so
// we need to check if it's time to do it and recompute the values
// of fAutoFlush and fAutoSave in terms of the number of entries.
// Decision can be based initially either on the number of bytes
// or the number of entries written.
Long64_t zipBytes = GetZipBytes();
if (fAutoFlush)
autoFlush = fAutoFlush < 0 ? (zipBytes > -fAutoFlush) : fEntries % fAutoFlush == 0;
if (fAutoSave)
autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
if (autoFlush || autoSave) {
// First call FlushBasket to make sure that fTotBytes is up to date.
FlushBasketsImpl();
autoFlush = false; // avoid auto flushing again later
// When we are in one-basket-per-cluster mode, there is no need to optimize basket:
// they will automatically grow to the size needed for an event cluster (with the basket
// shrinking preventing them from growing too much larger than the actually-used space).
if (!TestBit(TTree::kOnlyFlushAtCluster)) {
OptimizeBaskets(GetTotBytes(), 1, "");
if (gDebug > 0)
Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
fEntries, GetZipBytes(), fFlushedBytes);
}
fFlushedBytes = GetZipBytes();
fAutoFlush = fEntries; // Use test on entries rather than bytes
// subsequently in run
if (fAutoSave < 0) {
// Set fAutoSave to the largest integer multiple of
// fAutoFlush events such that fAutoSave*fFlushedBytes
// < (minus the input value of fAutoSave)
Long64_t totBytes = GetTotBytes();
if (zipBytes != 0) {
fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / zipBytes) / fEntries));
} else if (totBytes != 0) {
fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / totBytes) / fEntries));
} else {
TBufferFile b(TBuffer::kWrite, 10000);
TTree::Class()->WriteBuffer(b, (TTree *)this);
Long64_t total = b.Length();
fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / total) / fEntries));
}
} else if (fAutoSave > 0) {
fAutoSave = fAutoFlush * (fAutoSave / fAutoFlush);
}
if (fAutoSave != 0 && fEntries >= fAutoSave)
autoSave = true;
if (gDebug > 0)
Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
}
} else {
// Check if we need to auto flush
if (fAutoFlush) {
if (fNClusterRange == 0)
autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
else
autoFlush = (fEntries - (fClusterRangeEnd[fNClusterRange - 1] + 1)) % fAutoFlush == 0;
}
// Check if we need to auto save
if (fAutoSave)
autoSave = fEntries % fAutoSave == 0;
}
}
if (autoFlush) {
FlushBasketsImpl();
if (gDebug > 0)
Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
GetZipBytes(), fFlushedBytes);
fFlushedBytes = GetZipBytes();
}
if (autoSave) {
AutoSave(); // does not call FlushBasketsImpl() again
if (gDebug > 0)
Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
GetZipBytes(), fSavedBytes);
}
// Check that output file is still below the maximum size.
// If above, close the current file and continue on a new file.
// Currently, the automatic change of file is restricted
// to the case where the tree is in the top level directory.
if (fDirectory)
if (TFile *file = fDirectory->GetFile())
if ((TDirectory *)file == fDirectory && (file->GetEND() > fgMaxTreeSize))
ChangeFile(file);
return nerror == 0 ? nbytes : -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Search in the array for a branch matching the branch name,
/// with the branch possibly expressed as a 'full' path name (with dots).
static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
if (list==0 || branchname == 0 || branchname[0] == '\0') return 0;
Int_t nbranches = list->GetEntries();
UInt_t brlen = strlen(branchname);
for(Int_t index = 0; index < nbranches; ++index) {
TBranch *where = (TBranch*)list->UncheckedAt(index);
const char *name = where->GetName();
UInt_t len = strlen(name);
if (len && name[len-1]==']') {
const char *dim = strchr(name,'[');
if (dim) {
len = dim - name;
}
}
if (brlen == len && strncmp(branchname,name,len)==0) {
return where;
}
TBranch *next = 0;
if ((brlen >= len) && (branchname[len] == '.')
&& strncmp(name, branchname, len) == 0) {
// The prefix subbranch name match the branch name.
next = where->FindBranch(branchname);
if (!next) {
next = where->FindBranch(branchname+len+1);
}
if (next) return next;
}
const char *dot = strchr((char*)branchname,'.');
if (dot) {
if (len==(size_t)(dot-branchname) &&
strncmp(branchname,name,dot-branchname)==0 ) {
return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
}
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return the branch that correspond to the path 'branchname', which can
/// include the name of the tree or the omitted name of the parent branches.
/// In case of ambiguity, returns the first match.
TBranch* TTree::FindBranch(const char* branchname)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kFindBranch & fFriendLockStatus) {
return 0;
}
TBranch* branch = 0;
// If the first part of the name match the TTree name, look for the right part in the
// list of branches.
// This will allow the branchname to be preceded by
// the name of this tree.
if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
if (branch) return branch;
}
// If we did not find it, let's try to find the full name in the list of branches.
branch = R__FindBranchHelper(GetListOfBranches(), branchname);
if (branch) return branch;
// If we still did not find, let's try to find it within each branch assuming it does not the branch name.
TIter next(GetListOfBranches());
while ((branch = (TBranch*) next())) {
TBranch* nestedbranch = branch->FindBranch(branchname);
if (nestedbranch) {
return nestedbranch;
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindBranch);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
const char *subbranch = strstr(branchname, fe->GetName());
if (subbranch != branchname) {
subbranch = 0;
}
if (subbranch) {
subbranch += strlen(fe->GetName());
if (*subbranch != '.') {
subbranch = 0;
} else {
++subbranch;
}
}
std::ostringstream name;
if (subbranch) {
name << t->GetName() << "." << subbranch;
} else {
name << branchname;
}
branch = t->FindBranch(name.str().c_str());
if (branch) {
return branch;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Find leaf..
TLeaf* TTree::FindLeaf(const char* searchname)
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kFindLeaf & fFriendLockStatus) {
return 0;
}
// This will allow the branchname to be preceded by
// the name of this tree.
char* subsearchname = (char*) strstr(searchname, GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
if (subsearchname[0]==0) {
subsearchname = 0;
}
}
}
TString leafname;
TString leaftitle;
TString longname;
TString longtitle;
const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
// For leaves we allow for one level up to be prefixed to the name.
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leafname = leaf->GetName();
Ssiz_t dim = leafname.First('[');
if (dim >= 0) leafname.Remove(dim);
if (leafname == searchname) {
return leaf;
}
if (subsearchname && leafname == subsearchname) {
return leaf;
}
// The TLeafElement contains the branch name
// in its name, let's use the title.
leaftitle = leaf->GetTitle();
dim = leaftitle.First('[');
if (dim >= 0) leaftitle.Remove(dim);
if (leaftitle == searchname) {
return leaf;
}
if (subsearchname && leaftitle == subsearchname) {
return leaf;
}
if (!searchnameHasDot)
continue;
TBranch* branch = leaf->GetBranch();
if (branch) {
longname.Form("%s.%s",branch->GetName(),leafname.Data());
dim = longname.First('[');
if (dim>=0) longname.Remove(dim);
if (longname == searchname) {
return leaf;
}
if (subsearchname && longname == subsearchname) {
return leaf;
}
longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
dim = longtitle.First('[');
if (dim>=0) longtitle.Remove(dim);
if (longtitle == searchname) {
return leaf;
}
if (subsearchname && longtitle == subsearchname) {
return leaf;
}
// The following is for the case where the branch is only
// a sub-branch. Since we do not see it through
// TTree::GetListOfBranches, we need to see it indirectly.
// This is the less sturdy part of this search ... it may
// need refining ...
if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
return leaf;
}
if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
return leaf;
}
}
}
// Search in list of friends.
if (!fFriends) {
return 0;
}
TFriendLock lock(this, kFindLeaf);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
// If the alias is present replace it with the real name.
subsearchname = (char*) strstr(searchname, fe->GetName());
if (subsearchname != searchname) {
subsearchname = 0;
}
if (subsearchname) {
subsearchname += strlen(fe->GetName());
if (*subsearchname != '.') {
subsearchname = 0;
} else {
++subsearchname;
}
}
if (subsearchname) {
leafname.Form("%s.%s",t->GetName(),subsearchname);
} else {
leafname = searchname;
}
leaf = t->FindLeaf(leafname);
if (leaf) {
return leaf;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Fit a projected item(s) from a tree.
///
/// funcname is a TF1 function.
///
/// See TTree::Draw() for explanations of the other parameters.
///
/// By default the temporary histogram created is called htemp.
/// If varexp contains >>hnew , the new histogram created is called hnew
/// and it is kept in the current directory.
///
/// The function returns the number of selected entries.
///
/// Example:
/// ~~~ {.cpp}
/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
/// ~~~
/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
/// directory.
///
/// See also TTree::UnbinnedFit
///
/// ## Return status
///
/// The function returns the status of the histogram fit (see TH1::Fit)
/// If no entries were selected, the function returns -1;
/// (i.e. fitResult is null if the fit is OK)
Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
}
return -1;
}
namespace {
struct BoolRAIIToggle {
Bool_t &m_val;
BoolRAIIToggle(Bool_t &val) : m_val(val) { m_val = true; }
~BoolRAIIToggle() { m_val = false; }
};
}
////////////////////////////////////////////////////////////////////////////////
/// Write to disk all the basket that have not yet been individually written and
/// create an event cluster boundary (by default).
///
/// If the caller wishes to flush the baskets but not create an event cluster,
/// then set create_cluster to false.
///
/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
/// via TThreadExecutor to do this operation; one per basket compression. If the
/// caller utilizes TBB also, care must be taken to prevent deadlocks.
///
/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
/// run another one of the user's tasks in this thread. If the second user task
/// tries to acquire A, then a deadlock will occur. The example call sequence
/// looks like this:
///
/// - User acquires mutex A
/// - User calls FlushBaskets.
/// - ROOT launches N tasks and calls wait.
/// - TBB schedules another user task, T2.
/// - T2 tries to acquire mutex A.
///
/// At this point, the thread will deadlock: the code may function with IMT-mode
/// disabled if the user assumed the legacy code never would run their own TBB
/// tasks.
///
/// SO: users of TBB who want to enable IMT-mode should carefully review their
/// locking patterns and make sure they hold no coarse-grained application
/// locks when they invoke ROOT.
///
/// Return the number of bytes written or -1 in case of write error.
Int_t TTree::FlushBaskets(Bool_t create_cluster) const
{
Int_t retval = FlushBasketsImpl();
if (retval == -1) return retval;
if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
return retval;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal implementation of the FlushBaskets algorithm.
/// Unlike the public interface, this does NOT create an explicit event cluster
/// boundary; it is up to the (internal) caller to determine whether that should
/// done.
///
/// Otherwise, the comments for FlushBaskets applies.
///
Int_t TTree::FlushBasketsImpl() const
{
if (!fDirectory) return 0;
Int_t nbytes = 0;
Int_t nerror = 0;
TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
Int_t nb = lb->GetEntriesFast();
#ifdef R__USE_IMT
const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
if (useIMT) {
// ROOT-9668: here we need to check if the size of fSortedBranches is different from the
// size of the list of branches before triggering the initialisation of the fSortedBranches
// container to cover two cases:
// 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
// 2. We flushed at least once already but a branch has been be added to the tree since then
if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
BoolRAIIToggle sentry(fIMTFlush);
fIMTZipBytes.store(0);
fIMTTotBytes.store(0);
std::atomic<Int_t> nerrpar(0);
std::atomic<Int_t> nbpar(0);
std::atomic<Int_t> pos(0);
auto mapFunction = [&]() {
// The branch to process is obtained when the task starts to run.
// This way, since branches are sorted, we make sure that branches
// leading to big tasks are processed first. If we assigned the
// branch at task creation time, the scheduler would not necessarily
// respect our sorting.
Int_t j = pos.fetch_add(1);
auto branch = fSortedBranches[j].second;
if (R__unlikely(!branch)) { return; }
if (R__unlikely(gDebug > 0)) {
std::stringstream ss;
ss << std::this_thread::get_id();
Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
}
Int_t nbtask = branch->FlushBaskets();
if (nbtask < 0) { nerrpar++; }
else { nbpar += nbtask; }
};
ROOT::TThreadExecutor pool;
pool.Foreach(mapFunction, nb);
fIMTFlush = false;
const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
return nerrpar ? -1 : nbpar.load();
}
#endif
for (Int_t j = 0; j < nb; j++) {
TBranch* branch = (TBranch*) lb->UncheckedAt(j);
if (branch) {
Int_t nwrite = branch->FlushBaskets();
if (nwrite<0) {
++nerror;
} else {
nbytes += nwrite;
}
}
}
if (nerror) {
return -1;
} else {
return nbytes;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the expanded value of the alias. Search in the friends if any.
const char* TTree::GetAlias(const char* aliasName) const
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetAlias & fFriendLockStatus) {
return 0;
}
if (fAliases) {
TObject* alias = fAliases->FindObject(aliasName);
if (alias) {
return alias->GetTitle();
}
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t) {
const char* alias = t->GetAlias(aliasName);
if (alias) {
return alias;
}
const char* subAliasName = strstr(aliasName, fe->GetName());
if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
if (alias) {
return alias;
}
}
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the branch with the given name in this tree or its friends.
TBranch* TTree::GetBranch(const char* name)
{
if (name == 0) return 0;
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetBranch & fFriendLockStatus) {
return 0;
}
// Search using branches.
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
if (!branch) {
continue;
}
if (!strcmp(branch->GetName(), name)) {
return branch;
}
TObjArray* lb = branch->GetListOfBranches();
Int_t nb1 = lb->GetEntriesFast();
for (Int_t j = 0; j < nb1; j++) {
TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
if (!strcmp(b1->GetName(), name)) {
return b1;
}
TObjArray* lb1 = b1->GetListOfBranches();
Int_t nb2 = lb1->GetEntriesFast();
for (Int_t k = 0; k < nb2; k++) {
TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
if (!strcmp(b2->GetName(), name)) {
return b2;
}
}
}
}
// Search using leaves.
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (!strcmp(branch->GetName(), name)) {
return branch;
}
}
if (!fFriends) {
return 0;
}
// Search in list of friends.
TFriendLock lock(this, kGetBranch);
TIter next(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (t) {
TBranch* branch = t->GetBranch(name);
if (branch) {
return branch;
}
}
}
// Second pass in the list of friends when
// the branch name is prefixed by the tree name.
next.Reset();
while ((fe = (TFriendElement*) next())) {
TTree* t = fe->GetTree();
if (!t) {
continue;
}
char* subname = (char*) strstr(name, fe->GetName());
if (subname != name) {
continue;
}
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') {
continue;
}
subname++;
TBranch* branch = t->GetBranch(subname);
if (branch) {
return branch;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return status of branch with name branchname.
///
/// - 0 if branch is not activated
/// - 1 if branch is activated
Bool_t TTree::GetBranchStatus(const char* branchname) const
{
TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
if (br) {
return br->TestBit(kDoNotProcess) == 0;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Static function returning the current branch style.
///
/// - style = 0 old Branch
/// - style = 1 new Bronch
Int_t TTree::GetBranchStyle()
{
return fgBranchStyle;
}
////////////////////////////////////////////////////////////////////////////////
/// Used for automatic sizing of the cache.
///
/// Estimates a suitable size for the tree cache based on AutoFlush.
/// A cache sizing factor is taken from the configuration. If this yields zero
/// and withDefault is true the historical algorithm for default size is used.
Long64_t TTree::GetCacheAutoSize(Bool_t withDefault /* = kFALSE */ ) const
{
const char *stcs;
Double_t cacheFactor = 0.0;
if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
} else {
cacheFactor = TString(stcs).Atof();
}
if (cacheFactor < 0.0) {
// ignore negative factors
cacheFactor = 0.0;
}
Long64_t cacheSize = 0;
if (fAutoFlush < 0) cacheSize = Long64_t(-cacheFactor*fAutoFlush);
else if (fAutoFlush == 0) cacheSize = 0;
else cacheSize = Long64_t(cacheFactor*1.5*fAutoFlush*GetZipBytes()/(fEntries+1));
if (cacheSize >= (INT_MAX / 4)) {
cacheSize = INT_MAX / 4;
}
if (cacheSize < 0) {
cacheSize = 0;
}
if (cacheSize == 0 && withDefault) {
if (fAutoFlush < 0) cacheSize = -fAutoFlush;
else if (fAutoFlush == 0) cacheSize = 0;
else cacheSize = Long64_t(1.5*fAutoFlush*GetZipBytes()/(fEntries+1));
}
return cacheSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Return an iterator over the cluster of baskets starting at firstentry.
///
/// This iterator is not yet supported for TChain object.
/// ~~~ {.cpp}
/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
/// Long64_t clusterStart;
/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
/// }
/// ~~~
TTree::TClusterIterator TTree::GetClusterIterator(Long64_t firstentry)
{
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
return TClusterIterator(this,firstentry);
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the current file.
TFile* TTree::GetCurrentFile() const
{
if (!fDirectory || fDirectory==gROOT) {
return 0;
}
return fDirectory->GetFile();
}
////////////////////////////////////////////////////////////////////////////////
/// Return the number of entries matching the selection.
/// Return -1 in case of errors.
///
/// If the selection uses any arrays or containers, we return the number
/// of entries where at least one element match the selection.
/// GetEntries is implemented using the selector class TSelectorEntries,
/// which can be used directly (see code in TTreePlayer::GetEntries) for
/// additional option.
/// If SetEventList was used on the TTree or TChain, only that subset
/// of entries will be considered.
Long64_t TTree::GetEntries(const char *selection)
{
GetPlayer();
if (fPlayer) {
return fPlayer->GetEntries(selection);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the 1st Leaf named name in any Branch of this Tree or
/// any branch in the list of friend trees.
Long64_t TTree::GetEntriesFriend() const
{
if (fEntries) return fEntries;
if (!fFriends) return 0;
TFriendElement *fr = (TFriendElement*)fFriends->At(0);
if (!fr) return 0;
TTree *t = fr->GetTree();
if (t==0) return 0;
return t->GetEntriesFriend();
}
////////////////////////////////////////////////////////////////////////////////
/// Read all branches of entry and return total number of bytes read.
///
/// - `getall = 0` : get only active branches
/// - `getall = 1` : get all branches
///
/// The function returns the number of bytes read from the input buffer.
/// If entry does not exist the function returns 0.
/// If an I/O error occurs, the function returns -1.
///
/// If the Tree has friends, also read the friends entry.
///
/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
/// For example, if you have a Tree with several hundred branches, and you
/// are interested only by branches named "a" and "b", do
/// ~~~ {.cpp}
/// mytree.SetBranchStatus("*",0); //disable all branches
/// mytree.SetBranchStatus("a",1);
/// mytree.SetBranchStatus("b",1);
/// ~~~
/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
///
/// __WARNING!!__
/// If your Tree has been created in split mode with a parent branch "parent.",
/// ~~~ {.cpp}
/// mytree.SetBranchStatus("parent",1);
/// ~~~
/// will not activate the sub-branches of "parent". You should do:
/// ~~~ {.cpp}
/// mytree.SetBranchStatus("parent*",1);
/// ~~~
/// Without the trailing dot in the branch creation you have no choice but to
/// call SetBranchStatus explicitly for each of the sub branches.
///
/// An alternative is to call directly
/// ~~~ {.cpp}
/// brancha.GetEntry(i)
/// branchb.GetEntry(i);
/// ~~~
/// ## IMPORTANT NOTE
///
/// By default, GetEntry reuses the space allocated by the previous object
/// for each branch. You can force the previous object to be automatically
/// deleted if you call mybranch.SetAutoDelete(kTRUE) (default is kFALSE).
///
/// Example:
///
/// Consider the example in $ROOTSYS/test/Event.h
/// The top level branch in the tree T is declared with:
/// ~~~ {.cpp}
/// Event *event = 0; //event must be null or point to a valid object
/// //it must be initialized
/// T.SetBranchAddress("event",&event);
/// ~~~
/// When reading the Tree, one can choose one of these 3 options:
///
/// ## OPTION 1
///
/// ~~~ {.cpp}
/// for (Long64_t i=0;i<nentries;i++) {
/// T.GetEntry(i);
/// // the object event has been filled at this point
/// }
/// ~~~
/// The default (recommended). At the first entry an object of the class
/// Event will be created and pointed by event. At the following entries,
/// event will be overwritten by the new data. All internal members that are
/// TObject* are automatically deleted. It is important that these members
/// be in a valid state when GetEntry is called. Pointers must be correctly
/// initialized. However these internal members will not be deleted if the
/// characters "->" are specified as the first characters in the comment
/// field of the data member declaration.
///
/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
/// In this case, it is assumed that the pointer is never null (case of
/// pointer TClonesArray *fTracks in the Event example). If "->" is not
/// specified, the pointer member is read via buf >> pointer. In this case
/// the pointer may be null. Note that the option with "->" is faster to
/// read or write and it also consumes less space in the file.
///
/// ## OPTION 2
///
/// The option AutoDelete is set
/// ~~~ {.cpp}
/// TBranch *branch = T.GetBranch("event");
/// branch->SetAddress(&event);
/// branch->SetAutoDelete(kTRUE);
/// for (Long64_t i=0;i<nentries;i++) {
/// T.GetEntry(i);
/// // the object event has been filled at this point
/// }
/// ~~~
/// In this case, at each iteration, the object event is deleted by GetEntry
/// and a new instance of Event is created and filled.
///
/// ## OPTION 3
///
/// ~~~ {.cpp}
/// Same as option 1, but you delete yourself the event.
///
/// for (Long64_t i=0;i<nentries;i++) {
/// delete event;
/// event = 0; // EXTREMELY IMPORTANT
/// T.GetEntry(i);
/// // the object event has been filled at this point
/// }
/// ~~~
/// It is strongly recommended to use the default option 1. It has the
/// additional advantage that functions like TTree::Draw (internally calling
/// TTree::GetEntry) will be functional even when the classes in the file are
/// not available.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// object ownership policy of the underlying (user) data.
Int_t TTree::GetEntry(Long64_t entry, Int_t getall)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetEntry & fFriendLockStatus) return 0;
if (entry < 0 || entry >= fEntries) return 0;
Int_t i;
Int_t nbytes = 0;
fReadEntry = entry;
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
Int_t nbranches = fBranches.GetEntriesUnsafe();
Int_t nb=0;
auto seqprocessing = [&]() {
TBranch *branch;
for (i=0;i<nbranches;i++) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(entry, getall);
if (nb < 0) break;
nbytes += nb;
}
};
#ifdef R__USE_IMT
if (nbranches > 1 && ROOT::IsImplicitMTEnabled() && fIMTEnabled && !TTreeCacheUnzip::IsParallelUnzip()) {
if (fSortedBranches.empty())
InitializeBranchLists(true);
// Count branches are processed first and sequentially
for (auto branch : fSeqBranches) {
nb = branch->GetEntry(entry, getall);
if (nb < 0) break;
nbytes += nb;
}
if (nb < 0) return nb;
// Enable this IMT use case (activate its locks)
ROOT::Internal::TParBranchProcessingRAII pbpRAII;
Int_t errnb = 0;
std::atomic<Int_t> pos(0);
std::atomic<Int_t> nbpar(0);
auto mapFunction = [&]() {
// The branch to process is obtained when the task starts to run.
// This way, since branches are sorted, we make sure that branches
// leading to big tasks are processed first. If we assigned the
// branch at task creation time, the scheduler would not necessarily
// respect our sorting.
Int_t j = pos.fetch_add(1);
Int_t nbtask = 0;
auto branch = fSortedBranches[j].second;
if (gDebug > 0) {
std::stringstream ss;
ss << std::this_thread::get_id();
Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
}
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
nbtask = branch->GetEntry(entry, getall);
end = std::chrono::system_clock::now();
Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
fSortedBranches[j].first += tasktime;
if (nbtask < 0) errnb = nbtask;
else nbpar += nbtask;
};
ROOT::TThreadExecutor pool;
pool.Foreach(mapFunction, fSortedBranches.size());
if (errnb < 0) {
nb = errnb;
}
else {
// Save the number of bytes read by the tasks
nbytes += nbpar;
// Re-sort branches if necessary
if (++fNEntriesSinceSorting == kNEntriesResort) {
SortBranchesByTime();
fNEntriesSinceSorting = 0;
}
}
}
else {
seqprocessing();
}
#else
seqprocessing();
#endif
if (nb < 0) return nb;
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntry);
TIter nextf(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t) {
if (fe->TestBit(TFriendElement::kFromChain)) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else {
if ( t->LoadTreeFriend(entry,this) >= 0 ) {
nb = t->GetEntry(t->GetReadEntry(),getall);
} else nb = 0;
}
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
////////////////////////////////////////////////////////////////////////////////
/// Divides the top-level branches into two vectors: (i) branches to be
/// processed sequentially and (ii) branches to be processed in parallel.
/// Even if IMT is on, some branches might need to be processed first and in a
/// sequential fashion: in the parallelization of GetEntry, those are the
/// branches that store the size of another branch for every entry
/// (e.g. the size of an array branch). If such branches were processed
/// in parallel with the rest, there could be two threads invoking
/// TBranch::GetEntry on one of them at the same time, since a branch that
/// depends on a size (or count) branch will also invoke GetEntry on the latter.
/// This method can be invoked several times during the event loop if the TTree
/// is being written, for example when adding new branches. In these cases, the
/// `checkLeafCount` parameter is false.
/// \param[in] checkLeafCount True if we need to check whether some branches are
/// count leaves.
void TTree::InitializeBranchLists(bool checkLeafCount)
{
Int_t nbranches = fBranches.GetEntriesFast();
// The special branch fBranchRef needs to be processed sequentially:
// we add it once only.
if (fBranchRef && fBranchRef != fSeqBranches[0]) {
fSeqBranches.push_back(fBranchRef);
}
// The branches to be processed sequentially are those that are the leaf count of another branch
if (checkLeafCount) {
for (Int_t i = 0; i < nbranches; i++) {
TBranch* branch = (TBranch*)fBranches.UncheckedAt(i);
auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
if (leafCount) {
auto countBranch = leafCount->GetBranch();
if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
fSeqBranches.push_back(countBranch);
}
}
}
}
// Any branch that is not a leaf count can be safely processed in parallel when reading
// We need to reset the vector to make sure we do not re-add several times the same branch.
if (!checkLeafCount) {
fSortedBranches.clear();
}
for (Int_t i = 0; i < nbranches; i++) {
Long64_t bbytes = 0;
TBranch* branch = (TBranch*)fBranches.UncheckedAt(i);
if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
bbytes = branch->GetTotBytes("*");
fSortedBranches.emplace_back(bbytes, branch);
}
}
// Initially sort parallel branches by size
std::sort(fSortedBranches.begin(),
fSortedBranches.end(),
[](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
return a.first > b.first;
});
for (size_t i = 0; i < fSortedBranches.size(); i++) {
fSortedBranches[i].first = 0LL;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Sorts top-level branches by the last average task time recorded per branch.
void TTree::SortBranchesByTime()
{
for (size_t i = 0; i < fSortedBranches.size(); i++) {
fSortedBranches[i].first *= kNEntriesResortInv;
}
std::sort(fSortedBranches.begin(),
fSortedBranches.end(),
[](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
return a.first > b.first;
});
for (size_t i = 0; i < fSortedBranches.size(); i++) {
fSortedBranches[i].first = 0LL;
}
}
////////////////////////////////////////////////////////////////////////////////
///Returns the entry list assigned to this tree
TEntryList* TTree::GetEntryList()
{
return fEntryList;
}
////////////////////////////////////////////////////////////////////////////////
/// Return entry number corresponding to entry.
///
/// if no TEntryList set returns entry
/// else returns the entry number corresponding to the list index=entry
Long64_t TTree::GetEntryNumber(Long64_t entry) const
{
if (!fEntryList) {
return entry;
}
return fEntryList->GetEntry(entry);
}
////////////////////////////////////////////////////////////////////////////////
/// Return entry number corresponding to major and minor number.
/// Note that this function returns only the entry number, not the data
/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
/// the BuildIndex function has created a table of Long64_t* of sorted values
/// corresponding to val = major<<31 + minor;
/// The function performs binary search in this sorted table.
/// If it finds a pair that matches val, it returns directly the
/// index in the table.
/// If an entry corresponding to major and minor is not found, the function
/// returns the index of the major,minor pair immediately lower than the
/// requested value, ie it will return -1 if the pair is lower than
/// the first entry in the index.
///
/// See also GetEntryNumberWithIndex
Long64_t TTree::GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor) const
{
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithBestIndex(major, minor);
}
////////////////////////////////////////////////////////////////////////////////
/// Return entry number corresponding to major and minor number.
/// Note that this function returns only the entry number, not the data
/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
/// the BuildIndex function has created a table of Long64_t* of sorted values
/// corresponding to val = major<<31 + minor;
/// The function performs binary search in this sorted table.
/// If it finds a pair that matches val, it returns directly the
/// index in the table, otherwise it returns -1.
///
/// See also GetEntryNumberWithBestIndex
Long64_t TTree::GetEntryNumberWithIndex(Long64_t major, Long64_t minor) const
{
if (!fTreeIndex) {
return -1;
}
return fTreeIndex->GetEntryNumberWithIndex(major, minor);
}
////////////////////////////////////////////////////////////////////////////////
/// Read entry corresponding to major and minor number.
///
/// The function returns the total number of bytes read.
/// If the Tree has friend trees, the corresponding entry with
/// the index values (major,minor) is read. Note that the master Tree
/// and its friend may have different entry serial numbers corresponding
/// to (major,minor).
Int_t TTree::GetEntryWithIndex(Int_t major, Int_t minor)
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kGetEntryWithIndex & fFriendLockStatus) {
return 0;
}
Long64_t serial = GetEntryNumberWithIndex(major, minor);
if (serial < 0) {
return -1;
}
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
Int_t i;
Int_t nbytes = 0;
fReadEntry = serial;
TBranch *branch;
Int_t nbranches = fBranches.GetEntriesFast();
Int_t nb;
for (i = 0; i < nbranches; ++i) {
branch = (TBranch*)fBranches.UncheckedAt(i);
nb = branch->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
// GetEntry in list of friends
if (!fFriends) return nbytes;
TFriendLock lock(this,kGetEntryWithIndex);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *t = fe->GetTree();
if (t) {
serial = t->GetEntryNumberWithIndex(major,minor);
if (serial <0) return -nbytes;
nb = t->GetEntry(serial);
if (nb < 0) return nb;
nbytes += nb;
}
}
return nbytes;
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the TTree friend whose name or alias is 'friendname.
TTree* TTree::GetFriend(const char *friendname) const
{
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriend & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (strcmp(friendname,fe->GetName())==0
|| strcmp(friendname,fe->GetTreeName())==0) {
return fe->GetTree();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree *res = fe->GetTree()->GetFriend(friendname);
if (res) {
return res;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// If the 'tree' is a friend, this method returns its alias name.
///
/// This alias is an alternate name for the tree.
///
/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
/// to specify in which particular tree the branch or leaf can be found if
/// the friend trees have branches or leaves with the same name as the master
/// tree.
///
/// It can also be used in conjunction with an alias created using
/// TTree::SetAlias in a TTreeFormula, e.g.:
/// ~~~ {.cpp}
/// maintree->Draw("treealias.fPx - treealias.myAlias");
/// ~~~
/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
/// was created using TTree::SetAlias on the friend tree.
///
/// However, note that 'treealias.myAlias' will be expanded literally,
/// without remembering that it comes from the aliased friend and thus
/// the branch name might not be disambiguated properly, which means
/// that you may not be able to take advantage of this feature.
///
const char* TTree::GetFriendAlias(TTree* tree) const
{
if ((tree == this) || (tree == GetTree())) {
return 0;
}
// We already have been visited while recursively
// looking through the friends tree, let's return.
if (kGetFriendAlias & fFriendLockStatus) {
return 0;
}
if (!fFriends) {
return 0;
}
TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* t = fe->GetTree();
if (t == tree) {
return fe->GetName();
}
// Case of a chain:
if (t && t->GetTree() == tree) {
return fe->GetName();
}
}
// After looking at the first level,
// let's see if it is a friend of friends.
nextf.Reset();
fe = 0;
while ((fe = (TFriendElement*) nextf())) {
const char* res = fe->GetTree()->GetFriendAlias(tree);
if (res) {
return res;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the current set of IO settings
ROOT::TIOFeatures TTree::GetIOFeatures() const
{
return fIOFeatures;
}
////////////////////////////////////////////////////////////////////////////////
/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
TIterator* TTree::GetIteratorOnAllLeaves(Bool_t dir)
{
return new TTreeFriendLeafIter(this, dir);
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the 1st Leaf named name in any Branch of this
/// Tree or any branch in the list of friend trees.
///
/// The leaf name can contain the name of a friend tree with the
/// syntax: friend_dir_and_tree.full_leaf_name
/// the friend_dir_and_tree can be of the form:
/// ~~~ {.cpp}
/// TDirectoryName/TreeName
/// ~~~
TLeaf* TTree::GetLeafImpl(const char* branchname, const char *leafname)
{
TLeaf *leaf = 0;
if (branchname) {
TBranch *branch = FindBranch(branchname);
if (branch) {
leaf = branch->GetLeaf(leafname);
if (leaf) {
return leaf;
}
}
}
TIter nextl(GetListOfLeaves());
while ((leaf = (TLeaf*)nextl())) {
if (strcmp(leaf->GetName(),leafname)) continue;
if (branchname) {
UInt_t nbch = strlen(branchname);
TBranch *br = leaf->GetBranch();
const char* brname = br->GetName();
TBranch *mother = br->GetMother();
if (strncmp(brname,branchname,nbch)) {
if (mother != br) {
const char *mothername = mother->GetName();
UInt_t motherlen = strlen(mothername);
if (nbch > motherlen && strncmp(mothername,branchname,motherlen)==0 && (mothername[motherlen-1]=='.' || branchname[motherlen]=='.')) {
// The left part of the requested name match the name of the mother, let's see if the right part match the name of the branch.
if (strncmp(brname,branchname+motherlen+1,nbch-motherlen-1)) {
// No it does not
continue;
} // else we have match so we can proceed.
} else {
// no match
continue;
}
} else {
continue;
}
}
// The start of the branch name is identical to the content
// of 'aname' before the first '/'.
// Let's make sure that it is not longer (we are trying
// to avoid having jet2/value match the branch jet23
if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
continue;
}
}
return leaf;
}
if (!fFriends) return 0;
TFriendLock lock(this,kGetLeaf);
TIter next(fFriends);
TFriendElement *fe;
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t) {
leaf = t->GetLeaf(leafname);
if (leaf) return leaf;
}
}
//second pass in the list of friends when the leaf name
//is prefixed by the tree name
TString strippedArg;
next.Reset();
while ((fe = (TFriendElement*)next())) {
TTree *t = fe->GetTree();
if (t==0) continue;
char *subname = (char*)strstr(leafname,fe->GetName());
if (subname != leafname) continue;
Int_t l = strlen(fe->GetName());
subname += l;
if (*subname != '.') continue;
subname++;
strippedArg += subname;
leaf = t->GetLeaf(branchname,subname);
if (leaf) return leaf;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to the 1st Leaf named name in any Branch of this
/// Tree or any branch in the list of friend trees.
///
/// The leaf name can contain the name of a friend tree with the
/// syntax: friend_dir_and_tree.full_leaf_name
/// the friend_dir_and_tree can be of the form:
///
/// TDirectoryName/TreeName
TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
{
if (leafname == 0) return 0;
// We already have been visited while recursively looking
// through the friends tree, let return
if (kGetLeaf & fFriendLockStatus) {
return 0;
}
return GetLeafImpl(branchname,leafname);
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to first leaf named \param[name] in any branch of this
/// tree or its friend trees.
///
/// \param[name] may be in the form 'branch/leaf'
///
TLeaf* TTree::GetLeaf(const char *name)
{
// Return nullptr if name is invalid or if we have
// already been visited while searching friend trees
if (!name || (kGetLeaf & fFriendLockStatus))
return nullptr;
std::string path(name);
const auto sep = path.find_last_of("/");
if (sep != std::string::npos)
return GetLeafImpl(path.substr(0, sep).c_str(), name+sep+1);
return GetLeafImpl(nullptr, name);
}
////////////////////////////////////////////////////////////////////////////////
/// Return maximum of column with name columname.
/// if the Tree has an associated TEventList or TEntryList, the maximum
/// is computed for the entries in this list.
Double_t TTree::GetMaximum(const char* columname)
{
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
TBranch* branch = leaf->GetBranch();
Double_t cmax = -DBL_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0; j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val > cmax) {
cmax = val;
}
}
}
return cmax;
}
////////////////////////////////////////////////////////////////////////////////
/// Static function which returns the tree file size limit in bytes.
Long64_t TTree::GetMaxTreeSize()
{
return fgMaxTreeSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Return minimum of column with name columname.
/// if the Tree has an associated TEventList or TEntryList, the minimum
/// is computed for the entries in this list.
Double_t TTree::GetMinimum(const char* columname)
{
TLeaf* leaf = this->GetLeaf(columname);
if (!leaf) {
return 0;
}
// create cache if wanted
if (fCacheDoAutoInit)
SetCacheSizeAux();
TBranch* branch = leaf->GetBranch();
Double_t cmin = DBL_MAX;
for (Long64_t i = 0; i < fEntries; ++i) {
Long64_t entryNumber = this->GetEntryNumber(i);
if (entryNumber < 0) break;
branch->GetEntry(entryNumber);
for (Int_t j = 0;j < leaf->GetLen(); ++j) {
Double_t val = leaf->GetValue(j);
if (val < cmin) {
cmin = val;
}
}
}
return cmin;
}
////////////////////////////////////////////////////////////////////////////////
/// Load the TTreePlayer (if not already done).
TVirtualTreePlayer* TTree::GetPlayer()
{
if (fPlayer) {
return fPlayer;
}
fPlayer = TVirtualTreePlayer::TreePlayer(this);
return fPlayer;
}
////////////////////////////////////////////////////////////////////////////////
/// Find and return the TTreeCache registered with the file and which may
/// contain branches for us.
TTreeCache *TTree::GetReadCache(TFile *file) const
{
TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(this));
if (pe && pe->GetTree() != this)
pe = nullptr;
return pe;
}
////////////////////////////////////////////////////////////////////////////////
/// Find and return the TTreeCache registered with the file and which may
/// contain branches for us. If create is true and there is no cache
/// a new cache is created with default size.
TTreeCache *TTree::GetReadCache(TFile *file, Bool_t create)
{
TTreeCache *pe = GetReadCache(file);
if (create && !pe) {
if (fCacheDoAutoInit)
SetCacheSizeAux(kTRUE, -1);
pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(this));
if (pe && pe->GetTree() != this) pe = 0;
}
return pe;
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the list containing user objects associated to this tree.
///
/// The list is automatically created if it does not exist.
///
/// WARNING: By default the TTree destructor will delete all objects added
/// to this list. If you do not want these objects to be deleted,
/// call:
///
/// mytree->GetUserInfo()->Clear();
///
/// before deleting the tree.
TList* TTree::GetUserInfo()
{
if (!fUserInfo) {
fUserInfo = new TList();
fUserInfo->SetName("UserInfo");
}
return fUserInfo;
}
////////////////////////////////////////////////////////////////////////////////
/// Appends the cluster range information stored in 'fromtree' to this tree,
/// including the value of fAutoFlush.
///
/// This is used when doing a fast cloning (by TTreeCloner).
/// See also fAutoFlush and fAutoSave if needed.
void TTree::ImportClusterRanges(TTree *fromtree)
{
Long64_t autoflush = fromtree->GetAutoFlush();
if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
// nothing to do
} else if (fNClusterRange || fromtree->fNClusterRange) {
Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
if (newsize > fMaxClusterRange) {
if (fMaxClusterRange) {
fClusterRangeEnd = (Long64_t*)TStorage::ReAlloc(fClusterRangeEnd,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fClusterSize = (Long64_t*)TStorage::ReAlloc(fClusterSize,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fMaxClusterRange = newsize;
} else {
fMaxClusterRange = newsize;
fClusterRangeEnd = new Long64_t[fMaxClusterRange];
fClusterSize = new Long64_t[fMaxClusterRange];
}
}
if (fEntries) {
fClusterRangeEnd[fNClusterRange] = fEntries - 1;
fClusterSize[fNClusterRange] = fAutoFlush<0 ? 0 : fAutoFlush;
++fNClusterRange;
}
for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
fClusterRangeEnd[fNClusterRange] = fEntries + fromtree->fClusterRangeEnd[i];
fClusterSize[fNClusterRange] = fromtree->fClusterSize[i];
++fNClusterRange;
}
fAutoFlush = autoflush;
} else {
SetAutoFlush( autoflush );
}
Long64_t autosave = GetAutoSave();
if (autoflush > 0 && autosave > 0) {
SetAutoSave( autoflush*(autosave/autoflush) );
}
}
////////////////////////////////////////////////////////////////////////////////
/// Keep a maximum of fMaxEntries in memory.
void TTree::KeepCircular()
{
Int_t nb = fBranches.GetEntriesFast();
Long64_t maxEntries = fMaxEntries - (fMaxEntries / 10);
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->KeepCircular(maxEntries);
}
if (fNClusterRange) {
Long64_t entriesOffset = fEntries - maxEntries;
Int_t oldsize = fNClusterRange;
for(Int_t i = 0, j = 0; j < oldsize; ++j) {
if (fClusterRangeEnd[j] > entriesOffset) {
fClusterRangeEnd[i] = fClusterRangeEnd[j] - entriesOffset;
++i;
} else {
--fNClusterRange;
}
}
}
fEntries = maxEntries;
fReadEntry = -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
///
/// If maxmemory is non null and positive SetMaxVirtualSize is called
/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
/// The function returns the total number of baskets read into memory
/// if negative an error occurred while loading the branches.
/// This method may be called to force branch baskets in memory
/// when random access to branch entries is required.
/// If random access to only a few branches is required, you should
/// call directly TBranch::LoadBaskets.
Int_t TTree::LoadBaskets(Long64_t maxmemory)
{
if (maxmemory > 0) SetMaxVirtualSize(maxmemory);
TIter next(GetListOfLeaves());
TLeaf *leaf;
Int_t nimported = 0;
while ((leaf=(TLeaf*)next())) {
nimported += leaf->GetBranch()->LoadBaskets();//break;
}
return nimported;
}
////////////////////////////////////////////////////////////////////////////////
/// Set current entry.
///
/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
/// Returns -6 if an error occours in the notification callback (just as TChain::LoadTree()).
///
/// Note: This function is overloaded in TChain.
///
Long64_t TTree::LoadTree(Long64_t entry)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kLoadTree & fFriendLockStatus) {
// We need to return a negative value to avoid a circular list of friend
// to think that there is always an entry somewhere in the list.
return -1;
}
// create cache if wanted
if (fCacheDoAutoInit && entry >=0)
SetCacheSizeAux();
if (fNotify) {
if (fReadEntry < 0) {
fNotify->Notify();
}
}
fReadEntry = entry;
Bool_t friendHasEntry = kFALSE;
if (fFriends) {
// Set current entry in friends as well.
//
// An alternative would move this code to each of the
// functions calling LoadTree (and to overload a few more).
Bool_t needUpdate = kFALSE;
{
// This scope is need to insure the lock is released at the right time
TIter nextf(fFriends);
TFriendLock lock(this, kLoadTree);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
if (fe->TestBit(TFriendElement::kFromChain)) {
// This friend element was added by the chain that owns this
// tree, the chain will deal with loading the correct entry.
continue;
}
TTree* friendTree = fe->GetTree();
if (friendTree == 0) {
// Somehow we failed to retrieve the friend TTree.
} else if (friendTree->IsA() == TTree::Class()) {
// Friend is actually a tree.
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
} else {
// Friend is actually a chain.
// FIXME: This logic should be in the TChain override.
Int_t oldNumber = friendTree->GetTreeNumber();
if (friendTree->LoadTreeFriend(entry, this) >= 0) {
friendHasEntry = kTRUE;
}
Int_t newNumber = friendTree->GetTreeNumber();
if (oldNumber != newNumber) {
// We can not just compare the tree pointers because they could be reused.
// So we compare the tree number instead.
needUpdate = kTRUE;
}
}
} // for each friend
}
if (needUpdate) {
//update list of leaves in all TTreeFormula of the TTreePlayer (if any)
if (fPlayer) {
fPlayer->UpdateFormulaLeaves();
}
//Notify user if requested
if (fNotify) {
if(!fNotify->Notify()) return -6;
}
}
}
if ((fReadEntry >= fEntries) && !friendHasEntry) {
fReadEntry = -1;
return -2;
}
return fReadEntry;
}
////////////////////////////////////////////////////////////////////////////////
/// Load entry on behalf of our master tree, we may use an index.
///
/// Called by LoadTree() when the masterTree looks for the entry
/// number in a friend tree (us) corresponding to the passed entry
/// number in the masterTree.
///
/// If we have no index, our entry number and the masterTree entry
/// number are the same.
///
/// If we *do* have an index, we must find the (major, minor) value pair
/// in masterTree to locate our corresponding entry.
///
Long64_t TTree::LoadTreeFriend(Long64_t entry, TTree* masterTree)
{
if (!fTreeIndex) {
return LoadTree(entry);
}
return LoadTree(fTreeIndex->GetEntryNumberFriend(masterTree));
}
////////////////////////////////////////////////////////////////////////////////
/// Generate a skeleton analysis class for this tree.
///
/// The following files are produced: classname.h and classname.C.
/// If classname is 0, classname will be called "nameoftree".
///
/// The generated code in classname.h includes the following:
///
/// - Identification of the original tree and the input file name.
/// - Definition of an analysis class (data members and member functions).
/// - The following member functions:
/// - constructor (by default opening the tree file),
/// - GetEntry(Long64_t entry),
/// - Init(TTree* tree) to initialize a new TTree,
/// - Show(Long64_t entry) to read and dump entry.
///
/// The generated code in classname.C includes only the main
/// analysis function Loop.
///
/// To use this function:
///
/// - Open your tree file (eg: TFile f("myfile.root");)
/// - T->MakeClass("MyClass");
///
/// where T is the name of the TTree in file myfile.root,
/// and MyClass.h, MyClass.C the name of the files created by this function.
/// In a ROOT session, you can do:
/// ~~~ {.cpp}
/// root > .L MyClass.C
/// root > MyClass* t = new MyClass;
/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
/// root > t->Show(); // Show values of entry 12.
/// root > t->Show(16); // Read and show values of entry 16.
/// root > t->Loop(); // Loop on all entries.
/// ~~~
/// NOTE: Do not use the code generated for a single TTree which is part
/// of a TChain to process that entire TChain. The maximum dimensions
/// calculated for arrays on the basis of a single TTree from the TChain
/// might be (will be!) too small when processing all of the TTrees in
/// the TChain. You must use myChain.MakeClass() to generate the code,
/// not myTree.MakeClass(...).
Int_t TTree::MakeClass(const char* classname, Option_t* option)
{
GetPlayer();
if (!fPlayer) {
return 0;
}
return fPlayer->MakeClass(classname, option);
}
////////////////////////////////////////////////////////////////////////////////
/// Generate a skeleton function for this tree.
///
/// The function code is written on filename.
/// If filename is 0, filename will be called nameoftree.C
///
/// The generated code includes the following:
/// - Identification of the original Tree and Input file name,
/// - Opening the Tree file,
/// - Declaration of Tree variables,
/// - Setting of branches addresses,
/// - A skeleton for the entry loop.
///
/// To use this function:
///
/// - Open your Tree file (eg: TFile f("myfile.root");)
/// - T->MakeCode("MyAnalysis.C");
///
/// where T is the name of the TTree in file myfile.root
/// and MyAnalysis.C the name of the file created by this function.
///
/// NOTE: Since the implementation of this function, a new and better
/// function TTree::MakeClass() has been developed.
Int_t TTree::MakeCode(const char* filename)
{
Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeCode(filename);
}
////////////////////////////////////////////////////////////////////////////////
/// Generate a skeleton analysis class for this Tree using TBranchProxy.
///
/// TBranchProxy is the base of a class hierarchy implementing an
/// indirect access to the content of the branches of a TTree.
///
/// "proxyClassname" is expected to be of the form:
/// ~~~ {.cpp}
/// [path/]fileprefix
/// ~~~
/// The skeleton will then be generated in the file:
/// ~~~ {.cpp}
/// fileprefix.h
/// ~~~
/// located in the current directory or in 'path/' if it is specified.
/// The class generated will be named 'fileprefix'
///
/// "macrofilename" and optionally "cutfilename" are expected to point
/// to source files which will be included by the generated skeleton.
/// Method of the same name as the file(minus the extension and path)
/// will be called by the generated skeleton's Process method as follow:
/// ~~~ {.cpp}
/// [if (cutfilename())] htemp->Fill(macrofilename());
/// ~~~
/// "option" can be used select some of the optional features during
/// the code generation. The possible options are:
///
/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
///
/// 'maxUnrolling' controls how deep in the class hierarchy does the
/// system 'unroll' classes that are not split. Unrolling a class
/// allows direct access to its data members (this emulates the behavior
/// of TTreeFormula).
///
/// The main features of this skeleton are:
///
/// * on-demand loading of branches
/// * ability to use the 'branchname' as if it was a data member
/// * protection against array out-of-bounds errors
/// * ability to use the branch data as an object (when the user code is available)
///
/// For example with Event.root, if
/// ~~~ {.cpp}
/// Double_t somePx = fTracks.fPx[2];
/// ~~~
/// is executed by one of the method of the skeleton,
/// somePx will updated with the current value of fPx of the 3rd track.
///
/// Both macrofilename and the optional cutfilename are expected to be
/// the name of source files which contain at least a free standing
/// function with the signature:
/// ~~~ {.cpp}
/// x_t macrofilename(); // i.e function with the same name as the file
/// ~~~
/// and
/// ~~~ {.cpp}
/// y_t cutfilename(); // i.e function with the same name as the file
/// ~~~
/// x_t and y_t needs to be types that can convert respectively to a double
/// and a bool (because the skeleton uses:
///
/// if (cutfilename()) htemp->Fill(macrofilename());
///
/// These two functions are run in a context such that the branch names are
/// available as local variables of the correct (read-only) type.
///
/// Note that if you use the same 'variable' twice, it is more efficient
/// to 'cache' the value. For example:
/// ~~~ {.cpp}
/// Int_t n = fEventNumber; // Read fEventNumber
/// if (n<10 || n>10) { ... }
/// ~~~
/// is more efficient than
/// ~~~ {.cpp}
/// if (fEventNumber<10 || fEventNumber>10)
/// ~~~
/// Also, optionally, the generated selector will also call methods named
/// macrofilename_methodname in each of 6 main selector methods if the method
/// macrofilename_methodname exist (Where macrofilename is stripped of its
/// extension).
///
/// Concretely, with the script named h1analysisProxy.C,
///
/// - The method calls the method (if it exist)
/// - Begin -> void h1analysisProxy_Begin(TTree*);
/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
/// - Notify -> Bool_t h1analysisProxy_Notify();
/// - Process -> Bool_t h1analysisProxy_Process(Long64_t);
/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
/// - Terminate -> void h1analysisProxy_Terminate();
///
/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
/// it is included before the declaration of the proxy class. This can
/// be used in particular to insure that the include files needed by
/// the macro file are properly loaded.
///
/// The default histogram is accessible via the variable named 'htemp'.
///
/// If the library of the classes describing the data in the branch is
/// loaded, the skeleton will add the needed `include` statements and
/// give the ability to access the object stored in the branches.
///
/// To draw px using the file hsimple.root (generated by the
/// hsimple.C tutorial), we need a file named hsimple.cxx:
/// ~~~ {.cpp}
/// double hsimple() {
/// return px;
/// }
/// ~~~
/// MakeProxy can then be used indirectly via the TTree::Draw interface
/// as follow:
/// ~~~ {.cpp}
/// new TFile("hsimple.root")
/// ntuple->Draw("hsimple.cxx");
/// ~~~
/// A more complete example is available in the tutorials directory:
/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
/// which reimplement the selector found in h1analysis.C
Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
{
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeProxy(proxyClassname,macrofilename,cutfilename,option,maxUnrolling);
}
////////////////////////////////////////////////////////////////////////////////
/// Generate skeleton selector class for this tree.
///
/// The following files are produced: selector.h and selector.C.
/// If selector is 0, the selector will be called "nameoftree".
/// The option can be used to specify the branches that will have a data member.
/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
/// members and branch pointers instead of TTreeReaders).
/// - If option is empty, readers will be generated for each leaf.
/// - If option is "@", readers will be generated for the topmost branches.
/// - Individual branches can also be picked by their name:
/// - "X" generates readers for leaves of X.
/// - "@X" generates a reader for X as a whole.
/// - "@X;Y" generates a reader for X as a whole and also readers for the
/// leaves of Y.
/// - For further examples see the figure below.
///
/// \image html ttree_makeselector_option_examples.png
///
/// The generated code in selector.h includes the following:
/// - Identification of the original Tree and Input file name
/// - Definition of selector class (data and functions)
/// - The following class functions:
/// - constructor and destructor
/// - void Begin(TTree *tree)
/// - void SlaveBegin(TTree *tree)
/// - void Init(TTree *tree)
/// - Bool_t Notify()
/// - Bool_t Process(Long64_t entry)
/// - void Terminate()
/// - void SlaveTerminate()
///
/// The class selector derives from TSelector.
/// The generated code in selector.C includes empty functions defined above.
///
/// To use this function:
///
/// - connect your Tree file (eg: `TFile f("myfile.root");`)
/// - `T->MakeSelector("myselect");`
///
/// where T is the name of the Tree in file myfile.root
/// and myselect.h, myselect.C the name of the files created by this function.
/// In a ROOT session, you can do:
/// ~~~ {.cpp}
/// root > T->Process("myselect.C")
/// ~~~
Int_t TTree::MakeSelector(const char* selector, Option_t* option)
{
TString opt(option);
if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
return MakeClass(selector, "selector");
} else {
GetPlayer();
if (!fPlayer) return 0;
return fPlayer->MakeReader(selector, option);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Check if adding nbytes to memory we are still below MaxVirtualsize.
Bool_t TTree::MemoryFull(Int_t nbytes)
{
if ((fTotalBuffers + nbytes) < fMaxVirtualSize) {
return kFALSE;
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Static function merging the trees in the TList into a new tree.
///
/// Trees in the list can be memory or disk-resident trees.
/// The new tree is created in the current directory (memory if gROOT).
TTree* TTree::MergeTrees(TList* li, Option_t* options)
{
if (!li) return 0;
TIter next(li);
TTree *newtree = 0;
TObject *obj;
while ((obj=next())) {
if (!obj->InheritsFrom(TTree::Class())) continue;
TTree *tree = (TTree*)obj;
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
if (!newtree) {
newtree = (TTree*)tree->CloneTree();
if (!newtree) continue;
// Once the cloning is done, separate the trees,
// to avoid as many side-effects as possible
// The list of clones is guaranteed to exist since we
// just cloned the tree.
tree->GetListOfClones()->Remove(newtree);
tree->ResetBranchAddresses();
newtree->ResetBranchAddresses();
continue;
}
newtree->CopyAddresses(tree);
newtree->CopyEntries(tree,-1,options);
tree->ResetBranchAddresses(); // Disconnect from new tree.
}
if (newtree && newtree->GetTreeIndex()) {
newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
}
return newtree;
}
////////////////////////////////////////////////////////////////////////////////
/// Merge the trees in the TList into this tree.
///
/// Returns the total number of entries in the merged tree.
Long64_t TTree::Merge(TCollection* li, Option_t *options)
{
if (!li) return 0;
Long64_t storeAutoSave = fAutoSave;
// Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
// key would invalidate its iteration (or require costly measure to not use the deleted keys).
// Also since this is part of a merging operation, the output file is not as precious as in
// the general case since the input file should still be around.
fAutoSave = 0;
TIter next(li);
TTree *tree;
while ((tree = (TTree*)next())) {
if (tree==this) continue;
if (!tree->InheritsFrom(TTree::Class())) {
Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
fAutoSave = storeAutoSave;
return -1;
}
Long64_t nentries = tree->GetEntries();
if (nentries == 0) continue;
CopyAddresses(tree);
CopyEntries(tree,-1,options);
tree->ResetBranchAddresses();
}
fAutoSave = storeAutoSave;
return GetEntries();
}
////////////////////////////////////////////////////////////////////////////////
/// Merge the trees in the TList into this tree.
/// If info->fIsFirst is true, first we clone this TTree info the directory
/// info->fOutputDirectory and then overlay the new TTree information onto
/// this TTree object (so that this TTree object is now the appropriate to
/// use for further merging).
///
/// Returns the total number of entries in the merged tree.
Long64_t TTree::Merge(TCollection* li, TFileMergeInfo *info)
{
const char *options = info ? info->fOptions.Data() : "";
if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
TDirectory::TContext ctxt(info->fOutputDirectory);
TIOFeatures saved_features = fIOFeatures;
if (info->fIOFeatures) {
fIOFeatures = *(info->fIOFeatures);
}
TTree *newtree = CloneTree(-1, options);
fIOFeatures = saved_features;
if (newtree) {
newtree->Write();
delete newtree;
}
// Make sure things are really written out to disk before attempting any reading.
info->fOutputDirectory->GetFile()->Flush();
info->fOutputDirectory->ReadTObject(this,this->GetName());
}
if (!li) return 0;
Long64_t storeAutoSave = fAutoSave;
// Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
// key would invalidate its iteration (or require costly measure to not use the deleted keys).
// Also since this is part of a merging operation, the output file is not as precious as in
// the general case since the input file should still be around.
fAutoSave = 0;
TIter next(li);
TTree *tree;
while ((tree = (TTree*)next())) {
if (tree==this) continue;
if (!tree->InheritsFrom(TTree::Class())) {
Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
fAutoSave = storeAutoSave;
return -1;
}
// Copy MakeClass status.
tree->SetMakeClass(fMakeClass);
// Copy branch addresses.
CopyAddresses(tree);
CopyEntries(tree,-1,options);
tree->ResetBranchAddresses();
}
fAutoSave = storeAutoSave;
return GetEntries();
}
////////////////////////////////////////////////////////////////////////////////
/// Move a cache from a file to the current file in dir.
/// if src is null no operation is done, if dir is null or there is no
/// current file the cache is deleted.
void TTree::MoveReadCache(TFile *src, TDirectory *dir)
{
if (!src) return;
TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : 0;
if (src == dst) return;
TTreeCache *pf = GetReadCache(src);
if (dst) {
src->SetCacheRead(0,this);
dst->SetCacheRead(pf, this);
} else {
if (pf) {
pf->WaitFinishPrefetch();
}
src->SetCacheRead(0,this);
delete pf;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Function called when loading a new class library.
Bool_t TTree::Notify()
{
TIter next(GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) next())) {
leaf->Notify();
leaf->GetBranch()->Notify();
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// This function may be called after having filled some entries in a Tree.
/// Using the information in the existing branch buffers, it will reassign
/// new branch buffer sizes to optimize time and memory.
///
/// The function computes the best values for branch buffer sizes such that
/// the total buffer sizes is less than maxMemory and nearby entries written
/// at the same time.
/// In case the branch compression factor for the data written so far is less
/// than compMin, the compression is disabled.
///
/// if option ="d" an analysis report is printed.
void TTree::OptimizeBaskets(ULong64_t maxMemory, Float_t minComp, Option_t *option)
{
//Flush existing baskets if the file is writable
if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
TString opt( option );
opt.ToLower();
Bool_t pDebug = opt.Contains("d");
TObjArray *leaves = this->GetListOfLeaves();
Int_t nleaves = leaves->GetEntries();
Double_t treeSize = (Double_t)this->GetTotBytes();
if (nleaves == 0 || treeSize == 0) {
// We're being called too early, we really have nothing to do ...
return;
}
Double_t aveSize = treeSize/nleaves;
UInt_t bmin = 512;
UInt_t bmax = 256000;
Double_t memFactor = 1;
Int_t i, oldMemsize,newMemsize,oldBaskets,newBaskets;
i = oldMemsize = newMemsize = oldBaskets = newBaskets = 0;
//we make two passes
//one pass to compute the relative branch buffer sizes
//a second pass to compute the absolute values
for (Int_t pass =0;pass<2;pass++) {
oldMemsize = 0; //to count size of baskets in memory with old buffer size
newMemsize = 0; //to count size of baskets in memory with new buffer size
oldBaskets = 0; //to count number of baskets with old buffer size
newBaskets = 0; //to count number of baskets with new buffer size
for (i=0;i<nleaves;i++) {
TLeaf *leaf = (TLeaf*)leaves->At(i);
TBranch *branch = leaf->GetBranch();
Double_t totBytes = (Double_t)branch->GetTotBytes();
Double_t idealFactor = totBytes/aveSize;
UInt_t sizeOfOneEntry;
if (branch->GetEntries() == 0) {
// There is no data, so let's make a guess ...
sizeOfOneEntry = aveSize;
} else {
sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
}
Int_t oldBsize = branch->GetBasketSize();
oldMemsize += oldBsize;
oldBaskets += 1+Int_t(totBytes/oldBsize);
Int_t nb = branch->GetListOfBranches()->GetEntries();
if (nb > 0) {
newBaskets += 1+Int_t(totBytes/oldBsize);
continue;
}
Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
if (bsize < 0) bsize = bmax;
if (bsize > bmax) bsize = bmax;
UInt_t newBsize = UInt_t(bsize);
if (pass) { // only on the second pass so that it doesn't interfere with scaling
// If there is an entry offset, it will be stored in the same buffer as the object data; hence,
// we must bump up the size of the branch to account for this extra footprint.
// If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
// the value of GetEntries().
Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
if (branch->GetEntryOffsetLen()) {
newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
}
// We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
// with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
// resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
// at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
// stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
// structures we found a factor of 2 fewer baskets needed in the new scheme.
// rounds up, increases basket size to ensure all entries fit into single basket as intended
newBsize = newBsize - newBsize%512 + 512;
}
if (newBsize < sizeOfOneEntry) newBsize = sizeOfOneEntry;
if (newBsize < bmin) newBsize = bmin;
if (newBsize > 10000000) newBsize = bmax;
if (pass) {
if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
branch->SetBasketSize(newBsize);
}
newMemsize += newBsize;
// For this number to be somewhat accurate when newBsize is 'low'
// we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
// not let it be lower than 100+TBranch::fEntryOffsetLen.
newBaskets += 1+Int_t(totBytes/newBsize);
if (pass == 0) continue;
//Reset the compression level in case the compression factor is small
Double_t comp = 1;
if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
if (comp > 1 && comp < minComp) {
if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
branch->SetCompressionSettings(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal);
}
}
// coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
memFactor = Double_t(maxMemory)/Double_t(newMemsize);
if (memFactor > 100) memFactor = 100;
Double_t bmin_new = bmin*memFactor;
Double_t bmax_new = bmax*memFactor;
static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
// Really, really never go lower than 8 bytes (we use this number
// so that the calculation of the number of basket is consistent
// but in fact SetBasketSize will not let the size go below
// TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
// (The 2nd part being a slight over estimate of the key length.
static const UInt_t hardmin = 8;
bmin = (bmin_new > hardmax) ? hardmax : ( bmin_new < hardmin ? hardmin : (UInt_t)bmin_new );
bmax = (bmax_new > hardmax) ? bmin : (UInt_t)bmax_new;
}
if (pDebug) {
Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Interface to the Principal Components Analysis class.
///
/// Create an instance of TPrincipal
///
/// Fill it with the selected variables
///
/// - if option "n" is specified, the TPrincipal object is filled with
/// normalized variables.
/// - If option "p" is specified, compute the principal components
/// - If option "p" and "d" print results of analysis
/// - If option "p" and "h" generate standard histograms
/// - If option "p" and "c" generate code of conversion functions
/// - return a pointer to the TPrincipal object. It is the user responsibility
/// - to delete this object.
/// - The option default value is "np"
///
/// see TTree::Draw for explanation of the other parameters.
///
/// The created object is named "principal" and a reference to it
/// is added to the list of specials Root objects.
/// you can retrieve a pointer to the created object via:
/// ~~~ {.cpp}
/// TPrincipal *principal =
/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
/// ~~~
TPrincipal* TTree::Principal(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Principal(varexp, selection, option, nentries, firstentry);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Print a summary of the tree contents.
///
/// - If option contains "all" friend trees are also printed.
/// - If option contains "toponly" only the top level branches are printed.
/// - If option contains "clusters" information about the cluster of baskets is printed.
///
/// Wildcarding can be used to print only a subset of the branches, e.g.,
/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
void TTree::Print(Option_t* option) const
{
// We already have been visited while recursively looking
// through the friends tree, let's return.
if (kPrint & fFriendLockStatus) {
return;
}
Int_t s = 0;
Int_t skey = 0;
if (fDirectory) {
TKey* key = fDirectory->GetKey(GetName());
if (key) {
skey = key->GetKeylen();
s = key->GetNbytes();
}
}
Long64_t total = skey;
Long64_t zipBytes = GetZipBytes();
if (zipBytes > 0) {
total += GetTotBytes();
}
TBufferFile b(TBuffer::kWrite, 10000);
TTree::Class()->WriteBuffer(b, (TTree*) this);
total += b.Length();
Long64_t file = zipBytes + s;
Float_t cx = 1;
if (zipBytes) {
cx = (GetTotBytes() + 0.00001) / zipBytes;
}
Printf("******************************************************************************");
Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
Printf("* : : Tree compression factor = %6.2f *", cx);
Printf("******************************************************************************");
// Avoid many check of option validity
if (option == nullptr)
option = "";
if (strncmp(option,"clusters",strlen("clusters"))==0) {
Printf("%-16s %-16s %-16s %5s",
"Cluster Range #", "Entry Start", "Last Entry", "Size");
Int_t index= 0;
Long64_t clusterRangeStart = 0;
if (fNClusterRange) {
for( ; index < fNClusterRange; ++index) {
Printf("%-16d %-16lld %-16lld %5lld",
index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
clusterRangeStart = fClusterRangeEnd[index] + 1;
}
}
Printf("%-16d %-16lld %-16lld %5lld",
index, clusterRangeStart, fEntries - 1, fAutoFlush);
return;
}
Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
Int_t l;
TBranch* br = 0;
TLeaf* leaf = 0;
if (strstr(option, "toponly")) {
Long64_t *count = new Long64_t[nl];
Int_t keep =0;
for (l=0;l<nl;l++) {
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
if (strchr(br->GetName(),'.')) {
count[l] = -1;
count[keep] += br->GetZipBytes();
} else {
keep = l;
count[keep] = br->GetZipBytes();
}
}
for (l=0;l<nl;l++) {
if (count[l] < 0) continue;
leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
br = leaf->GetBranch();
Printf("branch: %-20s %9lld\n",br->GetName(),count[l]);
}
delete [] count;
} else {
TString reg = "*";
if (strlen(option) && strchr(option,'*')) reg = option;
TRegexp re(reg,kTRUE);
TIter next(const_cast<TTree*>(this)->GetListOfBranches());
TBranch::ResetCount();
while ((br= (TBranch*)next())) {
TString st = br->GetName();
st.ReplaceAll("/","_");
if (st.Index(re) == kNPOS) continue;
br->Print(option);
}
}
//print TRefTable (if one)
if (fBranchRef) fBranchRef->Print(option);
//print friends if option "all"
if (!fFriends || !strstr(option,"all")) return;
TIter nextf(fFriends);
TFriendLock lock(const_cast<TTree*>(this),kPrint);
TFriendElement *fr;
while ((fr = (TFriendElement*)nextf())) {
TTree * t = fr->GetTree();
if (t) t->Print(option);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Print statistics about the TreeCache for this tree.
/// Like:
/// ~~~ {.cpp}
/// ******TreeCache statistics for file: cms2.root ******
/// Reading 73921562 bytes in 716 transactions
/// Average transaction = 103.242405 Kbytes
/// Number of blocks in current cache: 202, total size : 6001193
/// ~~~
/// if option = "a" the list of blocks in the cache is printed
void TTree::PrintCacheStats(Option_t* option) const
{
TFile *f = GetCurrentFile();
if (!f) return;
TTreeCache *tc = GetReadCache(f);
if (tc) tc->Print(option);
}
////////////////////////////////////////////////////////////////////////////////
/// Process this tree executing the TSelector code in the specified filename.
/// The return value is -1 in case of error and TSelector::GetStatus() in
/// in case of success.
///
/// The code in filename is loaded (interpreted or compiled, see below),
/// filename must contain a valid class implementation derived from TSelector,
/// where TSelector has the following member functions:
///
/// - `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.
///
/// If filename is of the form file.C, the file will be interpreted.
///
/// If filename is of the form file.C++, the file file.C will be compiled
/// and dynamically loaded.
///
/// If filename is of the form file.C+, the file file.C will be compiled
/// and dynamically loaded. At next call, if file.C is older than file.o
/// and file.so, the file.C is not compiled, only file.so is loaded.
///
/// ## NOTE1
///
/// It may be more interesting to invoke directly the other Process function
/// accepting a TSelector* as argument.eg
/// ~~~ {.cpp}
/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
/// selector->CallSomeFunction(..);
/// mytree.Process(selector,..);
/// ~~~
/// ## NOTE2
//
/// One should not call this function twice with the same selector file
/// in the same script. If this is required, proceed as indicated in NOTE1,
/// by getting a pointer to the corresponding TSelector,eg
///
/// ### Workaround 1
///
/// ~~~ {.cpp}
/// void stubs1() {
/// TSelector *selector = TSelector::GetSelector("h1test.C");
/// TFile *f1 = new TFile("stubs_nood_le1.root");
/// TTree *h1 = (TTree*)f1->Get("h1");
/// h1->Process(selector);
/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
/// TTree *h2 = (TTree*)f2->Get("h1");
/// h2->Process(selector);
/// }
/// ~~~
/// or use ACLIC to compile the selector
///
/// ### Workaround 2
///
/// ~~~ {.cpp}
/// void stubs2() {
/// TFile *f1 = new TFile("stubs_nood_le1.root");
/// TTree *h1 = (TTree*)f1->Get("h1");
/// h1->Process("h1test.C+");
/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
/// TTree *h2 = (TTree*)f2->Get("h1");
/// h2->Process("h1test.C+");
/// }
/// ~~~
Long64_t TTree::Process(const char* filename, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Process(filename, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Process this tree executing the code in the specified selector.
/// The return value is -1 in case of error and TSelector::GetStatus() in
/// in case of success.
///
/// The TSelector class has the following member functions:
///
/// - `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.
///
/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
/// of the EventList, starting at firstentry, otherwise the loop is on the
/// specified Tree entries.
Long64_t TTree::Process(TSelector* selector, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Process(selector, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Make a projection of a tree using selections.
///
/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
/// projection of the tree will be filled in histogram hname.
/// Note that the dimension of hname must match with the dimension of varexp.
///
Long64_t TTree::Project(const char* hname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
TString var;
var.Form("%s>>%s", varexp, hname);
TString opt("goff");
if (option) {
opt.Form("%sgoff", option);
}
Long64_t nsel = Draw(var, selection, opt, nentries, firstentry);
return nsel;
}
////////////////////////////////////////////////////////////////////////////////
/// Loop over entries and return a TSQLResult object containing entries following selection.
TSQLResult* TTree::Query(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Query(varexp, selection, option, nentries, firstentry);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create or simply read branches from filename.
///
/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
/// is given in the first line of the file with a syntax like
/// ~~~ {.cpp}
/// A/D:Table[2]/F:Ntracks/I:astring/C
/// ~~~
/// otherwise branchDescriptor must be specified with the above syntax.
///
/// - If the type of the first variable is not specified, it is assumed to be "/F"
/// - If the type of any other variable is not specified, the type of the previous
/// variable is assumed. eg
/// - `x:y:z` (all variables are assumed of type "F"
/// - `x/D:y:z` (all variables are of type "D"
/// - `x:y/D:z` (x is type "F", y and z of type "D"
///
/// delimiter allows for the use of another delimiter besides whitespace.
/// This provides support for direct import of common data file formats
/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
/// branch description is taken from the first line in the file, but
/// delimiter is used for the branch names tokenization rather than ':'.
/// Note however that if the values in the first line do not use the
/// /[type] syntax, all variables are assumed to be of type "F".
/// If the filename ends with extensions .csv or .CSV and a delimiter is
/// not specified (besides ' '), the delimiter is automatically set to ','.
///
/// Lines in the input file starting with "#" are ignored. Leading whitespace
/// for each column data is skipped. Empty lines are skipped.
///
/// A TBranch object is created for each variable in the expression.
/// The total number of rows read from the file is returned.
///
/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
///
/// To fill a TTree with multiple input text files, proceed as indicated above
/// for the first input file and omit the second argument for subsequent calls
/// ~~~ {.cpp}
/// T.ReadFile("file1.dat","branch descriptor");
/// T.ReadFile("file2.dat");
/// ~~~
Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
{
std::ifstream in;
in.open(filename);
if (!in.good()) {
Error("ReadFile","Cannot open file: %s",filename);
return 0;
}
const char* ext = strrchr(filename, '.');
if(ext != NULL && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
delimiter = ',';
}
return ReadStream(in, branchDescriptor, delimiter);
}
////////////////////////////////////////////////////////////////////////////////
/// Determine which newline this file is using.
/// Return '\\r' for Windows '\\r\\n' as that already terminates.
char TTree::GetNewlineValue(std::istream &inputStream)
{
Long_t inPos = inputStream.tellg();
char newline = '\n';
while(1) {
char c = 0;
inputStream.get(c);
if(!inputStream.good()) {
Error("ReadStream","Error reading stream: no newline found.");
return 0;
}
if(c == newline) break;
if(c == '\r') {
newline = '\r';
break;
}
}
inputStream.clear();
inputStream.seekg(inPos);
return newline;
}
////////////////////////////////////////////////////////////////////////////////
/// Create or simply read branches from an input stream.
///
/// See reference information for TTree::ReadFile
Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
{
char newline = 0;
std::stringstream ss;
std::istream *inTemp;
Long_t inPos = inputStream.tellg();
if (!inputStream.good()) {
Error("ReadStream","Error reading stream");
return 0;
}
if (inPos == -1) {
ss << std::cin.rdbuf();
newline = GetNewlineValue(ss);
inTemp = &ss;
} else {
newline = GetNewlineValue(inputStream);
inTemp = &inputStream;
}
std::istream& in = *inTemp;
Long64_t nlines = 0;
TBranch *branch = 0;
Int_t nbranches = fBranches.GetEntries();
if (nbranches == 0) {
char *bdname = new char[4000];
char *bd = new char[100000];
Int_t nch = 0;
if (branchDescriptor) nch = strlen(branchDescriptor);
// branch Descriptor is null, read its definition from the first line in the file
if (!nch) {
do {
in.getline(bd, 100000, newline);
if (!in.good()) {
delete [] bdname;
delete [] bd;
Error("ReadStream","Error reading stream");
return 0;
}
char *cursor = bd;
while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
++cursor;
}
if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
break;
}
} while (true);
++nlines;
nch = strlen(bd);
} else {
strlcpy(bd,branchDescriptor,100000);
}
//parse the branch descriptor and create a branch for each element
//separated by ":"
void *address = &bd[90000];
char *bdcur = bd;
TString desc="", olddesc="F";
char bdelim = ':';
if(delimiter != ' ') {
bdelim = delimiter;
if (strchr(bdcur,bdelim)==0 && strchr(bdcur,':') != 0) {
// revert to the default
bdelim = ':';
}
}
while (bdcur) {
char *colon = strchr(bdcur,bdelim);
if (colon) *colon = 0;
strlcpy(bdname,bdcur,4000);
char *slash = strchr(bdname,'/');
if (slash) {
*slash = 0;
desc = bdcur;
olddesc = slash+1;
} else {
desc.Form("%s/%s",bdname,olddesc.Data());
}
char *bracket = strchr(bdname,'[');
if (bracket) {
*bracket = 0;
}
branch = new TBranch(this,bdname,address,desc.Data(),32000);
if (branch->IsZombie()) {
delete branch;
Warning("ReadStream","Illegal branch definition: %s",bdcur);
} else {
fBranches.Add(branch);
branch->SetAddress(0);
}
if (!colon)break;
bdcur = colon+1;
}
delete [] bdname;
delete [] bd;
}
nbranches = fBranches.GetEntries();
if (gDebug > 1) {
Info("ReadStream", "Will use branches:");
for (int i = 0 ; i < nbranches; ++i) {
TBranch* br = (TBranch*) fBranches.At(i);
Info("ReadStream", " %s: %s [%s]", br->GetName(),
br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
}
if (gDebug > 3) {
Info("ReadStream", "Dumping read tokens, format:");
Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
Info("ReadStream", " L: line number");
Info("ReadStream", " B: branch number");
Info("ReadStream", " gfbe: good / fail / bad / eof of token");
Info("ReadStream", " GFBE: good / fail / bad / eof of file");
Info("ReadStream", " T: Token being read");
}
}
//loop on all lines in the file
Long64_t nGoodLines = 0;
std::string line;
const char sDelimBuf[2] = { delimiter, 0 };
const char* sDelim = sDelimBuf;
if (delimiter == ' ') {
// ' ' really means whitespace
sDelim = "[ \t]";
}
while(in.good()) {
if (newline == '\r' && in.peek() == '\n') {
// Windows, skip '\n':
in.get();
}
std::getline(in, line, newline);
++nlines;
TString sLine(line);
sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
if (sLine.IsNull()) {
if (gDebug > 2) {
Info("ReadStream", "Skipping empty line number %lld", nlines);
}
continue; // silently skip empty lines
}
if (sLine[0] == '#') {
if (gDebug > 2) {
Info("ReadStream", "Skipping comment line number %lld: '%s'",
nlines, line.c_str());
}
continue;
}
if (gDebug > 2) {
Info("ReadStream", "Parsing line number %lld: '%s'",
nlines, line.c_str());
}
// Loop on branches and read the branch values into their buffer
branch = 0;
TString tok; // one column's data
TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
std::stringstream sToken; // string stream feeding leafData into leaves
Ssiz_t pos = 0;
Int_t iBranch = 0;
Bool_t goodLine = kTRUE; // whether the row can be filled into the tree
Int_t remainingLeafLen = 0; // remaining columns for the current leaf
while (goodLine && iBranch < nbranches
&& sLine.Tokenize(tok, pos, sDelim)) {
tok = tok.Strip(TString::kLeading); // skip leading whitespace
if (tok.IsNull() && delimiter == ' ') {
// 1 2 should not be interpreted as 1,,,2 but 1, 2.
// Thus continue until we have a non-empty token.
continue;
}
if (!remainingLeafLen) {
// next branch!
branch = (TBranch*)fBranches.At(iBranch);
}
TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
if (!remainingLeafLen) {
remainingLeafLen = leaf->GetLen();
if (leaf->GetMaximum() > 0) {
// This is a dynamic leaf length, i.e. most likely a TLeafC's
// string size. This still translates into one token:
remainingLeafLen = 1;
}
leafData = tok;
} else {
// append token to laf data:
leafData += " ";
leafData += tok;
}
--remainingLeafLen;
if (remainingLeafLen) {
// need more columns for this branch:
continue;
}
++iBranch;
// initialize stringstream with token
sToken.clear();
sToken.seekp(0, std::ios_base::beg);
sToken.str(leafData.Data());
sToken.seekg(0, std::ios_base::beg);
leaf->ReadValue(sToken, 0 /* 0 = "all" */);
if (gDebug > 3) {
Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
nlines, iBranch,
(int)sToken.good(), (int)sToken.fail(),
(int)sToken.bad(), (int)sToken.eof(),
(int)in.good(), (int)in.fail(),
(int)in.bad(), (int)in.eof(),
sToken.str().c_str());
}
// Error handling
if (sToken.bad()) {
// How could that happen for a stringstream?
Warning("ReadStream",
"Buffer error while reading data for branch %s on line %lld",
branch->GetName(), nlines);
} else if (!sToken.eof()) {
if (sToken.fail()) {
Warning("ReadStream",
"Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
tok.Data(), branch->GetName(), nlines);
goodLine = kFALSE;
} else {
std::string remainder;
std::getline(sToken, remainder, newline);
if (!remainder.empty()) {
Warning("ReadStream",
"Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
remainder.c_str(), branch->GetName(), nlines);
}
}
}
} // tokenizer loop
if (iBranch < nbranches) {
Warning("ReadStream",
"Read too few columns (%d < %d) in line %lld; ignoring line",
iBranch, nbranches, nlines);
goodLine = kFALSE;
} else if (pos != kNPOS) {
sLine = sLine.Strip(TString::kTrailing);
if (pos < sLine.Length()) {
Warning("ReadStream",
"Ignoring trailing \"%s\" while reading line %lld",
sLine.Data() + pos - 1 /* also print delimiter */,
nlines);
}
}
//we are now ready to fill the tree
if (goodLine) {
Fill();
++nGoodLines;
}
}
return nGoodLines;
}
////////////////////////////////////////////////////////////////////////////////
/// Make sure that obj (which is being deleted or will soon be) is no
/// longer referenced by this TTree.
void TTree::RecursiveRemove(TObject *obj)
{
if (obj == fEventList) {
fEventList = 0;
}
if (obj == fEntryList) {
fEntryList = 0;
}
if (fUserInfo) {
fUserInfo->RecursiveRemove(obj);
}
if (fPlayer == obj) {
fPlayer = 0;
}
if (fTreeIndex == obj) {
fTreeIndex = 0;
}
if (fAliases) {
fAliases->RecursiveRemove(obj);
}
if (fFriends) {
fFriends->RecursiveRemove(obj);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Refresh contents of this tree and its branches from the current status on disk.
///
/// One can call this function in case the tree file is being
/// updated by another process.
void TTree::Refresh()
{
if (!fDirectory->GetFile()) {
return;
}
fDirectory->ReadKeys();
fDirectory->Remove(this);
TTree* tree; fDirectory->GetObject(GetName(),tree);
if (!tree) {
return;
}
//copy info from tree header into this Tree
fEntries = 0;
fNClusterRange = 0;
ImportClusterRanges(tree);
fAutoSave = tree->fAutoSave;
fEntries = tree->fEntries;
fTotBytes = tree->GetTotBytes();
fZipBytes = tree->GetZipBytes();
fSavedBytes = tree->fSavedBytes;
fTotalBuffers = tree->fTotalBuffers.load();
//loop on all branches and update them
Int_t nleaves = fLeaves.GetEntriesFast();
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
branch->Refresh(tree->GetBranch(branch->GetName()));
}
fDirectory->Remove(tree);
fDirectory->Append(this);
delete tree;
tree = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Remove a friend from the list of friends.
void TTree::RemoveFriend(TTree* oldFriend)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kRemoveFriend & fFriendLockStatus) {
return;
}
if (!fFriends) {
return;
}
TFriendLock lock(this, kRemoveFriend);
TIter nextf(fFriends);
TFriendElement* fe = 0;
while ((fe = (TFriendElement*) nextf())) {
TTree* friend_t = fe->GetTree();
if (friend_t == oldFriend) {
fFriends->Remove(fe);
delete fe;
fe = 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Reset baskets, buffers and entries count in all branches and leaves.
void TTree::Reset(Option_t* option)
{
fNotify = 0;
fEntries = 0;
fNClusterRange = 0;
fTotBytes = 0;
fZipBytes = 0;
fFlushedBytes = 0;
fSavedBytes = 0;
fTotalBuffers = 0;
fChainOffset = 0;
fReadEntry = -1;
delete fTreeIndex;
fTreeIndex = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->Reset(option);
}
if (fBranchRef) {
fBranchRef->Reset();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Resets the state of this TTree after a merge (keep the customization but
/// forget the data).
void TTree::ResetAfterMerge(TFileMergeInfo *info)
{
fEntries = 0;
fNClusterRange = 0;
fTotBytes = 0;
fZipBytes = 0;
fSavedBytes = 0;
fFlushedBytes = 0;
fTotalBuffers = 0;
fChainOffset = 0;
fReadEntry = -1;
delete fTreeIndex;
fTreeIndex = 0;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->ResetAfterMerge(info);
}
if (fBranchRef) {
fBranchRef->ResetAfterMerge(info);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Tell all of our branches to set their addresses to zero.
///
/// Note: If any of our branches own any objects, they are deleted.
void TTree::ResetBranchAddress(TBranch *br)
{
if (br && br->GetTree()) {
br->ResetAddress();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Tell all of our branches to drop their current objects and allocate new ones.
void TTree::ResetBranchAddresses()
{
TObjArray* branches = GetListOfBranches();
Int_t nbranches = branches->GetEntriesFast();
for (Int_t i = 0; i < nbranches; ++i) {
TBranch* branch = (TBranch*) branches->UncheckedAt(i);
branch->ResetAddress();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Loop over tree entries and print entries passing selection.
///
/// - If varexp is 0 (or "") then print only first 8 columns.
/// - If varexp = "*" print all columns.
///
/// Otherwise a columns selection can be made using "var1:var2:var3".
/// See TTreePlayer::Scan for more information
Long64_t TTree::Scan(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->Scan(varexp, selection, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Set a tree variable alias.
///
/// Set an alias for an expression/formula based on the tree 'variables'.
///
/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
/// 'aliasFormula'.
///
/// If the content of 'aliasFormula' only contains symbol names, periods and
/// array index specification (for example event.fTracks[3]), then
/// the content of 'aliasName' can be used as the start of symbol.
///
/// If the alias 'aliasName' already existed, it is replaced by the new
/// value.
///
/// When being used, the alias can be preceded by an eventual 'Friend Alias'
/// (see TTree::GetFriendAlias)
///
/// Return true if it was added properly.
///
/// For example:
/// ~~~ {.cpp}
/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
/// tree->Draw("y2-y1:x2-x1");
///
/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
/// ~~~
Bool_t TTree::SetAlias(const char* aliasName, const char* aliasFormula)
{
if (!aliasName || !aliasFormula) {
return kFALSE;
}
if (!aliasName[0] || !aliasFormula[0]) {
return kFALSE;
}
if (!fAliases) {
fAliases = new TList;
} else {
TNamed* oldHolder = (TNamed*) fAliases->FindObject(aliasName);
if (oldHolder) {
oldHolder->SetTitle(aliasFormula);
return kTRUE;
}
}
TNamed* holder = new TNamed(aliasName, aliasFormula);
fAliases->Add(holder);
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// This function may be called at the start of a program to change
/// the default value for fAutoFlush.
///
/// ### CASE 1 : autof > 0
///
/// autof is the number of consecutive entries after which TTree::Fill will
/// flush all branch buffers to disk.
///
/// ### CASE 2 : autof < 0
///
/// When filling the Tree the branch buffers will be flushed to disk when
/// more than autof bytes have been written to the file. At the first FlushBaskets
/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
///
/// Calling this function with autof<0 is interesting when it is hard to estimate
/// the size of one entry. This value is also independent of the Tree.
///
/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
///
/// ### CASE 3 : autof = 0
///
/// The AutoFlush mechanism is disabled.
///
/// Flushing the buffers at regular intervals optimize the location of
/// consecutive entries on the disk by creating clusters of baskets.
///
/// A cluster of baskets is a set of baskets that contains all
/// the data for a (consecutive) set of entries and that is stored
/// consecutively on the disk. When reading all the branches, this
/// is the minimum set of baskets that the TTreeCache will read.
void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
{
// Implementation note:
//
// A positive value of autoflush determines the size (in number of entries) of
// a cluster of baskets.
//
// If the value of autoflush is changed over time (this happens in
// particular when the TTree results from fast merging many trees),
// we record the values of fAutoFlush in the data members:
// fClusterRangeEnd and fClusterSize.
// In the code we refer to a range of entries where the size of the
// cluster of baskets is the same (i.e the value of AutoFlush was
// constant) is called a ClusterRange.
//
// The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
// active (used) values and have fMaxClusterRange allocated entries.
//
// fClusterRangeEnd contains the last entries number of a cluster range.
// In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
// fClusterSize contains the size in number of entries of all the cluster
// within the given range.
// The last range (and the only one if fNClusterRange is zero) start at
// fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
// size of the cluster in this range is given by the value of fAutoFlush.
//
// For example printing the beginning and end of each the ranges can be done by:
//
// Printf("%-16s %-16s %-16s %5s",
// "Cluster Range #", "Entry Start", "Last Entry", "Size");
// Int_t index= 0;
// Long64_t clusterRangeStart = 0;
// if (fNClusterRange) {
// for( ; index < fNClusterRange; ++index) {
// Printf("%-16d %-16lld %-16lld %5lld",
// index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
// clusterRangeStart = fClusterRangeEnd[index] + 1;
// }
// }
// Printf("%-16d %-16lld %-16lld %5lld",
// index, prevEntry, fEntries - 1, fAutoFlush);
//
// Note: We store the entry number corresponding to the end of the cluster
// rather than its start in order to avoid using the array if the cluster
// size never varies (If there is only one value of AutoFlush for the whole TTree).
if( fAutoFlush != autof) {
if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
// The mechanism was already enabled, let's record the previous
// cluster if needed.
MarkEventCluster();
}
fAutoFlush = autof;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Mark the previous event as being at the end of the event cluster.
///
/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
/// is called, then the first cluster has 9 events.
void TTree::MarkEventCluster()
{
if (!fEntries) return;
if ( (fNClusterRange+1) > fMaxClusterRange ) {
if (fMaxClusterRange) {
// Resize arrays to hold a larger event cluster.
Int_t newsize = TMath::Max(10,Int_t(2*fMaxClusterRange));
fClusterRangeEnd = (Long64_t*)TStorage::ReAlloc(fClusterRangeEnd,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fClusterSize = (Long64_t*)TStorage::ReAlloc(fClusterSize,
newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
fMaxClusterRange = newsize;
} else {
// Cluster ranges have never been initialized; create them now.
fMaxClusterRange = 2;
fClusterRangeEnd = new Long64_t[fMaxClusterRange];
fClusterSize = new Long64_t[fMaxClusterRange];
}
}
fClusterRangeEnd[fNClusterRange] = fEntries - 1;
// If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
if (fAutoFlush > 0) {
// Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
// will appropriately go to the next event range.
fClusterSize[fNClusterRange] = fAutoFlush;
// Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
} else if (fNClusterRange == 0) {
fClusterSize[fNClusterRange] = fEntries;
} else {
fClusterSize[fNClusterRange] = fClusterRangeEnd[fNClusterRange] - fClusterRangeEnd[fNClusterRange-1];
}
++fNClusterRange;
}
////////////////////////////////////////////////////////////////////////////////
/// This function may be called at the start of a program to change
/// the default value for fAutoSave (and for SetAutoSave) is -300000000, ie 300 MBytes.
/// When filling the Tree the branch buffers as well as the Tree header
/// will be flushed to disk when the watermark is reached.
/// If fAutoSave is positive the watermark is reached when a multiple of fAutoSave
/// entries have been written.
/// If fAutoSave is negative the watermark is reached when -fAutoSave bytes
/// have been written to the file.
/// In case of a program crash, it will be possible to recover the data in the Tree
/// up to the last AutoSave point.
void TTree::SetAutoSave(Long64_t autos)
{
fAutoSave = autos;
}
////////////////////////////////////////////////////////////////////////////////
/// Set a branch's basket size.
///
/// bname is the name of a branch.
///
/// - if bname="*", apply to all branches.
/// - if bname="xxx*", apply to all branches with name starting with xxx
///
/// see TRegexp for wildcarding options
/// buffsize = branc basket size
void TTree::SetBasketSize(const char* bname, Int_t buffsize)
{
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname, kTRUE);
Int_t nb = 0;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
TBranch* branch = (TBranch*) leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
continue;
}
nb++;
branch->SetBasketSize(buffsize);
}
if (!nb) {
Error("SetBasketSize", "unknown branch -> '%s'", bname);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change branch address, dealing with clone trees properly.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
{
TBranch* branch = GetBranch(bname);
if (!branch) {
if (ptr) *ptr = 0;
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kMissingBranch;
}
return SetBranchAddressImp(branch,addr,ptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Verify the validity of the type of addr before calling SetBranchAddress.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
return SetBranchAddress(bname, addr, 0, ptrClass, datatype, isptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Verify the validity of the type of addr before calling SetBranchAddress.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
{
TBranch* branch = GetBranch(bname);
if (!branch) {
if (ptr) *ptr = 0;
Error("SetBranchAddress", "unknown branch -> %s", bname);
return kMissingBranch;
}
Int_t res = CheckBranchAddressType(branch, ptrClass, datatype, isptr);
// This will set the value of *ptr to branch.
if (res >= 0) {
// The check succeeded.
SetBranchAddressImp(branch,addr,ptr);
} else {
if (ptr) *ptr = 0;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// Change branch address, dealing with clone trees properly.
/// See TTree::CheckBranchAddressType for the semantic of the return value.
///
/// Note: See the comments in TBranchElement::SetAddress() for the
/// meaning of the addr parameter and the object ownership policy.
Int_t TTree::SetBranchAddressImp(TBranch *branch, void* addr, TBranch** ptr)
{
if (ptr) {
*ptr = branch;
}
if (fClones) {
void* oldAddr = branch->GetAddress();
TIter next(fClones);
TTree* clone = 0;
const char *bname = branch->GetName();
while ((clone = (TTree*) next())) {
TBranch* cloneBr = clone->GetBranch(bname);
if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
cloneBr->SetAddress(addr);
}
}
}
branch->SetAddress(addr);
return kVoidPtr;
}
////////////////////////////////////////////////////////////////////////////////
/// Set branch status to Process or DoNotProcess.
///
/// When reading a Tree, by default, all branches are read.
/// One can speed up considerably the analysis phase by activating
/// only the branches that hold variables involved in a query.
///
/// bname is the name of a branch.
///
/// - if bname="*", apply to all branches.
/// - if bname="xxx*", apply to all branches with name starting with xxx
///
/// see TRegexp for wildcarding options
///
/// - status = 1 branch will be processed
/// - = 0 branch will not be processed
///
/// Example:
///
/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
/// when doing T.GetEntry(i) all branches are read for entry i.
/// to read only the branches c and e, one can do
/// ~~~ {.cpp}
/// T.SetBranchStatus("*",0); //disable all branches
/// T.SetBranchStatus("c",1);
/// T.setBranchStatus("e",1);
/// T.GetEntry(i);
/// ~~~
/// bname is interpreted as a wildcarded TRegexp (see TRegexp::MakeWildcard).
/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
/// "b", but not any other branch with an "a" followed at some point by a
/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
/// support '|', and so you cannot select, e.g. track and shower branches
/// with "track|shower".
///
/// __WARNING! WARNING! WARNING!__
///
/// SetBranchStatus is matching the branch based on match of the branch
/// 'name' and not on the branch hierarchy! In order to be able to
/// selectively enable a top level object that is 'split' you need to make
/// sure the name of the top level branch is prefixed to the sub-branches'
/// name (by adding a dot ('.') at the end of the Branch creation and use the
/// corresponding bname.
///
/// I.e If your Tree has been created in split mode with a parent branch "parent."
/// (note the trailing dot).
/// ~~~ {.cpp}
/// T.SetBranchStatus("parent",1);
/// ~~~
/// will not activate the sub-branches of "parent". You should do:
/// ~~~ {.cpp}
/// T.SetBranchStatus("parent*",1);
/// ~~~
/// Without the trailing dot in the branch creation you have no choice but to
/// call SetBranchStatus explicitly for each of the sub branches.
///
/// An alternative to this function is to read directly and only
/// the interesting branches. Example:
/// ~~~ {.cpp}
/// TBranch *brc = T.GetBranch("c");
/// TBranch *bre = T.GetBranch("e");
/// brc->GetEntry(i);
/// bre->GetEntry(i);
/// ~~~
/// If found is not 0, the number of branch(es) found matching the regular
/// expression is returned in *found AND the error message 'unknown branch'
/// is suppressed.
void TTree::SetBranchStatus(const char* bname, Bool_t status, UInt_t* found)
{
// We already have been visited while recursively looking
// through the friends tree, let return
if (kSetBranchStatus & fFriendLockStatus) {
return;
}
if (0 == strcmp(bname, "")) {
Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
return;
}
TBranch *branch, *bcount, *bson;
TLeaf *leaf, *leafcount;
Int_t i,j;
Int_t nleaves = fLeaves.GetEntriesFast();
TRegexp re(bname,kTRUE);
Int_t nb = 0;
// first pass, loop on all branches
// for leafcount branches activate/deactivate in function of status
for (i=0;i<nleaves;i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
TString s = branch->GetName();
if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
TString longname;
longname.Form("%s.%s",GetName(),branch->GetName());
if (strcmp(bname,branch->GetName())
&& longname != bname
&& s.Index(re) == kNPOS) continue;
}
nb++;
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
if (status) bcount->ResetBit(kDoNotProcess);
else bcount->SetBit(kDoNotProcess);
}
}
if (nb==0 && strchr(bname,'*')==0) {
branch = GetBranch(bname);
if (branch) {
if (status) branch->ResetBit(kDoNotProcess);
else branch->SetBit(kDoNotProcess);
++nb;
}
}
//search in list of friends
UInt_t foundInFriend = 0;
if (fFriends) {
TFriendLock lock(this,kSetBranchStatus);
TIter nextf(fFriends);
TFriendElement *fe;
TString name;
while ((fe = (TFriendElement*)nextf())) {
TTree *t = fe->GetTree();
if (t==0) continue;
// If the alias is present replace it with the real name.
char *subbranch = (char*)strstr(bname,fe->GetName());
if (subbranch!=bname) subbranch = 0;
if (subbranch) {
subbranch += strlen(fe->GetName());
if ( *subbranch != '.' ) subbranch = 0;
else subbranch ++;
}
if (subbranch) {
name.Form("%s.%s",t->GetName(),subbranch);
} else {
name = bname;
}
t->SetBranchStatus(name,status, &foundInFriend);
}
}
if (!nb && !foundInFriend) {
if (found==0) {
if (status) {
if (strchr(bname,'*') != 0)
Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
else
Error("SetBranchStatus", "unknown branch -> %s", bname);
} else {
if (strchr(bname,'*') != 0)
Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
else
Warning("SetBranchStatus", "unknown branch -> %s", bname);
}
}
return;
}
if (found) *found = nb + foundInFriend;
// second pass, loop again on all branches
// activate leafcount branches for active branches only
for (i = 0; i < nleaves; i++) {
leaf = (TLeaf*)fLeaves.UncheckedAt(i);
branch = (TBranch*)leaf->GetBranch();
if (!branch->TestBit(kDoNotProcess)) {
leafcount = leaf->GetLeafCount();
if (leafcount) {
bcount = leafcount->GetBranch();
bcount->ResetBit(kDoNotProcess);
}
} else {
//Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
Int_t nbranches = branch->GetListOfBranches()->GetEntries();
for (j=0;j<nbranches;j++) {
bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
if (!bson) continue;
if (!bson->TestBit(kDoNotProcess)) {
if (bson->GetNleaves() <= 0) continue;
branch->ResetBit(kDoNotProcess);
break;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the current branch style. (static function)
///
/// - style = 0 old Branch
/// - style = 1 new Bronch
void TTree::SetBranchStyle(Int_t style)
{
fgBranchStyle = style;
}
////////////////////////////////////////////////////////////////////////////////
/// Set maximum size of the file cache .
//
/// - if cachesize = 0 the existing cache (if any) is deleted.
/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
/// the Tree (default is 30 MBytes).
///
/// Returns:
/// - 0 size set, cache was created if possible
/// - -1 on error
Int_t TTree::SetCacheSize(Long64_t cacheSize)
{
// remember that the user has requested an explicit cache setup
fCacheUserSet = kTRUE;
return SetCacheSizeAux(kFALSE, cacheSize);
}
////////////////////////////////////////////////////////////////////////////////
/// Set the size of the file cache and create it if possible.
///
/// If autocache is true:
/// this may be an autocreated cache, possibly enlarging an existing
/// autocreated cache. The size is calculated. The value passed in cacheSize:
/// - cacheSize = 0 make cache if default cache creation is enabled
/// - cacheSize = -1 make a default sized cache in any case
///
/// If autocache is false:
/// this is a user requested cache. cacheSize is used to size the cache.
/// This cache should never be automatically adjusted.
///
/// Returns:
/// - 0 size set, or existing autosized cache almost large enough.
/// (cache was created if possible)
/// - -1 on error
Int_t TTree::SetCacheSizeAux(Bool_t autocache /* = kTRUE */, Long64_t cacheSize /* = 0 */ )
{
if (autocache) {
// used as a once only control for automatic cache setup
fCacheDoAutoInit = kFALSE;
}
if (!autocache) {
// negative size means the user requests the default
if (cacheSize < 0) {
cacheSize = GetCacheAutoSize(kTRUE);
}
} else {
if (cacheSize == 0) {
cacheSize = GetCacheAutoSize();
} else if (cacheSize < 0) {
cacheSize = GetCacheAutoSize(kTRUE);
}
}
TFile* file = GetCurrentFile();
if (!file || GetTree() != this) {
// if there's no file or we are not a plain tree (e.g. if we're a TChain)
// do not create a cache, only record the size if one was given
if (!autocache) {
fCacheSize = cacheSize;
}
if (GetTree() != this) {
return 0;
}
if (!autocache && cacheSize>0) {
Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
}
return 0;
}
// Check for an existing cache
TTreeCache* pf = GetReadCache(file);
if (pf) {
if (autocache) {
// reset our cache status tracking in case existing cache was added
// by the user without using one of the TTree methods
fCacheSize = pf->GetBufferSize();
fCacheUserSet = !pf->IsAutoCreated();
if (fCacheUserSet) {
// existing cache was created by the user, don't change it
return 0;
}
} else {
// update the cache to ensure it records the user has explicitly
// requested it
pf->SetAutoCreated(kFALSE);
}
// if we're using an automatically calculated size and the existing
// cache is already almost large enough don't resize
if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
// already large enough
return 0;
}
if (cacheSize == fCacheSize) {
return 0;
}
if (cacheSize == 0) {
// delete existing cache
pf->WaitFinishPrefetch();
file->SetCacheRead(0,this);
delete pf;
pf = 0;
} else {
// resize
Int_t res = pf->SetBufferSize(cacheSize);
if (res < 0) {
return -1;
}
}
} else {
// no existing cache
if (autocache) {
if (fCacheUserSet) {
// value was already set manually.
if (fCacheSize == 0) return 0;
// Expected a cache should exist; perhaps the user moved it
// Do nothing more here.
if (cacheSize) {
Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
}
return -1;
}
}
}
fCacheSize = cacheSize;
if (cacheSize == 0 || pf) {
return 0;
}
#ifdef R__USE_IMT
if(TTreeCacheUnzip::IsParallelUnzip() && file->GetCompressionLevel() > 0)
pf = new TTreeCacheUnzip(this, cacheSize);
else
#endif
pf = new TTreeCache(this, cacheSize);
pf->SetAutoCreated(autocache);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
///interface to TTreeCache to set the cache entry range
///
/// Returns:
/// - 0 entry range set
/// - -1 on error
Int_t TTree::SetCacheEntryRange(Long64_t first, Long64_t last)
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("SetCacheEntryRange","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->SetCacheEntryRange(first, last);
}
} else {
Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
return -1;
}
tc->SetEntryRange(first,last);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Interface to TTreeCache to set the number of entries for the learning phase
void TTree::SetCacheLearnEntries(Int_t n)
{
TTreeCache::SetLearnEntries(n);
}
////////////////////////////////////////////////////////////////////////////////
/// Enable/Disable circularity for this tree.
///
/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
/// per branch in memory.
/// Note that when this function is called (maxEntries>0) the Tree
/// must be empty or having only one basket per branch.
/// if maxEntries <= 0 the tree circularity is disabled.
///
/// #### NOTE 1:
/// Circular Trees are interesting in online real time environments
/// to store the results of the last maxEntries events.
/// #### NOTE 2:
/// Calling SetCircular with maxEntries <= 0 is necessary before
/// merging circular Trees that have been saved on files.
/// #### NOTE 3:
/// SetCircular with maxEntries <= 0 is automatically called
/// by TChain::Merge
/// #### NOTE 4:
/// A circular Tree can still be saved in a file. When read back,
/// it is still a circular Tree and can be filled again.
void TTree::SetCircular(Long64_t maxEntries)
{
if (maxEntries <= 0) {
// Disable circularity.
fMaxEntries = 1000000000;
fMaxEntries *= 1000;
ResetBit(kCircular);
//in case the Tree was originally created in gROOT, the branch
//compression level was set to -1. If the Tree is now associated to
//a file, reset the compression level to the file compression level
if (fDirectory) {
TFile* bfile = fDirectory->GetFile();
Int_t compress = ROOT::RCompressionSetting::EDefaults::kUseGeneralPurpose;
if (bfile) {
compress = bfile->GetCompressionSettings();
}
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; i++) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->SetCompressionSettings(compress);
}
}
} else {
// Enable circularity.
fMaxEntries = maxEntries;
SetBit(kCircular);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the debug level and the debug range.
///
/// For entries in the debug range, the functions TBranchElement::Fill
/// and TBranchElement::GetEntry will print the number of bytes filled
/// or read for each branch.
void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
{
fDebug = level;
fDebugMin = min;
fDebugMax = max;
}
////////////////////////////////////////////////////////////////////////////////
/// Update the default value for the branch's fEntryOffsetLen.
/// If updateExisting is true, also update all the existing branches.
/// If newdefault is less than 10, the new default value will be 10.
void TTree::SetDefaultEntryOffsetLen(Int_t newdefault, Bool_t updateExisting)
{
if (newdefault < 10) {
newdefault = 10;
}
fDefaultEntryOffsetLen = newdefault;
if (updateExisting) {
TIter next( GetListOfBranches() );
TBranch *b;
while ( ( b = (TBranch*)next() ) ) {
b->SetEntryOffsetLen( newdefault, kTRUE );
}
if (fBranchRef) {
fBranchRef->SetEntryOffsetLen( newdefault, kTRUE );
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change the tree's directory.
///
/// Remove reference to this tree from current directory and
/// add reference to new directory dir. The dir parameter can
/// be 0 in which case the tree does not belong to any directory.
///
void TTree::SetDirectory(TDirectory* dir)
{
if (fDirectory == dir) {
return;
}
if (fDirectory) {
fDirectory->Remove(this);
// Delete or move the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,dir);
}
fDirectory = dir;
if (fDirectory) {
fDirectory->Append(this);
}
TFile* file = 0;
if (fDirectory) {
file = fDirectory->GetFile();
}
if (fBranchRef) {
fBranchRef->SetFile(file);
}
TBranch* b = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())) {
b->SetFile(file);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change number of entries in the tree.
///
/// If n >= 0, set number of entries in the tree = n.
///
/// If n < 0, set number of entries in the tree to match the
/// number of entries in each branch. (default for n is -1)
///
/// This function should be called only when one fills each branch
/// independently via TBranch::Fill without calling TTree::Fill.
/// Calling TTree::SetEntries() make sense only if the number of entries
/// in each branch is identical, a warning is issued otherwise.
/// The function returns the number of entries.
///
Long64_t TTree::SetEntries(Long64_t n)
{
// case 1 : force number of entries to n
if (n >= 0) {
fEntries = n;
return n;
}
// case 2; compute the number of entries from the number of entries in the branches
TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
Long64_t nMin = kMaxEntries;
Long64_t nMax = 0;
TIter next(GetListOfBranches());
while((b = (TBranch*) next())){
Long64_t n2 = b->GetEntries();
if (!bMin || n2 < nMin) {
nMin = n2;
bMin = b;
}
if (!bMax || n2 > nMax) {
nMax = n2;
bMax = b;
}
}
if (bMin && nMin != nMax) {
Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
bMin->GetName(), nMin, bMax->GetName(), nMax);
}
fEntries = nMax;
return fEntries;
}
////////////////////////////////////////////////////////////////////////////////
/// Set an EntryList
void TTree::SetEntryList(TEntryList *enlist, Option_t * /*opt*/)
{
if (fEntryList) {
//check if the previous entry list is owned by the tree
if (fEntryList->TestBit(kCanDelete)){
delete fEntryList;
}
}
fEventList = 0;
if (!enlist) {
fEntryList = 0;
return;
}
fEntryList = enlist;
fEntryList->SetTree(this);
}
////////////////////////////////////////////////////////////////////////////////
/// This function transfroms the given TEventList into a TEntryList
/// The new TEntryList is owned by the TTree and gets deleted when the tree
/// is deleted. This TEntryList can be returned by GetEntryList() function.
void TTree::SetEventList(TEventList *evlist)
{
fEventList = evlist;
if (fEntryList){
if (fEntryList->TestBit(kCanDelete)) {
TEntryList *tmp = fEntryList;
fEntryList = 0; // Avoid problem with RecursiveRemove.
delete tmp;
} else {
fEntryList = 0;
}
}
if (!evlist) {
fEntryList = 0;
fEventList = 0;
return;
}
fEventList = evlist;
char enlistname[100];
snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
fEntryList = new TEntryList(enlistname, evlist->GetTitle());
fEntryList->SetDirectory(0); // We own this.
Int_t nsel = evlist->GetN();
fEntryList->SetTree(this);
Long64_t entry;
for (Int_t i=0; i<nsel; i++){
entry = evlist->GetEntry(i);
fEntryList->Enter(entry);
}
fEntryList->SetReapplyCut(evlist->GetReapplyCut());
fEntryList->SetBit(kCanDelete, kTRUE);
}
////////////////////////////////////////////////////////////////////////////////
/// Set number of entries to estimate variable limits.
/// If n is -1, the estimate is set to be the current maximum
/// for the tree (i.e. GetEntries() + 1)
/// If n is less than -1, the behavior is undefined.
void TTree::SetEstimate(Long64_t n /* = 1000000 */)
{
if (n == 0) {
n = 10000;
} else if (n < 0) {
n = fEntries - n;
}
fEstimate = n;
GetPlayer();
if (fPlayer) {
fPlayer->SetEstimate(n);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Provide the end-user with the ability to enable/disable various experimental
/// IO features for this TTree.
///
/// Returns all the newly-set IO settings.
ROOT::TIOFeatures TTree::SetIOFeatures(const ROOT::TIOFeatures &features)
{
// Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
// error of their ways; this is just a safety check.
UChar_t featuresRequested = features.GetFeatures() & static_cast<UChar_t>(TBasket::EIOBits::kSupported);
UChar_t curFeatures = fIOFeatures.GetFeatures();
UChar_t newFeatures = ~curFeatures & featuresRequested;
curFeatures |= newFeatures;
fIOFeatures.Set(curFeatures);
ROOT::TIOFeatures newSettings(newFeatures);
return newSettings;
}
////////////////////////////////////////////////////////////////////////////////
/// Set fFileNumber to number.
/// fFileNumber is used by TTree::Fill to set the file name
/// for a new file to be created when the current file exceeds fgTreeMaxSize.
/// (see TTree::ChangeFile)
/// if fFileNumber=10, the new file name will have a suffix "_11",
/// ie, fFileNumber is incremented before setting the file name
void TTree::SetFileNumber(Int_t number)
{
if (fFileNumber < 0) {
Warning("SetFileNumber", "file number must be positive. Set to 0");
fFileNumber = 0;
return;
}
fFileNumber = number;
}
////////////////////////////////////////////////////////////////////////////////
/// Set all the branches in this TTree to be in decomposed object mode
/// (also known as MakeClass mode).
///
/// For MakeClass mode 0, the TTree expects the address where the data is stored
/// to be set by either the user or the TTree to the address of a full object
/// through the top level branch.
/// For MakeClass mode 1, this address is expected to point to a numerical type
/// or C-style array (variable or not) of numerical type, representing the
/// primitive data members.
/// The function's primary purpose is to allow the user to access the data
/// directly with numerical type variable rather than having to have the original
/// set of classes (or a reproduction thereof).
void TTree::SetMakeClass(Int_t make)
{
fMakeClass = make;
Int_t nb = fBranches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
branch->SetMakeClass(make);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the maximum size in bytes of a Tree file (static function).
/// The default size is 100000000000LL, ie 100 Gigabytes.
///
/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
/// the function closes the current file and starts writing into
/// a new file with a name of the style "file_1.root" if the original
/// requested file name was "file.root".
void TTree::SetMaxTreeSize(Long64_t maxsize)
{
fgMaxTreeSize = maxsize;
}
////////////////////////////////////////////////////////////////////////////////
/// Change the name of this tree.
void TTree::SetName(const char* name)
{
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update hashlists if we change the name.
TFile *file = 0;
TTreeCache *pf = 0;
if (fDirectory) {
fDirectory->Remove(this);
if ((file = GetCurrentFile())) {
pf = GetReadCache(file);
file->SetCacheRead(0,this,TFile::kDoNotDisconnect);
}
}
// This changes our hash value.
fName = name;
if (fDirectory) {
fDirectory->Append(this);
if (pf) {
file->SetCacheRead(pf,this,TFile::kDoNotDisconnect);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Change the name and title of this tree.
void TTree::SetObject(const char* name, const char* title)
{
if (gPad) {
gPad->Modified();
}
// Trees are named objects in a THashList.
// We must update hashlists if we change the name
TFile *file = 0;
TTreeCache *pf = 0;
if (fDirectory) {
fDirectory->Remove(this);
if ((file = GetCurrentFile())) {
pf = GetReadCache(file);
file->SetCacheRead(0,this,TFile::kDoNotDisconnect);
}
}
// This changes our hash value.
fName = name;
fTitle = title;
if (fDirectory) {
fDirectory->Append(this);
if (pf) {
file->SetCacheRead(pf,this,TFile::kDoNotDisconnect);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Enable or disable parallel unzipping of Tree buffers.
void TTree::SetParallelUnzip(Bool_t opt, Float_t RelSize)
{
#ifdef R__USE_IMT
if (GetTree() == 0) {
LoadTree(GetReadEntry());
if (!GetTree())
return;
}
if (GetTree() != this) {
GetTree()->SetParallelUnzip(opt, RelSize);
return;
}
TFile* file = GetCurrentFile();
if (!file)
return;
TTreeCache* pf = GetReadCache(file);
if (pf && !( opt ^ (nullptr != dynamic_cast<TTreeCacheUnzip*>(pf)))) {
// done with opt and type are in agreement.
return;
}
delete pf;
auto cacheSize = GetCacheAutoSize(kTRUE);
if (opt) {
auto unzip = new TTreeCacheUnzip(this, cacheSize);
unzip->SetUnzipBufferSize( Long64_t(cacheSize * RelSize) );
} else {
pf = new TTreeCache(this, cacheSize);
}
#else
(void)opt;
(void)RelSize;
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// Set perf stats
void TTree::SetPerfStats(TVirtualPerfStats *perf)
{
fPerfStats = perf;
}
////////////////////////////////////////////////////////////////////////////////
/// The current TreeIndex is replaced by the new index.
/// Note that this function does not delete the previous index.
/// This gives the possibility to play with more than one index, e.g.,
/// ~~~ {.cpp}
/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
/// tree.SetTreeIndex(newIndex);
/// tree.Draw();
/// tree.SetTreeIndex(oldIndex);
/// tree.Draw(); etc
/// ~~~
void TTree::SetTreeIndex(TVirtualIndex* index)
{
if (fTreeIndex) {
fTreeIndex->SetTree(0);
}
fTreeIndex = index;
}
////////////////////////////////////////////////////////////////////////////////
/// Set tree weight.
///
/// The weight is used by TTree::Draw to automatically weight each
/// selected entry in the resulting histogram.
///
/// For example the equivalent of:
/// ~~~ {.cpp}
/// T.Draw("x", "w")
/// ~~~
/// is:
/// ~~~ {.cpp}
/// T.SetWeight(w);
/// T.Draw("x");
/// ~~~
/// This function is redefined by TChain::SetWeight. In case of a
/// TChain, an option "global" may be specified to set the same weight
/// for all trees in the TChain instead of the default behaviour
/// using the weights of each tree in the chain (see TChain::SetWeight).
void TTree::SetWeight(Double_t w, Option_t*)
{
fWeight = w;
}
////////////////////////////////////////////////////////////////////////////////
/// Print values of all active leaves for entry.
///
/// - if entry==-1, print current entry (default)
/// - if a leaf is an array, a maximum of lenmax elements is printed.
void TTree::Show(Long64_t entry, Int_t lenmax)
{
if (entry != -1) {
Int_t ret = LoadTree(entry);
if (ret == -2) {
Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
return;
} else if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
}
ret = GetEntry(entry);
if (ret == -1) {
Error("Show()", "Cannot read entry %lld (I/O error)", entry);
return;
} else if (ret == 0) {
Error("Show()", "Cannot read entry %lld (no data read)", entry);
return;
}
}
printf("======> EVENT:%lld\n", fReadEntry);
TObjArray* leaves = GetListOfLeaves();
Int_t nleaves = leaves->GetEntriesFast();
Int_t ltype;
for (Int_t i = 0; i < nleaves; i++) {
TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
TBranch* branch = leaf->GetBranch();
if (branch->TestBit(kDoNotProcess)) {
continue;
}
Int_t len = leaf->GetLen();
if (len <= 0) {
continue;
}
len = TMath::Min(len, lenmax);
if (leaf->IsA() == TLeafElement::Class()) {
leaf->PrintValue(lenmax);
continue;
}
if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
continue;
}
ltype = 10;
if (leaf->IsA() == TLeafF::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafD::Class()) {
ltype = 5;
}
if (leaf->IsA() == TLeafC::Class()) {
len = 1;
ltype = 5;
};
printf(" %-15s = ", leaf->GetName());
for (Int_t l = 0; l < len; l++) {
leaf->PrintValue(l);
if (l == (len - 1)) {
printf("\n");
continue;
}
printf(", ");
if ((l % ltype) == 0) {
printf("\n ");
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Start the TTreeViewer on this tree.
///
/// - ww is the width of the canvas in pixels
/// - wh is the height of the canvas in pixels
void TTree::StartViewer()
{
GetPlayer();
if (fPlayer) {
fPlayer->StartViewer(600, 400);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Stop the cache learning phase
///
/// Returns:
/// - 0 learning phase stopped or not active
/// - -1 on error
Int_t TTree::StopCacheLearningPhase()
{
if (!GetTree()) {
if (LoadTree(0)<0) {
Error("StopCacheLearningPhase","Could not load a tree");
return -1;
}
}
if (GetTree()) {
if (GetTree() != this) {
return GetTree()->StopCacheLearningPhase();
}
} else {
Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
return -1;
}
TFile *f = GetCurrentFile();
if (!f) {
Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
return -1;
}
TTreeCache *tc = GetReadCache(f,kTRUE);
if (!tc) {
Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
return -1;
}
tc->StopLearningPhase();
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Set the fTree member for all branches and sub branches.
static void TBranch__SetTree(TTree *tree, TObjArray &branches)
{
Int_t nb = branches.GetEntriesFast();
for (Int_t i = 0; i < nb; ++i) {
TBranch* br = (TBranch*) branches.UncheckedAt(i);
br->SetTree(tree);
Int_t nBaskets = br->GetListOfBaskets()->GetEntries();
Int_t writeBasket = br->GetWriteBasket();
for (Int_t j=writeBasket,n=0;j>=0 && n<nBaskets;--j) {
TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
if (bk) {
tree->IncrementTotalBuffers(bk->GetBufferSize());
++n;
}
}
TBranch__SetTree(tree,*br->GetListOfBranches());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set the fTree member for all friend elements.
void TFriendElement__SetTree(TTree *tree, TList *frlist)
{
if (frlist) {
TObjLink *lnk = frlist->FirstLink();
while (lnk) {
TFriendElement *elem = (TFriendElement*)lnk->GetObject();
elem->fParentTree = tree;
lnk = lnk->Next();
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Stream a class object.
void TTree::Streamer(TBuffer& b)
{
if (b.IsReading()) {
UInt_t R__s, R__c;
if (fDirectory) {
fDirectory->Remove(this);
//delete the file cache if it points to this Tree
TFile *file = fDirectory->GetFile();
MoveReadCache(file,0);
}
fDirectory = 0;
fCacheDoAutoInit = kTRUE;
fCacheUserSet = kFALSE;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 4) {
b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
fBranches.SetOwner(kTRUE); // True needed only for R__v < 19 and most R__v == 19
if (fBranchRef) fBranchRef->SetTree(this);
TBranch__SetTree(this,fBranches);
TFriendElement__SetTree(this,fFriends);
if (fTreeIndex) {
fTreeIndex->SetTree(this);
}
if (fIndex.fN) {
Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
fIndex.Set(0);
fIndexValues.Set(0);
}
if (fEstimate <= 10000) {
fEstimate = 1000000;
}
if (fNClusterRange) {
// The I/O allocated just enough memory to hold the
// current set of ranges.
fMaxClusterRange = fNClusterRange;
}
if (GetCacheAutoSize() != 0) {
// a cache will be automatically created.
// No need for TTreePlayer::Process to enable the cache
fCacheSize = 0;
} else if (fAutoFlush < 0) {
// If there is no autoflush set, let's keep the cache completely
// disable by default for now.
fCacheSize = fAutoFlush;
} else if (fAutoFlush != 0) {
// Estimate the cluster size.
// This will allow TTree::Process to enable the cache.
Long64_t zipBytes = GetZipBytes();
Long64_t totBytes = GetTotBytes();
if (zipBytes != 0) {
fCacheSize = fAutoFlush*(zipBytes/fEntries);
} else if (totBytes != 0) {
fCacheSize = fAutoFlush*(totBytes/fEntries);
} else {
fCacheSize = 30000000;
}
if (fCacheSize >= (INT_MAX / 4)) {
fCacheSize = INT_MAX / 4;
} else if (fCacheSize == 0) {
fCacheSize = 30000000;
}
} else {
fCacheSize = 0;
}
ResetBit(kMustCleanup);
return;
}
//====process old versions before automatic schema evolution
Stat_t djunk;
Int_t ijunk;
TNamed::Streamer(b);
TAttLine::Streamer(b);
TAttFill::Streamer(b);
TAttMarker::Streamer(b);
b >> fScanField;
b >> ijunk; fMaxEntryLoop = (Long64_t)ijunk;
b >> ijunk; fMaxVirtualSize = (Long64_t)ijunk;
b >> djunk; fEntries = (Long64_t)djunk;
b >> djunk; fTotBytes = (Long64_t)djunk;
b >> djunk; fZipBytes = (Long64_t)djunk;
b >> ijunk; fAutoSave = (Long64_t)ijunk;
b >> ijunk; fEstimate = (Long64_t)ijunk;
if (fEstimate <= 10000) fEstimate = 1000000;
fBranches.Streamer(b);
if (fBranchRef) fBranchRef->SetTree(this);
TBranch__SetTree(this,fBranches);
fLeaves.Streamer(b);
fSavedBytes = fTotBytes;
if (R__v > 1) fIndexValues.Streamer(b);
if (R__v > 2) fIndex.Streamer(b);
if (R__v > 3) {
TList OldInfoList;
OldInfoList.Streamer(b);
OldInfoList.Delete();
}
fNClusterRange = 0;
fDefaultEntryOffsetLen = 1000;
ResetBit(kMustCleanup);
b.CheckByteCount(R__s, R__c, TTree::IsA());
//====end of old versions
} else {
if (fBranchRef) {
fBranchRef->Clear();
}
TRefTable *table = TRefTable::GetRefTable();
if (table) TRefTable::SetRefTable(0);
b.WriteClassBuffer(TTree::Class(), this);
if (table) TRefTable::SetRefTable(table);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Unbinned fit of one or more variable(s) from a tree.
///
/// funcname is a TF1 function.
///
/// See TTree::Draw for explanations of the other parameters.
///
/// Fit the variable varexp using the function funcname using the
/// selection cuts given by selection.
///
/// The list of fit options is given in parameter option.
///
/// - option = "Q" Quiet mode (minimum printing)
/// - option = "V" Verbose mode (default is between Q and V)
/// - option = "E" Perform better Errors estimation using Minos technique
/// - option = "M" More. Improve fit results
///
/// You can specify boundary limits for some or all parameters via
/// ~~~ {.cpp}
/// func->SetParLimits(p_number, parmin, parmax);
/// ~~~
/// if parmin>=parmax, the parameter is fixed
///
/// Note that you are not forced to fix the limits for all parameters.
/// For example, if you fit a function with 6 parameters, you can do:
/// ~~~ {.cpp}
/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
/// func->SetParLimits(4,-10,-4);
/// func->SetParLimits(5, 1,1);
/// ~~~
/// With this setup:
///
/// - Parameters 0->3 can vary freely
/// - Parameter 4 has boundaries [-10,-4] with initial value -8
/// - Parameter 5 is fixed to 100.
///
/// For the fit to be meaningful, the function must be self-normalized.
///
/// i.e. It must have the same integral regardless of the parameter
/// settings. Otherwise the fit will effectively just maximize the
/// area.
///
/// It is mandatory to have a normalization variable
/// which is fixed for the fit. e.g.
/// ~~~ {.cpp}
/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
/// f1->SetParameters(1, 3.1, 0.01);
/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
/// ~~~
/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
///
/// Return status:
///
/// - The function return the status of the fit in the following form
/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
/// - The fitResult is 0 is the fit is OK.
/// - The fitResult is negative in case of an error not connected with the fit.
/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
/// - If the number of selected entries is null the function returns -1
Int_t TTree::UnbinnedFit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
{
GetPlayer();
if (fPlayer) {
return fPlayer->UnbinnedFit(funcname, varexp, selection, option, nentries, firstentry);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Replace current attributes by current style.
void TTree::UseCurrentStyle()
{
if (gStyle->IsReading()) {
SetFillColor(gStyle->GetHistFillColor());
SetFillStyle(gStyle->GetHistFillStyle());
SetLineColor(gStyle->GetHistLineColor());
SetLineStyle(gStyle->GetHistLineStyle());
SetLineWidth(gStyle->GetHistLineWidth());
SetMarkerColor(gStyle->GetMarkerColor());
SetMarkerStyle(gStyle->GetMarkerStyle());
SetMarkerSize(gStyle->GetMarkerSize());
} else {
gStyle->SetHistFillColor(GetFillColor());
gStyle->SetHistFillStyle(GetFillStyle());
gStyle->SetHistLineColor(GetLineColor());
gStyle->SetHistLineStyle(GetLineStyle());
gStyle->SetHistLineWidth(GetLineWidth());
gStyle->SetMarkerColor(GetMarkerColor());
gStyle->SetMarkerStyle(GetMarkerStyle());
gStyle->SetMarkerSize(GetMarkerSize());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Write this object to the current directory. For more see TObject::Write
/// If option & kFlushBasket, call FlushBasket before writing the tree.
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
{
FlushBasketsImpl();
return TObject::Write(name, option, bufsize);
}
////////////////////////////////////////////////////////////////////////////////
/// Write this object to the current directory. For more see TObject::Write
/// If option & kFlushBasket, call FlushBasket before writing the tree.
Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize)
{
return ((const TTree*)this)->Write(name, option, bufsize);
}
////////////////////////////////////////////////////////////////////////////////
/// \class TTreeFriendLeafIter
///
/// Iterator on all the leaves in a TTree and its friend
ClassImp(TTreeFriendLeafIter);
////////////////////////////////////////////////////////////////////////////////
/// Create a new iterator. By default the iteration direction
/// is kIterForward. To go backward use kIterBackward.
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTree* tree, Bool_t dir)
: fTree(const_cast<TTree*>(tree))
, fLeafIter(0)
, fTreeIter(0)
, fDirection(dir)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor. Does NOT copy the 'cursor' location!
TTreeFriendLeafIter::TTreeFriendLeafIter(const TTreeFriendLeafIter& iter)
: TIterator(iter)
, fTree(iter.fTree)
, fLeafIter(0)
, fTreeIter(0)
, fDirection(iter.fDirection)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Overridden assignment operator. Does NOT copy the 'cursor' location!
TIterator& TTreeFriendLeafIter::operator=(const TIterator& rhs)
{
if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
const TTreeFriendLeafIter &rhs1 = (const TTreeFriendLeafIter &)rhs;
fDirection = rhs1.fDirection;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Overridden assignment operator. Does NOT copy the 'cursor' location!
TTreeFriendLeafIter& TTreeFriendLeafIter::operator=(const TTreeFriendLeafIter& rhs)
{
if (this != &rhs) {
fDirection = rhs.fDirection;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Go the next friend element
TObject* TTreeFriendLeafIter::Next()
{
if (!fTree) return 0;
TObject * next;
TTree * nextTree;
if (!fLeafIter) {
TObjArray *list = fTree->GetListOfLeaves();
if (!list) return 0; // Can happen with an empty chain.
fLeafIter = list->MakeIterator(fDirection);
if (!fLeafIter) return 0;
}
next = fLeafIter->Next();
if (!next) {
if (!fTreeIter) {
TCollection * list = fTree->GetListOfFriends();
if (!list) return next;
fTreeIter = list->MakeIterator(fDirection);
if (!fTreeIter) return 0;
}
TFriendElement * nextFriend = (TFriendElement*) fTreeIter->Next();
///nextTree = (TTree*)fTreeIter->Next();
if (nextFriend) {
nextTree = const_cast<TTree*>(nextFriend->GetTree());
if (!nextTree) return Next();
SafeDelete(fLeafIter);
fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
if (!fLeafIter) return 0;
next = fLeafIter->Next();
}
}
return next;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the object option stored in the list.
Option_t* TTreeFriendLeafIter::GetOption() const
{
if (fLeafIter) return fLeafIter->GetOption();
return "";
}
|
/** @file
HTTP state machine
@section license License
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
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 "../ProxyClientTransaction.h"
#include "HttpSM.h"
#include "HttpTransactHeaders.h"
#include "ProxyConfig.h"
#include "HttpServerSession.h"
#include "HttpDebugNames.h"
#include "HttpSessionManager.h"
#include "P_Cache.h"
#include "P_Net.h"
#include "StatPages.h"
#include "Log.h"
#include "LogAccessHttp.h"
#include "ICP.h"
#include "PluginVC.h"
#include "ReverseProxy.h"
#include "RemapProcessor.h"
#include "Transform.h"
#include "P_SSLConfig.h"
#include <openssl/ossl_typ.h>
#include <openssl/ssl.h>
#include "HttpPages.h"
#include "IPAllow.h"
//#include "I_Auth.h"
//#include "HttpAuthParams.h"
#include "congest/Congestion.h"
#include "ts/I_Layout.h"
#define DEFAULT_RESPONSE_BUFFER_SIZE_INDEX 6 // 8K
#define DEFAULT_REQUEST_BUFFER_SIZE_INDEX 6 // 8K
#define MIN_CONFIG_BUFFER_SIZE_INDEX 5 // 4K
#define hsm_release_assert(EX) \
{ \
if (!(EX)) { \
this->dump_state_on_assert(); \
_ink_assert(#EX, __FILE__, __LINE__); \
} \
}
/*
* Comment this off if you don't
* want httpSM to use new_empty_MIOBuffer(..) call
*/
#define USE_NEW_EMPTY_MIOBUFFER
extern int cache_config_read_while_writer;
// We have a debugging list that can use to find stuck
// state machines
DList(HttpSM, debug_link) debug_sm_list;
ink_mutex debug_sm_list_mutex;
static const int sub_header_size = sizeof("Content-type: ") - 1 + 2 + sizeof("Content-range: bytes ") - 1 + 4;
static const int boundary_size = 2 + sizeof("RANGE_SEPARATOR") - 1 + 2;
static const char *str_100_continue_response = "HTTP/1.1 100 Continue\r\n\r\n";
static const int len_100_continue_response = strlen(str_100_continue_response);
static const char *str_408_request_timeout_response = "HTTP/1.1 408 Request Timeout\r\nConnection: close\r\n\r\n";
static const int len_408_request_timeout_response = strlen(str_408_request_timeout_response);
namespace
{
/// Update the milestone state given the milestones and timer.
inline void
milestone_update_api_time(TransactionMilestones &milestones, ink_hrtime &api_timer)
{
// Bit of funkiness - we set @a api_timer to be the negative value when we're tracking
// non-active API time. In that case we need to make a note of it and flip the value back
// to positive.
if (api_timer) {
ink_hrtime delta;
bool active = api_timer >= 0;
if (!active) {
api_timer = -api_timer;
}
delta = Thread::get_hrtime_updated() - api_timer;
api_timer = 0;
// Zero or negative time is a problem because we want to signal *something* happened
// vs. no API activity at all. This can happen due to graininess or real time
// clock adjustment.
if (delta <= 0) {
delta = 1;
}
if (0 == milestones[TS_MILESTONE_PLUGIN_TOTAL]) {
milestones[TS_MILESTONE_PLUGIN_TOTAL] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_TOTAL] += delta;
if (active) {
if (0 == milestones[TS_MILESTONE_PLUGIN_ACTIVE]) {
milestones[TS_MILESTONE_PLUGIN_ACTIVE] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_ACTIVE] += delta;
}
}
}
}
ClassAllocator<HttpSM> httpSMAllocator("httpSMAllocator");
HttpVCTable::HttpVCTable()
{
memset(&vc_table, 0, sizeof(vc_table));
}
HttpVCTableEntry *
HttpVCTable::new_entry()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == nullptr) {
return vc_table + i;
}
}
ink_release_assert(0);
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VConnection *vc)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == vc) {
return vc_table + i;
}
}
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VIO *vio)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].read_vio == vio || vc_table[i].write_vio == vio) {
ink_assert(vc_table[i].vc != nullptr);
return vc_table + i;
}
}
return nullptr;
}
// bool HttpVCTable::remove_entry(HttpVCEntry* e)
//
// Deallocates all buffers from the associated
// entry and re-initializes it's other fields
// for reuse
//
void
HttpVCTable::remove_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc == nullptr || e->in_tunnel);
e->vc = nullptr;
e->eos = false;
if (e->read_buffer) {
free_MIOBuffer(e->read_buffer);
e->read_buffer = nullptr;
}
if (e->write_buffer) {
free_MIOBuffer(e->write_buffer);
e->write_buffer = nullptr;
}
e->read_vio = nullptr;
e->write_vio = nullptr;
e->vc_handler = nullptr;
e->vc_type = HTTP_UNKNOWN;
e->in_tunnel = false;
}
// bool HttpVCTable::cleanup_entry(HttpVCEntry* e)
//
// Closes the associate vc for the entry,
// and the call remove_entry
//
void
HttpVCTable::cleanup_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc);
if (e->in_tunnel == false) {
// Update stats
switch (e->vc_type) {
case HTTP_UA_VC:
// proxy.process.http.current_client_transactions is decremented in HttpSM::destroy
break;
default:
// This covers:
// HTTP_UNKNOWN, HTTP_SERVER_VC, HTTP_TRANSFORM_VC, HTTP_CACHE_READ_VC,
// HTTP_CACHE_WRITE_VC, HTTP_RAW_SERVER_VC
break;
}
e->vc->do_io_close();
e->vc = nullptr;
}
remove_entry(e);
}
void
HttpVCTable::cleanup_all()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc != nullptr) {
cleanup_entry(vc_table + i);
}
}
}
#define REMEMBER_EVENT_FILTER(e) 1
#define __REMEMBER(x) #x
#define _REMEMBER(x) __REMEMBER(x)
#define RECORD_FILE_LINE() history[pos].fileline = __FILE__ ":" _REMEMBER(__LINE__);
#define REMEMBER(e, r) \
{ \
if (REMEMBER_EVENT_FILTER(e)) { \
add_history_entry(__FILE__ ":" _REMEMBER(__LINE__), e, r); \
} \
}
#define DebugSM(tag, ...) DebugSpecific(debug_on, tag, __VA_ARGS__)
#ifdef STATE_ENTER
#undef STATE_ENTER
#endif
#define STATE_ENTER(state_name, event) \
{ \
/*ink_assert (magic == HTTP_SM_MAGIC_ALIVE); */ REMEMBER(event, reentrancy_count); \
DebugSM("http", "[%" PRId64 "] [%s, %s]", sm_id, #state_name, HttpDebugNames::get_event_name(event)); \
}
#define HTTP_SM_SET_DEFAULT_HANDLER(_h) \
{ \
REMEMBER(-1, reentrancy_count); \
default_handler = _h; \
}
static int next_sm_id = 0;
HttpSM::HttpSM()
: Continuation(nullptr),
sm_id(-1),
magic(HTTP_SM_MAGIC_DEAD),
// YTS Team, yamsat Plugin
enable_redirection(false),
redirect_url(nullptr),
redirect_url_len(0),
redirection_tries(0),
transfered_bytes(0),
post_failed(false),
debug_on(false),
plugin_tunnel_type(HTTP_NO_PLUGIN_TUNNEL),
plugin_tunnel(nullptr),
reentrancy_count(0),
history_pos(0),
tunnel(),
ua_entry(nullptr),
ua_session(nullptr),
background_fill(BACKGROUND_FILL_NONE),
ua_raw_buffer_reader(nullptr),
server_entry(nullptr),
server_session(nullptr),
will_be_private_ss(false),
shared_session_retries(0),
server_buffer_reader(nullptr),
transform_info(),
post_transform_info(),
has_active_plugin_agents(false),
second_cache_sm(nullptr),
default_handler(nullptr),
pending_action(nullptr),
last_action(HttpTransact::SM_ACTION_UNDEFINED),
// TODO: Now that bodies can be empty, should the body counters be set to -1 ? TS-2213
client_request_hdr_bytes(0),
client_request_body_bytes(0),
server_request_hdr_bytes(0),
server_request_body_bytes(0),
server_response_hdr_bytes(0),
server_response_body_bytes(0),
client_response_hdr_bytes(0),
client_response_body_bytes(0),
cache_response_hdr_bytes(0),
cache_response_body_bytes(0),
pushed_response_hdr_bytes(0),
pushed_response_body_bytes(0),
client_tcp_reused(false),
client_ssl_reused(false),
client_connection_is_ssl(false),
client_protocol("-"),
client_sec_protocol("-"),
client_cipher_suite("-"),
server_transact_count(0),
server_connection_is_ssl(false),
plugin_tag(nullptr),
plugin_id(0),
hooks_set(false),
cur_hook_id(TS_HTTP_LAST_HOOK),
cur_hook(nullptr),
cur_hooks(0),
callout_state(HTTP_API_NO_CALLOUT),
terminate_sm(false),
kill_this_async_done(false),
parse_range_done(false)
{
memset(&history, 0, sizeof(history));
memset(&vc_table, 0, sizeof(vc_table));
memset(&http_parser, 0, sizeof(http_parser));
}
void
HttpSM::cleanup()
{
t_state.destroy();
api_hooks.clear();
http_parser_clear(&http_parser);
// t_state.content_control.cleanup();
HttpConfig::release(t_state.http_config_param);
mutex.clear();
tunnel.mutex.clear();
cache_sm.mutex.clear();
transform_cache_sm.mutex.clear();
if (second_cache_sm) {
second_cache_sm->mutex.clear();
delete second_cache_sm;
}
magic = HTTP_SM_MAGIC_DEAD;
debug_on = false;
}
void
HttpSM::destroy()
{
cleanup();
httpSMAllocator.free(this);
}
void
HttpSM::init()
{
milestones[TS_MILESTONE_SM_START] = Thread::get_hrtime();
magic = HTTP_SM_MAGIC_ALIVE;
sm_id = 0;
// Unique state machine identifier.
// changed next_sm_id from int64_t to int because
// atomic(32) is faster than atomic64. The id is just
// for debugging, so it's OK if it wraps every few days,
// as long as the http_info bucket hash still works.
// (To test this, initialize next_sm_id to 0x7ffffff0)
// Leaving sm_id as int64_t to minimize code changes.
sm_id = (int64_t)ink_atomic_increment((&next_sm_id), 1);
t_state.state_machine_id = sm_id;
t_state.state_machine = this;
t_state.http_config_param = HttpConfig::acquire();
// Simply point to the global config for the time being, no need to copy this
// entire struct if nothing is going to change it.
t_state.txn_conf = &t_state.http_config_param->oride;
// update the cache info config structure so that
// selection from alternates happens correctly.
t_state.cache_info.config.cache_global_user_agent_header = t_state.txn_conf->global_user_agent_header ? true : false;
t_state.cache_info.config.ignore_accept_mismatch = t_state.http_config_param->ignore_accept_mismatch;
t_state.cache_info.config.ignore_accept_language_mismatch = t_state.http_config_param->ignore_accept_language_mismatch;
t_state.cache_info.config.ignore_accept_encoding_mismatch = t_state.http_config_param->ignore_accept_encoding_mismatch;
t_state.cache_info.config.ignore_accept_charset_mismatch = t_state.http_config_param->ignore_accept_charset_mismatch;
t_state.cache_info.config.cache_enable_default_vary_headers =
t_state.http_config_param->cache_enable_default_vary_headers ? true : false;
t_state.cache_info.config.cache_vary_default_text = t_state.http_config_param->cache_vary_default_text;
t_state.cache_info.config.cache_vary_default_images = t_state.http_config_param->cache_vary_default_images;
t_state.cache_info.config.cache_vary_default_other = t_state.http_config_param->cache_vary_default_other;
t_state.init();
// Added to skip dns if the document is in cache. DNS will be forced if there is a ip based ACL in
// cache control or parent.config or if the doc_in_cache_skip_dns is disabled or if http caching is disabled
// TODO: This probably doesn't honor this as a per-transaction overridable config.
t_state.force_dns = (ip_rule_in_CacheControlTable() || t_state.parent_params->parent_table->ipMatch ||
!(t_state.txn_conf->doc_in_cache_skip_dns) || !(t_state.txn_conf->cache_http));
http_parser.m_allow_non_http = t_state.http_config_param->parser_allow_non_http;
http_parser_init(&http_parser);
SET_HANDLER(&HttpSM::main_handler);
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.push(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
}
void
HttpSM::set_ua_half_close_flag()
{
ua_session->set_half_close_flag(true);
}
inline void
HttpSM::do_api_callout()
{
if (hooks_set) {
do_api_callout_internal();
} else {
handle_api_return();
}
}
int
HttpSM::state_add_to_list(int event, void * /* data ATS_UNUSED */)
{
// The list if for stat pages and general debugging
// The config variable exists mostly to allow us to
// measure an performance drop during benchmark runs
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_add_to_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = ((unsigned int)sm_id % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
// the client_vc`s timeout events can be triggered, so we should not
// reschedule the http_sm when the lock is not acquired.
// FIXME: the sm_list may miss some http_sms when the lock contention
if (lock.is_locked()) {
HttpSMList[bucket].sm_list.push(this);
}
}
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_START;
do_api_callout();
return EVENT_DONE;
}
int
HttpSM::state_remove_from_list(int event, void * /* data ATS_UNUSED */)
{
// The config parameters are guaranteed not change
// across the life of a transaction so it safe to
// check the config here and use it determine
// whether we need to strip ourselves off of the
// state page list
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_remove_from_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = ((unsigned int)sm_id % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
if (!lock.is_locked()) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_remove_from_list);
mutex->thread_holding->schedule_in(this, HTTP_LIST_RETRY);
return EVENT_DONE;
}
HttpSMList[bucket].sm_list.remove(this);
}
return this->kill_this_async_hook(EVENT_NONE, nullptr);
}
int
HttpSM::kill_this_async_hook(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */)
{
// In the base HttpSM, we don't have anything to
// do here. subclasses can override this function
// to do their own asynchronous cleanup
// So We're now ready to finish off the state machine
terminate_sm = true;
kill_this_async_done = true;
return EVENT_DONE;
}
void
HttpSM::start_sub_sm()
{
tunnel.init(this, mutex);
cache_sm.init(this, mutex);
transform_cache_sm.init(this, mutex);
}
void
HttpSM::attach_client_session(ProxyClientTransaction *client_vc, IOBufferReader *buffer_reader)
{
milestones[TS_MILESTONE_UA_BEGIN] = Thread::get_hrtime();
ink_assert(client_vc != nullptr);
NetVConnection *netvc = client_vc->get_netvc();
if (!netvc) {
return;
}
ua_session = client_vc;
// Collect log & stats information
client_tcp_reused = !(ua_session->is_first_transaction());
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc);
if (ssl_vc != nullptr) {
client_connection_is_ssl = true;
client_ssl_reused = ssl_vc->getSSLSessionCacheHit();
const char *protocol = ssl_vc->getSSLProtocol();
client_sec_protocol = protocol ? protocol : "-";
const char *cipher = ssl_vc->getSSLCipherSuite();
client_cipher_suite = cipher ? cipher : "-";
}
const char *protocol_str = client_vc->get_protocol_string();
client_protocol = protocol_str ? protocol_str : "-";
ink_release_assert(ua_session->get_half_close_flag() == false);
mutex = client_vc->mutex;
HTTP_INCREMENT_DYN_STAT(http_current_client_transactions_stat);
if (ua_session->debug()) {
debug_on = true;
}
start_sub_sm();
// Allocate a user agent entry in the state machine's
// vc table
ua_entry = vc_table.new_entry();
ua_entry->vc = client_vc;
ua_entry->vc_type = HTTP_UA_VC;
ats_ip_copy(&t_state.client_info.src_addr, netvc->get_remote_addr());
ats_ip_copy(&t_state.client_info.dst_addr, netvc->get_local_addr());
t_state.client_info.dst_addr.port() = netvc->get_local_port();
t_state.client_info.is_transparent = netvc->get_is_transparent();
t_state.backdoor_request = !client_vc->hooks_enabled();
t_state.client_info.port_attribute = static_cast<HttpProxyPort::TransportType>(netvc->attributes);
// Record api hook set state
hooks_set = client_vc->has_hooks();
// Setup for parsing the header
ua_buffer_reader = buffer_reader;
ua_entry->vc_handler = &HttpSM::state_read_client_request_header;
t_state.hdr_info.client_request.destroy();
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
http_parser_init(&http_parser);
// Prepare raw reader which will live until we are sure this is HTTP indeed
if (is_transparent_passthrough_allowed()) {
ua_raw_buffer_reader = buffer_reader->clone();
}
// We first need to run the transaction start hook. Since
// this hook maybe asynchronous, we need to disable IO on
// client but set the continuation to be the state machine
// so if we get an timeout events the sm handles them
ua_entry->read_vio = client_vc->do_io_read(this, 0, buffer_reader->mbuf);
/////////////////////////
// set up timeouts //
/////////////////////////
client_vc->set_inactivity_timeout(HRTIME_SECONDS(t_state.http_config_param->accept_no_activity_timeout));
client_vc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_in));
++reentrancy_count;
// Add our state sm to the sm list
state_add_to_list(EVENT_NONE, nullptr);
// This is another external entry point and it is possible for the state machine to get terminated
// while down the call chain from @c state_add_to_list. So we need to use the reentrancy_count to
// prevent cleanup there and do it here as we return to the external caller.
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
--reentrancy_count;
ink_assert(reentrancy_count >= 0);
}
}
void
HttpSM::setup_client_read_request_header()
{
ink_assert(ua_entry->vc_handler == &HttpSM::state_read_client_request_header);
ua_entry->read_vio = ua_session->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
// The header may already be in the buffer if this
// a request from a keep-alive connection
handleEvent(VC_EVENT_READ_READY, ua_entry->read_vio);
}
void
HttpSM::setup_blind_tunnel_port()
{
// We gotten a connect on a port for blind tunneling so
// call transact figure out where it is going
call_transact_and_set_next_state(HttpTransact::HandleBlindTunnel);
}
int
HttpSM::state_read_client_request_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_client_request_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(server_entry == nullptr);
ink_assert(server_session == nullptr);
int bytes_used = 0;
ink_assert(ua_entry->eos == false);
NetVConnection *netvc = ua_session->get_netvc();
if (!netvc && event != VC_EVENT_EOS) {
return 0;
}
switch (event) {
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_EOS:
ua_entry->eos = true;
if ((client_request_hdr_bytes > 0) && is_transparent_passthrough_allowed() && (ua_raw_buffer_reader != nullptr)) {
break;
}
// Fall through
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Close it &
// bail on the state machine
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
t_state.client_info.abort = HttpTransact::ABORTED;
terminate_sm = true;
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the accept timeout by the ProxyClientTransaction
//
if ((ua_buffer_reader->read_avail() > 0) && (client_request_hdr_bytes == 0)) {
milestones[TS_MILESTONE_UA_FIRST_READ] = Thread::get_hrtime();
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state = t_state.hdr_info.client_request.parse_req(&http_parser, ua_buffer_reader, &bytes_used, ua_entry->eos,
t_state.http_config_param->strict_uri_parsing);
client_request_hdr_bytes += bytes_used;
// Check to see if we are over the hdr size limit
if (client_request_hdr_bytes > t_state.txn_conf->request_hdr_max_size) {
DebugSM("http", "client header bytes were over max header size; treating as a bad request");
state = PARSE_RESULT_ERROR;
}
// We need to handle EOS as well as READ_READY because the client
// may have sent all of the data already followed by a fIN and that
// should be OK.
if (is_transparent_passthrough_allowed() && ua_raw_buffer_reader != nullptr) {
bool do_blind_tunnel = false;
// If we had a parse error and we're done reading data
// blind tunnel
if ((event == VC_EVENT_READ_READY || event == VC_EVENT_EOS) && state == PARSE_RESULT_ERROR) {
do_blind_tunnel = true;
// If we had a GET request that has data after the
// get request, do blind tunnel
} else if (state == PARSE_RESULT_DONE && t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET &&
ua_buffer_reader->read_avail() > 0 && !t_state.hdr_info.client_request.is_keep_alive_set()) {
do_blind_tunnel = true;
}
if (do_blind_tunnel) {
DebugSM("http", "[%" PRId64 "] first request on connection failed parsing, switching to passthrough.", sm_id);
t_state.transparent_passthrough = true;
http_parser_clear(&http_parser);
// Turn off read eventing until we get the
// blind tunnel infrastructure set up
if (netvc) {
netvc->do_io_read(this, 0, nullptr);
}
/* establish blind tunnel */
setup_blind_tunnel_port();
// Setting half close means we will send the FIN when we've written all of the data.
if (event == VC_EVENT_EOS) {
this->set_ua_half_close_flag();
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
return 0;
}
}
// Check to see if we are done parsing the header
if (state != PARSE_RESULT_CONT || ua_entry->eos || (state == PARSE_RESULT_CONT && event == VC_EVENT_READ_COMPLETE)) {
if (ua_raw_buffer_reader != nullptr) {
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
http_parser_clear(&http_parser);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
milestones[TS_MILESTONE_UA_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
DebugSM("http", "[%" PRId64 "] error parsing client request header", sm_id);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
case PARSE_RESULT_CONT:
if (ua_entry->eos) {
DebugSM("http_seq", "[%" PRId64 "] EOS before client request parsing finished", sm_id);
set_ua_abort(HttpTransact::ABORTED, event);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
} else if (event == VC_EVENT_READ_COMPLETE) {
DebugSM("http_parse", "[%" PRId64 "] VC_EVENT_READ_COMPLETE and PARSE CONT state", sm_id);
break;
} else {
if (is_transparent_passthrough_allowed() && ua_raw_buffer_reader != nullptr &&
ua_raw_buffer_reader->get_current_block()->write_avail() <= 0) {
// Disable passthrough regardless of eventual parsing failure or success -- otherwise
// we either have to consume some data or risk blocking the writer.
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
}
case PARSE_RESULT_DONE:
DebugSM("http", "[%" PRId64 "] done parsing client request header", sm_id);
ua_session->set_session_active();
if (t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 1) &&
(t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_POST ||
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_PUT) &&
t_state.http_config_param->send_100_continue_response) {
int len = 0;
const char *expect = t_state.hdr_info.client_request.value_get(MIME_FIELD_EXPECT, MIME_LEN_EXPECT, &len);
// When receive an "Expect: 100-continue" request from client, ATS sends a "100 Continue" response to client
// immediately, before receive the real response from original server.
if ((len == HTTP_LEN_100_CONTINUE) && (strncasecmp(expect, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0)) {
int64_t alloc_index = buffer_size_to_index(len_100_continue_response);
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
ua_entry->write_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = ua_entry->write_buffer->alloc_reader();
DebugSM("http_seq", "send 100 Continue response to client");
int64_t nbytes = ua_entry->write_buffer->write(str_100_continue_response, len_100_continue_response);
ua_session->do_io_write(netvc, nbytes, buf_start);
}
}
if (t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_TRACE ||
(t_state.hdr_info.request_content_length <= 0 && t_state.client_info.transfer_encoding != HttpTransact::CHUNKED_ENCODING)) {
// Enable further IO to watch for client aborts
ua_entry->read_vio->reenable();
} else {
// Disable further I/O on the client since there could
// be body that we are tunneling POST/PUT/CONNECT or
// extension methods and we can't issue another
// another IO later for the body with a different buffer
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
// YTS Team, yamsat Plugin
// Setting enable_redirection according to HttpConfig master
if ((t_state.txn_conf->number_of_redirections > 0) ||
(t_state.method == HTTP_WKSIDX_POST && HttpConfig::m_master.post_copy_size)) {
enable_redirection = t_state.txn_conf->redirection_enabled;
}
call_transact_and_set_next_state(HttpTransact::ModifyRequest);
break;
default:
ink_assert(!"not reached");
}
return 0;
}
#ifdef PROXY_DRAIN
int
HttpSM::state_drain_client_request_body(int event, void *data)
{
STATE_ENTER(&HttpSM::state_drain_client_request_body, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(ua_entry->vc == ua_session);
NetVConnection *netvc = ua_session->get_netvc();
if (!netvc && event != VC_EVENT_EOS)
return 0;
switch (event) {
case VC_EVENT_EOS:
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT: {
// Nothing we can do
terminate_sm = true;
break;
}
case VC_EVENT_READ_READY: {
int64_t avail = ua_buffer_reader->read_avail();
int64_t left = t_state.hdr_info.request_content_length - client_request_body_bytes;
// Since we are only reading what's needed to complete
// the post, there must be something left to do
ink_assert(avail < left);
client_request_body_bytes += avail;
ua_buffer_reader->consume(avail);
ua_entry->read_vio->reenable_re();
break;
}
case VC_EVENT_READ_COMPLETE: {
// We've finished draing the POST body
int64_t avail = ua_buffer_reader->read_avail();
ua_buffer_reader->consume(avail);
client_request_body_bytes += avail;
ink_assert(client_request_body_bytes == t_state.hdr_info.request_content_length);
ua_buffer_reader->mbuf->size_index = HTTP_HEADER_BUFFER_SIZE_INDEX;
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = ua_entry->vc->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
call_transact_and_set_next_state(NULL);
break;
}
default:
ink_release_assert(0);
}
return EVENT_DONE;
}
#endif /* PROXY_DRAIN */
int
HttpSM::state_watch_for_client_abort(int event, void *data)
{
STATE_ENTER(&HttpSM::state_watch_for_client_abort, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(ua_entry->vc == ua_session);
switch (event) {
/* EOS means that the client has initiated the connection shut down.
* Only half close the client connection so ATS can read additional
* data that may still be sent from the server and send it to the
* client.
*/
case VC_EVENT_EOS: {
// We got an early EOS.
NetVConnection *netvc = ua_session->get_netvc();
if (ua_session->allow_half_open()) {
if (netvc) {
netvc->do_io_shutdown(IO_SHUTDOWN_READ);
}
ua_entry->eos = true;
} else {
ua_session->do_io_close();
ua_buffer_reader = nullptr;
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
tunnel.kill_tunnel();
terminate_sm = true; // Just die already, the requester is gone
}
break;
}
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT: {
if (tunnel.is_tunnel_active()) {
// Check to see if the user agent is part of the tunnel.
// If so forward the event to the tunnel. Otherwise,
// kill the tunnel and fallthrough to the case
// where the tunnel is not active
HttpTunnelConsumer *c = tunnel.get_consumer(ua_session);
if (c && c->alive) {
DebugSM("http", "[%" PRId64 "] [watch_for_client_abort] "
"forwarding event %s to tunnel",
sm_id, HttpDebugNames::get_event_name(event));
tunnel.handleEvent(event, c->write_vio);
return 0;
} else {
tunnel.kill_tunnel();
}
}
// Disable further I/O on the client
if (ua_entry->read_vio) {
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
mark_server_down_on_client_abort();
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
set_ua_abort(HttpTransact::ABORTED, event);
terminate_sm = true;
break;
}
case VC_EVENT_READ_COMPLETE:
// XXX Work around for TS-1233.
case VC_EVENT_READ_READY:
// Ignore. Could be a pipelined request. We'll get to it
// when we finish the current transaction
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
void
HttpSM::setup_push_read_response_header()
{
ink_assert(server_session == nullptr);
ink_assert(server_entry == nullptr);
ink_assert(ua_session != nullptr);
ink_assert(t_state.method == HTTP_WKSIDX_PUSH);
// Set the handler to read the pushed response hdr
ua_entry->vc_handler = &HttpSM::state_read_push_response_header;
// We record both the total payload size as
// client_request_body_bytes and the bytes for the individual
// pushed hdr and body components
pushed_response_hdr_bytes = 0;
client_request_body_bytes = 0;
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
// We already done the READ when we read the client
// request header
ink_assert(ua_entry->read_vio);
// If there is anything in the buffer call the parsing routines
// since if the response is finished, we won't get any
// additional callbacks
int resp_hdr_state = VC_EVENT_CONT;
if (ua_buffer_reader->read_avail() > 0) {
if (ua_entry->eos) {
resp_hdr_state = state_read_push_response_header(VC_EVENT_EOS, ua_entry->read_vio);
} else {
resp_hdr_state = state_read_push_response_header(VC_EVENT_READ_READY, ua_entry->read_vio);
}
}
// It is possible that the entire PUSHed response header was already
// in the buffer. In this case we don't want to fire off any more
// IO since we are going to switch buffers when we go to tunnel to
// the cache
if (resp_hdr_state == VC_EVENT_CONT) {
ink_assert(ua_entry->eos == false);
ua_entry->read_vio = ua_session->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
}
}
int
HttpSM::state_read_push_response_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_push_response_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(t_state.current.server == nullptr);
int64_t data_size = 0;
int64_t bytes_used = 0;
// Not used here.
// bool parse_error = false;
// VIO* vio = (VIO*) data;
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// Fall through
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Send an error
t_state.client_info.abort = HttpTransact::ABORTED;
call_transact_and_set_next_state(HttpTransact::HandleBadPushRespHdr);
return 0;
}
int state = PARSE_RESULT_CONT;
while (ua_buffer_reader->read_avail() && state == PARSE_RESULT_CONT) {
const char *start = ua_buffer_reader->start();
const char *tmp = start;
data_size = ua_buffer_reader->block_read_avail();
ink_assert(data_size >= 0);
/////////////////////
// tokenize header //
/////////////////////
state =
t_state.hdr_info.server_response.parse_resp(&http_parser, &tmp, tmp + data_size, false // Only call w/ eof when data exhausted
);
bytes_used = tmp - start;
ink_release_assert(bytes_used <= data_size);
ua_buffer_reader->consume(bytes_used);
pushed_response_hdr_bytes += bytes_used;
client_request_body_bytes += bytes_used;
}
// We are out of data. If we've received an EOS we need to
// call the parser with (eof == true) so it can determine
// whether to use the response as is or declare a parse error
if (ua_entry->eos) {
const char *end = ua_buffer_reader->start();
state = t_state.hdr_info.server_response.parse_resp(&http_parser, &end, end, true // We are out of data after server eos
);
ink_release_assert(state == PARSE_RESULT_DONE || state == PARSE_RESULT_ERROR);
}
// Don't allow 0.9 (unparsable headers) since TS doesn't
// cache 0.9 responses
if (state == PARSE_RESULT_DONE && t_state.hdr_info.server_response.version_get() == HTTPVersion(0, 9)) {
state = PARSE_RESULT_ERROR;
}
if (state != PARSE_RESULT_CONT) {
// Disable further IO
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
http_parser_clear(&http_parser);
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
DebugSM("http", "[%" PRId64 "] error parsing push response header", sm_id);
call_transact_and_set_next_state(HttpTransact::HandleBadPushRespHdr);
break;
case PARSE_RESULT_CONT:
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
case PARSE_RESULT_DONE:
DebugSM("http", "[%" PRId64 "] done parsing push response header", sm_id);
call_transact_and_set_next_state(HttpTransact::HandlePushResponseHdr);
break;
default:
ink_assert(!"not reached");
}
return VC_EVENT_DONE;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_http_server_open()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_raw_http_server_open(int event, void *data)
{
STATE_ENTER(&HttpSM::state_raw_http_server_open, event);
ink_assert(server_entry == nullptr);
milestones[TS_MILESTONE_SERVER_CONNECT_END] = Thread::get_hrtime();
NetVConnection *netvc = nullptr;
pending_action = nullptr;
switch (event) {
case EVENT_INTERVAL:
// If we get EVENT_INTERNAL it means that we moved the transaction
// to a different thread in do_http_server_open. Since we didn't
// do any of the actual work in do_http_server_open, we have to
// go back and do it now.
do_http_server_open(true);
return 0;
case NET_EVENT_OPEN:
if (t_state.pCongestionEntry != nullptr) {
t_state.pCongestionEntry->connection_opened();
t_state.congestion_connection_opened = 1;
}
// Record the VC in our table
server_entry = vc_table.new_entry();
server_entry->vc = netvc = (NetVConnection *)data;
server_entry->vc_type = HTTP_RAW_SERVER_VC;
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
netvc->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
netvc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_out));
break;
case VC_EVENT_ERROR:
case NET_EVENT_OPEN_FAILED:
if (t_state.pCongestionEntry != nullptr) {
t_state.current.state = HttpTransact::CONNECTION_ERROR;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return 0;
} else {
t_state.current.state = HttpTransact::OPEN_RAW_ERROR;
// use this value just to get around other values
t_state.hdr_info.response_error = HttpTransact::STATUS_CODE_SERVER_ERROR;
}
break;
case CONGESTION_EVENT_CONGESTED_ON_F:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_F;
break;
case CONGESTION_EVENT_CONGESTED_ON_M:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_M;
break;
default:
ink_release_assert(0);
break;
}
call_transact_and_set_next_state(HttpTransact::OriginServerRawOpen);
return 0;
}
// int HttpSM::state_request_wait_for_transform_read(int event, void* data)
//
// We've done a successful transform open and issued a do_io_write
// to the transform. We are now ready for the transform to tell
// us it is now ready to be read from and it done modifying the
// server request header
//
int
HttpSM::state_request_wait_for_transform_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_request_wait_for_transform_read, event);
int64_t size = *((int64_t *)data);
switch (event) {
case TRANSFORM_READ_READY:
if (size != INT64_MAX && size >= 0) {
// We got a content length so update our internal
// data as well as fix up the request header
t_state.hdr_info.transform_request_cl = size;
t_state.hdr_info.server_request.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, size);
setup_server_send_request_api();
break;
} else {
// No content length from the post. This is a no go
// since http spec requires content length when
// sending a request message body. Change the event
// to an error and fall through
event = VC_EVENT_ERROR;
Log::error("Request transformation failed to set content length");
}
// FALLTHROUGH
default:
state_common_wait_for_transform_read(&post_transform_info, &HttpSM::tunnel_handler_post, event, data);
break;
}
return 0;
}
// int HttpSM::state_response_wait_for_transform_read(int event, void* data)
//
// We've done a successful transform open and issued a do_io_write
// to the transform. We are now ready for the transform to tell
// us it is now ready to be read from and it done modifying the
// user agent response header
//
int
HttpSM::state_response_wait_for_transform_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_response_wait_for_transform_read, event);
int64_t size = *((int64_t *)data);
switch (event) {
case TRANSFORM_READ_READY:
if (size != INT64_MAX && size >= 0) {
// We got a content length so update our internal state
t_state.hdr_info.transform_response_cl = size;
t_state.hdr_info.transform_response.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, size);
} else {
t_state.hdr_info.transform_response_cl = HTTP_UNDEFINED_CL;
}
call_transact_and_set_next_state(HttpTransact::handle_transform_ready);
break;
default:
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
break;
}
return 0;
}
// int HttpSM::state_common_wait_for_transform_read(...)
//
// This function handles the overlapping cases between request and response
// transforms which prevents code duplication
//
int
HttpSM::state_common_wait_for_transform_read(HttpTransformInfo *t_info, HttpSMHandler tunnel_handler, int event, void *data)
{
STATE_ENTER(&HttpSM::state_common_wait_for_transform_read, event);
HttpTunnelConsumer *c = nullptr;
switch (event) {
case HTTP_TUNNEL_EVENT_DONE:
// There are three reasons why the the tunnel could signal completed
// 1) there was error from the transform write
// 2) there was an error from the data source
// 3) the transform write completed before it sent
// TRANSFORM_READ_READY which is legal and in which
// case we should just wait for the transform read ready
c = tunnel.get_consumer(t_info->vc);
ink_assert(c != nullptr);
ink_assert(c->vc == t_info->entry->vc);
if (c->handler_state == HTTP_SM_TRANSFORM_FAIL) {
// Case 1 we failed to complete the write to the
// transform fall through to vc event error case
ink_assert(c->write_success == false);
} else if (c->producer->read_success == false) {
// Case 2 - error from data source
if (c->producer->vc_type == HT_HTTP_CLIENT) {
// Our source is the client. POST can't
// be truncated so forward to the tunnel
// handler to clean this mess up
ink_assert(t_info == &post_transform_info);
return (this->*tunnel_handler)(event, data);
} else {
// On the response side, we just forward as much
// as we can of truncated documents so
// just don't cache the result
ink_assert(t_info == &transform_info);
t_state.api_info.cache_transformed = false;
return 0;
}
} else {
// Case 3 - wait for transform read ready
return 0;
}
// FALLTHROUGH
case VC_EVENT_ERROR:
// Transform VC sends NULL on error conditions
if (!c) {
c = tunnel.get_consumer(t_info->vc);
ink_assert(c != nullptr);
}
vc_table.cleanup_entry(t_info->entry);
t_info->entry = nullptr;
// In Case 1: error due to transform write,
// we need to keep the original t_info->vc for transform_cleanup()
// to skip do_io_close(); otherwise, set it to NULL.
if (c->handler_state != HTTP_SM_TRANSFORM_FAIL) {
t_info->vc = nullptr;
}
if (c->producer->vc_type == HT_HTTP_CLIENT) {
/* Producer was the user agent and there was a failure transforming the POST.
Handling this is challenging and this isn't the best way but it at least
avoids a crash due to trying to send a response to a NULL'd out user agent.
The problem with not closing the user agent is handling draining of the
rest of the POST - the user agent may well not check for a response until that's
done in which case we can get a deadlock where the user agent never reads the
error response because the POST wasn't drained and the buffers filled up.
Draining has a potential bad impact on any pipelining which must be considered.
If we're not going to drain properly the next best choice is to shut down the
entire state machine since (1) there's no point in finishing the POST to the
origin and (2) there's no user agent connection to which to send the error response.
*/
terminate_sm = true;
} else {
tunnel.kill_tunnel();
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
}
break;
default:
ink_release_assert(0);
}
return 0;
}
// int HttpSM::state_api_callback(int event, void *data)
// InkAPI.cc calls us directly here to avoid problems
// with setting and changing the default_handler
// function. As such, this is an entry point
// and needs to handle the reentrancy counter and
// deallocation the state machine if necessary
//
int
HttpSM::state_api_callback(int event, void *data)
{
ink_release_assert(magic == HTTP_SM_MAGIC_ALIVE);
ink_assert(reentrancy_count >= 0);
reentrancy_count++;
milestone_update_api_time(milestones, api_timer);
STATE_ENTER(&HttpSM::state_api_callback, event);
state_api_callout(event, data);
// The sub-handler signals when it is time for the state
// machine to exit. We can only exit if we are not reentrantly
// called otherwise when the our call unwinds, we will be
// running on a dead state machine
//
// Because of the need for an api shutdown hook, kill_this()
// is also reentrant. As such, we don't want to decrement
// the reentrancy count until after we run kill_this()
//
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
reentrancy_count--;
ink_assert(reentrancy_count >= 0);
}
return VC_EVENT_CONT;
}
int
HttpSM::state_api_callout(int event, void *data)
{
// enum and variable for figuring out what the next action is after
// after we've finished the api state
enum AfterApiReturn_t {
API_RETURN_UNKNOWN = 0,
API_RETURN_CONTINUE,
API_RETURN_DEFERED_CLOSE,
API_RETURN_DEFERED_SERVER_ERROR,
API_RETURN_ERROR_JUMP,
API_RETURN_SHUTDOWN,
API_RETURN_INVALIDATE_ERROR
};
AfterApiReturn_t api_next = API_RETURN_UNKNOWN;
if (event != EVENT_NONE) {
STATE_ENTER(&HttpSM::state_api_callout, event);
}
if (api_timer < 0) {
// This happens when either the plugin lock was missed and the hook rescheduled or
// the transaction got an event without the plugin calling TsHttpTxnReenable().
// The call chain does not recurse here if @a api_timer < 0 which means this call
// is the first from an event dispatch in this case.
milestone_update_api_time(milestones, api_timer);
}
switch (event) {
case EVENT_INTERVAL:
ink_assert(pending_action == data);
pending_action = nullptr;
// FALLTHROUGH
case EVENT_NONE:
case HTTP_API_CONTINUE:
if ((cur_hook_id >= 0) && (cur_hook_id < TS_HTTP_LAST_HOOK)) {
if (!cur_hook) {
if (cur_hooks == 0) {
cur_hook = http_global_hooks->get(cur_hook_id);
cur_hooks++;
}
}
// even if ua_session is NULL, cur_hooks must
// be incremented otherwise cur_hooks is not set to 2 and
// transaction hooks (stored in api_hooks object) are not called.
if (!cur_hook) {
if (cur_hooks == 1) {
if (ua_session) {
cur_hook = ua_session->ssn_hook_get(cur_hook_id);
}
cur_hooks++;
}
}
if (!cur_hook) {
if (cur_hooks == 2) {
cur_hook = api_hooks.get(cur_hook_id);
cur_hooks++;
}
}
if (cur_hook) {
if (callout_state == HTTP_API_NO_CALLOUT) {
callout_state = HTTP_API_IN_CALLOUT;
}
/* The MUTEX_TRY_LOCK macro was changed so
that it can't handle NULL mutex'es. The plugins
can use null mutexes so we have to do this manually.
We need to take a smart pointer to the mutex since
the plugin could release it's mutex while we're on
the callout
*/
bool plugin_lock;
Ptr<ProxyMutex> plugin_mutex;
if (cur_hook->m_cont->mutex) {
plugin_mutex = cur_hook->m_cont->mutex;
plugin_lock = MUTEX_TAKE_TRY_LOCK(cur_hook->m_cont->mutex, mutex->thread_holding);
if (!plugin_lock) {
api_timer = -Thread::get_hrtime_updated();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_api_callout);
ink_assert(pending_action == nullptr);
pending_action = mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
// Should @a callout_state be reset back to HTTP_API_NO_CALLOUT here? Because the default
// handler has been changed the value isn't important to the rest of the state machine
// but not resetting means there is no way to reliably detect re-entrance to this state with an
// outstanding callout.
return 0;
}
} else {
plugin_lock = false;
}
DebugSM("http", "[%" PRId64 "] calling plugin on hook %s at hook %p", sm_id, HttpDebugNames::get_api_hook_name(cur_hook_id),
cur_hook);
APIHook *hook = cur_hook;
cur_hook = cur_hook->next();
if (!api_timer) {
api_timer = Thread::get_hrtime_updated();
}
hook->invoke(TS_EVENT_HTTP_READ_REQUEST_HDR + cur_hook_id, this);
if (api_timer > 0) { // true if the hook did not call TxnReenable()
milestone_update_api_time(milestones, api_timer);
api_timer = -Thread::get_hrtime_updated(); // set in order to track non-active callout duration
// which means that if we get back from the invoke with api_timer < 0 we're already
// tracking a non-complete callout from a chain so just let it ride. It will get cleaned
// up in state_api_callback when the plugin re-enables this transaction.
}
if (plugin_lock) {
Mutex_unlock(plugin_mutex, mutex->thread_holding);
}
return 0;
}
}
// Map the callout state into api_next
switch (callout_state) {
case HTTP_API_NO_CALLOUT:
case HTTP_API_IN_CALLOUT:
if (t_state.api_modifiable_cached_resp && t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE;
}
api_next = API_RETURN_CONTINUE;
break;
case HTTP_API_DEFERED_CLOSE:
api_next = API_RETURN_DEFERED_CLOSE;
break;
case HTTP_API_DEFERED_SERVER_ERROR:
api_next = API_RETURN_DEFERED_SERVER_ERROR;
break;
default:
ink_release_assert(0);
}
break;
case HTTP_API_ERROR:
if (callout_state == HTTP_API_DEFERED_CLOSE) {
api_next = API_RETURN_DEFERED_CLOSE;
} else if (cur_hook_id == TS_HTTP_TXN_CLOSE_HOOK) {
// If we are closing the state machine, we can't
// jump to an error state so just continue
api_next = API_RETURN_CONTINUE;
} else if (t_state.api_http_sm_shutdown) {
t_state.api_http_sm_shutdown = false;
t_state.cache_info.object_read = nullptr;
cache_sm.close_read();
transform_cache_sm.close_read();
release_server_session();
terminate_sm = true;
api_next = API_RETURN_SHUTDOWN;
t_state.squid_codes.log_code = SQUID_LOG_TCP_DENIED;
} else if (t_state.api_modifiable_cached_resp &&
t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_ERROR;
api_next = API_RETURN_INVALIDATE_ERROR;
} else {
api_next = API_RETURN_ERROR_JUMP;
}
break;
// We may receive an event from the tunnel
// if it took a long time to call the SEND_RESPONSE_HDR hook
case HTTP_TUNNEL_EVENT_DONE:
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
return 0;
default:
ink_assert(false);
terminate_sm = true;
return 0;
}
// Now that we're completed with the api state and figured out what
// to do next, do it
callout_state = HTTP_API_NO_CALLOUT;
api_timer = 0;
switch (api_next) {
case API_RETURN_CONTINUE:
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR) {
do_redirect();
}
handle_api_return();
break;
case API_RETURN_DEFERED_CLOSE:
ink_assert(t_state.api_next_action == HttpTransact::SM_ACTION_API_SM_SHUTDOWN);
do_api_callout();
break;
case API_RETURN_DEFERED_SERVER_ERROR:
ink_assert(t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR);
ink_assert(t_state.current.state != HttpTransact::CONNECTION_ALIVE);
call_transact_and_set_next_state(HttpTransact::HandleResponse);
break;
case API_RETURN_ERROR_JUMP:
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
break;
case API_RETURN_SHUTDOWN:
break;
case API_RETURN_INVALIDATE_ERROR:
do_cache_prepare_update();
break;
default:
case API_RETURN_UNKNOWN:
ink_release_assert(0);
}
return 0;
}
// void HttpSM::handle_api_return()
//
// Figures out what to do after calling api callouts
// have finished. This messy and I would like
// to come up with a cleaner way to handle the api
// return. The way we are doing things also makes a
// mess of set_next_state()
//
void
HttpSM::handle_api_return()
{
switch (t_state.api_next_action) {
case HttpTransact::SM_ACTION_API_SM_START:
if (t_state.client_info.port_attribute == HttpProxyPort::TRANSPORT_BLIND_TUNNEL) {
setup_blind_tunnel_port();
} else {
setup_client_read_request_header();
}
return;
case HttpTransact::SM_ACTION_API_PRE_REMAP:
case HttpTransact::SM_ACTION_API_POST_REMAP:
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_OS_DNS:
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE:
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE && t_state.api_cleanup_cache_read &&
t_state.api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_cleanup_cache_read = false;
t_state.cache_info.object_read = nullptr;
t_state.request_sent_time = UNDEFINED_TIME;
t_state.response_received_time = UNDEFINED_TIME;
cache_sm.close_read();
transform_cache_sm.close_read();
}
call_transact_and_set_next_state(nullptr);
return;
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
setup_server_send_request();
return;
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
// Set back the inactivity timeout
if (ua_session) {
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
// we have further processing to do
// based on what t_state.next_action is
break;
case HttpTransact::SM_ACTION_API_SM_SHUTDOWN:
state_remove_from_list(EVENT_NONE, nullptr);
return;
default:
ink_release_assert("! Not reached");
break;
}
switch (t_state.next_action) {
case HttpTransact::SM_ACTION_TRANSFORM_READ: {
HttpTunnelProducer *p = setup_transfer_from_transform();
perform_transform_cache_write_action();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_SERVER_READ: {
if (unlikely(t_state.did_upgrade_succeed)) {
// We've successfully handled the upgrade, let's now setup
// a blind tunnel.
if (t_state.is_websocket) {
HTTP_INCREMENT_DYN_STAT(http_websocket_current_active_client_connections_stat);
if (ua_session) {
DebugSM("http_websocket",
"(client session) Setting websocket active timeout=%" PRId64 "s and inactive timeout=%" PRId64 "s",
t_state.txn_conf->websocket_active_timeout, t_state.txn_conf->websocket_inactive_timeout);
ua_session->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_active_timeout));
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_inactive_timeout));
}
if (server_session) {
DebugSM("http_websocket",
"(server session) Setting websocket active timeout=%" PRId64 "s and inactive timeout=%" PRId64 "s",
t_state.txn_conf->websocket_active_timeout, t_state.txn_conf->websocket_inactive_timeout);
server_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_active_timeout));
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_inactive_timeout));
}
}
setup_blind_tunnel(true);
} else {
HttpTunnelProducer *p = setup_server_transfer();
perform_cache_write_action();
tunnel.tunnel_run(p);
}
break;
}
case HttpTransact::SM_ACTION_SERVE_FROM_CACHE: {
HttpTunnelProducer *p = setup_cache_read_transfer();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_WRITE: {
if (cache_sm.cache_write_vc) {
setup_internal_transfer(&HttpSM::tunnel_handler_cache_fill);
} else {
setup_internal_transfer(&HttpSM::tunnel_handler);
}
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_NOOP:
case HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE:
case HttpTransact::SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS:
case HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP: {
setup_internal_transfer(&HttpSM::tunnel_handler);
break;
}
case HttpTransact::SM_ACTION_REDIRECT_READ: {
// Clean up from any communication with previous servers
release_server_session();
call_transact_and_set_next_state(HttpTransact::HandleRequest);
break;
}
case HttpTransact::SM_ACTION_SSL_TUNNEL: {
setup_blind_tunnel(true);
break;
}
default: {
ink_release_assert(!"Should not get here");
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_http_server_open()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_http_server_open(int event, void *data)
{
DebugSM("http_track", "entered inside state_http_server_open");
STATE_ENTER(&HttpSM::state_http_server_open, event);
// TODO decide whether to uncomment after finish testing redirect
// ink_assert(server_entry == NULL);
pending_action = nullptr;
milestones[TS_MILESTONE_SERVER_CONNECT_END] = Thread::get_hrtime();
HttpServerSession *session;
switch (event) {
case NET_EVENT_OPEN:
session = (TS_SERVER_SESSION_SHARING_POOL_THREAD == t_state.http_config_param->server_session_sharing_pool) ?
THREAD_ALLOC_INIT(httpServerSessionAllocator, mutex->thread_holding) :
httpServerSessionAllocator.alloc();
session->sharing_pool = static_cast<TSServerSessionSharingPoolType>(t_state.http_config_param->server_session_sharing_pool);
session->sharing_match = static_cast<TSServerSessionSharingMatchType>(t_state.txn_conf->server_session_sharing_match);
// If origin_max_connections or origin_min_keep_alive_connections is
// set then we are metering the max and or min number
// of connections per host. Set enable_origin_connection_limiting
// to true in the server session so it will increment and decrement
// the connection count.
if (t_state.txn_conf->origin_max_connections > 0 || t_state.http_config_param->origin_min_keep_alive_connections > 0) {
DebugSM("http_ss", "[%" PRId64 "] max number of connections: %" PRIu64, sm_id, t_state.txn_conf->origin_max_connections);
session->enable_origin_connection_limiting = true;
}
/*UnixNetVConnection * vc = (UnixNetVConnection*)(ua_session->client_vc);
UnixNetVConnection *server_vc = (UnixNetVConnection*)data;
printf("client fd is :%d , server fd is %d\n",vc->con.fd,
server_vc->con.fd); */
session->attach_hostname(t_state.current.server->name);
session->new_connection(static_cast<NetVConnection *>(data));
session->state = HSS_ACTIVE;
attach_server_session(session);
if (t_state.current.request_to == HttpTransact::PARENT_PROXY) {
session->to_parent_proxy = true;
HTTP_INCREMENT_DYN_STAT(http_current_parent_proxy_connections_stat);
HTTP_INCREMENT_DYN_STAT(http_total_parent_proxy_connections_stat);
} else {
session->to_parent_proxy = false;
}
handle_http_server_open();
return 0;
case EVENT_INTERVAL: // Delayed call from another thread
if (server_session == nullptr) {
do_http_server_open();
}
break;
case VC_EVENT_ERROR:
case NET_EVENT_OPEN_FAILED:
t_state.current.state = HttpTransact::CONNECTION_ERROR;
// save the errno from the connect fail for future use (passed as negative value, flip back)
t_state.current.server->set_connect_fail(event == NET_EVENT_OPEN_FAILED ? -reinterpret_cast<intptr_t>(data) : ECONNABORTED);
/* If we get this error, then we simply can't bind to the 4-tuple to make the connection. There's no hope of
retries succeeding in the near future. The best option is to just shut down the connection without further
comment. The only known cause for this is outbound transparency combined with use client target address / source
port, as noted in TS-1424. If the keep alives desync the current connection can be attempting to rebind the 4
tuple simultaneously with the shut down of an existing connection. Dropping the client side will cause it to pick
a new source port and recover from this issue.
*/
if (EADDRNOTAVAIL == t_state.current.server->connect_result) {
if (is_debug_tag_set("http_tproxy")) {
ip_port_text_buffer ip_c, ip_s;
Debug("http_tproxy", "Force close of client connect (%s->%s) due to EADDRNOTAVAIL [%" PRId64 "]",
ats_ip_nptop(&t_state.client_info.src_addr.sa, ip_c, sizeof ip_c),
ats_ip_nptop(&t_state.server_info.dst_addr.sa, ip_s, sizeof ip_s), sm_id);
}
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE; // part of the problem, clear it.
terminate_sm = true;
} else {
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
return 0;
case CONGESTION_EVENT_CONGESTED_ON_F:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_F;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return 0;
case CONGESTION_EVENT_CONGESTED_ON_M:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_M;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return 0;
default:
Error("[HttpSM::state_http_server_open] Unknown event: %d", event);
ink_release_assert(0);
return 0;
}
return 0;
}
int
HttpSM::state_read_server_response_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_server_response_header, event);
ink_assert(server_entry->read_vio == (VIO *)data);
ink_assert(t_state.current.server->state == HttpTransact::STATE_UNDEFINED);
ink_assert(t_state.current.state == HttpTransact::STATE_UNDEFINED);
int bytes_used = 0;
VIO *vio = (VIO *)data;
switch (event) {
case VC_EVENT_EOS:
server_entry->eos = true;
// If no bytes were transmitted, the parser treats
// as a good 0.9 response which is technically is
// but it's indistinguishable from an overloaded
// server closing the connection so don't accept
// zero length responses
if (vio->ndone == 0) {
// Error handling function
handle_server_setup_error(event, data);
return 0;
}
// Fall through
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// Error handling function
handle_server_setup_error(event, data);
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the connect timeout when we set up to read the header
//
if (server_response_hdr_bytes == 0) {
milestones[TS_MILESTONE_SERVER_FIRST_READ] = Thread::get_hrtime();
if (t_state.api_txn_no_activity_timeout_value != -1) {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_MSECONDS(t_state.api_txn_no_activity_timeout_value));
} else {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
}
// For requests that contain a body, we can cancel the ua inactivity timeout.
if (ua_session && t_state.hdr_info.request_content_length) {
ua_session->cancel_inactivity_timeout();
}
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state =
t_state.hdr_info.server_response.parse_resp(&http_parser, server_buffer_reader, &bytes_used, server_entry->eos);
server_response_hdr_bytes += bytes_used;
// Don't allow 0.9 (unparsable headers) on keep-alive connections after
// the connection has already served a transaction as what we are likely
// looking at is garbage on a keep-alive channel corrupted by the origin
// server
if (state == PARSE_RESULT_DONE && t_state.hdr_info.server_response.version_get() == HTTPVersion(0, 9) &&
server_session->transact_count > 1) {
state = PARSE_RESULT_ERROR;
}
// Check to see if we are over the hdr size limit
if (server_response_hdr_bytes > t_state.txn_conf->response_hdr_max_size) {
state = PARSE_RESULT_ERROR;
}
if (state != PARSE_RESULT_CONT) {
// Disable further IO
server_entry->read_vio->nbytes = server_entry->read_vio->ndone;
http_parser_clear(&http_parser);
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR: {
// Many broken servers send really badly formed 302 redirects.
// Even if the parser doesn't like the redirect forward
// if it's got a Location header. We check the type of the
// response to make sure that the parser was able to parse
// something and didn't just throw up it's hands (INKqa05339)
bool allow_error = false;
if (t_state.hdr_info.server_response.type_get() == HTTP_TYPE_RESPONSE &&
t_state.hdr_info.server_response.status_get() == HTTP_STATUS_MOVED_TEMPORARILY) {
if (t_state.hdr_info.server_response.field_find(MIME_FIELD_LOCATION, MIME_LEN_LOCATION)) {
allow_error = true;
}
}
if (allow_error == false) {
DebugSM("http_seq", "Error parsing server response header");
t_state.current.state = HttpTransact::PARSE_ERROR;
// If the server closed prematurely on us, use the
// server setup error routine since it will forward
// error to a POST tunnel if any
if (event == VC_EVENT_EOS) {
handle_server_setup_error(VC_EVENT_EOS, data);
} else {
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
break;
}
// FALLTHROUGH (since we are allowing the parse error)
}
case PARSE_RESULT_DONE:
DebugSM("http_seq", "Done parsing server response header");
// Now that we know that we have all of the origin server
// response headers, we can reset the client inactivity
// timeout. This is unlikely to cause a recurrence of
// old bug because there will be no more retries now that
// the connection has been established. It is possible
// however. We do not need to reset the inactivity timeout
// if the request contains a body (noted by the
// request_content_length field) because it was never
// canceled.
//
// we now reset the client inactivity timeout only
// when we are ready to send the response headers. In the
// case of transform plugin, this is after the transform
// outputs the 1st byte, which can take a long time if the
// plugin buffers the whole response.
// Also, if the request contains a body, we cancel the timeout
// when we read the 1st byte of the origin server response.
/*
if (ua_session && !t_state.hdr_info.request_content_length) {
ua_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(
HttpConfig::m_master.accept_no_activity_timeout));
}
*/
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
t_state.transact_return_point = HttpTransact::HandleResponse;
t_state.api_next_action = HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR;
// if exceeded limit deallocate postdata buffers and disable redirection
if (enable_redirection && (redirection_tries < t_state.txn_conf->number_of_redirections)) {
++redirection_tries;
} else {
tunnel.deallocate_redirect_postdata_buffers();
enable_redirection = false;
}
do_api_callout();
break;
case PARSE_RESULT_CONT:
ink_assert(server_entry->eos == false);
server_entry->read_vio->reenable();
return VC_EVENT_CONT;
default:
ink_assert(!"not reached");
}
return 0;
}
int
HttpSM::state_send_server_request_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_send_server_request_header, event);
ink_assert(server_entry != nullptr);
ink_assert(server_entry->write_vio == (VIO *)data || server_entry->read_vio == (VIO *)data);
int method;
switch (event) {
case VC_EVENT_WRITE_READY:
server_entry->write_vio->reenable();
break;
case VC_EVENT_WRITE_COMPLETE:
// We are done sending the request header, deallocate
// our buffer and then decide what to do next
free_MIOBuffer(server_entry->write_buffer);
server_entry->write_buffer = nullptr;
method = t_state.hdr_info.server_request.method_get_wksidx();
if (!t_state.api_server_request_body_set && method != HTTP_WKSIDX_TRACE &&
(t_state.hdr_info.request_content_length > 0 || t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
if (post_transform_info.vc) {
setup_transform_to_server_transfer();
} else {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
} else {
// It's time to start reading the response
setup_server_read_response_header();
}
break;
case VC_EVENT_READ_READY:
// We already did the read for the response header and
// we got some data. Wait for the request header
// send before dealing with it. However, we need to
// disable further IO here since the whole response
// may be in the buffer and we can not switch buffers
// on the io core later
ink_assert(server_entry->read_vio == (VIO *)data);
// setting nbytes to ndone would disable reads and remove it from the read queue.
// We can't do this in the epoll paradigm because we may be missing epoll errors that would
// prevent us from leaving this state.
// setup_server_read_response_header will trigger READ_READY to itself if there is data in the buffer.
// server_entry->read_vio->nbytes = server_entry->read_vio->ndone;
break;
case VC_EVENT_EOS:
// EOS of stream comes from the read side. Treat it as
// as error if there is nothing in the read buffer. If
// there is something the server may have blasted back
// the response before receiving the request. Happens
// often with redirects
//
// If we are in the middle of an api callout, it
// means we haven't actually sent the request yet
// so the stuff in the buffer is garbage and we
// want to ignore it
//
server_entry->eos = true;
// I'm not sure about the above comment, but if EOS is received on read and we are
// still in this state, we must have not gotten WRITE_COMPLETE. With epoll we might not receive EOS
// from both read and write sides of a connection so it should be handled correctly (close tunnels,
// deallocate, etc) here with handle_server_setup_error(). Otherwise we might hang due to not shutting
// down and never receiving another event again.
/*if (server_buffer_reader->read_avail() > 0 && callout_state == HTTP_API_NO_CALLOUT) {
break;
} */
// Nothing in the buffer
// FALLTHROUGH to error
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
handle_server_setup_error(event, data);
break;
case VC_EVENT_READ_COMPLETE:
// new event expected due to TS-3189
DebugSM("http_ss", "read complete due to 0 byte do_io_read");
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
void
HttpSM::process_srv_info(HostDBInfo *r)
{
DebugSM("dns_srv", "beginning process_srv_info");
t_state.hostdb_entry = Ptr<HostDBInfo>(r);
/* we didn't get any SRV records, continue w normal lookup */
if (!r || !r->is_srv || !r->round_robin) {
t_state.dns_info.srv_hostname[0] = '\0';
t_state.dns_info.srv_lookup_success = false;
t_state.txn_conf->srv_enabled = false;
DebugSM("dns_srv", "No SRV records were available, continuing to lookup %s", t_state.dns_info.lookup_name);
} else {
HostDBRoundRobin *rr = r->rr();
HostDBInfo *srv = nullptr;
if (rr) {
srv = rr->select_best_srv(t_state.dns_info.srv_hostname, &mutex->thread_holding->generator, ink_cluster_time(),
(int)t_state.txn_conf->down_server_timeout);
}
if (!srv) {
t_state.dns_info.srv_lookup_success = false;
t_state.dns_info.srv_hostname[0] = '\0';
t_state.txn_conf->srv_enabled = false;
DebugSM("dns_srv", "SRV records empty for %s", t_state.dns_info.lookup_name);
} else {
t_state.dns_info.srv_lookup_success = true;
t_state.dns_info.srv_port = srv->data.srv.srv_port;
t_state.dns_info.srv_app = srv->app;
// t_state.dns_info.single_srv = (rr->good == 1);
ink_assert(srv->data.srv.key == makeHostHash(t_state.dns_info.srv_hostname));
DebugSM("dns_srv", "select SRV records %s", t_state.dns_info.srv_hostname);
}
}
return;
}
void
HttpSM::process_hostdb_info(HostDBInfo *r)
{
// Increment the refcount to our item, since we are pointing at it
t_state.hostdb_entry = Ptr<HostDBInfo>(r);
sockaddr const *client_addr = nullptr;
bool use_client_addr = t_state.http_config_param->use_client_target_addr == 1 && t_state.client_info.is_transparent &&
t_state.dns_info.os_addr_style == HttpTransact::DNSLookupInfo::OS_ADDR_TRY_DEFAULT;
if (use_client_addr) {
NetVConnection *vc = t_state.state_machine->ua_session ? t_state.state_machine->ua_session->get_netvc() : nullptr;
if (vc) {
client_addr = vc->get_local_addr();
// Regardless of whether the client address matches the DNS record or not,
// we want to use that address. Therefore, we copy over the client address
// info and skip the assignment from the DNS cache
ats_ip_copy(t_state.host_db_info.ip(), client_addr);
t_state.dns_info.os_addr_style = HttpTransact::DNSLookupInfo::OS_ADDR_TRY_CLIENT;
t_state.dns_info.lookup_success = true;
// Leave ret unassigned, so we don't overwrite the host_db_info
} else {
use_client_addr = false;
}
}
if (r && !r->is_failed()) {
ink_time_t now = ink_cluster_time();
HostDBInfo *ret = nullptr;
t_state.dns_info.lookup_success = true;
t_state.dns_info.lookup_validated = true;
HostDBRoundRobin *rr = r->round_robin ? r->rr() : nullptr;
if (rr) {
// if use_client_target_addr is set, make sure the client addr is in the results pool
if (use_client_addr && rr->find_ip(client_addr) == nullptr) {
DebugSM("http", "use_client_target_addr == 1. Client specified address is not in the pool, not validated.");
t_state.dns_info.lookup_validated = false;
} else {
// Since the time elapsed between current time and client_request_time
// may be very large, we cannot use client_request_time to approximate
// current time when calling select_best_http().
ret = rr->select_best_http(&t_state.client_info.src_addr.sa, now, static_cast<int>(t_state.txn_conf->down_server_timeout));
// set the srv target`s last_failure
if (t_state.dns_info.srv_lookup_success) {
uint32_t last_failure = 0xFFFFFFFF;
for (int i = 0; i < rr->rrcount && last_failure != 0; ++i) {
if (last_failure > rr->info(i).app.http_data.last_failure) {
last_failure = rr->info(i).app.http_data.last_failure;
}
}
if (last_failure != 0 && (uint32_t)(now - t_state.txn_conf->down_server_timeout) < last_failure) {
HostDBApplicationInfo app;
app.allotment.application1 = 0;
app.allotment.application2 = 0;
app.http_data.last_failure = last_failure;
hostDBProcessor.setby_srv(t_state.dns_info.lookup_name, 0, t_state.dns_info.srv_hostname, &app);
}
}
}
} else {
if (use_client_addr && !ats_ip_addr_eq(client_addr, &r->data.ip.sa)) {
DebugSM("http", "use_client_target_addr == 1. Comparing single addresses failed, not validated.");
t_state.dns_info.lookup_validated = false;
} else {
ret = r;
}
}
if (ret) {
t_state.host_db_info = *ret;
ink_release_assert(!t_state.host_db_info.reverse_dns);
ink_release_assert(ats_is_ip(t_state.host_db_info.ip()));
}
} else {
DebugSM("http", "[%" PRId64 "] DNS lookup failed for '%s'", sm_id, t_state.dns_info.lookup_name);
if (!use_client_addr) {
t_state.dns_info.lookup_success = false;
}
t_state.host_db_info.app.allotment.application1 = 0;
t_state.host_db_info.app.allotment.application2 = 0;
ink_assert(!t_state.host_db_info.round_robin);
}
milestones[TS_MILESTONE_DNS_LOOKUP_END] = Thread::get_hrtime();
if (is_debug_tag_set("http_timeout")) {
if (t_state.api_txn_dns_timeout_value != -1) {
int foo = (int)(milestones.difference_msec(TS_MILESTONE_DNS_LOOKUP_BEGIN, TS_MILESTONE_DNS_LOOKUP_END));
DebugSM("http_timeout", "DNS took: %d msec", foo);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_hostdb_lookup()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_hostdb_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_hostdb_lookup, event);
// ink_assert (m_origin_server_vc == 0);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed into
// REQ_FLAVOR_REVPROXY
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_HOST_DB_LOOKUP:
pending_action = nullptr;
process_hostdb_info((HostDBInfo *)data);
call_transact_and_set_next_state(nullptr);
break;
case EVENT_SRV_LOOKUP: {
pending_action = nullptr;
process_srv_info((HostDBInfo *)data);
char *host_name = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_hostname : t_state.dns_info.lookup_name;
HostDBProcessor::Options opt;
opt.port = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_port : t_state.server_info.dst_addr.host_order_port();
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ua_session->get_host_res_style();
Action *dns_lookup_action_handle =
hostDBProcessor.getbyname_imm(this, (process_hostdb_info_pfn)&HttpSM::process_hostdb_info, host_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
} break;
case EVENT_HOST_DB_IP_REMOVED:
ink_assert(!"Unexpected event from HostDB");
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
int
HttpSM::state_hostdb_reverse_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_hostdb_reverse_lookup, event);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed into
// REQ_FLAVOR_REVPROXY
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_HOST_DB_LOOKUP:
pending_action = nullptr;
if (data) {
t_state.request_data.hostname_str = ((HostDBInfo *)data)->hostname();
} else {
DebugSM("http", "[%" PRId64 "] reverse DNS lookup failed for '%s'", sm_id, t_state.dns_info.lookup_name);
}
call_transact_and_set_next_state(nullptr);
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM:state_mark_os_down()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_mark_os_down(int event, void *data)
{
HostDBInfo *mark_down = nullptr;
if (event == EVENT_HOST_DB_LOOKUP && data) {
HostDBInfo *r = (HostDBInfo *)data;
if (r->round_robin) {
// Look for the entry we need mark down in the round robin
ink_assert(t_state.current.server != nullptr);
ink_assert(t_state.current.request_to == HttpTransact::ORIGIN_SERVER);
if (t_state.current.server) {
mark_down = r->rr()->find_ip(&t_state.current.server->dst_addr.sa);
}
} else {
// No longer a round robin, check to see if our address is the same
if (ats_ip_addr_eq(t_state.host_db_info.ip(), r->ip())) {
mark_down = r;
}
}
if (mark_down) {
mark_host_failure(mark_down, t_state.request_sent_time);
}
}
// We either found our entry or we did not. Either way find
// the entry we should use now
return state_hostdb_lookup(event, data);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_handle_stat_page()
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_handle_stat_page(int event, void *data)
{
STATE_ENTER(&HttpSM::state_handle_stat_page, event);
switch (event) {
case STAT_PAGE_SUCCESS:
pending_action = nullptr;
if (data) {
StatPageData *spd = (StatPageData *)data;
t_state.internal_msg_buffer = spd->data;
if (spd->type) {
t_state.internal_msg_buffer_type = spd->type;
} else {
t_state.internal_msg_buffer_type = nullptr; // Defaults to text/html
}
t_state.internal_msg_buffer_size = spd->length;
t_state.internal_msg_buffer_fast_allocator_size = -1;
}
call_transact_and_set_next_state(HttpTransact::HandleStatPage);
break;
case STAT_PAGE_FAILURE:
pending_action = nullptr;
call_transact_and_set_next_state(HttpTransact::HandleStatPage);
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
///////////////////////////////////////////////////////////////
//
// HttpSM::state_auth_callback()
//
///////////////////////////////////////////////////////////////
// int
// HttpSM::state_auth_callback(int event, void *data)
//{
// STATE_ENTER(&HttpSM::state_auth_lookup, event);
// ink_release_assert(ua_entry != NULL);
// pending_action = NULL;
// if (event == AUTH_MODULE_EVENT) {
// authAdapter.HandleAuthResponse(event, data);
//} else {
// ink_release_assert(!"Unknown authentication module event");
//}
/************************************************************************\
* pending_action=ACTION_RESULT_DONE only if Authentication step has *
* been done & authorization is left *
* pending_action=NULL only if we have to set_next_state. *
* pending_action=something else. Don't do anything. *
* One more callback is pending *
\************************************************************************/
// if (authAdapter.stateChangeRequired()) {
// set_next_state();
//}
// OLD AND UGLY: if (pending_action == NULL) {
// OLD AND UGLY: pending_action=NULL;
// OLD AND UGLY: } else if(pending_action == ACTION_RESULT_DONE) {
// OLD AND UGLY: pending_action=NULL;
// OLD AND UGLY: }
// return EVENT_DONE;
//}
///////////////////////////////////////////////////////////////
//
// HttpSM::state_icp_lookup()
//
///////////////////////////////////////////////////////////////
int
HttpSM::state_icp_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_icp_lookup, event);
// ua_entry is NULL for scheduled updates
ink_release_assert(ua_entry != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
pending_action = nullptr;
switch (event) {
case ICP_LOOKUP_FOUND:
DebugSM("http", "ICP says ICP_LOOKUP_FOUND");
t_state.icp_lookup_success = true;
t_state.icp_ip_result = *(struct sockaddr_in *)data;
/*
* Disable ICP loop detection since the Cidera network
* insists on trying to preload the cache from a
* a sibling cache.
*
* // inhibit bad ICP looping behavior
* if (t_state.icp_ip_result.sin_addr.s_addr ==
* t_state.client_info.ip) {
* DebugSM("http","Loop in ICP config, bypassing...");
* t_state.icp_lookup_success = false;
* }
*/
break;
case ICP_LOOKUP_FAILED:
DebugSM("http", "ICP says ICP_LOOKUP_FAILED");
t_state.icp_lookup_success = false;
break;
default:
ink_release_assert(0);
break;
}
call_transact_and_set_next_state(HttpTransact::HandleICPLookup);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////
// HttpSM::state_cache_open_write()
//
// This state is set by set_next_state() for a cache open write
// (SERVER_READ_CACHE_WRITE)
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_cache_open_write(int event, void *data)
{
STATE_ENTER(&HttpSM : state_cache_open_write, event);
// Make sure we are on the "right" thread
if (ua_session) {
if ((pending_action = ua_session->adjust_thread(this, event, data))) {
return 0; // Go away if we reschedule
}
}
milestones[TS_MILESTONE_CACHE_OPEN_WRITE_END] = Thread::get_hrtime();
pending_action = nullptr;
switch (event) {
case CACHE_EVENT_OPEN_WRITE:
//////////////////////////////
// OPEN WRITE is successful //
//////////////////////////////
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_SUCCESS;
break;
case CACHE_EVENT_OPEN_WRITE_FAILED:
// Failed on the write lock and retrying the vector
// for reading
if (t_state.redirect_info.redirect_in_process) {
DebugSM("http_redirect", "[%" PRId64 "] CACHE_EVENT_OPEN_WRITE_FAILED during redirect follow", sm_id);
t_state.cache_open_write_fail_action = HttpTransact::CACHE_WL_FAIL_ACTION_DEFAULT;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
}
if (t_state.txn_conf->cache_open_write_fail_action == HttpTransact::CACHE_WL_FAIL_ACTION_DEFAULT) {
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
} else {
t_state.cache_open_write_fail_action = t_state.txn_conf->cache_open_write_fail_action;
if (!t_state.cache_info.object_read ||
(t_state.cache_open_write_fail_action == HttpTransact::CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_OR_REVALIDATE)) {
// cache miss, set wl_state to fail
DebugSM("http", "[%" PRId64 "] cache object read %p, cache_wl_fail_action %d", sm_id, t_state.cache_info.object_read,
t_state.cache_open_write_fail_action);
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
}
}
// INTENTIONAL FALL THROUGH
// Allow for stale object to be served
case CACHE_EVENT_OPEN_READ:
// The write vector was locked and the cache_sm retried
// and got the read vector again.
cache_sm.cache_read_vc->get_http_info(&t_state.cache_info.object_read);
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (cache_sm.cache_read_vc->is_ram_cache_hit()) {
t_state.cache_info.hit_miss_code = SQUID_HIT_RAM;
} else {
t_state.cache_info.hit_miss_code = SQUID_HIT_DISK;
}
ink_assert(t_state.cache_info.object_read != nullptr);
t_state.source = HttpTransact::SOURCE_CACHE;
// clear up CACHE_LOOKUP_MISS, let Freshness function decide
// hit status
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_READ_RETRY;
break;
case HTTP_TUNNEL_EVENT_DONE:
// In the case where we have issued a cache write for the
// transformed copy, the tunnel from the origin server to
// the transform may complete while we are waiting for
// the cache write. If this is the case, forward the event
// to the transform read state as it will know how to
// handle it
if (t_state.next_action == HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM) {
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
return 0;
}
// Fallthrough
default:
ink_release_assert(0);
}
if (t_state.api_lock_url != HttpTransact::LOCK_URL_FIRST) {
if (event == CACHE_EVENT_OPEN_WRITE || event == CACHE_EVENT_OPEN_WRITE_FAILED) {
if (t_state.api_lock_url == HttpTransact::LOCK_URL_SECOND) {
t_state.api_lock_url = HttpTransact::LOCK_URL_ORIGINAL;
do_cache_prepare_action(second_cache_sm, t_state.cache_info.second_object_read, true);
return 0;
} else {
t_state.api_lock_url = HttpTransact::LOCK_URL_DONE;
}
} else if (event != CACHE_EVENT_OPEN_READ || t_state.api_lock_url != HttpTransact::LOCK_URL_SECOND) {
t_state.api_lock_url = HttpTransact::LOCK_URL_QUIT;
}
}
// The write either succeeded or failed, notify transact
call_transact_and_set_next_state(nullptr);
return 0;
}
inline void
HttpSM::setup_cache_lookup_complete_api()
{
t_state.api_next_action = HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE;
do_api_callout();
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_cache_open_read()
//
// This state handles the result of CacheProcessor::open_read()
// that attempts to do cache lookup and open a particular cached
// object for reading.
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_cache_open_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_cache_open_read, event);
milestones[TS_MILESTONE_CACHE_OPEN_READ_END] = Thread::get_hrtime();
ink_assert(server_entry == nullptr);
ink_assert(t_state.cache_info.object_read == nullptr);
switch (event) {
case CACHE_EVENT_OPEN_READ: {
pending_action = nullptr;
DebugSM("http", "[%" PRId64 "] cache_open_read - CACHE_EVENT_OPEN_READ", sm_id);
/////////////////////////////////
// lookup/open is successful. //
/////////////////////////////////
ink_assert(cache_sm.cache_read_vc != nullptr);
t_state.source = HttpTransact::SOURCE_CACHE;
cache_sm.cache_read_vc->get_http_info(&t_state.cache_info.object_read);
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (cache_sm.cache_read_vc->is_ram_cache_hit()) {
t_state.cache_info.hit_miss_code = SQUID_HIT_RAM;
} else {
t_state.cache_info.hit_miss_code = SQUID_HIT_DISK;
}
ink_assert(t_state.cache_info.object_read != nullptr);
call_transact_and_set_next_state(HttpTransact::HandleCacheOpenRead);
break;
}
case CACHE_EVENT_OPEN_READ_FAILED:
pending_action = nullptr;
DebugSM("http", "[%" PRId64 "] cache_open_read - CACHE_EVENT_OPEN_READ_FAILED with %s (%d)", sm_id,
InkStrerror(-(intptr_t)data), (int)(intptr_t)data);
DebugSM("http", "[state_cache_open_read] open read failed.");
// Inform HttpTransact somebody else is updating the document
// HttpCacheSM already waited so transact should go ahead.
if ((intptr_t)data == -ECACHE_DOC_BUSY) {
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_DOC_BUSY;
} else {
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_MISS;
}
ink_assert(t_state.transact_return_point == nullptr);
t_state.transact_return_point = HttpTransact::HandleCacheOpenRead;
setup_cache_lookup_complete_api();
break;
default:
ink_release_assert("!Unknown event");
break;
}
return 0;
}
int
HttpSM::main_handler(int event, void *data)
{
ink_release_assert(magic == HTTP_SM_MAGIC_ALIVE);
HttpSMHandler jump_point = nullptr;
ink_assert(reentrancy_count >= 0);
reentrancy_count++;
// Don't use the state enter macro since it uses history
// space that we don't care about
DebugSM("http", "[%" PRId64 "] [HttpSM::main_handler, %s]", sm_id, HttpDebugNames::get_event_name(event));
HttpVCTableEntry *vc_entry = nullptr;
if (data != nullptr) {
// Only search the VC table if the event could have to
// do with a VIO to save a few cycles
if (event < VC_EVENT_EVENTS_START + 100) {
vc_entry = vc_table.find_entry((VIO *)data);
}
}
if (vc_entry) {
jump_point = vc_entry->vc_handler;
ink_assert(jump_point != (HttpSMHandler) nullptr);
ink_assert(vc_entry->vc != (VConnection *)nullptr);
(this->*jump_point)(event, data);
} else {
ink_assert(default_handler != (HttpSMHandler) nullptr);
(this->*default_handler)(event, data);
}
// The sub-handler signals when it is time for the state
// machine to exit. We can only exit if we are not reentrantly
// called otherwise when the our call unwinds, we will be
// running on a dead state machine
//
// Because of the need for an api shutdown hook, kill_this()
// is also reentrant. As such, we don't want to decrement
// the reentrancy count until after we run kill_this()
//
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
reentrancy_count--;
ink_assert(reentrancy_count >= 0);
}
return (VC_EVENT_CONT);
}
// void HttpSM::tunnel_handler_post_or_put()
//
// Handles the common cleanup tasks for Http post/put
// to prevent code duplication
//
void
HttpSM::tunnel_handler_post_or_put(HttpTunnelProducer *p)
{
ink_assert(p->vc_type == HT_HTTP_CLIENT);
HttpTunnelConsumer *c;
// If there is a post transform, remove it's entry from the State
// Machine's VC table
//
// MUST NOT clear the vc pointer from post_transform_info
// as this causes a double close of the transform vc in transform_cleanup
//
if (post_transform_info.vc != nullptr) {
ink_assert(post_transform_info.entry->in_tunnel == true);
ink_assert(post_transform_info.vc == post_transform_info.entry->vc);
vc_table.cleanup_entry(post_transform_info.entry);
post_transform_info.entry = nullptr;
}
switch (p->handler_state) {
case HTTP_SM_POST_SERVER_FAIL:
c = tunnel.get_consumer(server_entry->vc);
ink_assert(c->write_success == false);
break;
case HTTP_SM_POST_UA_FAIL:
// UA quit - shutdown the SM
ink_assert(p->read_success == false);
terminate_sm = true;
break;
case HTTP_SM_POST_SUCCESS:
// The post succeeded
ink_assert(p->read_success == true);
ink_assert(p->consumer_list.head->write_success == true);
tunnel.deallocate_buffers();
tunnel.reset();
// When the ua completed sending it's data we must have
// removed it from the tunnel
ink_release_assert(ua_entry->in_tunnel == false);
server_entry->in_tunnel = false;
break;
default:
ink_release_assert(0);
}
}
// int HttpSM::tunnel_handler_post(int event, void* data)
//
// Handles completion of any http request body tunnel
// Having 'post' in its name is a misnomer
//
int
HttpSM::tunnel_handler_post(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_post, event);
HttpTunnelProducer *p = ua_session != nullptr ? tunnel.get_producer(ua_session) : tunnel.get_producer(HT_HTTP_CLIENT);
if (!p) {
return 0; // Cannot do anything if there is no producer
}
if (event != HTTP_TUNNEL_EVENT_DONE) {
if ((event == VC_EVENT_WRITE_COMPLETE) || (event == VC_EVENT_EOS)) {
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
}
if (p->handler_state == HTTP_SM_POST_UA_FAIL) {
Debug("http_tunnel", "cleanup tunnel in tunnel_handler_post");
hsm_release_assert(ua_entry->in_tunnel == true);
ink_assert((event == VC_EVENT_WRITE_COMPLETE) || (event == VC_EVENT_EOS));
vc_table.cleanup_all();
tunnel.chain_abort_all(p);
p->read_vio = nullptr;
p->vc->do_io_close(EHTTP_ERROR);
tunnel_handler_post_or_put(p);
tunnel.kill_tunnel();
return 0;
}
}
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// The tunnel calls this when it is done
int p_handler_state = p->handler_state;
tunnel_handler_post_or_put(p);
switch (p_handler_state) {
case HTTP_SM_POST_SERVER_FAIL:
handle_post_failure();
break;
case HTTP_SM_POST_UA_FAIL:
break;
case HTTP_SM_POST_SUCCESS:
// It's time to start reading the response
setup_server_read_response_header();
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::tunnel_handler_cache_fill(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_fill, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
ink_release_assert(cache_sm.cache_write_vc);
tunnel.deallocate_buffers();
tunnel.deallocate_redirect_postdata_buffers();
tunnel.reset();
setup_server_transfer_to_cache_only();
tunnel.tunnel_run();
return 0;
}
int
HttpSM::tunnel_handler_100_continue(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_100_continue, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// We're done sending the 100 continue. If we succeeded,
// we set up to parse the next server response. If we
// failed, shutdown the state machine
HttpTunnelConsumer *c = tunnel.get_consumer(ua_session);
if (c->write_success) {
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.client_response.destroy();
tunnel.deallocate_buffers();
tunnel.deallocate_redirect_postdata_buffers();
tunnel.reset();
if (server_entry->eos) {
// if the server closed while sending the
// 100 continue header, handle it here so we
// don't assert later
DebugSM("http", "[%" PRId64 "] tunnel_handler_100_continue - server already "
"closed, terminating connection",
sm_id);
// Since 100 isn't a final (loggable) response header
// kill the 100 continue header and create an empty one
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
handle_server_setup_error(VC_EVENT_EOS, server_entry->read_vio);
} else {
setup_server_read_response_header();
}
} else {
terminate_sm = true;
}
return 0;
}
int
HttpSM::tunnel_handler_push(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_push, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// Check to see if the client is still around
HttpTunnelProducer *ua = (ua_session) ? tunnel.get_producer(ua_session) : tunnel.get_producer(HT_HTTP_CLIENT);
if (ua && !ua->read_success) {
// Client failed to send the body, it's gone. Kill the
// state machine
terminate_sm = true;
return 0;
}
HttpTunnelConsumer *cache = ua->consumer_list.head;
ink_release_assert(cache->vc_type == HT_CACHE_WRITE);
bool cache_write_success = cache->write_success;
// Reset tunneling state since we need to send a response
// to client as whether we succeeded
tunnel.deallocate_buffers();
tunnel.deallocate_redirect_postdata_buffers();
tunnel.reset();
if (cache_write_success) {
call_transact_and_set_next_state(HttpTransact::HandlePushTunnelSuccess);
} else {
call_transact_and_set_next_state(HttpTransact::HandlePushTunnelFailure);
}
return 0;
}
int
HttpSM::tunnel_handler(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// The tunnel calls this when it is done
terminate_sm = true;
if (unlikely(t_state.is_websocket)) {
HTTP_DECREMENT_DYN_STAT(http_websocket_current_active_client_connections_stat);
}
return 0;
}
/****************************************************
TUNNELING HANDLERS
******************************************************/
bool
HttpSM::is_http_server_eos_truncation(HttpTunnelProducer *p)
{
if ((p->do_dechunking || p->do_chunked_passthru) && p->chunked_handler.truncation) {
// TS-3054 - In the chunked cases, chunked data that is incomplete
// should not be cached, but it should be passed onto the client
// This makes ATS more transparent in the case of non-standard
// servers. The cache aborts are dealt with in other checks
// on the truncation flag elsewhere in the code. This return value
// invalidates the current data being passed over to the client.
// So changing it from return true to return false, so the partial data
// is passed onto the client.
return false;
}
//////////////////////////////////////////////////////////////
// If we did not get or did not trust the origin server's //
// content-length, read_content_length is unset. The //
// only way the end of the document is signaled is the //
// origin server closing the connection. However, we //
// need to protect against the document getting truncated //
// because the origin server crashed. The following //
// tabled outlines when we mark the server read as failed //
// //
// No C-L : read success //
// Received byts < C-L : read failed (=> Cache Abort) //
// Received byts == C-L : read success //
// Received byts > C-L : read success //
//////////////////////////////////////////////////////////////
int64_t cl = t_state.hdr_info.server_response.get_content_length();
if (cl != UNDEFINED_COUNT && cl > server_response_body_bytes) {
DebugSM("http", "[%" PRId64 "] server EOS after %" PRId64 " bytes, expected %" PRId64, sm_id, server_response_body_bytes, cl);
return true;
} else {
return false;
}
}
int
HttpSM::tunnel_handler_server(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_server, event);
milestones[TS_MILESTONE_SERVER_CLOSE] = Thread::get_hrtime();
bool close_connection = false;
if (t_state.current.server->keep_alive == HTTP_KEEPALIVE && server_entry->eos == false &&
plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL && t_state.txn_conf->keep_alive_enabled_out == 1) {
close_connection = false;
} else {
close_connection = true;
}
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
t_state.squid_codes.log_code = SQUID_LOG_ERR_READ_TIMEOUT;
t_state.squid_codes.hier_code = SQUID_HIER_TIMEOUT_DIRECT;
/* fallthru */
case VC_EVENT_EOS:
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.current.server->state = HttpTransact::INACTIVE_TIMEOUT;
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.current.server->state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_ERROR:
t_state.current.server->state = HttpTransact::CONNECTION_ERROR;
break;
case VC_EVENT_EOS:
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
break;
}
close_connection = true;
ink_assert(p->vc_type == HT_HTTP_SERVER);
if (is_http_server_eos_truncation(p)) {
DebugSM("http", "[%" PRId64 "] [HttpSM::tunnel_handler_server] aborting HTTP tunnel due to server truncation", sm_id);
tunnel.chain_abort_all(p);
// UA session may not be in the tunnel yet, don't NULL out the pointer in that case.
// Note: This is a hack. The correct solution is for the UA session to signal back to the SM
// when the UA is about to be destroyed and clean up the pointer there. That should be done once
// the TS-3612 changes are in place (and similarly for the server session).
/*if (ua_entry->in_tunnel)
ua_session = NULL; */
t_state.current.server->abort = HttpTransact::ABORTED;
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
t_state.squid_codes.log_code = SQUID_LOG_ERR_READ_ERROR;
} else {
DebugSM("http", "[%" PRId64 "] [HttpSM::tunnel_handler_server] finishing HTTP tunnel", sm_id);
p->read_success = true;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
// Appending reason to a response without Content-Length will result in
// the reason string being written to the client and a bad CL when reading from cache.
// I didn't find anywhere this appended reason is being used, so commenting it out.
/*
if (t_state.negative_caching && p->bytes_read == 0) {
int reason_len;
const char *reason = t_state.hdr_info.server_response.reason_get(&reason_len);
if (reason == NULL)
tunnel.append_message_to_producer_buffer(p, "Negative Response", sizeof("Negative Response") - 1);
else
tunnel.append_message_to_producer_buffer(p, reason, reason_len);
}
*/
tunnel.local_finish_all(p);
}
break;
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case VC_EVENT_READ_COMPLETE:
//
// The transfer completed successfully
// If there is still data in the buffer, the server
// sent too much indicating a failed transfer
p->read_success = true;
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
if (p->do_dechunking || p->do_chunked_passthru) {
if (p->chunked_handler.truncation) {
tunnel.abort_cache_write_finish_others(p);
// We couldn't read all chunks successfully:
// Disable keep-alive.
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
} else {
tunnel.local_finish_all(p);
}
}
break;
case HTTP_TUNNEL_EVENT_CONSUMER_DETACH:
// All consumers are prematurely gone. Shutdown
// the server connection
p->read_success = true;
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
close_connection = true;
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
// turn off negative caching in case there are multiple server contacts
if (t_state.negative_caching) {
t_state.negative_caching = false;
}
// If we had a ground fill, check update our status
if (background_fill == BACKGROUND_FILL_STARTED) {
background_fill = p->read_success ? BACKGROUND_FILL_COMPLETED : BACKGROUND_FILL_ABORTED;
HTTP_DECREMENT_DYN_STAT(http_background_fill_current_count_stat);
}
// We handled the event. Now either shutdown the connection or
// setup it up for keep-alive
ink_assert(server_entry->vc == p->vc);
ink_assert(p->vc_type == HT_HTTP_SERVER);
ink_assert(p->vc == server_session);
if (close_connection) {
p->vc->do_io_close();
server_session = nullptr; // Because p->vc == server_session
p->read_vio = nullptr;
/* TS-1424: if we're outbound transparent and using the client
source port for the outbound connection we must effectively
propagate server closes back to the client. Part of that is
disabling KeepAlive if the server closes.
*/
if (ua_session && ua_session->is_outbound_transparent() && t_state.http_config_param->use_client_source_port) {
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
} else {
server_session->attach_hostname(t_state.current.server->name);
server_session->server_trans_stat--;
HTTP_DECREMENT_DYN_STAT(http_current_server_transactions_stat);
// If the option to attach the server session to the client session is set
// and if the client is still around and the client is keep-alive, attach the
// server session to so the next ka request can use it. Server sessions will
// be placed into the shared pool if the next incoming request is for a different
// origin server
if (t_state.txn_conf->attach_server_session_to_client == 1 && ua_session && t_state.client_info.keep_alive == HTTP_KEEPALIVE) {
Debug("http", "attaching server session to the client");
ua_session->attach_server_session(server_session);
} else {
// Release the session back into the shared session pool
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
server_session->release();
}
}
return 0;
}
// int HttpSM::tunnel_handler_100_continue_ua(int event, HttpTunnelConsumer* c)
//
// Used for tunneling the 100 continue response. The tunnel
// should not close or release the user agent unless there is
// an error since the real response is yet to come
//
int
HttpSM::tunnel_handler_100_continue_ua(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_100_continue_ua, event);
ink_assert(c->vc == ua_session);
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// FALL-THROUGH
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
set_ua_abort(HttpTransact::ABORTED, event);
c->vc->do_io_close();
break;
case VC_EVENT_WRITE_COMPLETE:
// mark the vc as no longer in tunnel
// so we don't get hosed if the ua abort before
// real response header is received
ua_entry->in_tunnel = false;
c->write_success = true;
}
return 0;
}
bool
HttpSM::is_bg_fill_necessary(HttpTunnelConsumer *c)
{
ink_assert(c->vc_type == HT_HTTP_CLIENT);
if (c->producer->alive && // something there to read
server_entry && server_entry->vc && // from an origin server
server_session && server_session->get_netvc() && // which is still open and valid
c->producer->num_consumers > 1 // with someone else reading it
) {
// If threshold is 0.0 or negative then do background
// fill regardless of the content length. Since this
// is floating point just make sure the number is near zero
if (t_state.txn_conf->background_fill_threshold <= 0.001) {
return true;
}
int64_t ua_cl = t_state.hdr_info.client_response.get_content_length();
if (ua_cl > 0) {
int64_t ua_body_done = c->bytes_written - client_response_hdr_bytes;
float pDone = (float)ua_body_done / ua_cl;
// If we got a good content length. Check to make sure that we haven't already
// done more the content length since that would indicate the content-length
// is bogus. If we've done more than the threshold, continue the background fill
if (pDone <= 1.0 && pDone > t_state.txn_conf->background_fill_threshold) {
return true;
} else {
DebugSM("http", "[%" PRId64 "] no background. Only %%%f of %%%f done [%" PRId64 " / %" PRId64 " ]", sm_id, pDone,
t_state.txn_conf->background_fill_threshold, ua_body_done, ua_cl);
}
}
}
return false;
}
int
HttpSM::tunnel_handler_ua(int event, HttpTunnelConsumer *c)
{
bool close_connection = true;
HttpTunnelProducer *p = nullptr;
HttpTunnelConsumer *selfc = nullptr;
STATE_ENTER(&HttpSM::tunnel_handler_ua, event);
ink_assert(c->vc == ua_session);
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// FALL-THROUGH
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
// The user agent died or aborted. Check to
// see if we should setup a background fill
set_ua_abort(HttpTransact::ABORTED, event);
if (is_bg_fill_necessary(c)) {
DebugSM("http", "[%" PRId64 "] Initiating background fill", sm_id);
background_fill = BACKGROUND_FILL_STARTED;
HTTP_INCREMENT_DYN_STAT(http_background_fill_current_count_stat);
// There is another consumer (cache write) so
// detach the user agent
ink_assert(server_entry->vc == server_session);
ink_assert(c->is_downstream_from(server_session));
server_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->background_fill_active_timeout));
} else {
// No background fill
p = c->producer;
tunnel.chain_abort_all(c->producer);
selfc = p->self_consumer;
if (selfc) {
// This is the case where there is a transformation between ua and os
p = selfc->producer;
// if producer is the cache or OS, close the producer.
// Otherwise in case of large docs, producer iobuffer gets filled up,
// waiting for a consumer to consume data and the connection is never closed.
if (p->alive && ((p->vc_type == HT_CACHE_READ) || (p->vc_type == HT_HTTP_SERVER))) {
tunnel.chain_abort_all(p);
}
}
}
break;
case VC_EVENT_WRITE_COMPLETE:
c->write_success = true;
t_state.client_info.abort = HttpTransact::DIDNOT_ABORT;
if (t_state.client_info.keep_alive == HTTP_KEEPALIVE) {
if (t_state.www_auth_content != HttpTransact::CACHE_AUTH_SERVE || ua_session->get_server_session()) {
// successful keep-alive
close_connection = false;
}
// else { the authenticated server connection (cache
// authenticated feature) closed during the serve-from-cache.
// We want the client to issue a new connection for the
// session based authenticated mechanism like NTLM, instead
// of still using the existing client connection. }
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
client_response_body_bytes = c->bytes_written - client_response_hdr_bytes;
if (client_response_body_bytes < 0) {
client_response_body_bytes = 0;
}
// attribute the size written to the client from various sources
// NOTE: responses that go through a range transform are attributed
// to their original sources
// all other transforms attribute the total number of input bytes
// to a source in HttpSM::tunnel_handler_transform_write
//
HttpTransact::Source_t original_source = t_state.source;
if (HttpTransact::SOURCE_TRANSFORM == original_source && t_state.range_setup != HttpTransact::RANGE_NONE) {
original_source = t_state.pre_transform_source;
}
switch (original_source) {
case HttpTransact::SOURCE_HTTP_ORIGIN_SERVER:
server_response_body_bytes = client_response_body_bytes;
break;
case HttpTransact::SOURCE_CACHE:
cache_response_body_bytes = client_response_body_bytes;
break;
default:
break;
}
ink_assert(ua_entry->vc == c->vc);
if (close_connection) {
// If the client could be pipelining or is doing a POST, we need to
// set the ua_session into half close mode
// only external POSTs should be subject to this logic; ruling out internal POSTs here
bool is_eligible_post_request = (t_state.method == HTTP_WKSIDX_POST);
if (is_eligible_post_request) {
NetVConnection *vc = ua_session->get_netvc();
if (vc) {
is_eligible_post_request &= !vc->get_is_internal_request();
}
}
if ((is_eligible_post_request || t_state.client_info.pipeline_possible == true) && c->producer->vc_type != HT_STATIC &&
event == VC_EVENT_WRITE_COMPLETE) {
ua_session->set_half_close_flag(true);
}
ua_session->do_io_close();
} else {
ink_assert(ua_buffer_reader != nullptr);
ua_session->release(ua_buffer_reader);
ua_buffer_reader = nullptr;
// ua_session = NULL;
}
return 0;
}
int
HttpSM::tunnel_handler_ua_push(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_ua_push, event);
pushed_response_body_bytes += p->bytes_read;
client_request_body_bytes += p->bytes_read;
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
// Transfer terminated. Bail on the cache write.
t_state.client_info.abort = HttpTransact::ABORTED;
p->vc->do_io_close(EHTTP_ERROR);
p->read_vio = nullptr;
tunnel.chain_abort_all(p);
break;
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case VC_EVENT_READ_COMPLETE:
//
// The transfer completed successfully
p->read_success = true;
ua_entry->in_tunnel = false;
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
return 0;
}
int
HttpSM::tunnel_handler_cache_read(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_read, event);
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
ink_assert(t_state.cache_info.object_read->valid());
if (t_state.cache_info.object_read->object_size_get() != INT64_MAX || event == VC_EVENT_ERROR) {
// Abnormal termination
t_state.squid_codes.log_code = SQUID_LOG_TCP_SWAPFAIL;
p->vc->do_io_close(EHTTP_ERROR);
p->read_vio = nullptr;
tunnel.chain_abort_all(p);
HTTP_INCREMENT_DYN_STAT(http_cache_read_errors);
break;
} else {
tunnel.local_finish_all(p);
// fall through for the case INT64_MAX read with VC_EVENT_EOS
// callback (read successful)
}
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case HTTP_TUNNEL_EVENT_CONSUMER_DETACH:
p->read_success = true;
p->vc->do_io_close();
p->read_vio = nullptr;
break;
default:
ink_release_assert(0);
break;
}
HTTP_DECREMENT_DYN_STAT(http_current_cache_connections_stat);
return 0;
}
int
HttpSM::tunnel_handler_cache_write(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_write, event);
HttpTransact::CacheWriteStatus_t *status_ptr =
(c->producer->vc_type == HT_TRANSFORM) ? &t_state.cache_info.transform_write_status : &t_state.cache_info.write_status;
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
// Abnormal termination
*status_ptr = HttpTransact::CACHE_WRITE_ERROR;
c->write_vio = nullptr;
c->vc->do_io_close(EHTTP_ERROR);
HTTP_INCREMENT_DYN_STAT(http_cache_write_errors);
DebugSM("http", "[%" PRId64 "] aborting cache write due %s event from cache", sm_id, HttpDebugNames::get_event_name(event));
// abort the producer if the cache_writevc is the only consumer.
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.chain_abort_all(c->producer);
}
break;
case VC_EVENT_WRITE_COMPLETE:
// if we've never initiated a cache write
// abort the cache since it's finicky about a close
// in this case. This case can only occur
// we got a truncated header from the origin server
// but decided to accept it anyways
if (c->write_vio == nullptr) {
*status_ptr = HttpTransact::CACHE_WRITE_ERROR;
c->write_success = false;
c->vc->do_io_close(EHTTP_ERROR);
} else {
*status_ptr = HttpTransact::CACHE_WRITE_COMPLETE;
c->write_success = true;
c->write_vio = c->vc->do_io(VIO::CLOSE);
}
break;
default:
// All other events indicate problems
ink_assert(0);
break;
}
HTTP_DECREMENT_DYN_STAT(http_current_cache_connections_stat);
return 0;
}
int
HttpSM::tunnel_handler_post_ua(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_post_ua, event);
client_request_body_bytes = p->init_bytes_done + p->bytes_read;
int64_t alloc_index, nbytes;
IOBufferReader *buf_start;
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
if (client_response_hdr_bytes == 0) {
p->handler_state = HTTP_SM_POST_UA_FAIL;
set_ua_abort(HttpTransact::ABORTED, event);
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
HttpTransact::build_error_response(&t_state, HTTP_STATUS_REQUEST_TIMEOUT, "POST Request timeout", "timeout#inactivity",
nullptr);
break;
case VC_EVENT_ACTIVE_TIMEOUT:
HttpTransact::build_error_response(&t_state, HTTP_STATUS_REQUEST_TIMEOUT, "POST Request timeout", "timeout#activity",
nullptr);
break;
}
// send back 408 request timeout
alloc_index = buffer_size_to_index(len_408_request_timeout_response + t_state.internal_msg_buffer_size);
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
ua_entry->write_buffer = new_MIOBuffer(alloc_index);
buf_start = ua_entry->write_buffer->alloc_reader();
DebugSM("http_tunnel", "send 408 response to client to vc %p, tunnel vc %p", ua_session->get_netvc(), p->vc);
nbytes = ua_entry->write_buffer->write(str_408_request_timeout_response, len_408_request_timeout_response);
nbytes += ua_entry->write_buffer->write(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size);
p->vc->do_io_write(this, nbytes, buf_start);
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
return 0;
}
// fall through
case VC_EVENT_EOS:
// My reading of spec says that user agents can not terminate
// posts with a half close so this is an error
case VC_EVENT_ERROR:
// Did not complete post tunneling. Abort the
// server and close the ua
p->handler_state = HTTP_SM_POST_UA_FAIL;
set_ua_abort(HttpTransact::ABORTED, event);
tunnel.chain_abort_all(p);
p->read_vio = nullptr;
p->vc->do_io_close(EHTTP_ERROR);
// the in_tunnel status on both the ua & and
// it's consumer must already be set to true. Previously
// we were setting it again to true but incorrectly in
// the case of a transform
hsm_release_assert(ua_entry->in_tunnel == true);
if (p->consumer_list.head->vc_type == HT_TRANSFORM) {
hsm_release_assert(post_transform_info.entry->in_tunnel == true);
} else if (server_entry != nullptr) {
hsm_release_assert(server_entry->in_tunnel == true);
}
break;
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
p->handler_state = HTTP_SM_POST_SUCCESS;
p->read_success = true;
ua_entry->in_tunnel = false;
if (p->do_dechunking || p->do_chunked_passthru) {
if (p->chunked_handler.truncation) {
tunnel.abort_cache_write_finish_others(p);
} else {
tunnel.local_finish_all(p);
}
}
// Initiate another read to watch catch aborts and
// timeouts
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = p->vc->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
break;
default:
ink_release_assert(0);
}
return 0;
}
// YTS Team, yamsat Plugin
// Tunnel handler to deallocate the tunnel buffers and
// set redirect_in_process=false
// Copy partial POST data to buffers. Check for the various parameters including
// the maximum configured post data size
int
HttpSM::tunnel_handler_for_partial_post(int event, void * /* data ATS_UNUSED */)
{
STATE_ENTER(&HttpSM::tunnel_handler_for_partial_post, event);
tunnel.deallocate_buffers();
tunnel.reset();
tunnel.allocate_redirect_postdata_producer_buffer();
t_state.redirect_info.redirect_in_process = false;
if (post_failed) {
post_failed = false;
handle_post_failure();
} else {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
return 0;
}
int
HttpSM::tunnel_handler_post_server(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_post_server, event);
server_request_body_bytes = c->bytes_written;
switch (event) {
case VC_EVENT_EOS:
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// Did not complete post tunneling
//
// In the http case, we don't want to close
// the connection because the
// destroys the header buffer which may
// a response even though the tunnel failed.
// Shutdown both sides of the connection. This prevents us
// from getting any further events and signals to client
// that POST data will not be forwarded to the server. Doing
// shutdown on the write side will likely generate a TCP
// reset to the client but if the proxy wasn't here this is
// exactly what would happen.
// we should wait to shutdown read side of the
// client to prevent sending a reset
server_entry->eos = true;
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
// We may be reading from a transform. In that case, we
// want to close the transform
HttpTunnelProducer *ua_producer;
if (c->producer->vc_type == HT_TRANSFORM) {
if (c->producer->handler_state == HTTP_SM_TRANSFORM_OPEN) {
ink_assert(c->producer->vc == post_transform_info.vc);
c->producer->vc->do_io_close();
c->producer->alive = false;
c->producer->self_consumer->alive = false;
}
ua_producer = c->producer->self_consumer->producer;
} else {
ua_producer = c->producer;
}
ink_assert(ua_producer->vc_type == HT_HTTP_CLIENT);
ink_assert(ua_producer->vc == ua_session);
ink_assert(ua_producer->vc == ua_entry->vc);
// Before shutting down, initiate another read
// on the user agent in order to get timeouts
// coming to the state machine and not the tunnel
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
// YTS Team, yamsat Plugin
// When event is VC_EVENT_ERROR,and when redirection is enabled
// do not shut down the client read
if (enable_redirection) {
if (ua_producer->vc_type == HT_STATIC && event != VC_EVENT_ERROR && event != VC_EVENT_EOS) {
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
// ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
t_state.client_info.pipeline_possible = false;
} else {
if (ua_producer->vc_type == HT_STATIC && t_state.redirect_info.redirect_in_process) {
post_failed = true;
}
}
} else {
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
// we should not shutdown read side of the client here to prevent sending a reset
// ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
t_state.client_info.pipeline_possible = false;
} // end of added logic
// We want to shutdown the tunnel here and see if there
// is a response on from the server. Mark the user
// agent as down so that tunnel concludes.
ua_producer->alive = false;
ua_producer->handler_state = HTTP_SM_POST_SERVER_FAIL;
ink_assert(tunnel.is_tunnel_alive() == false);
break;
case VC_EVENT_WRITE_COMPLETE:
// Completed successfully
c->write_success = true;
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::tunnel_handler_ssl_producer(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_ssl_producer, event);
switch (event) {
case VC_EVENT_EOS:
// The write side of this connection is still alive
// so half-close the read
if (p->self_consumer->alive) {
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
tunnel.local_finish_all(p);
break;
}
// FALL THROUGH - both sides of the tunnel are dea
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The other side of the connection is either already dead
// or rendered inoperative by the error on the connection
// Note: use tunnel close vc so the tunnel knows we are
// nuking the of the connection as well
tunnel.close_vc(p);
tunnel.local_finish_all(p);
// Because we've closed the net vc this error came in, it's write
// direction is now dead as well. If that side still being fed data,
// we need to kill that pipe as well
if (p->self_consumer->producer->alive) {
p->self_consumer->producer->alive = false;
if (p->self_consumer->producer->self_consumer->alive) {
p->self_consumer->producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
tunnel.close_vc(p->self_consumer->producer);
}
}
break;
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
// We should never get these event since we don't know
// how long the stream is
default:
ink_release_assert(0);
}
// Update stats
switch (p->vc_type) {
case HT_HTTP_SERVER:
server_response_body_bytes += p->bytes_read;
break;
case HT_HTTP_CLIENT:
client_request_body_bytes += p->bytes_read;
break;
default:
// Covered here:
// HT_CACHE_READ, HT_CACHE_WRITE,
// HT_TRANSFORM, HT_STATIC.
break;
}
return 0;
}
int
HttpSM::tunnel_handler_ssl_consumer(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_ssl_consumer, event);
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// we need to mark the producer dead
// otherwise it can stay alive forever.
if (c->producer->alive) {
c->producer->alive = false;
if (c->producer->self_consumer->alive) {
c->producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
tunnel.close_vc(c->producer);
}
}
// Since we are changing the state of the self_producer
// we must have the tunnel shutdown the vc
tunnel.close_vc(c);
tunnel.local_finish_all(c->self_producer);
break;
case VC_EVENT_WRITE_COMPLETE:
// If we get this event, it means that the producer
// has finished and we wrote the remaining data
// to the consumer
//
// If the read side of this connection has not yet
// closed, do a write half-close and then wait for
// read side to close so that we don't cut off
// pipelined responses with TCP resets
//
// ink_assert(c->producer->alive == false);
c->write_success = true;
if (c->self_producer->alive == true) {
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
} else {
c->vc->do_io_close();
}
break;
default:
ink_release_assert(0);
}
// Update stats
switch (c->vc_type) {
case HT_HTTP_SERVER:
server_request_body_bytes += c->bytes_written;
break;
case HT_HTTP_CLIENT:
client_response_body_bytes += c->bytes_written;
break;
default:
// Handled here:
// HT_CACHE_READ, HT_CACHE_WRITE, HT_TRANSFORM,
// HT_STATIC
break;
}
return 0;
}
int
HttpSM::tunnel_handler_transform_write(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_transform_write, event);
HttpTransformInfo *i;
// Figure out if this the request or response transform
// : use post_transform_info.entry because post_transform_info.vc
// is not set to NULL after the post transform is done.
if (post_transform_info.entry) {
i = &post_transform_info;
ink_assert(c->vc == i->entry->vc);
} else {
i = &transform_info;
ink_assert(c->vc == i->vc);
ink_assert(c->vc == i->entry->vc);
}
switch (event) {
case VC_EVENT_ERROR:
// Transform error
tunnel.chain_abort_all(c->producer);
c->handler_state = HTTP_SM_TRANSFORM_FAIL;
c->vc->do_io_close(EHTTP_ERROR);
break;
case VC_EVENT_EOS:
// It possible the transform quit
// before the producer finished. If this is true
// we need shut down the producer if it doesn't
// have other consumers to serve or else it will
// fill up buffer and get hung
if (c->producer->alive && c->producer->num_consumers == 1) {
// Send a tunnel detach event to the producer
// to shut it down but indicates it should not abort
// downstream (on the other side of the transform)
// cache writes
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
// FALLTHROUGH
case VC_EVENT_WRITE_COMPLETE:
// write to transform complete - shutdown the write side
c->write_success = true;
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
// If the read side has not started up yet, then the
// this transform_vc is no longer owned by the tunnel
if (c->self_producer == nullptr) {
i->entry->in_tunnel = false;
} else if (c->self_producer->alive == false) {
// The read side of the Transform
// has already completed (possible when the
// transform intentionally truncates the response).
// So close it
c->vc->do_io(VIO::CLOSE);
}
break;
default:
ink_release_assert(0);
}
// attribute the size written to the transform from various sources
// NOTE: the range transform is excluded from this accounting and
// is instead handled in HttpSM::tunnel_handler_ua
//
// the reasoning is that the range transform is internal functionality
// in support of HTTP 1.1 compliance, therefore part of "normal" operation
// all other transforms are plugin driven and the difference between
// source data and final data should represent the transformation delta
//
if (t_state.range_setup == HttpTransact::RANGE_NONE) {
switch (t_state.pre_transform_source) {
case HttpTransact::SOURCE_HTTP_ORIGIN_SERVER:
server_response_body_bytes = client_response_body_bytes;
break;
case HttpTransact::SOURCE_CACHE:
cache_response_body_bytes = client_response_body_bytes;
break;
default:
break;
}
}
return 0;
}
int
HttpSM::tunnel_handler_transform_read(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_transform_read, event);
ink_assert(p->vc == transform_info.vc || p->vc == post_transform_info.vc);
switch (event) {
case VC_EVENT_ERROR:
// Transform error
tunnel.chain_abort_all(p->self_consumer->producer);
break;
case VC_EVENT_EOS:
// If we did not get enough data from the transform abort the
// cache write otherwise fallthrough to the transform
// completing successfully
if (t_state.hdr_info.transform_response_cl != HTTP_UNDEFINED_CL &&
p->read_vio->nbytes < t_state.hdr_info.transform_response_cl) {
tunnel.abort_cache_write_finish_others(p);
break;
}
// FALL-THROUGH
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
// Transform complete
p->read_success = true;
tunnel.local_finish_all(p);
break;
default:
ink_release_assert(0);
}
// it's possible that the write side of the
// transform hasn't detached yet. If it is still alive,
// don't close the transform vc
if (p->self_consumer->alive == false) {
p->vc->do_io_close();
}
p->handler_state = HTTP_SM_TRANSFORM_CLOSED;
return 0;
}
int
HttpSM::tunnel_handler_plugin_agent(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_plugin_client, event);
switch (event) {
case VC_EVENT_ERROR:
c->vc->do_io_close(EHTTP_ERROR); // close up
// Signal producer if we're the last consumer.
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
break;
case VC_EVENT_EOS:
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
// FALLTHROUGH
case VC_EVENT_WRITE_COMPLETE:
c->write_success = true;
c->vc->do_io(VIO::CLOSE);
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::state_srv_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_srv_lookup, event);
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_SRV_LOOKUP:
pending_action = nullptr;
process_srv_info((HostDBInfo *)data);
break;
case EVENT_SRV_IP_REMOVED:
ink_assert(!"Unexpected SRV event from HostDB. What up, Eric?");
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
int
HttpSM::state_remap_request(int event, void * /* data ATS_UNUSED */)
{
STATE_ENTER(&HttpSM::state_remap_request, event);
switch (event) {
case EVENT_REMAP_ERROR: {
ink_assert(!"this doesn't happen");
pending_action = nullptr;
Error("error remapping request [see previous errors]");
call_transact_and_set_next_state(HttpTransact::HandleRequest); // HandleRequest skips EndRemapRequest
break;
}
case EVENT_REMAP_COMPLETE: {
pending_action = nullptr;
DebugSM("url_rewrite", "completed processor-based remapping request for [%" PRId64 "]", sm_id);
t_state.url_remap_success = remapProcessor.finish_remap(&t_state);
call_transact_and_set_next_state(nullptr);
break;
}
default:
ink_assert("Unexpected event inside state_remap_request");
break;
}
return 0;
}
void
HttpSM::do_remap_request(bool run_inline)
{
DebugSM("http_seq", "[HttpSM::do_remap_request] Remapping request");
DebugSM("url_rewrite", "Starting a possible remapping for request [%" PRId64 "]", sm_id);
SSLConfig::scoped_config params;
bool ret = false;
if (t_state.cop_test_page == false) {
ret = remapProcessor.setup_for_remap(&t_state);
}
// Preserve effective url before remap
t_state.unmapped_url.create(t_state.hdr_info.client_request.url_get()->m_heap);
t_state.unmapped_url.copy(t_state.hdr_info.client_request.url_get());
// Depending on a variety of factors the HOST field may or may not have been promoted to the
// client request URL. The unmapped URL should always have that promotion done. If the HOST field
// is not already there, promote it only in the unmapped_url. This avoids breaking any logic that
// depends on the lack of promotion in the client request URL.
if (!t_state.unmapped_url.m_url_impl->m_ptr_host) {
MIMEField *host_field = t_state.hdr_info.client_request.field_find(MIME_FIELD_HOST, MIME_LEN_HOST);
if (host_field) {
int host_len;
const char *host_name = host_field->value_get(&host_len);
if (host_name && host_len) {
t_state.unmapped_url.host_set(host_name, host_len);
}
}
}
if (!ret) {
DebugSM("url_rewrite", "Could not find a valid remapping entry for this request [%" PRId64 "]", sm_id);
if (!run_inline) {
handleEvent(EVENT_REMAP_COMPLETE, nullptr);
}
return;
}
DebugSM("url_rewrite", "Found a remap map entry for [%" PRId64 "], attempting to remap request and call any plugins", sm_id);
Action *remap_action_handle = remapProcessor.perform_remap(this, &t_state);
if (remap_action_handle != ACTION_RESULT_DONE) {
DebugSM("url_rewrite", "Still more remapping needed for [%" PRId64 "]", sm_id);
ink_assert(!pending_action);
pending_action = remap_action_handle;
}
// check if the overridden client cert filename is already attached to an existing ssl context
if (t_state.txn_conf->client_cert_filepath && t_state.txn_conf->client_cert_filename) {
ats_scoped_str clientCert(Layout::relative_to(t_state.txn_conf->client_cert_filepath, t_state.txn_conf->client_cert_filename));
if (clientCert != nullptr) {
auto tCTX = params->getCTX(clientCert);
if (tCTX == nullptr) {
// make new client ctx and add it to the ctx list
auto tctx = params->getNewCTX(clientCert);
params->InsertCTX(clientCert, tctx);
}
}
}
return;
}
void
HttpSM::do_hostdb_lookup()
{
/*
//////////////////////////////////////////
// if a connection to the origin server //
// is currently opened --- close it. //
//////////////////////////////////////////
if (m_origin_server_vc != 0) {
origin_server_close(CLOSE_CONNECTION);
if (m_response_body_tunnel_buffer_.buf() != 0)
m_response_body_tunnel_buffer_.reset();
}
*/
ink_assert(t_state.dns_info.lookup_name != nullptr);
ink_assert(pending_action == nullptr);
milestones[TS_MILESTONE_DNS_LOOKUP_BEGIN] = Thread::get_hrtime();
if (t_state.txn_conf->srv_enabled) {
char d[MAXDNAME];
// Look at the next_hop_scheme to determine what scheme to put in the SRV lookup
unsigned int scheme_len = sprintf(d, "_%s._tcp.", hdrtoken_index_to_wks(t_state.next_hop_scheme));
ink_strlcpy(d + scheme_len, t_state.server_info.name, sizeof(d) - scheme_len);
DebugSM("dns_srv", "Beginning lookup of SRV records for origin %s", d);
HostDBProcessor::Options opt;
if (t_state.api_txn_dns_timeout_value != -1) {
opt.timeout = t_state.api_txn_dns_timeout_value;
}
Action *srv_lookup_action_handle =
hostDBProcessor.getSRVbyname_imm(this, (process_srv_info_pfn)&HttpSM::process_srv_info, d, 0, opt);
if (srv_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = srv_lookup_action_handle;
} else {
char *host_name = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_hostname : t_state.dns_info.lookup_name;
opt.port = t_state.dns_info.srv_lookup_success ?
t_state.dns_info.srv_port :
t_state.server_info.dst_addr.isValid() ? t_state.server_info.dst_addr.host_order_port() :
t_state.hdr_info.client_request.port_get();
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ua_session->get_host_res_style();
Action *dns_lookup_action_handle =
hostDBProcessor.getbyname_imm(this, (process_hostdb_info_pfn)&HttpSM::process_hostdb_info, host_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
}
return;
} else { /* we aren't using SRV stuff... */
DebugSM("http_seq", "[HttpSM::do_hostdb_lookup] Doing DNS Lookup");
// If there is not a current server, we must be looking up the origin
// server at the beginning of the transaction
int server_port = t_state.current.server ?
t_state.current.server->dst_addr.host_order_port() :
t_state.server_info.dst_addr.isValid() ? t_state.server_info.dst_addr.host_order_port() :
t_state.hdr_info.client_request.port_get();
if (t_state.api_txn_dns_timeout_value != -1) {
DebugSM("http_timeout", "beginning DNS lookup. allowing %d mseconds for DNS lookup", t_state.api_txn_dns_timeout_value);
}
HostDBProcessor::Options opt;
opt.port = server_port;
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ua_session->get_host_res_style();
Action *dns_lookup_action_handle = hostDBProcessor.getbyname_imm(this, (process_hostdb_info_pfn)&HttpSM::process_hostdb_info,
t_state.dns_info.lookup_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
return;
}
ink_assert(!"not reached");
return;
}
void
HttpSM::do_hostdb_reverse_lookup()
{
ink_assert(t_state.dns_info.lookup_name != nullptr);
ink_assert(pending_action == nullptr);
DebugSM("http_seq", "[HttpSM::do_hostdb_reverse_lookup] Doing reverse DNS Lookup");
IpEndpoint addr;
ats_ip_pton(t_state.dns_info.lookup_name, &addr.sa);
Action *dns_lookup_action_handle = hostDBProcessor.getbyaddr_re(this, &addr.sa);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
}
return;
}
void
HttpSM::do_hostdb_update_if_necessary()
{
int issue_update = 0;
if (t_state.current.server == nullptr || plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL) {
// No server, so update is not necessary
return;
}
// If we failed back over to the origin server, we don't have our
// hostdb information anymore which means we shouldn't update the hostdb
if (!ats_ip_addr_eq(&t_state.current.server->dst_addr.sa, t_state.host_db_info.ip())) {
DebugSM("http", "[%" PRId64 "] skipping hostdb update due to server failover", sm_id);
return;
}
if (t_state.updated_server_version != HostDBApplicationInfo::HTTP_VERSION_UNDEFINED) {
// we may have incorrectly assumed that the hostdb had the wrong version of
// http for the server because our first few connect attempts to the server
// failed, causing us to downgrade our requests to a lower version and changing
// our information about the server version.
//
// This test therefore just issues the update only if the hostdb version is
// in fact different from the version we want the value to be updated to.
if (t_state.host_db_info.app.http_data.http_version != t_state.updated_server_version) {
t_state.host_db_info.app.http_data.http_version = t_state.updated_server_version;
issue_update |= 1;
}
t_state.updated_server_version = HostDBApplicationInfo::HTTP_VERSION_UNDEFINED;
}
// Check to see if we need to report or clear a connection failure
if (t_state.current.server->had_connect_fail()) {
issue_update |= 1;
mark_host_failure(&t_state.host_db_info, t_state.client_request_time);
} else {
if (t_state.host_db_info.app.http_data.last_failure != 0) {
t_state.host_db_info.app.http_data.last_failure = 0;
issue_update |= 1;
char addrbuf[INET6_ADDRPORTSTRLEN];
DebugSM("http", "[%" PRId64 "] hostdb update marking IP: %s as up", sm_id,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
if (t_state.dns_info.srv_lookup_success && t_state.dns_info.srv_app.http_data.last_failure != 0) {
t_state.dns_info.srv_app.http_data.last_failure = 0;
hostDBProcessor.setby_srv(t_state.dns_info.lookup_name, 0, t_state.dns_info.srv_hostname, &t_state.dns_info.srv_app);
DebugSM("http", "[%" PRId64 "] hostdb update marking SRV: %s as up", sm_id, t_state.dns_info.srv_hostname);
}
}
if (issue_update) {
hostDBProcessor.setby(t_state.current.server->name, strlen(t_state.current.server->name), &t_state.current.server->dst_addr.sa,
&t_state.host_db_info.app);
}
char addrbuf[INET6_ADDRPORTSTRLEN];
DebugSM("http", "server info = %s", ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
return;
}
/*
* range entry valid [a,b] (a >= 0 and b >= 0 and a <= b)
* HttpTransact::RANGE_NONE if the content length of cached copy is zero or
* no range entry
* HttpTransact::RANGE_NOT_SATISFIABLE iff all range entries are valid but
* none overlap the current extent of the cached copy
* HttpTransact::RANGE_NOT_HANDLED if out-of-order Range entries or
* the cached copy`s content_length is INT64_MAX (e.g. read_from_writer and trunked)
* HttpTransact::RANGE_REQUESTED if all sub range entries are valid and
* in order (remove the entries that not overlap the extent of cache copy)
*/
void
HttpSM::parse_range_and_compare(MIMEField *field, int64_t content_length)
{
int prev_good_range = -1;
const char *value;
int value_len;
int n_values;
int nr = 0; // number of valid ranges, also index to range array.
int not_satisfy = 0;
HdrCsvIter csv;
const char *s, *e, *tmp;
RangeRecord *ranges = nullptr;
int64_t start, end;
ink_assert(field != nullptr && t_state.range_setup == HttpTransact::RANGE_NONE && t_state.ranges == nullptr);
if (content_length <= 0) {
return;
}
// ToDo: Can this really happen?
if (content_length == INT64_MAX) {
t_state.range_setup = HttpTransact::RANGE_NOT_HANDLED;
return;
}
if (parse_range_done) {
Debug("http_range", "parse_range already done, t_state.range_setup %d", t_state.range_setup);
return;
}
parse_range_done = true;
n_values = 0;
value = csv.get_first(field, &value_len);
while (value) {
++n_values;
value = csv.get_next(&value_len);
}
value = csv.get_first(field, &value_len);
if (n_values <= 0 || ptr_len_ncmp(value, value_len, "bytes=", 6)) {
return;
}
ranges = new RangeRecord[n_values];
value += 6; // skip leading 'bytes='
value_len -= 6;
// assume range_in_cache
t_state.range_in_cache = true;
for (; value; value = csv.get_next(&value_len)) {
if (!(tmp = (const char *)memchr(value, '-', value_len))) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
// process start value
s = value;
e = tmp;
// skip leading white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s >= e) {
start = -1;
} else {
for (start = 0; s < e && *s >= '0' && *s <= '9'; ++s) {
start = start * 10 + (*s - '0');
}
// skip last white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s < e || start < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
}
// process end value
s = tmp + 1;
e = value + value_len;
// skip leading white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s >= e) {
if (start < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
} else if (start >= content_length) {
not_satisfy++;
continue;
}
end = content_length - 1;
} else {
for (end = 0; s < e && *s >= '0' && *s <= '9'; ++s) {
end = end * 10 + (*s - '0');
}
// skip last white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s < e || end < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
if (start < 0) {
if (end >= content_length) {
end = content_length;
}
start = content_length - end;
end = content_length - 1;
} else if (start >= content_length && start <= end) {
not_satisfy++;
continue;
}
if (end >= content_length) {
end = content_length - 1;
}
}
if (start > end) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
if (prev_good_range >= 0 && start <= ranges[prev_good_range]._end) {
t_state.range_setup = HttpTransact::RANGE_NOT_HANDLED;
goto Lfaild;
}
ink_assert(start >= 0 && end >= 0 && start < content_length && end < content_length);
prev_good_range = nr;
ranges[nr]._start = start;
ranges[nr]._end = end;
++nr;
if (!cache_sm.cache_read_vc->is_pread_capable() && cache_config_read_while_writer == 2) {
// write in progress, check if request range not in cache yet
HTTPInfo::FragOffset *frag_offset_tbl = t_state.cache_info.object_read->get_frag_table();
int frag_offset_cnt = t_state.cache_info.object_read->get_frag_offset_count();
if (!frag_offset_tbl || !frag_offset_cnt || (frag_offset_tbl[frag_offset_cnt - 1] < (uint64_t)end)) {
Debug("http_range", "request range in cache, end %" PRId64 ", frg_offset_cnt %d" PRId64, end, frag_offset_cnt);
t_state.range_in_cache = false;
}
}
}
if (nr > 0) {
t_state.range_setup = HttpTransact::RANGE_REQUESTED;
t_state.ranges = ranges;
t_state.num_range_fields = nr;
return;
}
if (not_satisfy) {
t_state.range_setup = HttpTransact::RANGE_NOT_SATISFIABLE;
}
Lfaild:
t_state.range_in_cache = false;
t_state.num_range_fields = -1;
delete[] ranges;
return;
}
void
HttpSM::calculate_output_cl(int64_t num_chars_for_ct, int64_t num_chars_for_cl)
{
int i;
if (t_state.range_setup != HttpTransact::RANGE_REQUESTED && t_state.range_setup != HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
return;
}
ink_assert(t_state.ranges);
if (t_state.num_range_fields == 1) {
t_state.range_output_cl = t_state.ranges[0]._end - t_state.ranges[0]._start + 1;
} else {
for (i = 0; i < t_state.num_range_fields; i++) {
if (t_state.ranges[i]._start >= 0) {
t_state.range_output_cl += boundary_size;
t_state.range_output_cl += sub_header_size + num_chars_for_ct;
t_state.range_output_cl +=
num_chars_for_int(t_state.ranges[i]._start) + num_chars_for_int(t_state.ranges[i]._end) + num_chars_for_cl + 2;
t_state.range_output_cl += t_state.ranges[i]._end - t_state.ranges[i]._start + 1;
t_state.range_output_cl += 2;
}
}
t_state.range_output_cl += boundary_size + 2;
}
Debug("http_range", "Pre-calculated Content-Length for Range response is %" PRId64, t_state.range_output_cl);
}
void
HttpSM::do_range_parse(MIMEField *range_field)
{
int num_chars_for_ct = 0;
t_state.cache_info.object_read->response_get()->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &num_chars_for_ct);
int64_t content_length = t_state.cache_info.object_read->object_size_get();
int64_t num_chars_for_cl = num_chars_for_int(content_length);
parse_range_and_compare(range_field, content_length);
calculate_output_cl(num_chars_for_ct, num_chars_for_cl);
}
// this function looks for any Range: headers, parses them and either
// sets up a transform processor to handle the request OR defers to the
// HttpTunnel
void
HttpSM::do_range_setup_if_necessary()
{
MIMEField *field;
INKVConnInternal *range_trans;
int field_content_type_len = -1;
const char *content_type;
ink_assert(t_state.cache_info.object_read != nullptr);
field = t_state.hdr_info.client_request.field_find(MIME_FIELD_RANGE, MIME_LEN_RANGE);
ink_assert(field != nullptr);
t_state.range_setup = HttpTransact::RANGE_NONE;
if (t_state.method == HTTP_WKSIDX_GET && t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 1)) {
do_range_parse(field);
if (t_state.range_setup == HttpTransact::RANGE_REQUESTED) {
if (!t_state.range_in_cache) {
Debug("http_range", "range can't be satisfied from cache, force origin request");
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_MISS;
return;
}
// if only one range entry and pread is capable, no need transform range
if (t_state.num_range_fields == 1 && cache_sm.cache_read_vc->is_pread_capable()) {
t_state.range_setup = HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED;
} else if (api_hooks.get(TS_HTTP_RESPONSE_TRANSFORM_HOOK) == nullptr) {
Debug("http_trans", "Unable to accelerate range request, fallback to transform");
content_type = t_state.cache_info.object_read->response_get()->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE,
&field_content_type_len);
// create a Range: transform processor for requests of type Range: bytes=1-2,4-5,10-100 (eg. multiple ranges)
range_trans = transformProcessor.range_transform(mutex.get(), t_state.ranges, t_state.num_range_fields,
&t_state.hdr_info.transform_response, content_type, field_content_type_len,
t_state.cache_info.object_read->object_size_get());
api_hooks.append(TS_HTTP_RESPONSE_TRANSFORM_HOOK, range_trans);
}
}
}
}
void
HttpSM::do_cache_lookup_and_read()
{
// TODO decide whether to uncomment after finish testing redirect
// ink_assert(server_session == NULL);
ink_assert(pending_action == nullptr);
HTTP_INCREMENT_DYN_STAT(http_cache_lookups_stat);
milestones[TS_MILESTONE_CACHE_OPEN_READ_BEGIN] = Thread::get_hrtime();
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.lookup_count++;
// YTS Team, yamsat Plugin
// Changed the lookup_url to c_url which enables even
// the new redirect url to perform a CACHE_LOOKUP
URL *c_url;
if (t_state.redirect_info.redirect_in_process && !t_state.txn_conf->redirect_use_orig_cache_key) {
c_url = t_state.hdr_info.client_request.url_get();
} else {
c_url = t_state.cache_info.lookup_url;
}
DebugSM("http_seq", "[HttpSM::do_cache_lookup_and_read] [%" PRId64 "] Issuing cache lookup for URL %s", sm_id,
c_url->string_get(&t_state.arena));
HttpCacheKey key;
Cache::generate_key(&key, c_url, t_state.txn_conf->cache_generation_number);
Action *cache_action_handle =
cache_sm.open_read(&key, c_url, &t_state.hdr_info.client_request, &(t_state.cache_info.config),
(time_t)((t_state.cache_control.pin_in_cache_for < 0) ? 0 : t_state.cache_control.pin_in_cache_for));
//
// pin_in_cache value is an open_write parameter.
// It is passed in open_read to allow the cluster to
// optimize the typical open_read/open_read failed/open_write
// sequence.
//
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
REMEMBER((long)pending_action, reentrancy_count);
return;
}
void
HttpSM::do_cache_delete_all_alts(Continuation *cont)
{
// Do not delete a non-existant object.
ink_assert(t_state.cache_info.object_read);
DebugSM("http_seq", "[HttpSM::do_cache_delete_all_alts] Issuing cache delete for %s",
t_state.cache_info.lookup_url->string_get_ref());
Action *cache_action_handle = nullptr;
HttpCacheKey key;
Cache::generate_key(&key, t_state.cache_info.lookup_url, t_state.txn_conf->cache_generation_number);
cache_action_handle = cacheProcessor.remove(cont, &key, t_state.cache_control.cluster_cache_local);
if (cont != nullptr) {
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
}
return;
}
inline void
HttpSM::do_cache_prepare_write()
{
// statistically no need to retry when we are trying to lock
// LOCK_URL_SECOND url because the server's behavior is unlikely to change
milestones[TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN] = Thread::get_hrtime();
bool retry = (t_state.api_lock_url == HttpTransact::LOCK_URL_FIRST);
do_cache_prepare_action(&cache_sm, t_state.cache_info.object_read, retry);
}
inline void
HttpSM::do_cache_prepare_write_transform()
{
if (cache_sm.cache_write_vc != nullptr || tunnel.has_cache_writer()) {
do_cache_prepare_action(&transform_cache_sm, nullptr, false, true);
} else {
do_cache_prepare_action(&transform_cache_sm, nullptr, false);
}
}
void
HttpSM::do_cache_prepare_update()
{
if (t_state.cache_info.object_read != nullptr && t_state.cache_info.object_read->valid() &&
t_state.cache_info.object_store.valid() && t_state.cache_info.object_store.response_get() != nullptr &&
t_state.cache_info.object_store.response_get()->valid() &&
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET) {
t_state.cache_info.object_store.request_set(t_state.cache_info.object_read->request_get());
// t_state.cache_info.object_read = NULL;
// cache_sm.close_read();
t_state.transact_return_point = HttpTransact::HandleUpdateCachedObject;
ink_assert(cache_sm.cache_write_vc == nullptr);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
// don't retry read for update
do_cache_prepare_action(&cache_sm, t_state.cache_info.object_read, false);
} else {
t_state.api_modifiable_cached_resp = false;
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
}
}
void
HttpSM::do_cache_prepare_action(HttpCacheSM *c_sm, CacheHTTPInfo *object_read_info, bool retry, bool allow_multiple)
{
URL *o_url, *c_url, *s_url;
bool restore_client_request = false;
ink_assert(!pending_action);
if (t_state.api_lock_url == HttpTransact::LOCK_URL_FIRST) {
if (t_state.redirect_info.redirect_in_process) {
o_url = &(t_state.redirect_info.original_url);
ink_assert(o_url->valid());
restore_client_request = true;
s_url = o_url;
} else {
o_url = &(t_state.cache_info.original_url);
if (o_url->valid()) {
s_url = o_url;
} else {
s_url = t_state.cache_info.lookup_url;
}
}
} else if (t_state.api_lock_url == HttpTransact::LOCK_URL_SECOND) {
s_url = &t_state.cache_info.lookup_url_storage;
} else {
ink_assert(t_state.api_lock_url == HttpTransact::LOCK_URL_ORIGINAL);
s_url = &(t_state.cache_info.original_url);
restore_client_request = true;
}
// modify client request to make it have the url we are going to
// store into the cache
if (restore_client_request) {
c_url = t_state.hdr_info.client_request.url_get();
s_url->copy(c_url);
}
ink_assert(s_url != nullptr && s_url->valid());
DebugSM("http_cache_write", "[%" PRId64 "] writing to cache with URL %s", sm_id, s_url->string_get(&t_state.arena));
HttpCacheKey key;
Cache::generate_key(&key, s_url, t_state.txn_conf->cache_generation_number);
Action *cache_action_handle = c_sm->open_write(
&key, s_url, &t_state.hdr_info.client_request, object_read_info,
(time_t)((t_state.cache_control.pin_in_cache_for < 0) ? 0 : t_state.cache_control.pin_in_cache_for), retry, allow_multiple);
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
}
void
HttpSM::send_origin_throttled_response()
{
t_state.current.attempts = t_state.txn_conf->connect_attempts_max_retries;
// t_state.current.state = HttpTransact::CONNECTION_ERROR;
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_F;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::do_http_server_open()
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::do_http_server_open(bool raw)
{
int ip_family = t_state.current.server->dst_addr.sa.sa_family;
DebugSM("http_track", "entered inside do_http_server_open ][%s]", ats_ip_family_name(ip_family));
// Make sure we are on the "right" thread
if (ua_session) {
if ((pending_action = ua_session->adjust_thread(this, EVENT_INTERVAL, nullptr))) {
return; // Go away if we reschedule
}
}
pending_action = nullptr;
ink_assert(server_entry == nullptr);
// ua_entry can be null if a scheduled update is also a reverse proxy
// request. Added REVPROXY to the assert below, and then changed checks
// to be based on ua_session != NULL instead of req_flavor value.
ink_assert(ua_entry != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
ink_assert(pending_action == nullptr);
if (false == t_state.api_server_addr_set) {
ink_assert(t_state.current.server->dst_addr.host_order_port() > 0);
} else {
ink_assert(t_state.current.server->dst_addr.port() != 0); // verify the plugin set it to something.
}
char addrbuf[INET6_ADDRPORTSTRLEN];
DebugSM("http", "[%" PRId64 "] open connection to %s: %s", sm_id, t_state.current.server->name,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
if (plugin_tunnel) {
PluginVCCore *t = plugin_tunnel;
plugin_tunnel = nullptr;
Action *pvc_action_handle = t->connect_re(this);
// This connect call is always reentrant
ink_release_assert(pvc_action_handle == ACTION_RESULT_DONE);
return;
}
DebugSM("http_seq", "[HttpSM::do_http_server_open] Sending request to server");
milestones[TS_MILESTONE_SERVER_CONNECT] = Thread::get_hrtime();
if (milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] == 0) {
milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] = milestones[TS_MILESTONE_SERVER_CONNECT];
}
// Check for remap rule. If so, only apply ip_allow filter if it is activated (ip_allow_check_enabled_p set).
// Otherwise, if no remap rule is defined, apply the ip_allow filter.
if (!t_state.url_remap_success || t_state.url_map.getMapping()->ip_allow_check_enabled_p) {
// Method allowed on dest IP address check
sockaddr *server_ip = &t_state.current.server->dst_addr.sa;
IpAllow::scoped_config ip_allow;
if (ip_allow) {
const AclRecord *acl_record = ip_allow->match(server_ip, IpAllow::DEST_ADDR);
bool deny_request = false; // default is fail open.
int method = t_state.hdr_info.server_request.method_get_wksidx();
if (acl_record) {
// If empty, nothing is allowed, deny. Conversely if all methods are allowed it's OK, do not deny.
// Otherwise the method has to be checked specifically.
if (acl_record->isEmpty()) {
deny_request = true;
} else if (acl_record->_method_mask != AclRecord::ALL_METHOD_MASK) {
if (method != -1) {
deny_request = !acl_record->isMethodAllowed(method);
} else {
int method_str_len;
const char *method_str = t_state.hdr_info.server_request.method_get(&method_str_len);
deny_request = !acl_record->isNonstandardMethodAllowed(std::string(method_str, method_str_len));
}
}
}
if (deny_request) {
if (is_debug_tag_set("ip-allow")) {
ip_text_buffer ipb;
Warning("server '%s' prohibited by ip-allow policy", ats_ip_ntop(server_ip, ipb, sizeof(ipb)));
Debug("ip-allow", "Denial on %s:%s with mask %x", ats_ip_ntop(&t_state.current.server->dst_addr.sa, ipb, sizeof(ipb)),
hdrtoken_index_to_wks(method), acl_record ? acl_record->_method_mask : 0x0);
}
t_state.current.attempts = t_state.txn_conf->connect_attempts_max_retries; // prevent any more retries with this IP
call_transact_and_set_next_state(HttpTransact::Forbidden);
return;
}
}
}
// Congestion Check
if (t_state.pCongestionEntry != NULL) {
if (t_state.pCongestionEntry->F_congested() &&
(!t_state.pCongestionEntry->proxy_retry(milestones[TS_MILESTONE_SERVER_CONNECT]))) {
t_state.congestion_congested_or_failed = 1;
t_state.pCongestionEntry->stat_inc_F();
CONGEST_INCREMENT_DYN_STAT(congested_on_F_stat);
handleEvent(CONGESTION_EVENT_CONGESTED_ON_F, nullptr);
return;
} else if (t_state.pCongestionEntry->M_congested(ink_hrtime_to_sec(milestones[TS_MILESTONE_SERVER_CONNECT]))) {
t_state.pCongestionEntry->stat_inc_M();
t_state.congestion_congested_or_failed = 1;
CONGEST_INCREMENT_DYN_STAT(congested_on_M_stat);
handleEvent(CONGESTION_EVENT_CONGESTED_ON_M, nullptr);
return;
}
}
// If this is not a raw connection, we try to get a session from the
// shared session pool. Raw connections are for SSLs tunnel and
// require a new connection
//
// This problem with POST requests is a bug. Because of the issue of the
// race with us sending a request after server has closed but before the FIN
// gets to us, we should open a new connection for POST. I believe TS used
// to do this but as far I can tell the code that prevented keep-alive if
// there is a request body has been removed.
// If we are sending authorizations headers, mark the connection private
//
// We do this here because it means that we will not waste a connection from the pool if we already
// know that the session will be private. This is overridable meaning that if a plugin later decides
// it shouldn't be private it can still be returned to a shared pool.
//
if (t_state.txn_conf->auth_server_session_private == 1 &&
t_state.hdr_info.server_request.presence(MIME_PRESENCE_AUTHORIZATION | MIME_PRESENCE_PROXY_AUTHORIZATION |
MIME_PRESENCE_WWW_AUTHENTICATE)) {
DebugSM("http_ss_auth", "Setting server session to private for authorization header");
will_be_private_ss = true;
}
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
// don't share the session if keep-alive for post is not on
if (t_state.txn_conf->keep_alive_post_out == 0) {
DebugSM("http_ss", "Setting server session to private because of keep-alive post out");
will_be_private_ss = true;
}
}
// If there is already an attached server session mark it as private.
if (server_session != nullptr && will_be_private_ss) {
set_server_session_private(true);
}
if (raw == false && TS_SERVER_SESSION_SHARING_MATCH_NONE != t_state.txn_conf->server_session_sharing_match &&
(t_state.txn_conf->keep_alive_post_out == 1 || t_state.hdr_info.request_content_length == 0) && !is_private() &&
ua_session != nullptr) {
HSMresult_t shared_result;
shared_result = httpSessionManager.acquire_session(this, // state machine
&t_state.current.server->dst_addr.sa, // ip + port
t_state.current.server->name, // hostname
ua_session, // has ptr to bound ua sessions
this // sm
);
switch (shared_result) {
case HSM_DONE:
hsm_release_assert(server_session != nullptr);
handle_http_server_open();
return;
case HSM_NOT_FOUND:
hsm_release_assert(server_session == nullptr);
break;
case HSM_RETRY:
// Could not get shared pool lock
// FIX: should retry lock
break;
default:
hsm_release_assert(0);
}
}
// Avoid a problem where server session sharing is disabled and we have keep-alive, we are trying to open a new server
// session when we already have an attached server session.
else if ((TS_SERVER_SESSION_SHARING_MATCH_NONE == t_state.txn_conf->server_session_sharing_match || is_private()) &&
(ua_session != nullptr)) {
HttpServerSession *existing_ss = ua_session->get_server_session();
if (existing_ss) {
// [amc] Not sure if this is the best option, but we don't get here unless session sharing is disabled
// so there's no point in further checking on the match or pool values. But why check anything? The
// client has already exchanged a request with this specific origin server and has sent another one
// shouldn't we just automatically keep the association?
if (ats_ip_addr_port_eq(&existing_ss->get_server_ip().sa, &t_state.current.server->dst_addr.sa)) {
ua_session->attach_server_session(nullptr);
existing_ss->state = HSS_ACTIVE;
this->attach_server_session(existing_ss);
hsm_release_assert(server_session != nullptr);
handle_http_server_open();
return;
} else {
// As this is in the non-sharing configuration, we want to close
// the existing connection and call connect_re to get a new one
existing_ss->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
existing_ss->release();
ua_session->attach_server_session(nullptr);
}
}
}
// Otherwise, we release the existing connection and call connect_re
// to get a new one.
// ua_session is null when t_state.req_flavor == REQ_FLAVOR_SCHEDULED_UPDATE
else if (ua_session != nullptr) {
HttpServerSession *existing_ss = ua_session->get_server_session();
if (existing_ss) {
existing_ss->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
existing_ss->release();
ua_session->attach_server_session(nullptr);
}
}
// Check to see if we have reached the max number of connections.
// Atomically read the current number of connections and check to see
// if we have gone above the max allowed.
if (t_state.http_config_param->server_max_connections > 0) {
int64_t sum;
HTTP_READ_GLOBAL_DYN_SUM(http_current_server_connections_stat, sum);
// Note that there is a potential race condition here where
// the value of the http_current_server_connections_stat gets changed
// between the statement above and the check below.
// If this happens, we might go over the max by 1 but this is ok.
if (sum >= t_state.http_config_param->server_max_connections) {
httpSessionManager.purge_keepalives();
// Eventually may want to have a queue as the origin_max_connection does to allow for a combination
// of retries and errors. But at this point, we are just going to allow the error case.
t_state.current.state = HttpTransact::CONNECTION_ERROR;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return;
}
}
// Check to see if we have reached the max number of connections on this
// host.
if (t_state.txn_conf->origin_max_connections > 0) {
ConnectionCount *connections = ConnectionCount::getInstance();
INK_MD5 hostname_hash;
MD5Context md5_ctx;
md5_ctx.hash_immediate(hostname_hash, static_cast<const void *>(t_state.current.server->name),
strlen(t_state.current.server->name));
if (connections->getCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match) >=
t_state.txn_conf->origin_max_connections) {
ip_port_text_buffer addrbuf;
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf));
DebugSM("http", "[%" PRId64 "] over the number of connection for this host: %s", sm_id, addrbuf);
Warning("[%" PRId64 "] over the max number of connections for this host: %s", sm_id, addrbuf);
ink_assert(pending_action == nullptr);
// if we were previously queued, or the queue is disabled-- just reschedule
if (t_state.origin_request_queued || t_state.txn_conf->origin_max_connections_queue < 0) {
pending_action = eventProcessor.schedule_in(this, HRTIME_MSECONDS(100));
return;
} else if (t_state.txn_conf->origin_max_connections_queue > 0) { // If we have a queue, lets see if there is a slot
ConnectionCountQueue *waiting_connections = ConnectionCountQueue::getInstance();
// if there is space in the queue
if (waiting_connections->getCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match) <
t_state.txn_conf->origin_max_connections_queue) {
t_state.origin_request_queued = true;
Debug("http", "[%" PRId64 "] queued for this host: %s", sm_id,
ats_ip_ntop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
waiting_connections->incrementCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match, 1);
pending_action = eventProcessor.schedule_in(this, HRTIME_MSECONDS(100));
} else { // the queue is full
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
send_origin_throttled_response();
}
} else { // the queue is set to 0
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
send_origin_throttled_response();
}
return;
}
}
// We did not manage to get an existing session
// and need to open a new connection
Action *connect_action_handle;
NetVCOptions opt;
opt.f_blocking_connect = false;
opt.set_sock_param(t_state.txn_conf->sock_recv_buffer_size_out, t_state.txn_conf->sock_send_buffer_size_out,
t_state.txn_conf->sock_option_flag_out, t_state.txn_conf->sock_packet_mark_out,
t_state.txn_conf->sock_packet_tos_out);
opt.ip_family = ip_family;
if (ua_session) {
opt.local_port = ua_session->get_outbound_port();
const IpAddr &outbound_ip = AF_INET6 == ip_family ? ua_session->get_outbound_ip6() : ua_session->get_outbound_ip4();
if (outbound_ip.isValid()) {
opt.addr_binding = NetVCOptions::INTF_ADDR;
opt.local_ip = outbound_ip;
} else if (ua_session->is_outbound_transparent()) {
opt.addr_binding = NetVCOptions::FOREIGN_ADDR;
opt.local_ip = t_state.client_info.src_addr;
/* If the connection is server side transparent, we can bind to the
port that the client chose instead of randomly assigning one at
the proxy. This is controlled by the 'use_client_source_port'
configuration parameter.
*/
NetVConnection *client_vc = ua_session->get_netvc();
if (t_state.http_config_param->use_client_source_port && nullptr != client_vc) {
opt.local_port = client_vc->get_remote_port();
}
}
}
int scheme_to_use = t_state.scheme; // get initial scheme
if (!t_state.is_websocket) { // if not websocket, then get scheme from server request
int new_scheme_to_use = t_state.hdr_info.server_request.url_get()->scheme_get_wksidx();
// if the server_request url scheme was never set, try the client_request
if (new_scheme_to_use < 0) {
new_scheme_to_use = t_state.hdr_info.client_request.url_get()->scheme_get_wksidx();
}
if (new_scheme_to_use >= 0) { // found a new scheme, use it
scheme_to_use = new_scheme_to_use;
}
}
// draft-stenberg-httpbis-tcp recommends only enabling TFO on indempotent methods or
// those with intervening protocol layers (eg. TLS).
if (scheme_to_use == URL_WKSIDX_HTTPS || HttpTransactHeaders::is_method_idempotent(t_state.method)) {
opt.f_tcp_fastopen = (t_state.txn_conf->sock_option_flag_out & NetVCOptions::SOCK_OPT_TCP_FAST_OPEN);
}
if (scheme_to_use == URL_WKSIDX_HTTPS) {
DebugSM("http", "calling sslNetProcessor.connect_re");
int len = 0;
const char *host = t_state.hdr_info.server_request.host_get(&len);
if (host && len > 0) {
opt.set_sni_servername(host, len);
}
if (t_state.txn_conf->client_cert_filepath && t_state.txn_conf->client_cert_filename) {
ats_scoped_str clientCert(
(Layout::relative_to(t_state.txn_conf->client_cert_filepath, t_state.txn_conf->client_cert_filename)));
if (clientCert != nullptr) {
opt.set_client_certname(clientCert);
}
}
connect_action_handle = sslNetProcessor.connect_re(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
&opt);
} else if (t_state.method != HTTP_WKSIDX_CONNECT) {
DebugSM("http", "calling netProcessor.connect_re");
connect_action_handle = netProcessor.connect_re(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
&opt);
} else {
// CONNECT method
MgmtInt connect_timeout;
ink_assert(t_state.method == HTTP_WKSIDX_CONNECT);
// Set the inactivity timeout to the connect timeout so that we
// we fail this server if it doesn't start sending the response
// header
if (t_state.current.server == &t_state.parent_info) {
connect_timeout = t_state.http_config_param->parent_connect_timeout;
} else if (t_state.pCongestionEntry != nullptr) {
connect_timeout = t_state.pCongestionEntry->connect_timeout();
} else {
connect_timeout = t_state.txn_conf->connect_attempts_timeout;
}
DebugSM("http", "calling netProcessor.connect_s");
connect_action_handle = netProcessor.connect_s(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
connect_timeout, &opt);
}
if (connect_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = connect_action_handle;
}
return;
}
void
HttpSM::do_icp_lookup()
{
ink_assert(pending_action == nullptr);
URL *o_url = &t_state.cache_info.original_url;
Action *icp_lookup_action_handle = icpProcessor.ICPQuery(this, o_url->valid() ? o_url : t_state.cache_info.lookup_url);
if (icp_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = icp_lookup_action_handle;
}
return;
}
void
HttpSM::do_api_callout_internal()
{
if (t_state.backdoor_request) {
handle_api_return();
return;
}
switch (t_state.api_next_action) {
case HttpTransact::SM_ACTION_API_SM_START:
cur_hook_id = TS_HTTP_TXN_START_HOOK;
break;
case HttpTransact::SM_ACTION_API_PRE_REMAP:
cur_hook_id = TS_HTTP_PRE_REMAP_HOOK;
break;
case HttpTransact::SM_ACTION_API_POST_REMAP:
cur_hook_id = TS_HTTP_POST_REMAP_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
cur_hook_id = TS_HTTP_READ_REQUEST_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_OS_DNS:
cur_hook_id = TS_HTTP_OS_DNS_HOOK;
break;
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
cur_hook_id = TS_HTTP_SEND_REQUEST_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
cur_hook_id = TS_HTTP_READ_CACHE_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE:
cur_hook_id = TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
cur_hook_id = TS_HTTP_READ_RESPONSE_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
cur_hook_id = TS_HTTP_SEND_RESPONSE_HDR_HOOK;
milestones[TS_MILESTONE_UA_BEGIN_WRITE] = Thread::get_hrtime();
break;
case HttpTransact::SM_ACTION_API_SM_SHUTDOWN:
if (callout_state == HTTP_API_IN_CALLOUT || callout_state == HTTP_API_DEFERED_SERVER_ERROR) {
callout_state = HTTP_API_DEFERED_CLOSE;
return;
} else {
cur_hook_id = TS_HTTP_TXN_CLOSE_HOOK;
}
break;
default:
cur_hook_id = (TSHttpHookID)-1;
ink_assert(!"not reached");
}
cur_hook = nullptr;
cur_hooks = 0;
state_api_callout(0, nullptr);
}
VConnection *
HttpSM::do_post_transform_open()
{
ink_assert(post_transform_info.vc == nullptr);
if (is_action_tag_set("http_post_nullt")) {
txn_hook_prepend(TS_HTTP_REQUEST_TRANSFORM_HOOK, transformProcessor.null_transform(mutex.get()));
}
post_transform_info.vc = transformProcessor.open(this, api_hooks.get(TS_HTTP_REQUEST_TRANSFORM_HOOK));
if (post_transform_info.vc) {
// Record the transform VC in our table
post_transform_info.entry = vc_table.new_entry();
post_transform_info.entry->vc = post_transform_info.vc;
post_transform_info.entry->vc_type = HTTP_TRANSFORM_VC;
}
return post_transform_info.vc;
}
VConnection *
HttpSM::do_transform_open()
{
ink_assert(transform_info.vc == nullptr);
APIHook *hooks;
if (is_action_tag_set("http_nullt")) {
txn_hook_prepend(TS_HTTP_RESPONSE_TRANSFORM_HOOK, transformProcessor.null_transform(mutex.get()));
}
hooks = api_hooks.get(TS_HTTP_RESPONSE_TRANSFORM_HOOK);
if (hooks) {
transform_info.vc = transformProcessor.open(this, hooks);
// Record the transform VC in our table
transform_info.entry = vc_table.new_entry();
transform_info.entry->vc = transform_info.vc;
transform_info.entry->vc_type = HTTP_TRANSFORM_VC;
} else {
transform_info.vc = nullptr;
}
return transform_info.vc;
}
void
HttpSM::mark_host_failure(HostDBInfo *info, time_t time_down)
{
char addrbuf[INET6_ADDRPORTSTRLEN];
if (info->app.http_data.last_failure == 0) {
char *url_str = t_state.hdr_info.client_request.url_string_get(&t_state.arena, nullptr);
Log::error("CONNECT: could not connect to %s "
"for '%s' (setting last failure time)",
ats_ip_ntop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)), url_str ? url_str : "<none>");
if (url_str) {
t_state.arena.str_free(url_str);
}
}
info->app.http_data.last_failure = time_down;
#ifdef DEBUG
ink_assert(ink_cluster_time() + t_state.txn_conf->down_server_timeout > time_down);
#endif
DebugSM("http", "[%" PRId64 "] hostdb update marking IP: %s as down", sm_id,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
void
HttpSM::set_ua_abort(HttpTransact::AbortState_t ua_abort, int event)
{
t_state.client_info.abort = ua_abort;
switch (ua_abort) {
case HttpTransact::ABORTED:
case HttpTransact::MAYBE_ABORTED:
t_state.squid_codes.log_code = SQUID_LOG_ERR_CLIENT_ABORT;
break;
default:
// Handled here:
// HttpTransact::ABORT_UNDEFINED, HttpTransact::DIDNOT_ABORT
break;
}
// Set the connection attribute code for the client so that
// we log the client finish code correctly
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.client_info.state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.client_info.state = HttpTransact::INACTIVE_TIMEOUT;
break;
case VC_EVENT_ERROR:
t_state.client_info.state = HttpTransact::CONNECTION_ERROR;
break;
}
}
void
HttpSM::mark_server_down_on_client_abort()
{
/////////////////////////////////////////////////////
// Check see if the client aborted because the //
// origin server was too slow in sending the //
// response header. If so, mark that //
// server as down so other clients won't try to //
// for revalidation or select it from a round //
// robin set //
// //
// Note: we do not want to mark parent or icp //
// proxies as down with this metric because //
// that upstream proxy may be working but //
// the actual origin server is one that is hung //
/////////////////////////////////////////////////////
if (t_state.current.request_to == HttpTransact::ORIGIN_SERVER && t_state.hdr_info.request_content_length <= 0) {
if (milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] != 0 && milestones[TS_MILESTONE_SERVER_FIRST_READ] == 0) {
// Check to see if client waited for the threshold
// to declare the origin server as down
ink_hrtime wait = Thread::get_hrtime() - milestones[TS_MILESTONE_SERVER_FIRST_CONNECT];
if (wait < 0) {
wait = 0;
}
if (ink_hrtime_to_sec(wait) > t_state.txn_conf->client_abort_threshold) {
t_state.current.server->set_connect_fail(ETIMEDOUT);
do_hostdb_update_if_necessary();
}
}
}
}
// void HttpSM::release_server_session()
//
// Called when we are not tunneling a response from the
// server. If the session is keep alive, release it back to the
// shared pool, otherwise close it
//
void
HttpSM::release_server_session(bool serve_from_cache)
{
if (server_session == nullptr) {
return;
}
if (TS_SERVER_SESSION_SHARING_MATCH_NONE != t_state.txn_conf->server_session_sharing_match && t_state.current.server != nullptr &&
t_state.current.server->keep_alive == HTTP_KEEPALIVE && t_state.hdr_info.server_response.valid() &&
t_state.hdr_info.server_request.valid() && (t_state.hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED ||
(t_state.hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD &&
t_state.www_auth_content != HttpTransact::CACHE_AUTH_NONE)) &&
plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
HTTP_DECREMENT_DYN_STAT(http_current_server_transactions_stat);
server_session->server_trans_stat--;
server_session->attach_hostname(t_state.current.server->name);
if (t_state.www_auth_content == HttpTransact::CACHE_AUTH_NONE || serve_from_cache == false) {
// Must explicitly set the keep_alive_no_activity time before doing the release
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
server_session->release();
} else {
// an authenticated server connection - attach to the local client
// we are serving from cache for the current transaction
t_state.www_auth_content = HttpTransact::CACHE_AUTH_SERVE;
ua_session->attach_server_session(server_session, false);
}
} else {
server_session->do_io_close();
}
ink_assert(server_entry->vc == server_session);
server_entry->in_tunnel = true;
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
server_session = nullptr;
}
// void HttpSM::handle_post_failure()
//
// We failed in our attempt post (or put) a document
// to the server. Two cases happen here. The normal
// one is the server died, in which case we ought to
// return an error to the client. The second one is
// stupid. The server returned a response without reading
// all the post data. In order to be as transparent as
// possible process the server's response
void
HttpSM::handle_post_failure()
{
STATE_ENTER(&HttpSM::handle_post_failure, VC_EVENT_NONE);
ink_assert(ua_entry->vc == ua_session);
ink_assert(server_entry->eos == true);
// First order of business is to clean up from
// the tunnel
// note: since the tunnel is providing the buffer for a lingering
// client read (for abort watching purposes), we need to stop
// the read
if (false == t_state.redirect_info.redirect_in_process) {
ua_entry->read_vio = ua_session->do_io_read(this, 0, nullptr);
}
ua_entry->in_tunnel = false;
server_entry->in_tunnel = false;
// disable redirection in case we got a partial response and then EOS, because the buffer might not
// have the full post and it's deallocating the post buffers here
enable_redirection = false;
tunnel.deallocate_redirect_postdata_buffers();
// Don't even think about doing keep-alive after this debacle
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
if (server_buffer_reader->read_avail() > 0) {
tunnel.deallocate_buffers();
tunnel.reset();
// There's data from the server so try to read the header
setup_server_read_response_header();
} else {
tunnel.deallocate_buffers();
tunnel.reset();
// Server died
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
}
// void HttpSM::handle_http_server_open()
//
// The server connection is now open. If there is a POST or PUT,
// we need setup a transform is there is one otherwise we need
// to send the request header
//
void
HttpSM::handle_http_server_open()
{
// if we were a queued request, we need to decrement the queue size-- as we got a connection
if (t_state.origin_request_queued) {
INK_MD5 hostname_hash;
MD5Context md5_ctx;
md5_ctx.hash_immediate(hostname_hash, static_cast<const void *>(t_state.current.server->name),
strlen(t_state.current.server->name));
ConnectionCountQueue *waiting_connections = ConnectionCountQueue::getInstance();
waiting_connections->incrementCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match, -1);
// The request is now not queued. This is important if the request will ever retry, the t_state is re-used
t_state.origin_request_queued = false;
}
// [bwyatt] applying per-transaction OS netVC options here
// IFF they differ from the netVC's current options.
// This should keep this from being redundant on a
// server session's first transaction.
if (nullptr != server_session) {
NetVConnection *vc = server_session->get_netvc();
if (vc != nullptr && (vc->options.sockopt_flags != t_state.txn_conf->sock_option_flag_out ||
vc->options.packet_mark != t_state.txn_conf->sock_packet_mark_out ||
vc->options.packet_tos != t_state.txn_conf->sock_packet_tos_out)) {
vc->options.sockopt_flags = t_state.txn_conf->sock_option_flag_out;
vc->options.packet_mark = t_state.txn_conf->sock_packet_mark_out;
vc->options.packet_tos = t_state.txn_conf->sock_packet_tos_out;
vc->apply_options();
}
}
if (t_state.pCongestionEntry != nullptr) {
if (t_state.congestion_connection_opened == 0) {
t_state.congestion_connection_opened = 1;
t_state.pCongestionEntry->connection_opened();
}
}
int method = t_state.hdr_info.server_request.method_get_wksidx();
if (method != HTTP_WKSIDX_TRACE &&
(t_state.hdr_info.request_content_length > 0 || t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) &&
do_post_transform_open()) {
do_setup_post_tunnel(HTTP_TRANSFORM_VC);
} else {
setup_server_send_request_api();
}
}
// void HttpSM::handle_server_setup_error(int event, void* data)
//
// Handles setting t_state.current.state and calling
// Transact in between opening an origin server connection
// and receiving the response header (in the case of the
// POST, a post tunnel happens in between the sending
// request header and reading the response header
//
void
HttpSM::handle_server_setup_error(int event, void *data)
{
VIO *vio = (VIO *)data;
ink_assert(vio != nullptr);
STATE_ENTER(&HttpSM::handle_server_setup_error, event);
// If there is POST or PUT tunnel wait for the tunnel
// to figure out that things have gone to hell
if (tunnel.is_tunnel_active()) {
ink_assert(server_entry->read_vio == data || server_entry->write_vio == data);
DebugSM("http", "[%" PRId64 "] [handle_server_setup_error] "
"forwarding event %s to post tunnel",
sm_id, HttpDebugNames::get_event_name(event));
HttpTunnelConsumer *c = tunnel.get_consumer(server_entry->vc);
// it is possible only user agent post->post transform is set up
// this happened for Linux iocore where NET_EVENT_OPEN was returned
// for a non-existing listening port. the hack is to pass the error
// event for server connection to post_transform_info
if (c == nullptr && post_transform_info.vc) {
c = tunnel.get_consumer(post_transform_info.vc);
// c->handler_state = HTTP_SM_TRANSFORM_FAIL;
// No point in proceeding if there is no consumer
// Do we need to do additional clean up in the c == NULL case?
if (c != nullptr) {
HttpTunnelProducer *ua_producer = c->producer;
ink_assert(ua_entry->vc == ua_producer->vc);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
ua_producer->alive = false;
ua_producer->handler_state = HTTP_SM_POST_SERVER_FAIL;
tunnel.handleEvent(VC_EVENT_ERROR, c->write_vio);
}
} else {
// c could be null here as well
if (c != nullptr) {
tunnel.handleEvent(event, c->write_vio);
}
}
return;
} else {
if (post_transform_info.vc) {
HttpTunnelConsumer *c = tunnel.get_consumer(post_transform_info.vc);
if (c && c->handler_state == HTTP_SM_TRANSFORM_OPEN) {
vc_table.cleanup_entry(post_transform_info.entry);
post_transform_info.entry = nullptr;
tunnel.deallocate_buffers();
tunnel.reset();
}
}
}
if (event == VC_EVENT_ERROR) {
t_state.cause_of_death_errno = server_session->get_netvc()->lerrno;
}
switch (event) {
case VC_EVENT_EOS:
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
break;
case VC_EVENT_ERROR:
t_state.current.state = HttpTransact::CONNECTION_ERROR;
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.current.state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
// If we're writing the request and get an inactivity timeout
// before any bytes are written, the connection to the
// server failed
// In case of TIMEOUT, the iocore sends back
// server_entry->read_vio instead of the write_vio
// if (vio->op == VIO::WRITE && vio->ndone == 0) {
if (server_entry->write_vio && server_entry->write_vio->nbytes > 0 && server_entry->write_vio->ndone == 0) {
t_state.current.state = HttpTransact::CONNECTION_ERROR;
} else {
t_state.current.state = HttpTransact::INACTIVE_TIMEOUT;
}
break;
default:
ink_release_assert(0);
}
// Closedown server connection and deallocate buffers
ink_assert(server_entry->in_tunnel == false);
// if we are waiting on a plugin callout for
// HTTP_API_SEND_REQUEST_HDR defer calling transact until
// after we've finished processing the plugin callout
switch (callout_state) {
case HTTP_API_NO_CALLOUT:
// Normal fast path case, no api callouts in progress
break;
case HTTP_API_IN_CALLOUT:
case HTTP_API_DEFERED_SERVER_ERROR:
// Callout in progress note that we are in deferring
// the server error
callout_state = HTTP_API_DEFERED_SERVER_ERROR;
return;
case HTTP_API_DEFERED_CLOSE:
// The user agent has shutdown killing the sm
// but we are stuck waiting for the server callout
// to finish so do nothing here. We don't care
// about the server connection at this and are
// just waiting till we can execute the close hook
return;
default:
ink_release_assert(0);
}
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
void
HttpSM::setup_transform_to_server_transfer()
{
ink_assert(post_transform_info.vc != nullptr);
ink_assert(post_transform_info.entry->vc == post_transform_info.vc);
int64_t nbytes = t_state.hdr_info.transform_request_cl;
int64_t alloc_index = buffer_size_to_index(nbytes);
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
HttpTunnelConsumer *c = tunnel.get_consumer(post_transform_info.vc);
HttpTunnelProducer *p = tunnel.add_producer(post_transform_info.vc, nbytes, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "post transform");
tunnel.chain(c, p);
post_transform_info.entry->in_tunnel = true;
tunnel.add_consumer(server_entry->vc, post_transform_info.vc, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER,
"http server post");
server_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
#ifdef PROXY_DRAIN
void
HttpSM::do_drain_request_body()
{
int64_t post_bytes = t_state.hdr_info.request_content_length;
int64_t avail = ua_buffer_reader->read_avail();
int64_t act_on = (avail < post_bytes) ? avail : post_bytes;
client_request_body_bytes = act_on;
ua_buffer_reader->consume(act_on);
ink_assert(client_request_body_bytes <= post_bytes);
if (client_request_body_bytes < post_bytes) {
ua_buffer_reader->mbuf->size_index = buffer_size_to_index(t_state.hdr_info.request_content_length);
ua_entry->vc_handler = &HttpSM::state_drain_client_request_body;
ua_entry->read_vio = ua_entry->vc->do_io_read(this, post_bytes - client_request_body_bytes, ua_buffer_reader->mbuf);
} else {
call_transact_and_set_next_state(NULL);
}
}
#endif /* PROXY_DRAIN */
void
HttpSM::do_setup_post_tunnel(HttpVC_t to_vc_type)
{
bool chunked = (t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING);
bool post_redirect = false;
HttpTunnelProducer *p = nullptr;
// YTS Team, yamsat Plugin
// if redirect_in_process and redirection is enabled add static producer
if (t_state.redirect_info.redirect_in_process && enable_redirection &&
(tunnel.postbuf && tunnel.postbuf->postdata_copy_buffer_start != nullptr &&
tunnel.postbuf->postdata_producer_buffer != nullptr)) {
post_redirect = true;
// copy the post data into a new producer buffer for static producer
tunnel.postbuf->postdata_producer_buffer->write(tunnel.postbuf->postdata_copy_buffer_start);
int64_t post_bytes = tunnel.postbuf->postdata_producer_reader->read_avail();
transfered_bytes = post_bytes;
p = tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, post_bytes, tunnel.postbuf->postdata_producer_reader,
(HttpProducerHandler) nullptr, HT_STATIC, "redirect static agent post");
// the tunnel has taken over the buffer and will free it
tunnel.postbuf->postdata_producer_buffer = nullptr;
tunnel.postbuf->postdata_producer_reader = nullptr;
} else {
int64_t alloc_index;
// content length is undefined, use default buffer size
if (t_state.hdr_info.request_content_length == HTTP_UNDEFINED_CL) {
alloc_index = (int)t_state.txn_conf->default_buffer_size_index;
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > MAX_BUFFER_SIZE_INDEX) {
alloc_index = DEFAULT_REQUEST_BUFFER_SIZE_INDEX;
}
} else {
alloc_index = buffer_size_to_index(t_state.hdr_info.request_content_length);
}
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
int64_t post_bytes = chunked ? INT64_MAX : t_state.hdr_info.request_content_length;
// Note: Many browsers, Netscape and IE included send two extra
// bytes (CRLF) at the end of the post. We just ignore those
// bytes since the sending them is not spec
// Next order of business if copy the remaining data from the
// header buffer into new buffer
client_request_body_bytes = post_buffer->write(ua_buffer_reader, chunked ? ua_buffer_reader->read_avail() : post_bytes);
ua_buffer_reader->consume(client_request_body_bytes);
p = tunnel.add_producer(ua_entry->vc, post_bytes - transfered_bytes, buf_start, &HttpSM::tunnel_handler_post_ua, HT_HTTP_CLIENT,
"user agent post");
}
ua_entry->in_tunnel = true;
switch (to_vc_type) {
case HTTP_TRANSFORM_VC:
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_request_wait_for_transform_read);
ink_assert(post_transform_info.entry != nullptr);
ink_assert(post_transform_info.entry->vc == post_transform_info.vc);
tunnel.add_consumer(post_transform_info.entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"post transform");
post_transform_info.entry->in_tunnel = true;
break;
case HTTP_SERVER_VC:
// YTS Team, yamsat Plugin
// When redirect in process is true and redirection is enabled
// add http server as the consumer
if (post_redirect) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_for_partial_post);
tunnel.add_consumer(server_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER,
"redirect http server post");
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
tunnel.add_consumer(server_entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER, "http server post");
}
server_entry->in_tunnel = true;
break;
default:
ink_release_assert(0);
break;
}
if (chunked) {
tunnel.set_producer_chunking_action(p, 0, TCA_PASSTHRU_CHUNKED_CONTENT);
}
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
tunnel.tunnel_run(p);
// If we're half closed, we got a FIN from the client. Forward it on to the origin server
// now that we have the tunnel operational.
if (ua_session->get_half_close_flag()) {
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
}
}
// void HttpSM::perform_transform_cache_write_action()
//
// Called to do cache write from the transform
//
void
HttpSM::perform_transform_cache_write_action()
{
DebugSM("http", "[%" PRId64 "] perform_transform_cache_write_action %s", sm_id,
HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
if (t_state.range_setup) {
return;
}
switch (t_state.cache_info.transform_action) {
case HttpTransact::CACHE_DO_NO_ACTION: {
// Nothing to do
transform_cache_sm.end_both();
break;
}
case HttpTransact::CACHE_DO_WRITE: {
transform_cache_sm.close_read();
t_state.cache_info.transform_write_status = HttpTransact::CACHE_WRITE_IN_PROGRESS;
setup_cache_write_transfer(&transform_cache_sm, transform_info.entry->vc, &t_state.cache_info.transform_store,
client_response_hdr_bytes, "cache write t");
break;
}
default:
ink_release_assert(0);
break;
}
}
// void HttpSM::perform_cache_write_action()
//
// Called to do cache write, delete and updates based
// on s->cache_info.action. Does not setup cache
// read tunnels
//
void
HttpSM::perform_cache_write_action()
{
DebugSM("http", "[%" PRId64 "] perform_cache_write_action %s", sm_id,
HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
switch (t_state.cache_info.action) {
case HttpTransact::CACHE_DO_NO_ACTION:
{
// Nothing to do
cache_sm.end_both();
break;
}
case HttpTransact::CACHE_DO_SERVE: {
cache_sm.abort_write();
break;
}
case HttpTransact::CACHE_DO_DELETE: {
// Write close deletes the old alternate
cache_sm.close_write();
cache_sm.close_read();
break;
}
case HttpTransact::CACHE_DO_SERVE_AND_DELETE: {
// FIX ME: need to set up delete for after cache write has
// completed
break;
}
case HttpTransact::CACHE_DO_SERVE_AND_UPDATE: {
issue_cache_update();
break;
}
case HttpTransact::CACHE_DO_UPDATE: {
cache_sm.close_read();
issue_cache_update();
break;
}
case HttpTransact::CACHE_DO_WRITE:
case HttpTransact::CACHE_DO_REPLACE:
// Fix need to set up delete for after cache write has
// completed
if (transform_info.entry == nullptr || t_state.api_info.cache_untransformed == true) {
cache_sm.close_read();
t_state.cache_info.write_status = HttpTransact::CACHE_WRITE_IN_PROGRESS;
setup_cache_write_transfer(&cache_sm, server_entry->vc, &t_state.cache_info.object_store, client_response_hdr_bytes,
"cache write");
} else {
// We are not caching the untransformed. We might want to
// use the cache writevc to cache the transformed copy
ink_assert(transform_cache_sm.cache_write_vc == nullptr);
transform_cache_sm.cache_write_vc = cache_sm.cache_write_vc;
cache_sm.cache_write_vc = nullptr;
}
break;
default:
ink_release_assert(0);
break;
}
}
void
HttpSM::issue_cache_update()
{
ink_assert(cache_sm.cache_write_vc != nullptr);
if (cache_sm.cache_write_vc) {
t_state.cache_info.object_store.request_sent_time_set(t_state.request_sent_time);
t_state.cache_info.object_store.response_received_time_set(t_state.response_received_time);
ink_assert(t_state.cache_info.object_store.request_sent_time_get() > 0);
ink_assert(t_state.cache_info.object_store.response_received_time_get() > 0);
cache_sm.cache_write_vc->set_http_info(&t_state.cache_info.object_store);
t_state.cache_info.object_store.clear();
}
// Now close the write which commits the update
cache_sm.close_write();
}
int
HttpSM::write_header_into_buffer(HTTPHdr *h, MIOBuffer *b)
{
int bufindex;
int dumpoffset;
int done, tmp;
IOBufferBlock *block;
dumpoffset = 0;
do {
bufindex = 0;
tmp = dumpoffset;
block = b->get_current_block();
ink_assert(block->write_avail() > 0);
done = h->print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
ink_assert(bufindex > 0);
b->fill(bufindex);
if (!done) {
b->add_block();
}
} while (!done);
return dumpoffset;
}
void
HttpSM::attach_server_session(HttpServerSession *s)
{
hsm_release_assert(server_session == nullptr);
hsm_release_assert(server_entry == nullptr);
hsm_release_assert(s->state == HSS_ACTIVE);
server_session = s;
server_transact_count = server_session->transact_count++;
// Propagate the per client IP debugging
if (ua_session) {
s->get_netvc()->control_flags = get_cont_flags();
} else { // If there is no ua_session no sense in continuing to attach the server session
return;
}
// Set the mutex so that we have something to update
// stats with
server_session->mutex = this->mutex;
HTTP_INCREMENT_DYN_STAT(http_current_server_transactions_stat);
++s->server_trans_stat;
// Record the VC in our table
server_entry = vc_table.new_entry();
server_entry->vc = server_session;
server_entry->vc_type = HTTP_SERVER_VC;
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
// es - is this a concern here in HttpSM? Does it belong somewhere else?
// Get server and client connections
UnixNetVConnection *server_vc = dynamic_cast<UnixNetVConnection *>(server_session->get_netvc());
UnixNetVConnection *client_vc = (UnixNetVConnection *)(ua_session->get_netvc());
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(client_vc);
// Verifying that the user agent and server sessions/transactions are operating on the same thread.
ink_release_assert(!server_vc || !client_vc || server_vc->thread == client_vc->thread);
bool associated_connection = false;
if (server_vc) { // if server_vc isn't a PluginVC
if (ssl_vc) { // if incoming connection is SSL
bool client_trace = ssl_vc->getSSLTrace();
if (client_trace) {
// get remote address and port to mark corresponding traces
const sockaddr *remote_addr = ssl_vc->get_remote_addr();
uint16_t remote_port = ssl_vc->get_remote_port();
server_vc->setOriginTrace(true);
server_vc->setOriginTraceAddr(remote_addr);
server_vc->setOriginTracePort(remote_port);
associated_connection = true;
}
}
}
if (!associated_connection && server_vc) {
server_vc->setOriginTrace(false);
server_vc->setOriginTraceAddr(nullptr);
server_vc->setOriginTracePort(0);
}
// set flag for server session is SSL
SSLNetVConnection *server_ssl_vc = dynamic_cast<SSLNetVConnection *>(server_vc);
if (server_ssl_vc) {
server_connection_is_ssl = true;
}
// Initiate a read on the session so that the SM and not
// session manager will get called back if the timeout occurs
// or the server closes on us. The IO Core now requires us to
// do the read with a buffer and a size so preallocate the
// buffer
server_buffer_reader = server_session->get_reader();
// ts-3189 We are only setting up an empty read at this point. This
// is sufficient to have the timeout errors directed to the appropriate
// SM handler, but we don't want to read any data until the tunnel has
// been set up. This isn't such a big deal with GET results, since
// if no tunnels are set up, there is no danger of data being delivered
// to the wrong tunnel's consumer handler. But for post and other
// methods that send data after the request, two tunnels are created in
// series, and with a full read set up at this point, the EOS from the
// first tunnel was sometimes behind handled by the consumer of the
// first tunnel instead of the producer of the second tunnel.
// The real read is setup in setup_server_read_response_header()
//
server_entry->read_vio = server_session->do_io_read(this, 0, server_session->read_buffer);
// Transfer control of the write side as well
server_entry->write_vio = server_session->do_io_write(this, 0, nullptr);
// Setup the timeouts
// Set the inactivity timeout to the connect timeout so that we
// we fail this server if it doesn't start sending the response
// header
MgmtInt connect_timeout;
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
connect_timeout = t_state.txn_conf->post_connect_attempts_timeout;
} else if (t_state.current.server == &t_state.parent_info) {
connect_timeout = t_state.http_config_param->parent_connect_timeout;
} else {
connect_timeout = t_state.txn_conf->connect_attempts_timeout;
}
if (t_state.pCongestionEntry != nullptr) {
connect_timeout = t_state.pCongestionEntry->connect_timeout();
}
if (t_state.api_txn_connect_timeout_value != -1) {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_MSECONDS(t_state.api_txn_connect_timeout_value));
} else {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(connect_timeout));
}
if (t_state.api_txn_active_timeout_value != -1) {
server_session->get_netvc()->set_active_timeout(HRTIME_MSECONDS(t_state.api_txn_active_timeout_value));
} else {
server_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_out));
}
if (plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL || will_be_private_ss) {
DebugSM("http_ss", "Setting server session to private");
set_server_session_private(true);
}
}
void
HttpSM::setup_server_send_request_api()
{
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR;
do_api_callout();
}
void
HttpSM::setup_server_send_request()
{
int hdr_length;
int64_t msg_len = 0; /* lv: just make gcc happy */
hsm_release_assert(server_entry != nullptr);
hsm_release_assert(server_session != nullptr);
hsm_release_assert(server_entry->vc == server_session);
// Send the request header
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
server_entry->write_buffer = new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
if (t_state.api_server_request_body_set) {
msg_len = t_state.internal_msg_buffer_size;
t_state.hdr_info.server_request.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, msg_len);
}
if (!t_state.cop_test_page) {
DUMP_HEADER("http_hdrs", &(t_state.hdr_info.server_request), t_state.state_machine_id, "Proxy's Request after hooks");
}
// We need a reader so bytes don't fall off the end of
// the buffer
IOBufferReader *buf_start = server_entry->write_buffer->alloc_reader();
server_request_hdr_bytes = hdr_length = write_header_into_buffer(&t_state.hdr_info.server_request, server_entry->write_buffer);
// the plugin decided to append a message to the request
if (t_state.api_server_request_body_set) {
DebugSM("http", "[%" PRId64 "] appending msg of %" PRId64 " bytes to request %s", sm_id, msg_len, t_state.internal_msg_buffer);
hdr_length += server_entry->write_buffer->write(t_state.internal_msg_buffer, msg_len);
server_request_body_bytes = msg_len;
}
milestones[TS_MILESTONE_SERVER_BEGIN_WRITE] = Thread::get_hrtime();
server_entry->write_vio = server_entry->vc->do_io_write(this, hdr_length, buf_start);
}
void
HttpSM::setup_server_read_response_header()
{
ink_assert(server_session != nullptr);
ink_assert(server_entry != nullptr);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed in REQ_FLAVOR_REVPROXY
ink_assert(ua_session != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
// We should have set the server_buffer_reader
// we sent the request header
ink_assert(server_buffer_reader != nullptr);
// Now that we've got the ability to read from the
// server, setup to read the response header
server_entry->vc_handler = &HttpSM::state_read_server_response_header;
t_state.current.state = HttpTransact::STATE_UNDEFINED;
t_state.current.server->state = HttpTransact::STATE_UNDEFINED;
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
server_response_hdr_bytes = 0;
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = 0;
// We already done the READ when we setup the connection to
// read the request header
ink_assert(server_entry->read_vio);
// The tunnel from OS to UA is now setup. Ready to read the response
server_entry->read_vio = server_session->do_io_read(this, INT64_MAX, server_buffer_reader->mbuf);
// If there is anything in the buffer call the parsing routines
// since if the response is finished, we won't get any
// additional callbacks
if (server_buffer_reader->read_avail() > 0) {
state_read_server_response_header((server_entry->eos) ? VC_EVENT_EOS : VC_EVENT_READ_READY, server_entry->read_vio);
}
}
HttpTunnelProducer *
HttpSM::setup_cache_read_transfer()
{
int64_t alloc_index, hdr_size;
int64_t doc_size;
ink_assert(cache_sm.cache_read_vc != nullptr);
doc_size = t_state.cache_info.object_read->object_size_get();
alloc_index = buffer_size_to_index(doc_size + index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX));
#ifndef USE_NEW_EMPTY_MIOBUFFER
MIOBuffer *buf = new_MIOBuffer(alloc_index);
#else
MIOBuffer *buf = new_empty_MIOBuffer(alloc_index);
buf->append_block(HTTP_HEADER_BUFFER_SIZE_INDEX);
#endif
buf->water_mark = (int)t_state.txn_conf->default_buffer_water_mark;
IOBufferReader *buf_start = buf->alloc_reader();
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = hdr_size = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
cache_response_hdr_bytes = client_response_hdr_bytes;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
if (doc_size != INT64_MAX) {
doc_size += hdr_size;
}
HttpTunnelProducer *p = tunnel.add_producer(cache_sm.cache_read_vc, doc_size, buf_start, &HttpSM::tunnel_handler_cache_read,
HT_CACHE_READ, "cache read");
tunnel.add_consumer(ua_entry->vc, cache_sm.cache_read_vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
// if size of a cached item is not known, we'll do chunking for keep-alive HTTP/1.1 clients
// this only applies to read-while-write cases where origin server sends a dynamically generated chunked content
// w/o providing a Content-Length header
if (t_state.client_info.receive_chunked_response) {
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_CHUNK_CONTENT);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
}
ua_entry->in_tunnel = true;
cache_sm.cache_read_vc = nullptr;
return p;
}
HttpTunnelProducer *
HttpSM::setup_cache_transfer_to_transform()
{
int64_t alloc_index;
int64_t doc_size;
ink_assert(cache_sm.cache_read_vc != nullptr);
ink_assert(transform_info.vc != nullptr);
ink_assert(transform_info.entry->vc == transform_info.vc);
// grab this here
cache_response_hdr_bytes = t_state.hdr_info.cache_response.length_get();
doc_size = t_state.cache_info.object_read->object_size_get();
alloc_index = buffer_size_to_index(doc_size);
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_response_wait_for_transform_read);
HttpTunnelProducer *p = tunnel.add_producer(cache_sm.cache_read_vc, doc_size, buf_start, &HttpSM::tunnel_handler_cache_read,
HT_CACHE_READ, "cache read");
tunnel.add_consumer(transform_info.vc, cache_sm.cache_read_vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"transform write");
transform_info.entry->in_tunnel = true;
cache_sm.cache_read_vc = nullptr;
return p;
}
void
HttpSM::setup_cache_write_transfer(HttpCacheSM *c_sm, VConnection *source_vc, HTTPInfo *store_info, int64_t skip_bytes,
const char *name)
{
ink_assert(c_sm->cache_write_vc != nullptr);
ink_assert(t_state.request_sent_time > 0);
ink_assert(t_state.response_received_time > 0);
store_info->request_sent_time_set(t_state.request_sent_time);
store_info->response_received_time_set(t_state.response_received_time);
c_sm->cache_write_vc->set_http_info(store_info);
store_info->clear();
tunnel.add_consumer(c_sm->cache_write_vc, source_vc, &HttpSM::tunnel_handler_cache_write, HT_CACHE_WRITE, name, skip_bytes);
c_sm->cache_write_vc = nullptr;
}
void
HttpSM::setup_100_continue_transfer()
{
MIOBuffer *buf = new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
IOBufferReader *buf_start = buf->alloc_reader();
// First write the client response header into the buffer
ink_assert(t_state.client_info.http_version != HTTPVersion(0, 9));
client_response_hdr_bytes = write_header_into_buffer(&t_state.hdr_info.client_response, buf);
ink_assert(client_response_hdr_bytes > 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_100_continue);
// Setup the tunnel to the client
HttpTunnelProducer *p = tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, client_response_hdr_bytes, buf_start,
(HttpProducerHandler) nullptr, HT_STATIC, "internal msg - 100 continue");
tunnel.add_consumer(ua_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_100_continue_ua, HT_HTTP_CLIENT,
"user agent");
// Make sure the half_close is not set.
ua_session->set_half_close_flag(false);
ua_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::setup_error_transfer()
//
// The proxy has generated an error message which it
// is sending to the client. For some cases, however,
// such as when the proxy is transparent, returning
// a proxy-generated error message exposes the proxy,
// destroying transparency. The HttpBodyFactory code,
// therefore, does not generate an error message body
// in such cases. This function checks for the presence
// of an error body. If its not present, it closes the
// connection to the user, else it simply calls
// setup_write_proxy_internal, which is the standard
// routine for setting up proxy-generated responses.
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::setup_error_transfer()
{
if (t_state.internal_msg_buffer) {
// Since we need to send the error message, call the API
// function
ink_assert(t_state.internal_msg_buffer_size > 0);
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
} else {
DebugSM("http", "[setup_error_transfer] Now closing connection ...");
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
// ua_session = NULL;
terminate_sm = true;
t_state.source = HttpTransact::SOURCE_INTERNAL;
}
}
void
HttpSM::setup_internal_transfer(HttpSMHandler handler_arg)
{
bool is_msg_buf_present;
if (t_state.internal_msg_buffer) {
is_msg_buf_present = true;
ink_assert(t_state.internal_msg_buffer_size > 0);
// Set the content length here since a plugin
// may have changed the error body
t_state.hdr_info.client_response.set_content_length(t_state.internal_msg_buffer_size);
t_state.hdr_info.client_response.field_delete(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
// set internal_msg_buffer_type if available
if (t_state.internal_msg_buffer_type) {
int len = strlen(t_state.internal_msg_buffer_type);
if (len > 0) {
t_state.hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, t_state.internal_msg_buffer_type,
len);
}
ats_free(t_state.internal_msg_buffer_type);
t_state.internal_msg_buffer_type = nullptr;
} else {
t_state.hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/html", 9);
}
} else {
is_msg_buf_present = false;
// If we are sending a response that can have a body
// but doesn't have a body add a content-length of zero.
// Needed for keep-alive on PURGE requests
if (!is_response_body_precluded(t_state.hdr_info.client_response.status_get(), t_state.method)) {
t_state.hdr_info.client_response.set_content_length(0);
t_state.hdr_info.client_response.field_delete(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
}
}
t_state.source = HttpTransact::SOURCE_INTERNAL;
int64_t buf_size =
index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX) + (is_msg_buf_present ? t_state.internal_msg_buffer_size : 0);
MIOBuffer *buf = new_MIOBuffer(buffer_size_to_index(buf_size));
IOBufferReader *buf_start = buf->alloc_reader();
// First write the client response header into the buffer
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
int64_t nbytes = client_response_hdr_bytes;
// Next append the message onto the MIOBuffer
// From HTTP/1.1 RFC:
// "The HEAD method is identical to GET except that the server
// MUST NOT return a message-body in the response. The metainformation
// in the HTTP headers in response to a HEAD request SHOULD be
// identical to the information sent in response to a GET request."
// --> do not append the message onto the MIOBuffer and keep our pointer
// to it so that it can be freed.
if (is_msg_buf_present && t_state.method != HTTP_WKSIDX_HEAD) {
nbytes += t_state.internal_msg_buffer_size;
if (t_state.internal_msg_buffer_fast_allocator_size < 0) {
buf->append_xmalloced(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size);
} else {
buf->append_fast_allocated(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size,
t_state.internal_msg_buffer_fast_allocator_size);
}
// The IOBufferBlock will free the msg buffer when necessary so
// eliminate our pointer to it
t_state.internal_msg_buffer = nullptr;
t_state.internal_msg_buffer_size = 0;
}
HTTP_SM_SET_DEFAULT_HANDLER(handler_arg);
// Clear the decks before we setup the new producers
// As things stand, we cannot have two static producers operating at
// once
tunnel.reset();
// Setup the tunnel to the client
HttpTunnelProducer *p =
tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, nbytes, buf_start, (HttpProducerHandler) nullptr, HT_STATIC, "internal msg");
tunnel.add_consumer(ua_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
ua_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
// int HttpSM::find_http_resp_buffer_size(int cl)
//
// Returns the allocation index for the buffer for
// a response based on the content length
//
int
HttpSM::find_http_resp_buffer_size(int64_t content_length)
{
int64_t buf_size;
int64_t alloc_index;
if (content_length == HTTP_UNDEFINED_CL) {
// Try use our configured default size. Otherwise pick
// the default size
alloc_index = (int)t_state.txn_conf->default_buffer_size_index;
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > DEFAULT_MAX_BUFFER_SIZE) {
alloc_index = DEFAULT_RESPONSE_BUFFER_SIZE_INDEX;
}
} else {
#ifdef WRITE_AND_TRANSFER
buf_size = HTTP_HEADER_BUFFER_SIZE + content_length - index_to_buffer_size(HTTP_SERVER_RESP_HDR_BUFFER_INDEX);
#else
buf_size = index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX) + content_length;
#endif
alloc_index = buffer_size_to_index(buf_size);
}
return alloc_index;
}
// int HttpSM::server_transfer_init()
//
// Moves data from the header buffer into the reply buffer
// and return the number of bytes we should use for initiating the
// tunnel
//
int64_t
HttpSM::server_transfer_init(MIOBuffer *buf, int hdr_size)
{
int64_t nbytes;
int64_t to_copy = INT64_MAX;
ink_assert(t_state.current.server != nullptr); // should have been set up if we're doing a transfer.
if (server_entry->eos == true) {
// The server has shutdown on us already so the only data
// we'll get is already in the buffer
nbytes = server_buffer_reader->read_avail() + hdr_size;
} else if (t_state.hdr_info.response_content_length == HTTP_UNDEFINED_CL) {
nbytes = -1;
} else {
// Set to copy to the number of bytes we want to write as
// if the server is sending us a bogus response we have to
// truncate it as we've already decided to trust the content
// length
to_copy = t_state.hdr_info.response_content_length;
nbytes = t_state.hdr_info.response_content_length + hdr_size;
}
// Next order of business if copy the remaining data from the
// header buffer into new buffer.
int64_t server_response_pre_read_bytes =
#ifdef WRITE_AND_TRANSFER
/* relinquish the space in server_buffer and let
the tunnel use the trailing space
*/
buf->write_and_transfer_left_over_space(server_buffer_reader, to_copy);
#else
buf->write(server_buffer_reader, to_copy);
#endif
server_buffer_reader->consume(server_response_pre_read_bytes);
// If we know the length & copied the entire body
// of the document out of the header buffer make
// sure the server isn't screwing us by having sent too
// much. If it did, we want to close the server connection
if (server_response_pre_read_bytes == to_copy && server_buffer_reader->read_avail() > 0) {
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
#ifdef LAZY_BUF_ALLOC
// reset the server session buffer
server_session->reset_read_buffer();
#endif
return nbytes;
}
HttpTunnelProducer *
HttpSM::setup_server_transfer_to_transform()
{
int64_t alloc_index;
int64_t nbytes;
alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
nbytes = server_transfer_init(buf, 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_response_wait_for_transform_read);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.add_consumer(transform_info.vc, server_entry->vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"transform write");
server_entry->in_tunnel = true;
transform_info.entry->in_tunnel = true;
if (t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
client_response_hdr_bytes = 0; // fixed by YTS Team, yamsat
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_DECHUNK_CONTENT);
}
return p;
}
HttpTunnelProducer *
HttpSM::setup_transfer_from_transform()
{
int64_t alloc_index = find_server_buffer_size();
// TODO change this call to new_empty_MIOBuffer()
MIOBuffer *buf = new_MIOBuffer(alloc_index);
buf->water_mark = (int)t_state.txn_conf->default_buffer_water_mark;
IOBufferReader *buf_start = buf->alloc_reader();
HttpTunnelConsumer *c = tunnel.get_consumer(transform_info.vc);
ink_assert(c != nullptr);
ink_assert(c->vc == transform_info.vc);
ink_assert(c->vc_type == HT_TRANSFORM);
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p = tunnel.add_producer(transform_info.vc, INT64_MAX, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "transform read");
tunnel.chain(c, p);
tunnel.add_consumer(ua_entry->vc, transform_info.vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
transform_info.entry->in_tunnel = true;
ua_entry->in_tunnel = true;
this->setup_plugin_agents(p);
if (t_state.client_info.receive_chunked_response) {
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_CHUNK_CONTENT);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
}
return p;
}
HttpTunnelProducer *
HttpSM::setup_transfer_from_transform_to_cache_only()
{
int64_t alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
HttpTunnelConsumer *c = tunnel.get_consumer(transform_info.vc);
ink_assert(c != nullptr);
ink_assert(c->vc == transform_info.vc);
ink_assert(c->vc_type == HT_TRANSFORM);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p = tunnel.add_producer(transform_info.vc, INT64_MAX, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "transform read");
tunnel.chain(c, p);
transform_info.entry->in_tunnel = true;
ink_assert(t_state.cache_info.transform_action == HttpTransact::CACHE_DO_WRITE);
perform_transform_cache_write_action();
return p;
}
void
HttpSM::setup_server_transfer_to_cache_only()
{
TunnelChunkingAction_t action;
int64_t alloc_index;
int64_t nbytes;
alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
action = (t_state.current.server && t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) ?
TCA_DECHUNK_CONTENT :
TCA_PASSTHRU_DECHUNKED_CONTENT;
nbytes = server_transfer_init(buf, 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.set_producer_chunking_action(p, 0, action);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
setup_cache_write_transfer(&cache_sm, server_entry->vc, &t_state.cache_info.object_store, 0, "cache write");
server_entry->in_tunnel = true;
}
HttpTunnelProducer *
HttpSM::setup_server_transfer()
{
DebugSM("http", "Setup Server Transfer");
int64_t alloc_index, hdr_size;
int64_t nbytes;
alloc_index = find_server_buffer_size();
#ifndef USE_NEW_EMPTY_MIOBUFFER
MIOBuffer *buf = new_MIOBuffer(alloc_index);
#else
MIOBuffer *buf = new_empty_MIOBuffer(alloc_index);
buf->append_block(HTTP_HEADER_BUFFER_SIZE_INDEX);
#endif
buf->water_mark = (int)t_state.txn_conf->default_buffer_water_mark;
IOBufferReader *buf_start = buf->alloc_reader();
// we need to know if we are going to chunk the response or not
// before we write the response header into buffer
TunnelChunkingAction_t action;
if (t_state.client_info.receive_chunked_response == false) {
if (t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
action = TCA_DECHUNK_CONTENT;
} else {
action = TCA_PASSTHRU_DECHUNKED_CONTENT;
}
} else {
if (t_state.current.server->transfer_encoding != HttpTransact::CHUNKED_ENCODING) {
if (t_state.client_info.http_version == HTTPVersion(0, 9)) {
action = TCA_PASSTHRU_DECHUNKED_CONTENT; // send as-is
} else {
action = TCA_CHUNK_CONTENT;
}
} else {
action = TCA_PASSTHRU_CHUNKED_CONTENT;
}
}
if (action == TCA_CHUNK_CONTENT || action == TCA_PASSTHRU_CHUNKED_CONTENT) { // remove Content-Length
t_state.hdr_info.client_response.field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
}
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = hdr_size = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
nbytes = server_transfer_init(buf, hdr_size);
if (t_state.negative_caching && t_state.hdr_info.server_response.status_get() == HTTP_STATUS_NO_CONTENT) {
int s = sizeof("No Content") - 1;
buf->write("No Content", s);
nbytes += s;
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.add_consumer(ua_entry->vc, server_entry->vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
ua_entry->in_tunnel = true;
server_entry->in_tunnel = true;
this->setup_plugin_agents(p);
// If the incoming server response is chunked and the client does not
// expect a chunked response, then dechunk it. Otherwise, if the
// incoming response is not chunked and the client expects a chunked
// response, then chunk it.
/*
// this block is moved up so that we know if we need to remove
// Content-Length field from response header before writing the
// response header into buffer bz50730
TunnelChunkingAction_t action;
if (t_state.client_info.receive_chunked_response == false) {
if (t_state.current.server->transfer_encoding ==
HttpTransact::CHUNKED_ENCODING)
action = TCA_DECHUNK_CONTENT;
else action = TCA_PASSTHRU_DECHUNKED_CONTENT;
}
else {
if (t_state.current.server->transfer_encoding !=
HttpTransact::CHUNKED_ENCODING)
action = TCA_CHUNK_CONTENT;
else action = TCA_PASSTHRU_CHUNKED_CONTENT;
}
*/
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, action);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
return p;
}
HttpTunnelProducer *
HttpSM::setup_push_transfer_to_cache()
{
int64_t nbytes, alloc_index;
alloc_index = find_http_resp_buffer_size(t_state.hdr_info.request_content_length);
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
ink_release_assert(t_state.hdr_info.request_content_length != HTTP_UNDEFINED_CL);
nbytes = t_state.hdr_info.request_content_length - pushed_response_hdr_bytes;
ink_release_assert(nbytes >= 0);
if (ua_entry->eos == true) {
// The ua has shutdown on us already so the only data
// we'll get is already in the buffer. Make sure it
// fulfills the stated length
int64_t avail = ua_buffer_reader->read_avail();
if (avail < nbytes) {
// Client failed to send the body, it's gone. Kill the
// state machine
terminate_sm = true;
return nullptr;
}
}
// Next order of business is copy the remaining data from the
// header buffer into new buffer.
pushed_response_body_bytes = buf->write(ua_buffer_reader, nbytes);
ua_buffer_reader->consume(pushed_response_body_bytes);
client_request_body_bytes += pushed_response_body_bytes;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_push);
HttpTunnelProducer *p =
tunnel.add_producer(ua_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_ua_push, HT_HTTP_CLIENT, "user_agent");
setup_cache_write_transfer(&cache_sm, ua_entry->vc, &t_state.cache_info.object_store, 0, "cache write");
ua_entry->in_tunnel = true;
return p;
}
void
HttpSM::setup_blind_tunnel(bool send_response_hdr)
{
HttpTunnelConsumer *c_ua;
HttpTunnelConsumer *c_os;
HttpTunnelProducer *p_ua;
HttpTunnelProducer *p_os;
MIOBuffer *from_ua_buf = new_MIOBuffer(BUFFER_SIZE_INDEX_32K);
MIOBuffer *to_ua_buf = new_MIOBuffer(BUFFER_SIZE_INDEX_32K);
IOBufferReader *r_from = from_ua_buf->alloc_reader();
IOBufferReader *r_to = to_ua_buf->alloc_reader();
milestones[TS_MILESTONE_SERVER_BEGIN_WRITE] = Thread::get_hrtime();
if (send_response_hdr) {
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, to_ua_buf);
} else {
client_response_hdr_bytes = 0;
}
client_request_body_bytes = 0;
if (ua_raw_buffer_reader != nullptr) {
client_request_body_bytes += from_ua_buf->write(ua_raw_buffer_reader, client_request_hdr_bytes);
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
// Next order of business if copy the remaining data from the
// header buffer into new buffer
client_request_body_bytes += from_ua_buf->write(ua_buffer_reader);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
p_os =
tunnel.add_producer(server_entry->vc, -1, r_to, &HttpSM::tunnel_handler_ssl_producer, HT_HTTP_SERVER, "http server - tunnel");
c_ua = tunnel.add_consumer(ua_entry->vc, server_entry->vc, &HttpSM::tunnel_handler_ssl_consumer, HT_HTTP_CLIENT,
"user agent - tunnel");
p_ua = tunnel.add_producer(ua_entry->vc, -1, r_from, &HttpSM::tunnel_handler_ssl_producer, HT_HTTP_CLIENT, "user agent - tunnel");
c_os = tunnel.add_consumer(server_entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_ssl_consumer, HT_HTTP_SERVER,
"http server - tunnel");
// Make the tunnel aware that the entries are bi-directional
tunnel.chain(c_os, p_os);
tunnel.chain(c_ua, p_ua);
ua_entry->in_tunnel = true;
server_entry->in_tunnel = true;
tunnel.tunnel_run();
// If we're half closed, we got a FIN from the client. Forward it on to the origin server
// now that we have the tunnel operational.
if (ua_session->get_half_close_flag()) {
p_ua->vc->do_io_shutdown(IO_SHUTDOWN_READ);
}
}
void
HttpSM::setup_plugin_agents(HttpTunnelProducer *p)
{
APIHook *agent = txn_hook_get(TS_HTTP_RESPONSE_CLIENT_HOOK);
has_active_plugin_agents = agent != nullptr;
while (agent) {
INKVConnInternal *contp = static_cast<INKVConnInternal *>(agent->m_cont);
tunnel.add_consumer(contp, p->vc, &HttpSM::tunnel_handler_plugin_agent, HT_HTTP_CLIENT, "plugin agent");
// We don't put these in the SM VC table because the tunnel
// will clean them up in do_io_close().
agent = agent->next();
}
}
inline void
HttpSM::transform_cleanup(TSHttpHookID hook, HttpTransformInfo *info)
{
APIHook *t_hook = api_hooks.get(hook);
if (t_hook && info->vc == nullptr) {
do {
VConnection *t_vcon = t_hook->m_cont;
t_vcon->do_io_close();
t_hook = t_hook->m_link.next;
} while (t_hook != nullptr);
}
}
void
HttpSM::plugin_agents_cleanup()
{
// If this is set then all of the plugin agent VCs were put in
// the VC table and cleaned up there. This handles the case where
// something went wrong early.
if (!has_active_plugin_agents) {
APIHook *agent = txn_hook_get(TS_HTTP_RESPONSE_CLIENT_HOOK);
while (agent) {
INKVConnInternal *contp = static_cast<INKVConnInternal *>(agent->m_cont);
contp->do_io_close();
agent = agent->next();
}
}
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::kill_this()
//
// This function has two phases. One before we call the asynchronous
// clean up routines (api and list removal) and one after.
// The state about which phase we are in is kept in
// HttpSM::kill_this_async_done
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::kill_this()
{
ink_release_assert(reentrancy_count == 1);
tunnel.deallocate_redirect_postdata_buffers();
enable_redirection = false;
if (kill_this_async_done == false) {
////////////////////////////////
// cancel uncompleted actions //
////////////////////////////////
// The action should be cancelled only if
// the state machine is in HTTP_API_NO_CALLOUT
// state. This is because we are depending on the
// callout to complete for the state machine to
// get killed.
if (callout_state == HTTP_API_NO_CALLOUT && pending_action) {
pending_action->cancel();
pending_action = nullptr;
}
cache_sm.end_both();
if (second_cache_sm) {
second_cache_sm->end_both();
}
transform_cache_sm.end_both();
vc_table.cleanup_all();
// tunnel.deallocate_buffers();
// Why don't we just kill the tunnel? Might still be
// active if the state machine is going down hard,
// and we should clean it up.
tunnel.kill_tunnel();
// It possible that a plugin added transform hook
// but the hook never executed due to a client abort
// In that case, we need to manually close all the
// transforms to prevent memory leaks (INKqa06147)
if (hooks_set) {
transform_cleanup(TS_HTTP_RESPONSE_TRANSFORM_HOOK, &transform_info);
transform_cleanup(TS_HTTP_REQUEST_TRANSFORM_HOOK, &post_transform_info);
plugin_agents_cleanup();
}
// It's also possible that the plugin_tunnel vc was never
// executed due to not contacting the server
if (plugin_tunnel) {
plugin_tunnel->kill_no_connect();
plugin_tunnel = nullptr;
}
server_session = nullptr;
// So we don't try to nuke the state machine
// if the plugin receives event we must reset
// the terminate_flag
terminate_sm = false;
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_SHUTDOWN;
do_api_callout();
}
// The reentrancy_count is still valid up to this point since
// the api shutdown hook is asynchronous and double frees can
// happen if the reentrancy count is not still valid until
// after all asynch callouts have completed
//
// Once we get to this point, we could be waiting for async
// completion in which case we need to decrement the reentrancy
// count since the entry points can't do it for us since they
// don't know if the state machine has been destroyed. In the
// case we really are done with asynch callouts, decrement the
// reentrancy count since it seems tacky to destruct a state
// machine with non-zero count
reentrancy_count--;
ink_release_assert(reentrancy_count == 0);
// If the api shutdown & list removal was synchronous
// then the value of kill_this_async_done has changed so
// we must check it again
if (kill_this_async_done == true) {
if (t_state.http_config_param->enable_http_stats) {
update_stats();
}
if (ua_session) {
ua_session->transaction_done();
}
// In the async state, the plugin could have been
// called resulting in the creation of a plugin_tunnel.
// So it needs to be deleted now.
if (plugin_tunnel) {
plugin_tunnel->kill_no_connect();
plugin_tunnel = nullptr;
}
if (t_state.pCongestionEntry != nullptr) {
if (t_state.congestion_congested_or_failed != 1) {
t_state.pCongestionEntry->go_alive();
}
}
ink_assert(pending_action == nullptr);
ink_release_assert(vc_table.is_table_clear() == true);
ink_release_assert(tunnel.is_tunnel_active() == false);
HTTP_SM_SET_DEFAULT_HANDLER(nullptr);
if (!t_state.cop_test_page || t_state.http_config_param->record_cop_page) {
//////////////
// Log Data //
//////////////
DebugSM("http_seq", "[HttpSM::update_stats] Logging transaction");
if (Log::transaction_logging_enabled() && t_state.api_info.logging_enabled) {
LogAccessHttp accessor(this);
int ret = Log::access(&accessor);
if (ret & Log::FULL) {
DebugSM("http", "[update_stats] Logging system indicates FULL.");
}
if (ret & Log::FAIL) {
Log::error("failed to log transaction for at least one log object");
}
}
}
if (redirect_url != nullptr) {
ats_free((void *)redirect_url);
redirect_url = nullptr;
redirect_url_len = 0;
}
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.remove(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
DebugSM("http", "[%" PRId64 "] deallocating sm", sm_id);
// authAdapter.destroyState();
HTTP_DECREMENT_DYN_STAT(http_current_client_transactions_stat);
destroy();
}
}
void
HttpSM::update_stats()
{
milestones[TS_MILESTONE_SM_FINISH] = Thread::get_hrtime();
if (t_state.cop_test_page && !t_state.http_config_param->record_cop_page) {
DebugSM("http_seq", "Skipping cop heartbeat logging & stats due to config");
return;
}
if (is_action_tag_set("bad_length_state_dump")) {
if (t_state.hdr_info.client_response.valid() && t_state.hdr_info.client_response.status_get() == HTTP_STATUS_OK) {
int64_t p_resp_cl = t_state.hdr_info.client_response.get_content_length();
int64_t resp_size = client_response_body_bytes;
if (!((p_resp_cl == -1 || p_resp_cl == resp_size || resp_size == 0))) {
Error("[%" PRId64 "] Truncated content detected", sm_id);
dump_state_on_assert();
}
} else if (client_request_hdr_bytes == 0) {
Error("[%" PRId64 "] Zero length request header received", sm_id);
dump_state_on_assert();
}
}
if (is_action_tag_set("assert_jtest_length")) {
if (t_state.hdr_info.client_response.valid() && t_state.hdr_info.client_response.status_get() == HTTP_STATUS_OK) {
int64_t p_resp_cl = t_state.hdr_info.client_response.get_content_length();
int64_t resp_size = client_response_body_bytes;
ink_release_assert(p_resp_cl == -1 || p_resp_cl == resp_size || resp_size == 0);
}
}
ink_hrtime total_time = milestones.elapsed(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH);
// ua_close will not be assigned properly in some exceptional situation.
// TODO: Assign ua_close with suitable value when HttpTunnel terminates abnormally.
if (milestones[TS_MILESTONE_UA_CLOSE] == 0 && milestones[TS_MILESTONE_UA_READ_HEADER_DONE] > 0) {
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
}
// request_process_time = The time after the header is parsed to the completion of the transaction
ink_hrtime request_process_time = milestones[TS_MILESTONE_UA_CLOSE] - milestones[TS_MILESTONE_UA_READ_HEADER_DONE];
HttpTransact::client_result_stat(&t_state, total_time, request_process_time);
ink_hrtime ua_write_time;
if (milestones[TS_MILESTONE_UA_BEGIN_WRITE] != 0 && milestones[TS_MILESTONE_UA_CLOSE] != 0) {
ua_write_time = milestones.elapsed(TS_MILESTONE_UA_BEGIN_WRITE, TS_MILESTONE_UA_CLOSE);
} else {
ua_write_time = -1;
}
ink_hrtime os_read_time;
if (milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] != 0 && milestones[TS_MILESTONE_SERVER_CLOSE] != 0) {
os_read_time = milestones.elapsed(TS_MILESTONE_SERVER_READ_HEADER_DONE, TS_MILESTONE_SERVER_CLOSE);
} else {
os_read_time = -1;
}
HttpTransact::update_size_and_time_stats(
&t_state, total_time, ua_write_time, os_read_time, client_request_hdr_bytes, client_request_body_bytes,
client_response_hdr_bytes, client_response_body_bytes, server_request_hdr_bytes, server_request_body_bytes,
server_response_hdr_bytes, server_response_body_bytes, pushed_response_hdr_bytes, pushed_response_body_bytes, milestones);
/*
if (is_action_tag_set("http_handler_times")) {
print_all_http_handler_times();
}
*/
// print slow requests if the threshold is set (> 0) and if we are over the time threshold
if (t_state.txn_conf->slow_log_threshold != 0 && ink_hrtime_from_msec(t_state.txn_conf->slow_log_threshold) < total_time) {
URL *url = t_state.hdr_info.client_request.url_get();
char url_string[256] = "";
int offset = 0;
int skip = 0;
t_state.hdr_info.client_request.url_print(url_string, sizeof(url_string) - 1, &offset, &skip);
url_string[offset] = 0; // NULL terminate the string
// unique id
char unique_id_string[128] = "";
// [amc] why do we check the URL to get a MIME field?
if (nullptr != url && url->valid()) {
int length = 0;
const char *field = t_state.hdr_info.client_request.value_get(MIME_FIELD_X_ID, MIME_LEN_X_ID, &length);
if (field != nullptr) {
ink_strlcpy(unique_id_string, field, sizeof(unique_id_string));
}
}
// set the fd for the request
int fd = 0;
NetVConnection *vc = nullptr;
if (ua_session != nullptr) {
vc = ua_session->get_netvc();
if (vc != nullptr) {
fd = vc->get_socket();
} else {
fd = -1;
}
}
// get the status code, lame that we have to check to see if it is valid or we will assert in the method call
int status = 0;
if (t_state.hdr_info.client_response.valid()) {
status = t_state.hdr_info.client_response.status_get();
}
char client_ip[INET6_ADDRSTRLEN];
ats_ip_ntop(&t_state.client_info.src_addr, client_ip, sizeof(client_ip));
Error("[%" PRId64 "] Slow Request: "
"client_ip: %s:%u "
"protocol: %s "
"url: %s "
"status: %d "
"unique id: %s "
"redirection_tries: %d "
"bytes: %" PRId64 " "
"fd: %d "
"client state: %d "
"server state: %d "
"ua_begin: %.3f "
"ua_first_read: %.3f "
"ua_read_header_done: %.3f "
"cache_open_read_begin: %.3f "
"cache_open_read_end: %.3f "
"dns_lookup_begin: %.3f "
"dns_lookup_end: %.3f "
"server_connect: %.3f "
"server_connect_end: %.3f "
"server_first_read: %.3f "
"server_read_header_done: %.3f "
"server_close: %.3f "
"ua_write: %.3f "
"ua_close: %.3f "
"sm_finish: %.3f "
"plugin_active: %.3f "
"plugin_total: %.3f",
sm_id, client_ip, t_state.client_info.src_addr.host_order_port(), ua_session ? ua_session->get_protocol_string() : "-1",
url_string, status, unique_id_string, redirection_tries, client_response_body_bytes, fd, t_state.client_info.state,
t_state.server_info.state, milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_FIRST_READ),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_READ_HEADER_DONE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_READ),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_READ_HEADER_DONE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CLOSE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN_WRITE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_CLOSE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_PLUGIN_ACTIVE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_PLUGIN_TOTAL));
}
}
//
// void HttpSM::dump_state_on_assert
// Debugging routine to dump the state machine's history
// and other state on an assertion failure
// We use Diags::Status instead of stderr since
// Diags works both on UNIX & NT
//
void
HttpSM::dump_state_on_assert()
{
Error("[%" PRId64 "] ------- begin http state dump -------", sm_id);
int hist_size = this->history_pos;
if (this->history_pos > HISTORY_SIZE) {
hist_size = HISTORY_SIZE;
Error(" History Wrap around. history_pos: %d", this->history_pos);
}
// Loop through the history and dump it
for (int i = 0; i < hist_size; i++) {
int r = history[i].reentrancy;
int e = history[i].event;
Error("%d %d %s", e, r, history[i].fileline);
}
// Dump the via string
Error("Via String: [%s]\n", t_state.via_string);
// Dump header info
dump_state_hdr(&t_state.hdr_info.client_request, "Client Request");
dump_state_hdr(&t_state.hdr_info.server_request, "Server Request");
dump_state_hdr(&t_state.hdr_info.server_response, "Server Response");
dump_state_hdr(&t_state.hdr_info.transform_response, "Transform Response");
dump_state_hdr(&t_state.hdr_info.client_response, "Client Response");
Error("[%" PRId64 "] ------- end http state dump ---------", sm_id);
}
void
HttpSM::dump_state_hdr(HTTPHdr *h, const char *s)
{
// Dump the client request if available
if (h->valid()) {
int l = h->length_get();
char *hdr_buf = (char *)ats_malloc(l + 1);
int index = 0;
int offset = 0;
h->print(hdr_buf, l, &index, &offset);
hdr_buf[l] = '\0';
Error(" ---- %s [%" PRId64 "] ----\n%s\n", s, sm_id, hdr_buf);
ats_free(hdr_buf);
}
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact Interface ****
**** ****
*****************************************************************************
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::call_transact_and_set_next_state(f)
//
// This routine takes an HttpTransact function <f>, calls the function
// to perform some actions on the current HttpTransact::State, and
// then uses the HttpTransact return action code to set the next
// handler (state) for the state machine. HttpTransact could have
// returned the handler directly, but returns action codes in hopes of
// making a cleaner separation between the state machine and the
// HttpTransact logic.
//
//////////////////////////////////////////////////////////////////////////
// Where is the goatherd?
void
HttpSM::call_transact_and_set_next_state(TransactEntryFunc_t f)
{
last_action = t_state.next_action; // remember where we were
// The callee can either specify a method to call in to Transact,
// or call with NULL which indicates that Transact should use
// its stored entry point.
if (f == nullptr) {
ink_release_assert(t_state.transact_return_point != nullptr);
t_state.transact_return_point(&t_state);
} else {
f(&t_state);
}
DebugSM("http", "[%" PRId64 "] State Transition: %s -> %s", sm_id, HttpDebugNames::get_action_name(last_action),
HttpDebugNames::get_action_name(t_state.next_action));
set_next_state();
return;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::set_next_state()
//
// call_transact_and_set_next_state() was broken into two parts, one
// which calls the HttpTransact method and the second which sets the
// next state. In a case which set_next_state() was not completed,
// the state function calls set_next_state() to retry setting the
// state.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpSM::set_next_state()
{
///////////////////////////////////////////////////////////////////////
// Use the returned "next action" code to set the next state handler //
///////////////////////////////////////////////////////////////////////
switch (t_state.next_action) {
case HttpTransact::SM_ACTION_API_PRE_REMAP:
case HttpTransact::SM_ACTION_API_POST_REMAP:
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_OS_DNS:
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE: {
t_state.api_next_action = t_state.next_action;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_POST_REMAP_SKIP: {
call_transact_and_set_next_state(nullptr);
break;
}
case HttpTransact::SM_ACTION_REMAP_REQUEST: {
if (!remapProcessor.using_separate_thread()) {
do_remap_request(true); /* run inline */
DebugSM("url_rewrite", "completed inline remapping request for [%" PRId64 "]", sm_id);
t_state.url_remap_success = remapProcessor.finish_remap(&t_state);
call_transact_and_set_next_state(nullptr);
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_remap_request);
do_remap_request(false); /* dont run inline (iow on another thread) */
}
break;
}
case HttpTransact::SM_ACTION_DNS_LOOKUP: {
sockaddr const *addr;
if (t_state.api_server_addr_set) {
/* If the API has set the server address before the OS DNS lookup
* then we can skip the lookup
*/
ip_text_buffer ipb;
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup for API supplied target %s.",
ats_ip_ntop(&t_state.server_info.dst_addr, ipb, sizeof(ipb)));
// this seems wasteful as we will just copy it right back
ats_ip_copy(t_state.host_db_info.ip(), &t_state.server_info.dst_addr);
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
} else if (0 == ats_ip_pton(t_state.dns_info.lookup_name, t_state.host_db_info.ip()) &&
ats_is_ip_loopback(t_state.host_db_info.ip())) {
// If it's 127.0.0.1 or ::1 don't bother with hostdb
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup for %s because it's loopback",
t_state.dns_info.lookup_name);
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(NULL);
break;
} else if (url_remap_mode == HttpTransact::URL_REMAP_FOR_OS && t_state.first_dns_lookup) {
DebugSM("cdn", "Skipping DNS Lookup");
// skip the DNS lookup
t_state.first_dns_lookup = false;
call_transact_and_set_next_state(HttpTransact::HandleFiltering);
break;
} else if (t_state.http_config_param->use_client_target_addr == 2 && !t_state.url_remap_success &&
t_state.parent_result.result != PARENT_SPECIFIED && t_state.client_info.is_transparent &&
t_state.dns_info.os_addr_style == HttpTransact::DNSLookupInfo::OS_ADDR_TRY_DEFAULT &&
ats_is_ip(addr = t_state.state_machine->ua_session->get_netvc()->get_local_addr())) {
/* If the connection is client side transparent and the URL
* was not remapped/directed to parent proxy, we can use the
* client destination IP address instead of doing a DNS
* lookup. This is controlled by the 'use_client_target_addr'
* configuration parameter.
*/
if (is_debug_tag_set("dns")) {
ip_text_buffer ipb;
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup for client supplied target %s.",
ats_ip_ntop(addr, ipb, sizeof(ipb)));
}
ats_ip_copy(t_state.host_db_info.ip(), addr);
if (t_state.hdr_info.client_request.version_get() == HTTPVersion(0, 9)) {
t_state.host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_09;
} else if (t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 0)) {
t_state.host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_10;
} else {
t_state.host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_11;
}
t_state.dns_info.lookup_success = true;
// cache this result so we don't have to unreliably duplicate the
// logic later if the connect fails.
t_state.dns_info.os_addr_style = HttpTransact::DNSLookupInfo::OS_ADDR_TRY_CLIENT;
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.parent_result.result == PARENT_UNDEFINED && t_state.dns_info.lookup_success) {
// Already set, and we don't have a parent proxy to lookup
ink_assert(ats_is_ip(t_state.host_db_info.ip()));
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup, provided by plugin");
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.dns_info.looking_up == HttpTransact::ORIGIN_SERVER && t_state.http_config_param->no_dns_forward_to_parent &&
t_state.parent_result.result != PARENT_UNDEFINED) {
if (t_state.cop_test_page) {
NetVConnection *vc = t_state.state_machine->ua_session->get_netvc();
if (vc) {
ats_ip_copy(t_state.host_db_info.ip(), vc->get_local_addr());
}
}
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_hostdb_lookup);
ink_assert(t_state.dns_info.looking_up != HttpTransact::UNDEFINED_LOOKUP);
do_hostdb_lookup();
break;
}
case HttpTransact::SM_ACTION_DNS_REVERSE_LOOKUP: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_hostdb_reverse_lookup);
do_hostdb_reverse_lookup();
break;
}
case HttpTransact::SM_ACTION_CACHE_LOOKUP: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_read);
do_cache_lookup_and_read();
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN: {
if (congestionControlEnabled && (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_UNDEFINED)) {
t_state.congest_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_congestion_control_lookup);
if (!do_congestion_control_lookup()) {
break;
}
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_http_server_open);
// We need to close the previous attempt
if (server_entry) {
ink_assert(server_entry->vc_type == HTTP_SERVER_VC);
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
server_session = nullptr;
} else {
// Now that we have gotten the user agent request, we can cancel
// the inactivity timeout associated with it. Note, however, that
// we must not cancel the inactivity timeout if the message
// contains a body (as indicated by the non-zero request_content_length
// field). This indicates that a POST operation is taking place and
// that the client is still sending data to the origin server. The
// origin server cannot reply until the entire request is received. In
// light of this dependency, TS must ensure that the client finishes
// sending its request and for this reason, the inactivity timeout
// cannot be cancelled.
if (ua_session && !t_state.hdr_info.request_content_length) {
ua_session->cancel_inactivity_timeout();
} else if (!ua_session) {
terminate_sm = true;
return; // Give up if there is no session
}
}
do_http_server_open();
break;
}
case HttpTransact::SM_ACTION_SERVER_PARSE_NEXT_HDR: {
setup_server_read_response_header();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_100_RESPONSE: {
setup_100_continue_transfer();
break;
}
case HttpTransact::SM_ACTION_SERVER_READ: {
t_state.source = HttpTransact::SOURCE_HTTP_ORIGIN_SERVER;
if (transform_info.vc) {
ink_assert(t_state.hdr_info.client_response.valid() == 0);
ink_assert((t_state.hdr_info.transform_response.valid() ? true : false) == true);
HttpTunnelProducer *p = setup_server_transfer_to_transform();
perform_cache_write_action();
tunnel.tunnel_run(p);
} else {
ink_assert((t_state.hdr_info.client_response.valid() ? true : false) == true);
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
// check to see if we are going to handle the redirection from server response and if there is a plugin hook set
if (hooks_set && is_redirect_required() == false) {
do_api_callout_internal();
} else {
do_redirect();
handle_api_return();
}
}
break;
}
case HttpTransact::SM_ACTION_SERVE_FROM_CACHE: {
ink_assert(t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE ||
t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE_AND_DELETE ||
t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE_AND_UPDATE);
release_server_session(true);
t_state.source = HttpTransact::SOURCE_CACHE;
if (transform_info.vc) {
ink_assert(t_state.hdr_info.client_response.valid() == 0);
ink_assert((t_state.hdr_info.transform_response.valid() ? true : false) == true);
t_state.hdr_info.cache_response.create(HTTP_TYPE_RESPONSE);
t_state.hdr_info.cache_response.copy(&t_state.hdr_info.transform_response);
HttpTunnelProducer *p = setup_cache_transfer_to_transform();
perform_cache_write_action();
tunnel.tunnel_run(p);
} else {
ink_assert((t_state.hdr_info.client_response.valid() ? true : false) == true);
t_state.hdr_info.cache_response.create(HTTP_TYPE_RESPONSE);
t_state.hdr_info.cache_response.copy(&t_state.hdr_info.client_response);
perform_cache_write_action();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
// check to see if we are going to handle the redirection from server response and if there is a plugin hook set
if (hooks_set && is_redirect_required() == false) {
do_api_callout_internal();
} else {
do_redirect();
handle_api_return();
}
}
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE: {
ink_assert((cache_sm.cache_write_vc == nullptr) || t_state.redirect_info.redirect_in_process);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
do_cache_prepare_write();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_WRITE: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_NOOP: {
if (server_entry != nullptr && server_entry->in_tunnel == false) {
release_server_session();
}
// If we're in state SEND_API_RESPONSE_HDR, it means functions
// registered to hook SEND_RESPONSE_HDR have already been called. So we do not
// need to call do_api_callout. Otherwise TS loops infinitely in this state !
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR) {
handle_api_return();
} else {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
}
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE: {
// Nuke all the alternates since this is mostly likely
// the result of a delete method
cache_sm.end_both();
do_cache_delete_all_alts(nullptr);
release_server_session();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS: {
issue_cache_update();
cache_sm.close_read();
release_server_session();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP: {
setup_error_transfer();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_REQUEST: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_handle_stat_page);
Action *action_handle = statPagesManager.handle_http(this, &t_state.hdr_info.client_request);
if (action_handle != ACTION_RESULT_DONE) {
pending_action = action_handle;
}
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_RR_MARK_DOWN: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_mark_os_down);
ink_assert(t_state.dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
// TODO: This might not be optimal (or perhaps even correct), but it will
// effectively mark the host as down. What's odd is that state_mark_os_down
// above isn't triggering.
HttpSM::do_hostdb_update_if_necessary();
do_hostdb_lookup();
break;
}
case HttpTransact::SM_ACTION_SSL_TUNNEL: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN: {
if (congestionControlEnabled && (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_UNDEFINED)) {
t_state.congest_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_congestion_control_lookup);
if (!do_congestion_control_lookup()) {
break;
}
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_raw_http_server_open);
ink_assert(server_entry == nullptr);
do_http_server_open(true);
break;
}
case HttpTransact::SM_ACTION_ICP_QUERY: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_icp_lookup);
do_icp_lookup();
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM: {
ink_assert(t_state.cache_info.transform_action == HttpTransact::CACHE_PREPARE_TO_WRITE);
if (transform_cache_sm.cache_write_vc) {
// We've already got the write_vc that
// didn't use for the untransformed copy
ink_assert(cache_sm.cache_write_vc == nullptr);
ink_assert(t_state.api_info.cache_untransformed == false);
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_SUCCESS;
call_transact_and_set_next_state(nullptr);
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
do_cache_prepare_write_transform();
}
break;
}
case HttpTransact::SM_ACTION_TRANSFORM_READ: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_READ_PUSH_HDR: {
setup_push_read_response_header();
break;
}
case HttpTransact::SM_ACTION_STORE_PUSH_BODY: {
// This can return NULL - do we really want to run the tunnel in that case?
// But that's how it was before this change.
HttpTunnelProducer *p = setup_push_transfer_to_cache();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_CACHE_PREPARE_UPDATE: {
ink_assert(t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE);
do_cache_prepare_update();
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_UPDATE: {
if (t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_ERROR) {
t_state.cache_info.object_read = nullptr;
cache_sm.close_read();
}
issue_cache_update();
call_transact_and_set_next_state(nullptr);
break;
}
#ifdef PROXY_DRAIN
case HttpTransact::SM_ACTION_DRAIN_REQUEST_BODY: {
do_drain_request_body();
break;
}
#endif /* PROXY_DRAIN */
case HttpTransact::SM_ACTION_CONTINUE: {
ink_release_assert(!"Not implemented");
}
default: {
ink_release_assert("!Unknown next action");
}
}
}
void
clear_http_handler_times()
{
}
bool
HttpSM::do_congestion_control_lookup()
{
ink_assert(pending_action == nullptr);
Action *congestion_control_action_handle = get_congest_entry(this, &t_state.request_data, &t_state.pCongestionEntry);
if (congestion_control_action_handle != ACTION_RESULT_DONE) {
pending_action = congestion_control_action_handle;
return false;
}
return true;
}
int
HttpSM::state_congestion_control_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_congestion_control_lookup, event);
if (event == CONGESTION_EVENT_CONTROL_LOOKUP_DONE) {
pending_action = nullptr;
t_state.next_action = t_state.congest_saved_next_action;
t_state.transact_return_point = nullptr;
set_next_state();
} else {
if (pending_action != nullptr) {
pending_action->cancel();
pending_action = nullptr;
}
if (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN) {
return state_http_server_open(event, data);
} else if (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
return state_raw_http_server_open(event, data);
}
}
return 0;
}
// YTS Team, yamsat Plugin
void
HttpSM::do_redirect()
{
DebugSM("http_redirect", "[HttpSM::do_redirect]");
if (!enable_redirection || redirection_tries >= t_state.txn_conf->number_of_redirections) {
tunnel.deallocate_redirect_postdata_buffers();
return;
}
// if redirect_url is set by an user's plugin, yts will redirect to this url anyway.
if (is_redirect_required()) {
if (redirect_url != nullptr || t_state.hdr_info.client_response.field_find(MIME_FIELD_LOCATION, MIME_LEN_LOCATION)) {
if (Log::transaction_logging_enabled() && t_state.api_info.logging_enabled) {
LogAccessHttp accessor(this);
if (redirect_url == nullptr) {
if (t_state.squid_codes.log_code == SQUID_LOG_TCP_HIT) {
t_state.squid_codes.log_code = SQUID_LOG_TCP_HIT_REDIRECT;
} else {
t_state.squid_codes.log_code = SQUID_LOG_TCP_MISS_REDIRECT;
}
} else {
if (t_state.squid_codes.log_code == SQUID_LOG_TCP_HIT) {
t_state.squid_codes.log_code = SQUID_LOG_TCP_HIT_X_REDIRECT;
} else {
t_state.squid_codes.log_code = SQUID_LOG_TCP_MISS_X_REDIRECT;
}
}
int ret = Log::access(&accessor);
if (ret & Log::FULL) {
DebugSM("http", "[update_stats] Logging system indicates FULL.");
}
if (ret & Log::FAIL) {
Log::error("failed to log transaction for at least one log object");
}
}
if (redirect_url != nullptr) {
redirect_request(redirect_url, redirect_url_len);
ats_free((void *)redirect_url);
redirect_url = nullptr;
redirect_url_len = 0;
HTTP_INCREMENT_DYN_STAT(http_total_x_redirect_stat);
} else {
// get the location header and setup the redirect
int redir_len;
char *redir_url = (char *)t_state.hdr_info.client_response.value_get(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, &redir_len);
redirect_request(redir_url, redir_len);
}
} else {
enable_redirection = false;
}
} else {
enable_redirection = false;
}
}
void
HttpSM::redirect_request(const char *redirect_url, const int redirect_len)
{
DebugSM("http_redirect", "[HttpSM::redirect_request]");
// get a reference to the client request header and client url and check to see if the url is valid
HTTPHdr &clientRequestHeader = t_state.hdr_info.client_request;
URL &clientUrl = *clientRequestHeader.url_get();
if (!clientUrl.valid()) {
return;
}
bool valid_origHost = true;
int origHost_len, origMethod_len;
char origHost[MAXDNAME];
char origMethod[255];
int origPort = 80;
if (t_state.hdr_info.server_request.valid()) {
char *tmpOrigHost;
origPort = t_state.hdr_info.server_request.port_get();
tmpOrigHost = (char *)t_state.hdr_info.server_request.value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &origHost_len);
if (tmpOrigHost) {
memcpy(origHost, tmpOrigHost, origHost_len);
origHost[origHost_len] = '\0';
} else {
valid_origHost = false;
}
char *tmpOrigMethod = (char *)t_state.hdr_info.server_request.method_get(&origMethod_len);
if (tmpOrigMethod) {
memcpy(origMethod, tmpOrigMethod, origMethod_len);
} else {
valid_origHost = false;
}
} else {
DebugSM("http_redir_error", "t_state.hdr_info.server_request not valid");
valid_origHost = false;
}
t_state.redirect_info.redirect_in_process = true;
// set the passed in location url and parse it
URL &redirectUrl = t_state.redirect_info.redirect_url;
if (!redirectUrl.valid()) {
redirectUrl.create(nullptr);
}
// reset the path from previous redirects (if any)
t_state.redirect_info.redirect_url.path_set(nullptr, 0);
// redirectUrl.user_set(redirect_url, redirect_len);
redirectUrl.parse(redirect_url, redirect_len);
// copy the client url to the original url
URL &origUrl = t_state.redirect_info.original_url;
if (!origUrl.valid()) {
origUrl.create(nullptr);
origUrl.copy(&clientUrl);
}
// copy the redirect url to the client url
clientUrl.copy(&redirectUrl);
//(bug 2540703) Clear the previous response if we will attempt the redirect
if (t_state.hdr_info.client_response.valid()) {
// XXX - doing a destroy() for now, we can do a fileds_clear() if we have performance issue
t_state.hdr_info.client_response.destroy();
}
int scheme = t_state.next_hop_scheme;
int scheme_len = hdrtoken_index_to_length(scheme);
const char *next_hop_scheme = hdrtoken_index_to_wks(scheme);
char scheme_str[scheme_len + 1];
if (next_hop_scheme) {
memcpy(scheme_str, next_hop_scheme, scheme_len);
} else {
valid_origHost = false;
}
t_state.hdr_info.server_request.destroy();
// we want to close the server session
// will do that in handle_api_return under the
// HttpTransact::SM_ACTION_REDIRECT_READ state
t_state.parent_result.reset();
t_state.request_sent_time = 0;
t_state.response_received_time = 0;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_INIT;
t_state.next_action = HttpTransact::SM_ACTION_REDIRECT_READ;
// we have a new OS and need to have DNS lookup the new OS
t_state.dns_info.lookup_success = false;
t_state.force_dns = false;
if (t_state.txn_conf->cache_http) {
t_state.cache_info.object_read = nullptr;
}
bool noPortInHost = HttpConfig::m_master.redirection_host_no_port;
// check to see if the client request passed a host header, if so copy the host and port from the redirect url and
// make a new host header
if (t_state.hdr_info.client_request.presence(MIME_PRESENCE_HOST)) {
int host_len;
const char *host = clientUrl.host_get(&host_len);
if (host != nullptr) {
int port = clientUrl.port_get();
int redirectSchemeLen;
const char *redirectScheme = clientUrl.scheme_get(&redirectSchemeLen);
if (redirectScheme == nullptr) {
clientUrl.scheme_set(scheme_str, scheme_len);
DebugSM("http_redirect", "[HttpSM::redirect_request] URL without scheme %.*s", redirectSchemeLen, redirectScheme);
}
if (noPortInHost) {
int redirectSchemeIdx = clientUrl.scheme_get_wksidx();
bool defaultPort =
(((redirectSchemeIdx == URL_WKSIDX_HTTP) && (port == 80)) || ((redirectSchemeIdx == URL_WKSIDX_HTTPS) && (port == 443)));
if (!defaultPort) {
noPortInHost = false;
}
}
if (!noPortInHost) {
char buf[host_len + 7]; // 5 + 1 + 1 ("12345" + ':' + '\0')
host_len = snprintf(buf, host_len + 7, "%.*s:%d", host_len, host, port);
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
t_state.hdr_info.client_request.m_target_cached = false;
t_state.hdr_info.server_request.m_target_cached = false;
} else {
// the client request didn't have a host, so use the current origin host
if (valid_origHost) {
char *saveptr = nullptr;
// the client request didn't have a host, so use the current origin host
DebugSM("http_redirect", "[HttpSM::redirect_request] keeping client request host %s://%s", next_hop_scheme, origHost);
char *origHostNoPort = strtok_r(origHost, ":", &saveptr);
if (origHostNoPort == nullptr) {
goto LhostError;
}
host_len = strlen(origHostNoPort);
if (noPortInHost) {
int redirectSchemeIdx = t_state.next_hop_scheme;
bool defaultPort = (((redirectSchemeIdx == URL_WKSIDX_HTTP) && (origPort == 80)) ||
((redirectSchemeIdx == URL_WKSIDX_HTTPS) && (origPort == 443)));
if (!defaultPort) {
noPortInHost = false;
}
}
if (!noPortInHost) {
char buf[host_len + 7]; // 5 + 1 + 1 ("12345" + ':' + '\0')
host_len = snprintf(buf, host_len + 7, "%s:%d", origHostNoPort, origPort);
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, origHostNoPort, host_len);
}
// Cleanup of state etc.
url_nuke_proxy_stuff(clientUrl.m_url_impl);
url_nuke_proxy_stuff(t_state.hdr_info.client_request.m_url_cached.m_url_impl);
t_state.hdr_info.client_request.method_set(origMethod, origMethod_len);
t_state.hdr_info.client_request.m_target_cached = false;
t_state.hdr_info.server_request.m_target_cached = false;
clientUrl.scheme_set(scheme_str, scheme_len);
} else {
LhostError:
// the server request didn't have a host, so remove it from the headers
t_state.hdr_info.client_request.field_delete(MIME_FIELD_HOST, MIME_LEN_HOST);
}
}
}
if (!t_state.cop_test_page) {
DUMP_HEADER("http_hdrs", &t_state.hdr_info.client_request, sm_id, "Framed Client Request..checking");
}
}
void
HttpSM::set_http_schedule(Continuation *contp)
{
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::get_http_schedule);
schedule_cont = contp;
}
int
HttpSM::get_http_schedule(int event, void * /* data ATS_UNUSED */)
{
bool plugin_lock;
Ptr<ProxyMutex> plugin_mutex;
if (schedule_cont->mutex) {
plugin_mutex = schedule_cont->mutex;
plugin_lock = MUTEX_TAKE_TRY_LOCK(schedule_cont->mutex, mutex->thread_holding);
if (!plugin_lock) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::get_http_schedule);
ink_assert(pending_action == nullptr);
pending_action = mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
return 0;
} else {
pending_action = nullptr; // if there was a pending action, it'll get freed after this returns so clear it.
}
} else {
plugin_lock = false;
}
// handle Mutex;
schedule_cont->handleEvent(event, this);
if (plugin_lock) {
Mutex_unlock(plugin_mutex, mutex->thread_holding);
}
return 0;
}
bool
HttpSM::set_server_session_private(bool private_session)
{
if (server_session != nullptr) {
server_session->private_session = private_session;
return true;
}
return false;
}
inline bool
HttpSM::is_private()
{
bool res = false;
if (server_session) {
res = server_session->private_session;
} else if (ua_session) {
HttpServerSession *ss = ua_session->get_server_session();
if (ss) {
res = ss->private_session;
} else if (will_be_private_ss) {
res = will_be_private_ss;
}
}
return res;
}
// check to see if redirection is enabled and less than max redirections tries or if a plugin enabled redirection
inline bool
HttpSM::is_redirect_required()
{
bool redirect_required = (enable_redirection && (redirection_tries <= t_state.txn_conf->number_of_redirections));
DebugSM("http_redirect", "is_redirect_required %u", redirect_required);
if (redirect_required == true) {
HTTPStatus status = t_state.hdr_info.client_response.status_get();
// check to see if the response from the orgin was a 301, 302, or 303
switch (status) {
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
case HTTP_STATUS_MOVED_TEMPORARILY: // 302
case HTTP_STATUS_SEE_OTHER: // 303
case HTTP_STATUS_USE_PROXY: // 305
case HTTP_STATUS_TEMPORARY_REDIRECT: // 307
redirect_required = true;
break;
default:
redirect_required = false;
break;
}
// if redirect_url is set by an user's plugin, ats will redirect to this url anyway.
if (redirect_url != nullptr) {
redirect_required = true;
}
}
return redirect_required;
}
// Fill in the client protocols used. Return the number of entries returned
int
HttpSM::populate_client_protocol(const char **result, int n) const
{
int retval = 0;
if (n > 0) {
const char *proto = HttpSM::find_proto_string(t_state.hdr_info.client_request.version_get());
if (proto) {
result[0] = proto;
retval = 1;
if (n > retval && ua_session) {
retval += ua_session->populate_protocol(result + retval, n - retval);
}
}
}
return retval;
}
// Look for a specific protocol
const char *
HttpSM::client_protocol_contains(const char *tag_prefix) const
{
const char *retval = nullptr;
const char *proto = HttpSM::find_proto_string(t_state.hdr_info.client_request.version_get());
if (proto) {
unsigned int tag_prefix_len = strlen(tag_prefix);
if (tag_prefix_len <= strlen(proto) && strncmp(tag_prefix, proto, tag_prefix_len) == 0) {
retval = proto;
} else if (ua_session) {
retval = ua_session->protocol_contains(tag_prefix);
}
}
return retval;
}
const char *
HttpSM::find_proto_string(HTTPVersion version) const
{
if (version == HTTPVersion(1, 1)) {
return TS_PROTO_TAG_HTTP_1_1;
} else if (version == HTTPVersion(1, 0)) {
return TS_PROTO_TAG_HTTP_1_0;
} else {
return nullptr;
}
}
Issue #1443 - Fix early or duplicate 404 error handling
/** @file
HTTP state machine
@section license License
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
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 "../ProxyClientTransaction.h"
#include "HttpSM.h"
#include "HttpTransactHeaders.h"
#include "ProxyConfig.h"
#include "HttpServerSession.h"
#include "HttpDebugNames.h"
#include "HttpSessionManager.h"
#include "P_Cache.h"
#include "P_Net.h"
#include "StatPages.h"
#include "Log.h"
#include "LogAccessHttp.h"
#include "ICP.h"
#include "PluginVC.h"
#include "ReverseProxy.h"
#include "RemapProcessor.h"
#include "Transform.h"
#include "P_SSLConfig.h"
#include <openssl/ossl_typ.h>
#include <openssl/ssl.h>
#include "HttpPages.h"
#include "IPAllow.h"
//#include "I_Auth.h"
//#include "HttpAuthParams.h"
#include "congest/Congestion.h"
#include "ts/I_Layout.h"
#define DEFAULT_RESPONSE_BUFFER_SIZE_INDEX 6 // 8K
#define DEFAULT_REQUEST_BUFFER_SIZE_INDEX 6 // 8K
#define MIN_CONFIG_BUFFER_SIZE_INDEX 5 // 4K
#define hsm_release_assert(EX) \
{ \
if (!(EX)) { \
this->dump_state_on_assert(); \
_ink_assert(#EX, __FILE__, __LINE__); \
} \
}
/*
* Comment this off if you don't
* want httpSM to use new_empty_MIOBuffer(..) call
*/
#define USE_NEW_EMPTY_MIOBUFFER
extern int cache_config_read_while_writer;
// We have a debugging list that can use to find stuck
// state machines
DList(HttpSM, debug_link) debug_sm_list;
ink_mutex debug_sm_list_mutex;
static const int sub_header_size = sizeof("Content-type: ") - 1 + 2 + sizeof("Content-range: bytes ") - 1 + 4;
static const int boundary_size = 2 + sizeof("RANGE_SEPARATOR") - 1 + 2;
static const char *str_100_continue_response = "HTTP/1.1 100 Continue\r\n\r\n";
static const int len_100_continue_response = strlen(str_100_continue_response);
static const char *str_408_request_timeout_response = "HTTP/1.1 408 Request Timeout\r\nConnection: close\r\n\r\n";
static const int len_408_request_timeout_response = strlen(str_408_request_timeout_response);
namespace
{
/// Update the milestone state given the milestones and timer.
inline void
milestone_update_api_time(TransactionMilestones &milestones, ink_hrtime &api_timer)
{
// Bit of funkiness - we set @a api_timer to be the negative value when we're tracking
// non-active API time. In that case we need to make a note of it and flip the value back
// to positive.
if (api_timer) {
ink_hrtime delta;
bool active = api_timer >= 0;
if (!active) {
api_timer = -api_timer;
}
delta = Thread::get_hrtime_updated() - api_timer;
api_timer = 0;
// Zero or negative time is a problem because we want to signal *something* happened
// vs. no API activity at all. This can happen due to graininess or real time
// clock adjustment.
if (delta <= 0) {
delta = 1;
}
if (0 == milestones[TS_MILESTONE_PLUGIN_TOTAL]) {
milestones[TS_MILESTONE_PLUGIN_TOTAL] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_TOTAL] += delta;
if (active) {
if (0 == milestones[TS_MILESTONE_PLUGIN_ACTIVE]) {
milestones[TS_MILESTONE_PLUGIN_ACTIVE] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_ACTIVE] += delta;
}
}
}
}
ClassAllocator<HttpSM> httpSMAllocator("httpSMAllocator");
HttpVCTable::HttpVCTable()
{
memset(&vc_table, 0, sizeof(vc_table));
}
HttpVCTableEntry *
HttpVCTable::new_entry()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == nullptr) {
return vc_table + i;
}
}
ink_release_assert(0);
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VConnection *vc)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == vc) {
return vc_table + i;
}
}
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VIO *vio)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].read_vio == vio || vc_table[i].write_vio == vio) {
ink_assert(vc_table[i].vc != nullptr);
return vc_table + i;
}
}
return nullptr;
}
// bool HttpVCTable::remove_entry(HttpVCEntry* e)
//
// Deallocates all buffers from the associated
// entry and re-initializes it's other fields
// for reuse
//
void
HttpVCTable::remove_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc == nullptr || e->in_tunnel);
e->vc = nullptr;
e->eos = false;
if (e->read_buffer) {
free_MIOBuffer(e->read_buffer);
e->read_buffer = nullptr;
}
if (e->write_buffer) {
free_MIOBuffer(e->write_buffer);
e->write_buffer = nullptr;
}
e->read_vio = nullptr;
e->write_vio = nullptr;
e->vc_handler = nullptr;
e->vc_type = HTTP_UNKNOWN;
e->in_tunnel = false;
}
// bool HttpVCTable::cleanup_entry(HttpVCEntry* e)
//
// Closes the associate vc for the entry,
// and the call remove_entry
//
void
HttpVCTable::cleanup_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc);
if (e->in_tunnel == false) {
// Update stats
switch (e->vc_type) {
case HTTP_UA_VC:
// proxy.process.http.current_client_transactions is decremented in HttpSM::destroy
break;
default:
// This covers:
// HTTP_UNKNOWN, HTTP_SERVER_VC, HTTP_TRANSFORM_VC, HTTP_CACHE_READ_VC,
// HTTP_CACHE_WRITE_VC, HTTP_RAW_SERVER_VC
break;
}
e->vc->do_io_close();
e->vc = nullptr;
}
remove_entry(e);
}
void
HttpVCTable::cleanup_all()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc != nullptr) {
cleanup_entry(vc_table + i);
}
}
}
#define REMEMBER_EVENT_FILTER(e) 1
#define __REMEMBER(x) #x
#define _REMEMBER(x) __REMEMBER(x)
#define RECORD_FILE_LINE() history[pos].fileline = __FILE__ ":" _REMEMBER(__LINE__);
#define REMEMBER(e, r) \
{ \
if (REMEMBER_EVENT_FILTER(e)) { \
add_history_entry(__FILE__ ":" _REMEMBER(__LINE__), e, r); \
} \
}
#define DebugSM(tag, ...) DebugSpecific(debug_on, tag, __VA_ARGS__)
#ifdef STATE_ENTER
#undef STATE_ENTER
#endif
#define STATE_ENTER(state_name, event) \
{ \
/*ink_assert (magic == HTTP_SM_MAGIC_ALIVE); */ REMEMBER(event, reentrancy_count); \
DebugSM("http", "[%" PRId64 "] [%s, %s]", sm_id, #state_name, HttpDebugNames::get_event_name(event)); \
}
#define HTTP_SM_SET_DEFAULT_HANDLER(_h) \
{ \
REMEMBER(-1, reentrancy_count); \
default_handler = _h; \
}
static int next_sm_id = 0;
HttpSM::HttpSM()
: Continuation(nullptr),
sm_id(-1),
magic(HTTP_SM_MAGIC_DEAD),
// YTS Team, yamsat Plugin
enable_redirection(false),
redirect_url(nullptr),
redirect_url_len(0),
redirection_tries(0),
transfered_bytes(0),
post_failed(false),
debug_on(false),
plugin_tunnel_type(HTTP_NO_PLUGIN_TUNNEL),
plugin_tunnel(nullptr),
reentrancy_count(0),
history_pos(0),
tunnel(),
ua_entry(nullptr),
ua_session(nullptr),
background_fill(BACKGROUND_FILL_NONE),
ua_raw_buffer_reader(nullptr),
server_entry(nullptr),
server_session(nullptr),
will_be_private_ss(false),
shared_session_retries(0),
server_buffer_reader(nullptr),
transform_info(),
post_transform_info(),
has_active_plugin_agents(false),
second_cache_sm(nullptr),
default_handler(nullptr),
pending_action(nullptr),
last_action(HttpTransact::SM_ACTION_UNDEFINED),
// TODO: Now that bodies can be empty, should the body counters be set to -1 ? TS-2213
client_request_hdr_bytes(0),
client_request_body_bytes(0),
server_request_hdr_bytes(0),
server_request_body_bytes(0),
server_response_hdr_bytes(0),
server_response_body_bytes(0),
client_response_hdr_bytes(0),
client_response_body_bytes(0),
cache_response_hdr_bytes(0),
cache_response_body_bytes(0),
pushed_response_hdr_bytes(0),
pushed_response_body_bytes(0),
client_tcp_reused(false),
client_ssl_reused(false),
client_connection_is_ssl(false),
client_protocol("-"),
client_sec_protocol("-"),
client_cipher_suite("-"),
server_transact_count(0),
server_connection_is_ssl(false),
plugin_tag(nullptr),
plugin_id(0),
hooks_set(false),
cur_hook_id(TS_HTTP_LAST_HOOK),
cur_hook(nullptr),
cur_hooks(0),
callout_state(HTTP_API_NO_CALLOUT),
terminate_sm(false),
kill_this_async_done(false),
parse_range_done(false)
{
memset(&history, 0, sizeof(history));
memset(&vc_table, 0, sizeof(vc_table));
memset(&http_parser, 0, sizeof(http_parser));
}
void
HttpSM::cleanup()
{
t_state.destroy();
api_hooks.clear();
http_parser_clear(&http_parser);
// t_state.content_control.cleanup();
HttpConfig::release(t_state.http_config_param);
mutex.clear();
tunnel.mutex.clear();
cache_sm.mutex.clear();
transform_cache_sm.mutex.clear();
if (second_cache_sm) {
second_cache_sm->mutex.clear();
delete second_cache_sm;
}
magic = HTTP_SM_MAGIC_DEAD;
debug_on = false;
}
void
HttpSM::destroy()
{
cleanup();
httpSMAllocator.free(this);
}
void
HttpSM::init()
{
milestones[TS_MILESTONE_SM_START] = Thread::get_hrtime();
magic = HTTP_SM_MAGIC_ALIVE;
sm_id = 0;
// Unique state machine identifier.
// changed next_sm_id from int64_t to int because
// atomic(32) is faster than atomic64. The id is just
// for debugging, so it's OK if it wraps every few days,
// as long as the http_info bucket hash still works.
// (To test this, initialize next_sm_id to 0x7ffffff0)
// Leaving sm_id as int64_t to minimize code changes.
sm_id = (int64_t)ink_atomic_increment((&next_sm_id), 1);
t_state.state_machine_id = sm_id;
t_state.state_machine = this;
t_state.http_config_param = HttpConfig::acquire();
// Simply point to the global config for the time being, no need to copy this
// entire struct if nothing is going to change it.
t_state.txn_conf = &t_state.http_config_param->oride;
// update the cache info config structure so that
// selection from alternates happens correctly.
t_state.cache_info.config.cache_global_user_agent_header = t_state.txn_conf->global_user_agent_header ? true : false;
t_state.cache_info.config.ignore_accept_mismatch = t_state.http_config_param->ignore_accept_mismatch;
t_state.cache_info.config.ignore_accept_language_mismatch = t_state.http_config_param->ignore_accept_language_mismatch;
t_state.cache_info.config.ignore_accept_encoding_mismatch = t_state.http_config_param->ignore_accept_encoding_mismatch;
t_state.cache_info.config.ignore_accept_charset_mismatch = t_state.http_config_param->ignore_accept_charset_mismatch;
t_state.cache_info.config.cache_enable_default_vary_headers =
t_state.http_config_param->cache_enable_default_vary_headers ? true : false;
t_state.cache_info.config.cache_vary_default_text = t_state.http_config_param->cache_vary_default_text;
t_state.cache_info.config.cache_vary_default_images = t_state.http_config_param->cache_vary_default_images;
t_state.cache_info.config.cache_vary_default_other = t_state.http_config_param->cache_vary_default_other;
t_state.init();
// Added to skip dns if the document is in cache. DNS will be forced if there is a ip based ACL in
// cache control or parent.config or if the doc_in_cache_skip_dns is disabled or if http caching is disabled
// TODO: This probably doesn't honor this as a per-transaction overridable config.
t_state.force_dns = (ip_rule_in_CacheControlTable() || t_state.parent_params->parent_table->ipMatch ||
!(t_state.txn_conf->doc_in_cache_skip_dns) || !(t_state.txn_conf->cache_http));
http_parser.m_allow_non_http = t_state.http_config_param->parser_allow_non_http;
http_parser_init(&http_parser);
SET_HANDLER(&HttpSM::main_handler);
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.push(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
}
void
HttpSM::set_ua_half_close_flag()
{
ua_session->set_half_close_flag(true);
}
inline void
HttpSM::do_api_callout()
{
if (hooks_set) {
do_api_callout_internal();
} else {
handle_api_return();
}
}
int
HttpSM::state_add_to_list(int event, void * /* data ATS_UNUSED */)
{
// The list if for stat pages and general debugging
// The config variable exists mostly to allow us to
// measure an performance drop during benchmark runs
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_add_to_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = ((unsigned int)sm_id % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
// the client_vc`s timeout events can be triggered, so we should not
// reschedule the http_sm when the lock is not acquired.
// FIXME: the sm_list may miss some http_sms when the lock contention
if (lock.is_locked()) {
HttpSMList[bucket].sm_list.push(this);
}
}
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_START;
do_api_callout();
return EVENT_DONE;
}
int
HttpSM::state_remove_from_list(int event, void * /* data ATS_UNUSED */)
{
// The config parameters are guaranteed not change
// across the life of a transaction so it safe to
// check the config here and use it determine
// whether we need to strip ourselves off of the
// state page list
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_remove_from_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = ((unsigned int)sm_id % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
if (!lock.is_locked()) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_remove_from_list);
mutex->thread_holding->schedule_in(this, HTTP_LIST_RETRY);
return EVENT_DONE;
}
HttpSMList[bucket].sm_list.remove(this);
}
return this->kill_this_async_hook(EVENT_NONE, nullptr);
}
int
HttpSM::kill_this_async_hook(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */)
{
// In the base HttpSM, we don't have anything to
// do here. subclasses can override this function
// to do their own asynchronous cleanup
// So We're now ready to finish off the state machine
terminate_sm = true;
kill_this_async_done = true;
return EVENT_DONE;
}
void
HttpSM::start_sub_sm()
{
tunnel.init(this, mutex);
cache_sm.init(this, mutex);
transform_cache_sm.init(this, mutex);
}
void
HttpSM::attach_client_session(ProxyClientTransaction *client_vc, IOBufferReader *buffer_reader)
{
milestones[TS_MILESTONE_UA_BEGIN] = Thread::get_hrtime();
ink_assert(client_vc != nullptr);
NetVConnection *netvc = client_vc->get_netvc();
if (!netvc) {
return;
}
ua_session = client_vc;
// Collect log & stats information
client_tcp_reused = !(ua_session->is_first_transaction());
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc);
if (ssl_vc != nullptr) {
client_connection_is_ssl = true;
client_ssl_reused = ssl_vc->getSSLSessionCacheHit();
const char *protocol = ssl_vc->getSSLProtocol();
client_sec_protocol = protocol ? protocol : "-";
const char *cipher = ssl_vc->getSSLCipherSuite();
client_cipher_suite = cipher ? cipher : "-";
}
const char *protocol_str = client_vc->get_protocol_string();
client_protocol = protocol_str ? protocol_str : "-";
ink_release_assert(ua_session->get_half_close_flag() == false);
mutex = client_vc->mutex;
HTTP_INCREMENT_DYN_STAT(http_current_client_transactions_stat);
if (ua_session->debug()) {
debug_on = true;
}
start_sub_sm();
// Allocate a user agent entry in the state machine's
// vc table
ua_entry = vc_table.new_entry();
ua_entry->vc = client_vc;
ua_entry->vc_type = HTTP_UA_VC;
ats_ip_copy(&t_state.client_info.src_addr, netvc->get_remote_addr());
ats_ip_copy(&t_state.client_info.dst_addr, netvc->get_local_addr());
t_state.client_info.dst_addr.port() = netvc->get_local_port();
t_state.client_info.is_transparent = netvc->get_is_transparent();
t_state.backdoor_request = !client_vc->hooks_enabled();
t_state.client_info.port_attribute = static_cast<HttpProxyPort::TransportType>(netvc->attributes);
// Record api hook set state
hooks_set = client_vc->has_hooks();
// Setup for parsing the header
ua_buffer_reader = buffer_reader;
ua_entry->vc_handler = &HttpSM::state_read_client_request_header;
t_state.hdr_info.client_request.destroy();
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
http_parser_init(&http_parser);
// Prepare raw reader which will live until we are sure this is HTTP indeed
if (is_transparent_passthrough_allowed()) {
ua_raw_buffer_reader = buffer_reader->clone();
}
// We first need to run the transaction start hook. Since
// this hook maybe asynchronous, we need to disable IO on
// client but set the continuation to be the state machine
// so if we get an timeout events the sm handles them
ua_entry->read_vio = client_vc->do_io_read(this, 0, buffer_reader->mbuf);
/////////////////////////
// set up timeouts //
/////////////////////////
client_vc->set_inactivity_timeout(HRTIME_SECONDS(t_state.http_config_param->accept_no_activity_timeout));
client_vc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_in));
++reentrancy_count;
// Add our state sm to the sm list
state_add_to_list(EVENT_NONE, nullptr);
// This is another external entry point and it is possible for the state machine to get terminated
// while down the call chain from @c state_add_to_list. So we need to use the reentrancy_count to
// prevent cleanup there and do it here as we return to the external caller.
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
--reentrancy_count;
ink_assert(reentrancy_count >= 0);
}
}
void
HttpSM::setup_client_read_request_header()
{
ink_assert(ua_entry->vc_handler == &HttpSM::state_read_client_request_header);
ua_entry->read_vio = ua_session->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
// The header may already be in the buffer if this
// a request from a keep-alive connection
handleEvent(VC_EVENT_READ_READY, ua_entry->read_vio);
}
void
HttpSM::setup_blind_tunnel_port()
{
// We gotten a connect on a port for blind tunneling so
// call transact figure out where it is going
call_transact_and_set_next_state(HttpTransact::HandleBlindTunnel);
}
int
HttpSM::state_read_client_request_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_client_request_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(server_entry == nullptr);
ink_assert(server_session == nullptr);
int bytes_used = 0;
ink_assert(ua_entry->eos == false);
NetVConnection *netvc = ua_session->get_netvc();
if (!netvc && event != VC_EVENT_EOS) {
return 0;
}
switch (event) {
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_EOS:
ua_entry->eos = true;
if ((client_request_hdr_bytes > 0) && is_transparent_passthrough_allowed() && (ua_raw_buffer_reader != nullptr)) {
break;
}
// Fall through
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Close it &
// bail on the state machine
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
t_state.client_info.abort = HttpTransact::ABORTED;
terminate_sm = true;
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the accept timeout by the ProxyClientTransaction
//
if ((ua_buffer_reader->read_avail() > 0) && (client_request_hdr_bytes == 0)) {
milestones[TS_MILESTONE_UA_FIRST_READ] = Thread::get_hrtime();
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state = t_state.hdr_info.client_request.parse_req(&http_parser, ua_buffer_reader, &bytes_used, ua_entry->eos,
t_state.http_config_param->strict_uri_parsing);
client_request_hdr_bytes += bytes_used;
// Check to see if we are over the hdr size limit
if (client_request_hdr_bytes > t_state.txn_conf->request_hdr_max_size) {
DebugSM("http", "client header bytes were over max header size; treating as a bad request");
state = PARSE_RESULT_ERROR;
}
// We need to handle EOS as well as READ_READY because the client
// may have sent all of the data already followed by a fIN and that
// should be OK.
if (is_transparent_passthrough_allowed() && ua_raw_buffer_reader != nullptr) {
bool do_blind_tunnel = false;
// If we had a parse error and we're done reading data
// blind tunnel
if ((event == VC_EVENT_READ_READY || event == VC_EVENT_EOS) && state == PARSE_RESULT_ERROR) {
do_blind_tunnel = true;
// If we had a GET request that has data after the
// get request, do blind tunnel
} else if (state == PARSE_RESULT_DONE && t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET &&
ua_buffer_reader->read_avail() > 0 && !t_state.hdr_info.client_request.is_keep_alive_set()) {
do_blind_tunnel = true;
}
if (do_blind_tunnel) {
DebugSM("http", "[%" PRId64 "] first request on connection failed parsing, switching to passthrough.", sm_id);
t_state.transparent_passthrough = true;
http_parser_clear(&http_parser);
// Turn off read eventing until we get the
// blind tunnel infrastructure set up
if (netvc) {
netvc->do_io_read(this, 0, nullptr);
}
/* establish blind tunnel */
setup_blind_tunnel_port();
// Setting half close means we will send the FIN when we've written all of the data.
if (event == VC_EVENT_EOS) {
this->set_ua_half_close_flag();
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
return 0;
}
}
// Check to see if we are done parsing the header
if (state != PARSE_RESULT_CONT || ua_entry->eos || (state == PARSE_RESULT_CONT && event == VC_EVENT_READ_COMPLETE)) {
if (ua_raw_buffer_reader != nullptr) {
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
http_parser_clear(&http_parser);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
milestones[TS_MILESTONE_UA_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
DebugSM("http", "[%" PRId64 "] error parsing client request header", sm_id);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
case PARSE_RESULT_CONT:
if (ua_entry->eos) {
DebugSM("http_seq", "[%" PRId64 "] EOS before client request parsing finished", sm_id);
set_ua_abort(HttpTransact::ABORTED, event);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
} else if (event == VC_EVENT_READ_COMPLETE) {
DebugSM("http_parse", "[%" PRId64 "] VC_EVENT_READ_COMPLETE and PARSE CONT state", sm_id);
break;
} else {
if (is_transparent_passthrough_allowed() && ua_raw_buffer_reader != nullptr &&
ua_raw_buffer_reader->get_current_block()->write_avail() <= 0) {
// Disable passthrough regardless of eventual parsing failure or success -- otherwise
// we either have to consume some data or risk blocking the writer.
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
}
case PARSE_RESULT_DONE:
DebugSM("http", "[%" PRId64 "] done parsing client request header", sm_id);
ua_session->set_session_active();
if (t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 1) &&
(t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_POST ||
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_PUT) &&
t_state.http_config_param->send_100_continue_response) {
int len = 0;
const char *expect = t_state.hdr_info.client_request.value_get(MIME_FIELD_EXPECT, MIME_LEN_EXPECT, &len);
// When receive an "Expect: 100-continue" request from client, ATS sends a "100 Continue" response to client
// immediately, before receive the real response from original server.
if ((len == HTTP_LEN_100_CONTINUE) && (strncasecmp(expect, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0)) {
int64_t alloc_index = buffer_size_to_index(len_100_continue_response);
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
ua_entry->write_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = ua_entry->write_buffer->alloc_reader();
DebugSM("http_seq", "send 100 Continue response to client");
int64_t nbytes = ua_entry->write_buffer->write(str_100_continue_response, len_100_continue_response);
ua_session->do_io_write(netvc, nbytes, buf_start);
}
}
if (t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_TRACE ||
(t_state.hdr_info.request_content_length <= 0 && t_state.client_info.transfer_encoding != HttpTransact::CHUNKED_ENCODING)) {
// Enable further IO to watch for client aborts
ua_entry->read_vio->reenable();
} else {
// Disable further I/O on the client since there could
// be body that we are tunneling POST/PUT/CONNECT or
// extension methods and we can't issue another
// another IO later for the body with a different buffer
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
// YTS Team, yamsat Plugin
// Setting enable_redirection according to HttpConfig master
if ((t_state.txn_conf->number_of_redirections > 0) ||
(t_state.method == HTTP_WKSIDX_POST && HttpConfig::m_master.post_copy_size)) {
enable_redirection = t_state.txn_conf->redirection_enabled;
}
call_transact_and_set_next_state(HttpTransact::ModifyRequest);
break;
default:
ink_assert(!"not reached");
}
return 0;
}
#ifdef PROXY_DRAIN
int
HttpSM::state_drain_client_request_body(int event, void *data)
{
STATE_ENTER(&HttpSM::state_drain_client_request_body, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(ua_entry->vc == ua_session);
NetVConnection *netvc = ua_session->get_netvc();
if (!netvc && event != VC_EVENT_EOS)
return 0;
switch (event) {
case VC_EVENT_EOS:
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT: {
// Nothing we can do
terminate_sm = true;
break;
}
case VC_EVENT_READ_READY: {
int64_t avail = ua_buffer_reader->read_avail();
int64_t left = t_state.hdr_info.request_content_length - client_request_body_bytes;
// Since we are only reading what's needed to complete
// the post, there must be something left to do
ink_assert(avail < left);
client_request_body_bytes += avail;
ua_buffer_reader->consume(avail);
ua_entry->read_vio->reenable_re();
break;
}
case VC_EVENT_READ_COMPLETE: {
// We've finished draing the POST body
int64_t avail = ua_buffer_reader->read_avail();
ua_buffer_reader->consume(avail);
client_request_body_bytes += avail;
ink_assert(client_request_body_bytes == t_state.hdr_info.request_content_length);
ua_buffer_reader->mbuf->size_index = HTTP_HEADER_BUFFER_SIZE_INDEX;
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = ua_entry->vc->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
call_transact_and_set_next_state(NULL);
break;
}
default:
ink_release_assert(0);
}
return EVENT_DONE;
}
#endif /* PROXY_DRAIN */
int
HttpSM::state_watch_for_client_abort(int event, void *data)
{
STATE_ENTER(&HttpSM::state_watch_for_client_abort, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(ua_entry->vc == ua_session);
switch (event) {
/* EOS means that the client has initiated the connection shut down.
* Only half close the client connection so ATS can read additional
* data that may still be sent from the server and send it to the
* client.
*/
case VC_EVENT_EOS: {
// We got an early EOS.
NetVConnection *netvc = ua_session->get_netvc();
if (ua_session->allow_half_open()) {
if (netvc) {
netvc->do_io_shutdown(IO_SHUTDOWN_READ);
}
ua_entry->eos = true;
} else {
ua_session->do_io_close();
ua_buffer_reader = nullptr;
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
tunnel.kill_tunnel();
terminate_sm = true; // Just die already, the requester is gone
}
break;
}
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT: {
if (tunnel.is_tunnel_active()) {
// Check to see if the user agent is part of the tunnel.
// If so forward the event to the tunnel. Otherwise,
// kill the tunnel and fallthrough to the case
// where the tunnel is not active
HttpTunnelConsumer *c = tunnel.get_consumer(ua_session);
if (c && c->alive) {
DebugSM("http", "[%" PRId64 "] [watch_for_client_abort] "
"forwarding event %s to tunnel",
sm_id, HttpDebugNames::get_event_name(event));
tunnel.handleEvent(event, c->write_vio);
return 0;
} else {
tunnel.kill_tunnel();
}
}
// Disable further I/O on the client
if (ua_entry->read_vio) {
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
mark_server_down_on_client_abort();
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
set_ua_abort(HttpTransact::ABORTED, event);
terminate_sm = true;
break;
}
case VC_EVENT_READ_COMPLETE:
// XXX Work around for TS-1233.
case VC_EVENT_READ_READY:
// Ignore. Could be a pipelined request. We'll get to it
// when we finish the current transaction
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
void
HttpSM::setup_push_read_response_header()
{
ink_assert(server_session == nullptr);
ink_assert(server_entry == nullptr);
ink_assert(ua_session != nullptr);
ink_assert(t_state.method == HTTP_WKSIDX_PUSH);
// Set the handler to read the pushed response hdr
ua_entry->vc_handler = &HttpSM::state_read_push_response_header;
// We record both the total payload size as
// client_request_body_bytes and the bytes for the individual
// pushed hdr and body components
pushed_response_hdr_bytes = 0;
client_request_body_bytes = 0;
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
// We already done the READ when we read the client
// request header
ink_assert(ua_entry->read_vio);
// If there is anything in the buffer call the parsing routines
// since if the response is finished, we won't get any
// additional callbacks
int resp_hdr_state = VC_EVENT_CONT;
if (ua_buffer_reader->read_avail() > 0) {
if (ua_entry->eos) {
resp_hdr_state = state_read_push_response_header(VC_EVENT_EOS, ua_entry->read_vio);
} else {
resp_hdr_state = state_read_push_response_header(VC_EVENT_READ_READY, ua_entry->read_vio);
}
}
// It is possible that the entire PUSHed response header was already
// in the buffer. In this case we don't want to fire off any more
// IO since we are going to switch buffers when we go to tunnel to
// the cache
if (resp_hdr_state == VC_EVENT_CONT) {
ink_assert(ua_entry->eos == false);
ua_entry->read_vio = ua_session->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
}
}
int
HttpSM::state_read_push_response_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_push_response_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(t_state.current.server == nullptr);
int64_t data_size = 0;
int64_t bytes_used = 0;
// Not used here.
// bool parse_error = false;
// VIO* vio = (VIO*) data;
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// Fall through
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Send an error
t_state.client_info.abort = HttpTransact::ABORTED;
call_transact_and_set_next_state(HttpTransact::HandleBadPushRespHdr);
return 0;
}
int state = PARSE_RESULT_CONT;
while (ua_buffer_reader->read_avail() && state == PARSE_RESULT_CONT) {
const char *start = ua_buffer_reader->start();
const char *tmp = start;
data_size = ua_buffer_reader->block_read_avail();
ink_assert(data_size >= 0);
/////////////////////
// tokenize header //
/////////////////////
state =
t_state.hdr_info.server_response.parse_resp(&http_parser, &tmp, tmp + data_size, false // Only call w/ eof when data exhausted
);
bytes_used = tmp - start;
ink_release_assert(bytes_used <= data_size);
ua_buffer_reader->consume(bytes_used);
pushed_response_hdr_bytes += bytes_used;
client_request_body_bytes += bytes_used;
}
// We are out of data. If we've received an EOS we need to
// call the parser with (eof == true) so it can determine
// whether to use the response as is or declare a parse error
if (ua_entry->eos) {
const char *end = ua_buffer_reader->start();
state = t_state.hdr_info.server_response.parse_resp(&http_parser, &end, end, true // We are out of data after server eos
);
ink_release_assert(state == PARSE_RESULT_DONE || state == PARSE_RESULT_ERROR);
}
// Don't allow 0.9 (unparsable headers) since TS doesn't
// cache 0.9 responses
if (state == PARSE_RESULT_DONE && t_state.hdr_info.server_response.version_get() == HTTPVersion(0, 9)) {
state = PARSE_RESULT_ERROR;
}
if (state != PARSE_RESULT_CONT) {
// Disable further IO
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
http_parser_clear(&http_parser);
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
DebugSM("http", "[%" PRId64 "] error parsing push response header", sm_id);
call_transact_and_set_next_state(HttpTransact::HandleBadPushRespHdr);
break;
case PARSE_RESULT_CONT:
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
case PARSE_RESULT_DONE:
DebugSM("http", "[%" PRId64 "] done parsing push response header", sm_id);
call_transact_and_set_next_state(HttpTransact::HandlePushResponseHdr);
break;
default:
ink_assert(!"not reached");
}
return VC_EVENT_DONE;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_http_server_open()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_raw_http_server_open(int event, void *data)
{
STATE_ENTER(&HttpSM::state_raw_http_server_open, event);
ink_assert(server_entry == nullptr);
milestones[TS_MILESTONE_SERVER_CONNECT_END] = Thread::get_hrtime();
NetVConnection *netvc = nullptr;
pending_action = nullptr;
switch (event) {
case EVENT_INTERVAL:
// If we get EVENT_INTERNAL it means that we moved the transaction
// to a different thread in do_http_server_open. Since we didn't
// do any of the actual work in do_http_server_open, we have to
// go back and do it now.
do_http_server_open(true);
return 0;
case NET_EVENT_OPEN:
if (t_state.pCongestionEntry != nullptr) {
t_state.pCongestionEntry->connection_opened();
t_state.congestion_connection_opened = 1;
}
// Record the VC in our table
server_entry = vc_table.new_entry();
server_entry->vc = netvc = (NetVConnection *)data;
server_entry->vc_type = HTTP_RAW_SERVER_VC;
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
netvc->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
netvc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_out));
break;
case VC_EVENT_ERROR:
case NET_EVENT_OPEN_FAILED:
if (t_state.pCongestionEntry != nullptr) {
t_state.current.state = HttpTransact::CONNECTION_ERROR;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return 0;
} else {
t_state.current.state = HttpTransact::OPEN_RAW_ERROR;
// use this value just to get around other values
t_state.hdr_info.response_error = HttpTransact::STATUS_CODE_SERVER_ERROR;
}
break;
case CONGESTION_EVENT_CONGESTED_ON_F:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_F;
break;
case CONGESTION_EVENT_CONGESTED_ON_M:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_M;
break;
default:
ink_release_assert(0);
break;
}
call_transact_and_set_next_state(HttpTransact::OriginServerRawOpen);
return 0;
}
// int HttpSM::state_request_wait_for_transform_read(int event, void* data)
//
// We've done a successful transform open and issued a do_io_write
// to the transform. We are now ready for the transform to tell
// us it is now ready to be read from and it done modifying the
// server request header
//
int
HttpSM::state_request_wait_for_transform_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_request_wait_for_transform_read, event);
int64_t size = *((int64_t *)data);
switch (event) {
case TRANSFORM_READ_READY:
if (size != INT64_MAX && size >= 0) {
// We got a content length so update our internal
// data as well as fix up the request header
t_state.hdr_info.transform_request_cl = size;
t_state.hdr_info.server_request.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, size);
setup_server_send_request_api();
break;
} else {
// No content length from the post. This is a no go
// since http spec requires content length when
// sending a request message body. Change the event
// to an error and fall through
event = VC_EVENT_ERROR;
Log::error("Request transformation failed to set content length");
}
// FALLTHROUGH
default:
state_common_wait_for_transform_read(&post_transform_info, &HttpSM::tunnel_handler_post, event, data);
break;
}
return 0;
}
// int HttpSM::state_response_wait_for_transform_read(int event, void* data)
//
// We've done a successful transform open and issued a do_io_write
// to the transform. We are now ready for the transform to tell
// us it is now ready to be read from and it done modifying the
// user agent response header
//
int
HttpSM::state_response_wait_for_transform_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_response_wait_for_transform_read, event);
int64_t size = *((int64_t *)data);
switch (event) {
case TRANSFORM_READ_READY:
if (size != INT64_MAX && size >= 0) {
// We got a content length so update our internal state
t_state.hdr_info.transform_response_cl = size;
t_state.hdr_info.transform_response.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, size);
} else {
t_state.hdr_info.transform_response_cl = HTTP_UNDEFINED_CL;
}
call_transact_and_set_next_state(HttpTransact::handle_transform_ready);
break;
default:
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
break;
}
return 0;
}
// int HttpSM::state_common_wait_for_transform_read(...)
//
// This function handles the overlapping cases between request and response
// transforms which prevents code duplication
//
int
HttpSM::state_common_wait_for_transform_read(HttpTransformInfo *t_info, HttpSMHandler tunnel_handler, int event, void *data)
{
STATE_ENTER(&HttpSM::state_common_wait_for_transform_read, event);
HttpTunnelConsumer *c = nullptr;
switch (event) {
case HTTP_TUNNEL_EVENT_DONE:
// There are three reasons why the the tunnel could signal completed
// 1) there was error from the transform write
// 2) there was an error from the data source
// 3) the transform write completed before it sent
// TRANSFORM_READ_READY which is legal and in which
// case we should just wait for the transform read ready
c = tunnel.get_consumer(t_info->vc);
ink_assert(c != nullptr);
ink_assert(c->vc == t_info->entry->vc);
if (c->handler_state == HTTP_SM_TRANSFORM_FAIL) {
// Case 1 we failed to complete the write to the
// transform fall through to vc event error case
ink_assert(c->write_success == false);
} else if (c->producer->read_success == false) {
// Case 2 - error from data source
if (c->producer->vc_type == HT_HTTP_CLIENT) {
// Our source is the client. POST can't
// be truncated so forward to the tunnel
// handler to clean this mess up
ink_assert(t_info == &post_transform_info);
return (this->*tunnel_handler)(event, data);
} else {
// On the response side, we just forward as much
// as we can of truncated documents so
// just don't cache the result
ink_assert(t_info == &transform_info);
t_state.api_info.cache_transformed = false;
return 0;
}
} else {
// Case 3 - wait for transform read ready
return 0;
}
// FALLTHROUGH
case VC_EVENT_ERROR:
// Transform VC sends NULL on error conditions
if (!c) {
c = tunnel.get_consumer(t_info->vc);
ink_assert(c != nullptr);
}
vc_table.cleanup_entry(t_info->entry);
t_info->entry = nullptr;
// In Case 1: error due to transform write,
// we need to keep the original t_info->vc for transform_cleanup()
// to skip do_io_close(); otherwise, set it to NULL.
if (c->handler_state != HTTP_SM_TRANSFORM_FAIL) {
t_info->vc = nullptr;
}
if (c->producer->vc_type == HT_HTTP_CLIENT) {
/* Producer was the user agent and there was a failure transforming the POST.
Handling this is challenging and this isn't the best way but it at least
avoids a crash due to trying to send a response to a NULL'd out user agent.
The problem with not closing the user agent is handling draining of the
rest of the POST - the user agent may well not check for a response until that's
done in which case we can get a deadlock where the user agent never reads the
error response because the POST wasn't drained and the buffers filled up.
Draining has a potential bad impact on any pipelining which must be considered.
If we're not going to drain properly the next best choice is to shut down the
entire state machine since (1) there's no point in finishing the POST to the
origin and (2) there's no user agent connection to which to send the error response.
*/
terminate_sm = true;
} else {
tunnel.kill_tunnel();
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
}
break;
default:
ink_release_assert(0);
}
return 0;
}
// int HttpSM::state_api_callback(int event, void *data)
// InkAPI.cc calls us directly here to avoid problems
// with setting and changing the default_handler
// function. As such, this is an entry point
// and needs to handle the reentrancy counter and
// deallocation the state machine if necessary
//
int
HttpSM::state_api_callback(int event, void *data)
{
ink_release_assert(magic == HTTP_SM_MAGIC_ALIVE);
ink_assert(reentrancy_count >= 0);
reentrancy_count++;
milestone_update_api_time(milestones, api_timer);
STATE_ENTER(&HttpSM::state_api_callback, event);
state_api_callout(event, data);
// The sub-handler signals when it is time for the state
// machine to exit. We can only exit if we are not reentrantly
// called otherwise when the our call unwinds, we will be
// running on a dead state machine
//
// Because of the need for an api shutdown hook, kill_this()
// is also reentrant. As such, we don't want to decrement
// the reentrancy count until after we run kill_this()
//
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
reentrancy_count--;
ink_assert(reentrancy_count >= 0);
}
return VC_EVENT_CONT;
}
int
HttpSM::state_api_callout(int event, void *data)
{
// enum and variable for figuring out what the next action is after
// after we've finished the api state
enum AfterApiReturn_t {
API_RETURN_UNKNOWN = 0,
API_RETURN_CONTINUE,
API_RETURN_DEFERED_CLOSE,
API_RETURN_DEFERED_SERVER_ERROR,
API_RETURN_ERROR_JUMP,
API_RETURN_SHUTDOWN,
API_RETURN_INVALIDATE_ERROR
};
AfterApiReturn_t api_next = API_RETURN_UNKNOWN;
if (event != EVENT_NONE) {
STATE_ENTER(&HttpSM::state_api_callout, event);
}
if (api_timer < 0) {
// This happens when either the plugin lock was missed and the hook rescheduled or
// the transaction got an event without the plugin calling TsHttpTxnReenable().
// The call chain does not recurse here if @a api_timer < 0 which means this call
// is the first from an event dispatch in this case.
milestone_update_api_time(milestones, api_timer);
}
switch (event) {
case EVENT_INTERVAL:
ink_assert(pending_action == data);
pending_action = nullptr;
// FALLTHROUGH
case EVENT_NONE:
case HTTP_API_CONTINUE:
if ((cur_hook_id >= 0) && (cur_hook_id < TS_HTTP_LAST_HOOK)) {
if (!cur_hook) {
if (cur_hooks == 0) {
cur_hook = http_global_hooks->get(cur_hook_id);
cur_hooks++;
}
}
// even if ua_session is NULL, cur_hooks must
// be incremented otherwise cur_hooks is not set to 2 and
// transaction hooks (stored in api_hooks object) are not called.
if (!cur_hook) {
if (cur_hooks == 1) {
if (ua_session) {
cur_hook = ua_session->ssn_hook_get(cur_hook_id);
}
cur_hooks++;
}
}
if (!cur_hook) {
if (cur_hooks == 2) {
cur_hook = api_hooks.get(cur_hook_id);
cur_hooks++;
}
}
if (cur_hook) {
if (callout_state == HTTP_API_NO_CALLOUT) {
callout_state = HTTP_API_IN_CALLOUT;
}
/* The MUTEX_TRY_LOCK macro was changed so
that it can't handle NULL mutex'es. The plugins
can use null mutexes so we have to do this manually.
We need to take a smart pointer to the mutex since
the plugin could release it's mutex while we're on
the callout
*/
bool plugin_lock;
Ptr<ProxyMutex> plugin_mutex;
if (cur_hook->m_cont->mutex) {
plugin_mutex = cur_hook->m_cont->mutex;
plugin_lock = MUTEX_TAKE_TRY_LOCK(cur_hook->m_cont->mutex, mutex->thread_holding);
if (!plugin_lock) {
api_timer = -Thread::get_hrtime_updated();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_api_callout);
ink_assert(pending_action == nullptr);
pending_action = mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
// Should @a callout_state be reset back to HTTP_API_NO_CALLOUT here? Because the default
// handler has been changed the value isn't important to the rest of the state machine
// but not resetting means there is no way to reliably detect re-entrance to this state with an
// outstanding callout.
return 0;
}
} else {
plugin_lock = false;
}
DebugSM("http", "[%" PRId64 "] calling plugin on hook %s at hook %p", sm_id, HttpDebugNames::get_api_hook_name(cur_hook_id),
cur_hook);
APIHook *hook = cur_hook;
cur_hook = cur_hook->next();
if (!api_timer) {
api_timer = Thread::get_hrtime_updated();
}
hook->invoke(TS_EVENT_HTTP_READ_REQUEST_HDR + cur_hook_id, this);
if (api_timer > 0) { // true if the hook did not call TxnReenable()
milestone_update_api_time(milestones, api_timer);
api_timer = -Thread::get_hrtime_updated(); // set in order to track non-active callout duration
// which means that if we get back from the invoke with api_timer < 0 we're already
// tracking a non-complete callout from a chain so just let it ride. It will get cleaned
// up in state_api_callback when the plugin re-enables this transaction.
}
if (plugin_lock) {
Mutex_unlock(plugin_mutex, mutex->thread_holding);
}
return 0;
}
}
// Map the callout state into api_next
switch (callout_state) {
case HTTP_API_NO_CALLOUT:
case HTTP_API_IN_CALLOUT:
if (t_state.api_modifiable_cached_resp && t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE;
}
api_next = API_RETURN_CONTINUE;
break;
case HTTP_API_DEFERED_CLOSE:
api_next = API_RETURN_DEFERED_CLOSE;
break;
case HTTP_API_DEFERED_SERVER_ERROR:
api_next = API_RETURN_DEFERED_SERVER_ERROR;
break;
default:
ink_release_assert(0);
}
break;
case HTTP_API_ERROR:
if (callout_state == HTTP_API_DEFERED_CLOSE) {
api_next = API_RETURN_DEFERED_CLOSE;
} else if (cur_hook_id == TS_HTTP_TXN_CLOSE_HOOK) {
// If we are closing the state machine, we can't
// jump to an error state so just continue
api_next = API_RETURN_CONTINUE;
} else if (t_state.api_http_sm_shutdown) {
t_state.api_http_sm_shutdown = false;
t_state.cache_info.object_read = nullptr;
cache_sm.close_read();
transform_cache_sm.close_read();
release_server_session();
terminate_sm = true;
api_next = API_RETURN_SHUTDOWN;
t_state.squid_codes.log_code = SQUID_LOG_TCP_DENIED;
} else if (t_state.api_modifiable_cached_resp &&
t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_ERROR;
api_next = API_RETURN_INVALIDATE_ERROR;
} else {
api_next = API_RETURN_ERROR_JUMP;
}
break;
// We may receive an event from the tunnel
// if it took a long time to call the SEND_RESPONSE_HDR hook
case HTTP_TUNNEL_EVENT_DONE:
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
return 0;
default:
ink_assert(false);
terminate_sm = true;
return 0;
}
// Now that we're completed with the api state and figured out what
// to do next, do it
callout_state = HTTP_API_NO_CALLOUT;
api_timer = 0;
switch (api_next) {
case API_RETURN_CONTINUE:
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR) {
do_redirect();
}
handle_api_return();
break;
case API_RETURN_DEFERED_CLOSE:
ink_assert(t_state.api_next_action == HttpTransact::SM_ACTION_API_SM_SHUTDOWN);
do_api_callout();
break;
case API_RETURN_DEFERED_SERVER_ERROR:
ink_assert(t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR);
ink_assert(t_state.current.state != HttpTransact::CONNECTION_ALIVE);
call_transact_and_set_next_state(HttpTransact::HandleResponse);
break;
case API_RETURN_ERROR_JUMP:
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
break;
case API_RETURN_SHUTDOWN:
break;
case API_RETURN_INVALIDATE_ERROR:
do_cache_prepare_update();
break;
default:
case API_RETURN_UNKNOWN:
ink_release_assert(0);
}
return 0;
}
// void HttpSM::handle_api_return()
//
// Figures out what to do after calling api callouts
// have finished. This messy and I would like
// to come up with a cleaner way to handle the api
// return. The way we are doing things also makes a
// mess of set_next_state()
//
void
HttpSM::handle_api_return()
{
switch (t_state.api_next_action) {
case HttpTransact::SM_ACTION_API_SM_START:
if (t_state.client_info.port_attribute == HttpProxyPort::TRANSPORT_BLIND_TUNNEL) {
setup_blind_tunnel_port();
} else {
setup_client_read_request_header();
}
return;
case HttpTransact::SM_ACTION_API_PRE_REMAP:
case HttpTransact::SM_ACTION_API_POST_REMAP:
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_OS_DNS:
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE:
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE && t_state.api_cleanup_cache_read &&
t_state.api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_cleanup_cache_read = false;
t_state.cache_info.object_read = nullptr;
t_state.request_sent_time = UNDEFINED_TIME;
t_state.response_received_time = UNDEFINED_TIME;
cache_sm.close_read();
transform_cache_sm.close_read();
}
call_transact_and_set_next_state(nullptr);
return;
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
setup_server_send_request();
return;
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
// Set back the inactivity timeout
if (ua_session) {
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
// we have further processing to do
// based on what t_state.next_action is
break;
case HttpTransact::SM_ACTION_API_SM_SHUTDOWN:
state_remove_from_list(EVENT_NONE, nullptr);
return;
default:
ink_release_assert("! Not reached");
break;
}
switch (t_state.next_action) {
case HttpTransact::SM_ACTION_TRANSFORM_READ: {
HttpTunnelProducer *p = setup_transfer_from_transform();
perform_transform_cache_write_action();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_SERVER_READ: {
if (unlikely(t_state.did_upgrade_succeed)) {
// We've successfully handled the upgrade, let's now setup
// a blind tunnel.
if (t_state.is_websocket) {
HTTP_INCREMENT_DYN_STAT(http_websocket_current_active_client_connections_stat);
if (ua_session) {
DebugSM("http_websocket",
"(client session) Setting websocket active timeout=%" PRId64 "s and inactive timeout=%" PRId64 "s",
t_state.txn_conf->websocket_active_timeout, t_state.txn_conf->websocket_inactive_timeout);
ua_session->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_active_timeout));
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_inactive_timeout));
}
if (server_session) {
DebugSM("http_websocket",
"(server session) Setting websocket active timeout=%" PRId64 "s and inactive timeout=%" PRId64 "s",
t_state.txn_conf->websocket_active_timeout, t_state.txn_conf->websocket_inactive_timeout);
server_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_active_timeout));
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_inactive_timeout));
}
}
setup_blind_tunnel(true);
} else {
HttpTunnelProducer *p = setup_server_transfer();
perform_cache_write_action();
tunnel.tunnel_run(p);
}
break;
}
case HttpTransact::SM_ACTION_SERVE_FROM_CACHE: {
HttpTunnelProducer *p = setup_cache_read_transfer();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_WRITE: {
if (cache_sm.cache_write_vc) {
setup_internal_transfer(&HttpSM::tunnel_handler_cache_fill);
} else {
setup_internal_transfer(&HttpSM::tunnel_handler);
}
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_NOOP:
case HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE:
case HttpTransact::SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS:
case HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP: {
setup_internal_transfer(&HttpSM::tunnel_handler);
break;
}
case HttpTransact::SM_ACTION_REDIRECT_READ: {
// Clean up from any communication with previous servers
release_server_session();
call_transact_and_set_next_state(HttpTransact::HandleRequest);
break;
}
case HttpTransact::SM_ACTION_SSL_TUNNEL: {
setup_blind_tunnel(true);
break;
}
default: {
ink_release_assert(!"Should not get here");
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_http_server_open()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_http_server_open(int event, void *data)
{
DebugSM("http_track", "entered inside state_http_server_open");
STATE_ENTER(&HttpSM::state_http_server_open, event);
// TODO decide whether to uncomment after finish testing redirect
// ink_assert(server_entry == NULL);
pending_action = nullptr;
milestones[TS_MILESTONE_SERVER_CONNECT_END] = Thread::get_hrtime();
HttpServerSession *session;
switch (event) {
case NET_EVENT_OPEN:
session = (TS_SERVER_SESSION_SHARING_POOL_THREAD == t_state.http_config_param->server_session_sharing_pool) ?
THREAD_ALLOC_INIT(httpServerSessionAllocator, mutex->thread_holding) :
httpServerSessionAllocator.alloc();
session->sharing_pool = static_cast<TSServerSessionSharingPoolType>(t_state.http_config_param->server_session_sharing_pool);
session->sharing_match = static_cast<TSServerSessionSharingMatchType>(t_state.txn_conf->server_session_sharing_match);
// If origin_max_connections or origin_min_keep_alive_connections is
// set then we are metering the max and or min number
// of connections per host. Set enable_origin_connection_limiting
// to true in the server session so it will increment and decrement
// the connection count.
if (t_state.txn_conf->origin_max_connections > 0 || t_state.http_config_param->origin_min_keep_alive_connections > 0) {
DebugSM("http_ss", "[%" PRId64 "] max number of connections: %" PRIu64, sm_id, t_state.txn_conf->origin_max_connections);
session->enable_origin_connection_limiting = true;
}
/*UnixNetVConnection * vc = (UnixNetVConnection*)(ua_session->client_vc);
UnixNetVConnection *server_vc = (UnixNetVConnection*)data;
printf("client fd is :%d , server fd is %d\n",vc->con.fd,
server_vc->con.fd); */
session->attach_hostname(t_state.current.server->name);
session->new_connection(static_cast<NetVConnection *>(data));
session->state = HSS_ACTIVE;
attach_server_session(session);
if (t_state.current.request_to == HttpTransact::PARENT_PROXY) {
session->to_parent_proxy = true;
HTTP_INCREMENT_DYN_STAT(http_current_parent_proxy_connections_stat);
HTTP_INCREMENT_DYN_STAT(http_total_parent_proxy_connections_stat);
} else {
session->to_parent_proxy = false;
}
handle_http_server_open();
return 0;
case EVENT_INTERVAL: // Delayed call from another thread
if (server_session == nullptr) {
do_http_server_open();
}
break;
case VC_EVENT_ERROR:
case NET_EVENT_OPEN_FAILED:
t_state.current.state = HttpTransact::CONNECTION_ERROR;
// save the errno from the connect fail for future use (passed as negative value, flip back)
t_state.current.server->set_connect_fail(event == NET_EVENT_OPEN_FAILED ? -reinterpret_cast<intptr_t>(data) : ECONNABORTED);
/* If we get this error, then we simply can't bind to the 4-tuple to make the connection. There's no hope of
retries succeeding in the near future. The best option is to just shut down the connection without further
comment. The only known cause for this is outbound transparency combined with use client target address / source
port, as noted in TS-1424. If the keep alives desync the current connection can be attempting to rebind the 4
tuple simultaneously with the shut down of an existing connection. Dropping the client side will cause it to pick
a new source port and recover from this issue.
*/
if (EADDRNOTAVAIL == t_state.current.server->connect_result) {
if (is_debug_tag_set("http_tproxy")) {
ip_port_text_buffer ip_c, ip_s;
Debug("http_tproxy", "Force close of client connect (%s->%s) due to EADDRNOTAVAIL [%" PRId64 "]",
ats_ip_nptop(&t_state.client_info.src_addr.sa, ip_c, sizeof ip_c),
ats_ip_nptop(&t_state.server_info.dst_addr.sa, ip_s, sizeof ip_s), sm_id);
}
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE; // part of the problem, clear it.
terminate_sm = true;
} else {
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
return 0;
case CONGESTION_EVENT_CONGESTED_ON_F:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_F;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return 0;
case CONGESTION_EVENT_CONGESTED_ON_M:
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_M;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return 0;
default:
Error("[HttpSM::state_http_server_open] Unknown event: %d", event);
ink_release_assert(0);
return 0;
}
return 0;
}
int
HttpSM::state_read_server_response_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_server_response_header, event);
ink_assert(server_entry->read_vio == (VIO *)data);
ink_assert(t_state.current.server->state == HttpTransact::STATE_UNDEFINED);
ink_assert(t_state.current.state == HttpTransact::STATE_UNDEFINED);
int bytes_used = 0;
VIO *vio = (VIO *)data;
switch (event) {
case VC_EVENT_EOS:
server_entry->eos = true;
// If no bytes were transmitted, the parser treats
// as a good 0.9 response which is technically is
// but it's indistinguishable from an overloaded
// server closing the connection so don't accept
// zero length responses
if (vio->ndone == 0) {
// Error handling function
handle_server_setup_error(event, data);
return 0;
}
// Fall through
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// Error handling function
handle_server_setup_error(event, data);
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the connect timeout when we set up to read the header
//
if (server_response_hdr_bytes == 0) {
milestones[TS_MILESTONE_SERVER_FIRST_READ] = Thread::get_hrtime();
if (t_state.api_txn_no_activity_timeout_value != -1) {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_MSECONDS(t_state.api_txn_no_activity_timeout_value));
} else {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
}
// For requests that contain a body, we can cancel the ua inactivity timeout.
if (ua_session && t_state.hdr_info.request_content_length) {
ua_session->cancel_inactivity_timeout();
}
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state =
t_state.hdr_info.server_response.parse_resp(&http_parser, server_buffer_reader, &bytes_used, server_entry->eos);
server_response_hdr_bytes += bytes_used;
// Don't allow 0.9 (unparsable headers) on keep-alive connections after
// the connection has already served a transaction as what we are likely
// looking at is garbage on a keep-alive channel corrupted by the origin
// server
if (state == PARSE_RESULT_DONE && t_state.hdr_info.server_response.version_get() == HTTPVersion(0, 9) &&
server_session->transact_count > 1) {
state = PARSE_RESULT_ERROR;
}
// Check to see if we are over the hdr size limit
if (server_response_hdr_bytes > t_state.txn_conf->response_hdr_max_size) {
state = PARSE_RESULT_ERROR;
}
if (state != PARSE_RESULT_CONT) {
// Disable further IO
server_entry->read_vio->nbytes = server_entry->read_vio->ndone;
http_parser_clear(&http_parser);
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR: {
// Many broken servers send really badly formed 302 redirects.
// Even if the parser doesn't like the redirect forward
// if it's got a Location header. We check the type of the
// response to make sure that the parser was able to parse
// something and didn't just throw up it's hands (INKqa05339)
bool allow_error = false;
if (t_state.hdr_info.server_response.type_get() == HTTP_TYPE_RESPONSE &&
t_state.hdr_info.server_response.status_get() == HTTP_STATUS_MOVED_TEMPORARILY) {
if (t_state.hdr_info.server_response.field_find(MIME_FIELD_LOCATION, MIME_LEN_LOCATION)) {
allow_error = true;
}
}
if (allow_error == false) {
DebugSM("http_seq", "Error parsing server response header");
t_state.current.state = HttpTransact::PARSE_ERROR;
// If the server closed prematurely on us, use the
// server setup error routine since it will forward
// error to a POST tunnel if any
if (event == VC_EVENT_EOS) {
handle_server_setup_error(VC_EVENT_EOS, data);
} else {
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
break;
}
// FALLTHROUGH (since we are allowing the parse error)
}
case PARSE_RESULT_DONE:
DebugSM("http_seq", "Done parsing server response header");
// Now that we know that we have all of the origin server
// response headers, we can reset the client inactivity
// timeout. This is unlikely to cause a recurrence of
// old bug because there will be no more retries now that
// the connection has been established. It is possible
// however. We do not need to reset the inactivity timeout
// if the request contains a body (noted by the
// request_content_length field) because it was never
// canceled.
//
// we now reset the client inactivity timeout only
// when we are ready to send the response headers. In the
// case of transform plugin, this is after the transform
// outputs the 1st byte, which can take a long time if the
// plugin buffers the whole response.
// Also, if the request contains a body, we cancel the timeout
// when we read the 1st byte of the origin server response.
/*
if (ua_session && !t_state.hdr_info.request_content_length) {
ua_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(
HttpConfig::m_master.accept_no_activity_timeout));
}
*/
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
t_state.transact_return_point = HttpTransact::HandleResponse;
t_state.api_next_action = HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR;
// if exceeded limit deallocate postdata buffers and disable redirection
if (enable_redirection && (redirection_tries < t_state.txn_conf->number_of_redirections)) {
++redirection_tries;
} else {
tunnel.deallocate_redirect_postdata_buffers();
enable_redirection = false;
}
do_api_callout();
break;
case PARSE_RESULT_CONT:
ink_assert(server_entry->eos == false);
server_entry->read_vio->reenable();
return VC_EVENT_CONT;
default:
ink_assert(!"not reached");
}
return 0;
}
int
HttpSM::state_send_server_request_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_send_server_request_header, event);
ink_assert(server_entry != nullptr);
ink_assert(server_entry->write_vio == (VIO *)data || server_entry->read_vio == (VIO *)data);
int method;
switch (event) {
case VC_EVENT_WRITE_READY:
server_entry->write_vio->reenable();
break;
case VC_EVENT_WRITE_COMPLETE:
// We are done sending the request header, deallocate
// our buffer and then decide what to do next
free_MIOBuffer(server_entry->write_buffer);
server_entry->write_buffer = nullptr;
method = t_state.hdr_info.server_request.method_get_wksidx();
if (!t_state.api_server_request_body_set && method != HTTP_WKSIDX_TRACE &&
(t_state.hdr_info.request_content_length > 0 || t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
if (post_transform_info.vc) {
setup_transform_to_server_transfer();
} else {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
} else {
// It's time to start reading the response
setup_server_read_response_header();
}
break;
case VC_EVENT_READ_READY:
// We already did the read for the response header and
// we got some data. Wait for the request header
// send before dealing with it. However, we need to
// disable further IO here since the whole response
// may be in the buffer and we can not switch buffers
// on the io core later
ink_assert(server_entry->read_vio == (VIO *)data);
// setting nbytes to ndone would disable reads and remove it from the read queue.
// We can't do this in the epoll paradigm because we may be missing epoll errors that would
// prevent us from leaving this state.
// setup_server_read_response_header will trigger READ_READY to itself if there is data in the buffer.
// server_entry->read_vio->nbytes = server_entry->read_vio->ndone;
break;
case VC_EVENT_EOS:
// EOS of stream comes from the read side. Treat it as
// as error if there is nothing in the read buffer. If
// there is something the server may have blasted back
// the response before receiving the request. Happens
// often with redirects
//
// If we are in the middle of an api callout, it
// means we haven't actually sent the request yet
// so the stuff in the buffer is garbage and we
// want to ignore it
//
server_entry->eos = true;
// I'm not sure about the above comment, but if EOS is received on read and we are
// still in this state, we must have not gotten WRITE_COMPLETE. With epoll we might not receive EOS
// from both read and write sides of a connection so it should be handled correctly (close tunnels,
// deallocate, etc) here with handle_server_setup_error(). Otherwise we might hang due to not shutting
// down and never receiving another event again.
/*if (server_buffer_reader->read_avail() > 0 && callout_state == HTTP_API_NO_CALLOUT) {
break;
} */
// Nothing in the buffer
// FALLTHROUGH to error
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
handle_server_setup_error(event, data);
break;
case VC_EVENT_READ_COMPLETE:
// new event expected due to TS-3189
DebugSM("http_ss", "read complete due to 0 byte do_io_read");
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
void
HttpSM::process_srv_info(HostDBInfo *r)
{
DebugSM("dns_srv", "beginning process_srv_info");
t_state.hostdb_entry = Ptr<HostDBInfo>(r);
/* we didn't get any SRV records, continue w normal lookup */
if (!r || !r->is_srv || !r->round_robin) {
t_state.dns_info.srv_hostname[0] = '\0';
t_state.dns_info.srv_lookup_success = false;
t_state.txn_conf->srv_enabled = false;
DebugSM("dns_srv", "No SRV records were available, continuing to lookup %s", t_state.dns_info.lookup_name);
} else {
HostDBRoundRobin *rr = r->rr();
HostDBInfo *srv = nullptr;
if (rr) {
srv = rr->select_best_srv(t_state.dns_info.srv_hostname, &mutex->thread_holding->generator, ink_cluster_time(),
(int)t_state.txn_conf->down_server_timeout);
}
if (!srv) {
t_state.dns_info.srv_lookup_success = false;
t_state.dns_info.srv_hostname[0] = '\0';
t_state.txn_conf->srv_enabled = false;
DebugSM("dns_srv", "SRV records empty for %s", t_state.dns_info.lookup_name);
} else {
t_state.dns_info.srv_lookup_success = true;
t_state.dns_info.srv_port = srv->data.srv.srv_port;
t_state.dns_info.srv_app = srv->app;
// t_state.dns_info.single_srv = (rr->good == 1);
ink_assert(srv->data.srv.key == makeHostHash(t_state.dns_info.srv_hostname));
DebugSM("dns_srv", "select SRV records %s", t_state.dns_info.srv_hostname);
}
}
return;
}
void
HttpSM::process_hostdb_info(HostDBInfo *r)
{
// Increment the refcount to our item, since we are pointing at it
t_state.hostdb_entry = Ptr<HostDBInfo>(r);
sockaddr const *client_addr = nullptr;
bool use_client_addr = t_state.http_config_param->use_client_target_addr == 1 && t_state.client_info.is_transparent &&
t_state.dns_info.os_addr_style == HttpTransact::DNSLookupInfo::OS_ADDR_TRY_DEFAULT;
if (use_client_addr) {
NetVConnection *vc = t_state.state_machine->ua_session ? t_state.state_machine->ua_session->get_netvc() : nullptr;
if (vc) {
client_addr = vc->get_local_addr();
// Regardless of whether the client address matches the DNS record or not,
// we want to use that address. Therefore, we copy over the client address
// info and skip the assignment from the DNS cache
ats_ip_copy(t_state.host_db_info.ip(), client_addr);
t_state.dns_info.os_addr_style = HttpTransact::DNSLookupInfo::OS_ADDR_TRY_CLIENT;
t_state.dns_info.lookup_success = true;
// Leave ret unassigned, so we don't overwrite the host_db_info
} else {
use_client_addr = false;
}
}
if (r && !r->is_failed()) {
ink_time_t now = ink_cluster_time();
HostDBInfo *ret = nullptr;
t_state.dns_info.lookup_success = true;
t_state.dns_info.lookup_validated = true;
HostDBRoundRobin *rr = r->round_robin ? r->rr() : nullptr;
if (rr) {
// if use_client_target_addr is set, make sure the client addr is in the results pool
if (use_client_addr && rr->find_ip(client_addr) == nullptr) {
DebugSM("http", "use_client_target_addr == 1. Client specified address is not in the pool, not validated.");
t_state.dns_info.lookup_validated = false;
} else {
// Since the time elapsed between current time and client_request_time
// may be very large, we cannot use client_request_time to approximate
// current time when calling select_best_http().
ret = rr->select_best_http(&t_state.client_info.src_addr.sa, now, static_cast<int>(t_state.txn_conf->down_server_timeout));
// set the srv target`s last_failure
if (t_state.dns_info.srv_lookup_success) {
uint32_t last_failure = 0xFFFFFFFF;
for (int i = 0; i < rr->rrcount && last_failure != 0; ++i) {
if (last_failure > rr->info(i).app.http_data.last_failure) {
last_failure = rr->info(i).app.http_data.last_failure;
}
}
if (last_failure != 0 && (uint32_t)(now - t_state.txn_conf->down_server_timeout) < last_failure) {
HostDBApplicationInfo app;
app.allotment.application1 = 0;
app.allotment.application2 = 0;
app.http_data.last_failure = last_failure;
hostDBProcessor.setby_srv(t_state.dns_info.lookup_name, 0, t_state.dns_info.srv_hostname, &app);
}
}
}
} else {
if (use_client_addr && !ats_ip_addr_eq(client_addr, &r->data.ip.sa)) {
DebugSM("http", "use_client_target_addr == 1. Comparing single addresses failed, not validated.");
t_state.dns_info.lookup_validated = false;
} else {
ret = r;
}
}
if (ret) {
t_state.host_db_info = *ret;
ink_release_assert(!t_state.host_db_info.reverse_dns);
ink_release_assert(ats_is_ip(t_state.host_db_info.ip()));
}
} else {
DebugSM("http", "[%" PRId64 "] DNS lookup failed for '%s'", sm_id, t_state.dns_info.lookup_name);
if (!use_client_addr) {
t_state.dns_info.lookup_success = false;
}
t_state.host_db_info.app.allotment.application1 = 0;
t_state.host_db_info.app.allotment.application2 = 0;
ink_assert(!t_state.host_db_info.round_robin);
}
milestones[TS_MILESTONE_DNS_LOOKUP_END] = Thread::get_hrtime();
if (is_debug_tag_set("http_timeout")) {
if (t_state.api_txn_dns_timeout_value != -1) {
int foo = (int)(milestones.difference_msec(TS_MILESTONE_DNS_LOOKUP_BEGIN, TS_MILESTONE_DNS_LOOKUP_END));
DebugSM("http_timeout", "DNS took: %d msec", foo);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_hostdb_lookup()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_hostdb_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_hostdb_lookup, event);
// ink_assert (m_origin_server_vc == 0);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed into
// REQ_FLAVOR_REVPROXY
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_HOST_DB_LOOKUP:
pending_action = nullptr;
process_hostdb_info((HostDBInfo *)data);
call_transact_and_set_next_state(nullptr);
break;
case EVENT_SRV_LOOKUP: {
pending_action = nullptr;
process_srv_info((HostDBInfo *)data);
char *host_name = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_hostname : t_state.dns_info.lookup_name;
HostDBProcessor::Options opt;
opt.port = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_port : t_state.server_info.dst_addr.host_order_port();
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ua_session->get_host_res_style();
Action *dns_lookup_action_handle =
hostDBProcessor.getbyname_imm(this, (process_hostdb_info_pfn)&HttpSM::process_hostdb_info, host_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
} break;
case EVENT_HOST_DB_IP_REMOVED:
ink_assert(!"Unexpected event from HostDB");
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
int
HttpSM::state_hostdb_reverse_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_hostdb_reverse_lookup, event);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed into
// REQ_FLAVOR_REVPROXY
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_HOST_DB_LOOKUP:
pending_action = nullptr;
if (data) {
t_state.request_data.hostname_str = ((HostDBInfo *)data)->hostname();
} else {
DebugSM("http", "[%" PRId64 "] reverse DNS lookup failed for '%s'", sm_id, t_state.dns_info.lookup_name);
}
call_transact_and_set_next_state(nullptr);
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM:state_mark_os_down()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_mark_os_down(int event, void *data)
{
HostDBInfo *mark_down = nullptr;
if (event == EVENT_HOST_DB_LOOKUP && data) {
HostDBInfo *r = (HostDBInfo *)data;
if (r->round_robin) {
// Look for the entry we need mark down in the round robin
ink_assert(t_state.current.server != nullptr);
ink_assert(t_state.current.request_to == HttpTransact::ORIGIN_SERVER);
if (t_state.current.server) {
mark_down = r->rr()->find_ip(&t_state.current.server->dst_addr.sa);
}
} else {
// No longer a round robin, check to see if our address is the same
if (ats_ip_addr_eq(t_state.host_db_info.ip(), r->ip())) {
mark_down = r;
}
}
if (mark_down) {
mark_host_failure(mark_down, t_state.request_sent_time);
}
}
// We either found our entry or we did not. Either way find
// the entry we should use now
return state_hostdb_lookup(event, data);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_handle_stat_page()
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_handle_stat_page(int event, void *data)
{
STATE_ENTER(&HttpSM::state_handle_stat_page, event);
switch (event) {
case STAT_PAGE_SUCCESS:
pending_action = nullptr;
if (data) {
StatPageData *spd = (StatPageData *)data;
t_state.internal_msg_buffer = spd->data;
if (spd->type) {
t_state.internal_msg_buffer_type = spd->type;
} else {
t_state.internal_msg_buffer_type = nullptr; // Defaults to text/html
}
t_state.internal_msg_buffer_size = spd->length;
t_state.internal_msg_buffer_fast_allocator_size = -1;
}
call_transact_and_set_next_state(HttpTransact::HandleStatPage);
break;
case STAT_PAGE_FAILURE:
pending_action = nullptr;
call_transact_and_set_next_state(HttpTransact::HandleStatPage);
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
///////////////////////////////////////////////////////////////
//
// HttpSM::state_auth_callback()
//
///////////////////////////////////////////////////////////////
// int
// HttpSM::state_auth_callback(int event, void *data)
//{
// STATE_ENTER(&HttpSM::state_auth_lookup, event);
// ink_release_assert(ua_entry != NULL);
// pending_action = NULL;
// if (event == AUTH_MODULE_EVENT) {
// authAdapter.HandleAuthResponse(event, data);
//} else {
// ink_release_assert(!"Unknown authentication module event");
//}
/************************************************************************\
* pending_action=ACTION_RESULT_DONE only if Authentication step has *
* been done & authorization is left *
* pending_action=NULL only if we have to set_next_state. *
* pending_action=something else. Don't do anything. *
* One more callback is pending *
\************************************************************************/
// if (authAdapter.stateChangeRequired()) {
// set_next_state();
//}
// OLD AND UGLY: if (pending_action == NULL) {
// OLD AND UGLY: pending_action=NULL;
// OLD AND UGLY: } else if(pending_action == ACTION_RESULT_DONE) {
// OLD AND UGLY: pending_action=NULL;
// OLD AND UGLY: }
// return EVENT_DONE;
//}
///////////////////////////////////////////////////////////////
//
// HttpSM::state_icp_lookup()
//
///////////////////////////////////////////////////////////////
int
HttpSM::state_icp_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_icp_lookup, event);
// ua_entry is NULL for scheduled updates
ink_release_assert(ua_entry != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
pending_action = nullptr;
switch (event) {
case ICP_LOOKUP_FOUND:
DebugSM("http", "ICP says ICP_LOOKUP_FOUND");
t_state.icp_lookup_success = true;
t_state.icp_ip_result = *(struct sockaddr_in *)data;
/*
* Disable ICP loop detection since the Cidera network
* insists on trying to preload the cache from a
* a sibling cache.
*
* // inhibit bad ICP looping behavior
* if (t_state.icp_ip_result.sin_addr.s_addr ==
* t_state.client_info.ip) {
* DebugSM("http","Loop in ICP config, bypassing...");
* t_state.icp_lookup_success = false;
* }
*/
break;
case ICP_LOOKUP_FAILED:
DebugSM("http", "ICP says ICP_LOOKUP_FAILED");
t_state.icp_lookup_success = false;
break;
default:
ink_release_assert(0);
break;
}
call_transact_and_set_next_state(HttpTransact::HandleICPLookup);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////
// HttpSM::state_cache_open_write()
//
// This state is set by set_next_state() for a cache open write
// (SERVER_READ_CACHE_WRITE)
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_cache_open_write(int event, void *data)
{
STATE_ENTER(&HttpSM : state_cache_open_write, event);
// Make sure we are on the "right" thread
if (ua_session) {
if ((pending_action = ua_session->adjust_thread(this, event, data))) {
return 0; // Go away if we reschedule
}
}
milestones[TS_MILESTONE_CACHE_OPEN_WRITE_END] = Thread::get_hrtime();
pending_action = nullptr;
switch (event) {
case CACHE_EVENT_OPEN_WRITE:
//////////////////////////////
// OPEN WRITE is successful //
//////////////////////////////
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_SUCCESS;
break;
case CACHE_EVENT_OPEN_WRITE_FAILED:
// Failed on the write lock and retrying the vector
// for reading
if (t_state.redirect_info.redirect_in_process) {
DebugSM("http_redirect", "[%" PRId64 "] CACHE_EVENT_OPEN_WRITE_FAILED during redirect follow", sm_id);
t_state.cache_open_write_fail_action = HttpTransact::CACHE_WL_FAIL_ACTION_DEFAULT;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
}
if (t_state.txn_conf->cache_open_write_fail_action == HttpTransact::CACHE_WL_FAIL_ACTION_DEFAULT) {
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
} else {
t_state.cache_open_write_fail_action = t_state.txn_conf->cache_open_write_fail_action;
if (!t_state.cache_info.object_read ||
(t_state.cache_open_write_fail_action == HttpTransact::CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_OR_REVALIDATE)) {
// cache miss, set wl_state to fail
DebugSM("http", "[%" PRId64 "] cache object read %p, cache_wl_fail_action %d", sm_id, t_state.cache_info.object_read,
t_state.cache_open_write_fail_action);
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
}
}
// INTENTIONAL FALL THROUGH
// Allow for stale object to be served
case CACHE_EVENT_OPEN_READ:
// The write vector was locked and the cache_sm retried
// and got the read vector again.
cache_sm.cache_read_vc->get_http_info(&t_state.cache_info.object_read);
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (cache_sm.cache_read_vc->is_ram_cache_hit()) {
t_state.cache_info.hit_miss_code = SQUID_HIT_RAM;
} else {
t_state.cache_info.hit_miss_code = SQUID_HIT_DISK;
}
ink_assert(t_state.cache_info.object_read != nullptr);
t_state.source = HttpTransact::SOURCE_CACHE;
// clear up CACHE_LOOKUP_MISS, let Freshness function decide
// hit status
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_READ_RETRY;
break;
case HTTP_TUNNEL_EVENT_DONE:
// In the case where we have issued a cache write for the
// transformed copy, the tunnel from the origin server to
// the transform may complete while we are waiting for
// the cache write. If this is the case, forward the event
// to the transform read state as it will know how to
// handle it
if (t_state.next_action == HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM) {
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
return 0;
}
// Fallthrough
default:
ink_release_assert(0);
}
if (t_state.api_lock_url != HttpTransact::LOCK_URL_FIRST) {
if (event == CACHE_EVENT_OPEN_WRITE || event == CACHE_EVENT_OPEN_WRITE_FAILED) {
if (t_state.api_lock_url == HttpTransact::LOCK_URL_SECOND) {
t_state.api_lock_url = HttpTransact::LOCK_URL_ORIGINAL;
do_cache_prepare_action(second_cache_sm, t_state.cache_info.second_object_read, true);
return 0;
} else {
t_state.api_lock_url = HttpTransact::LOCK_URL_DONE;
}
} else if (event != CACHE_EVENT_OPEN_READ || t_state.api_lock_url != HttpTransact::LOCK_URL_SECOND) {
t_state.api_lock_url = HttpTransact::LOCK_URL_QUIT;
}
}
// The write either succeeded or failed, notify transact
call_transact_and_set_next_state(nullptr);
return 0;
}
inline void
HttpSM::setup_cache_lookup_complete_api()
{
t_state.api_next_action = HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE;
do_api_callout();
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_cache_open_read()
//
// This state handles the result of CacheProcessor::open_read()
// that attempts to do cache lookup and open a particular cached
// object for reading.
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_cache_open_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_cache_open_read, event);
milestones[TS_MILESTONE_CACHE_OPEN_READ_END] = Thread::get_hrtime();
ink_assert(server_entry == nullptr);
ink_assert(t_state.cache_info.object_read == nullptr);
switch (event) {
case CACHE_EVENT_OPEN_READ: {
pending_action = nullptr;
DebugSM("http", "[%" PRId64 "] cache_open_read - CACHE_EVENT_OPEN_READ", sm_id);
/////////////////////////////////
// lookup/open is successful. //
/////////////////////////////////
ink_assert(cache_sm.cache_read_vc != nullptr);
t_state.source = HttpTransact::SOURCE_CACHE;
cache_sm.cache_read_vc->get_http_info(&t_state.cache_info.object_read);
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (cache_sm.cache_read_vc->is_ram_cache_hit()) {
t_state.cache_info.hit_miss_code = SQUID_HIT_RAM;
} else {
t_state.cache_info.hit_miss_code = SQUID_HIT_DISK;
}
ink_assert(t_state.cache_info.object_read != nullptr);
call_transact_and_set_next_state(HttpTransact::HandleCacheOpenRead);
break;
}
case CACHE_EVENT_OPEN_READ_FAILED:
pending_action = nullptr;
DebugSM("http", "[%" PRId64 "] cache_open_read - CACHE_EVENT_OPEN_READ_FAILED with %s (%d)", sm_id,
InkStrerror(-(intptr_t)data), (int)(intptr_t)data);
DebugSM("http", "[state_cache_open_read] open read failed.");
// Inform HttpTransact somebody else is updating the document
// HttpCacheSM already waited so transact should go ahead.
if ((intptr_t)data == -ECACHE_DOC_BUSY) {
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_DOC_BUSY;
} else {
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_MISS;
}
ink_assert(t_state.transact_return_point == nullptr);
t_state.transact_return_point = HttpTransact::HandleCacheOpenRead;
setup_cache_lookup_complete_api();
break;
default:
ink_release_assert("!Unknown event");
break;
}
return 0;
}
int
HttpSM::main_handler(int event, void *data)
{
ink_release_assert(magic == HTTP_SM_MAGIC_ALIVE);
HttpSMHandler jump_point = nullptr;
ink_assert(reentrancy_count >= 0);
reentrancy_count++;
// Don't use the state enter macro since it uses history
// space that we don't care about
DebugSM("http", "[%" PRId64 "] [HttpSM::main_handler, %s]", sm_id, HttpDebugNames::get_event_name(event));
HttpVCTableEntry *vc_entry = nullptr;
if (data != nullptr) {
// Only search the VC table if the event could have to
// do with a VIO to save a few cycles
if (event < VC_EVENT_EVENTS_START + 100) {
vc_entry = vc_table.find_entry((VIO *)data);
}
}
if (vc_entry) {
jump_point = vc_entry->vc_handler;
ink_assert(jump_point != (HttpSMHandler) nullptr);
ink_assert(vc_entry->vc != (VConnection *)nullptr);
(this->*jump_point)(event, data);
} else {
ink_assert(default_handler != (HttpSMHandler) nullptr);
(this->*default_handler)(event, data);
}
// The sub-handler signals when it is time for the state
// machine to exit. We can only exit if we are not reentrantly
// called otherwise when the our call unwinds, we will be
// running on a dead state machine
//
// Because of the need for an api shutdown hook, kill_this()
// is also reentrant. As such, we don't want to decrement
// the reentrancy count until after we run kill_this()
//
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
reentrancy_count--;
ink_assert(reentrancy_count >= 0);
}
return (VC_EVENT_CONT);
}
// void HttpSM::tunnel_handler_post_or_put()
//
// Handles the common cleanup tasks for Http post/put
// to prevent code duplication
//
void
HttpSM::tunnel_handler_post_or_put(HttpTunnelProducer *p)
{
ink_assert(p->vc_type == HT_HTTP_CLIENT);
HttpTunnelConsumer *c;
// If there is a post transform, remove it's entry from the State
// Machine's VC table
//
// MUST NOT clear the vc pointer from post_transform_info
// as this causes a double close of the transform vc in transform_cleanup
//
if (post_transform_info.vc != nullptr) {
ink_assert(post_transform_info.entry->in_tunnel == true);
ink_assert(post_transform_info.vc == post_transform_info.entry->vc);
vc_table.cleanup_entry(post_transform_info.entry);
post_transform_info.entry = nullptr;
}
switch (p->handler_state) {
case HTTP_SM_POST_SERVER_FAIL:
c = tunnel.get_consumer(server_entry->vc);
ink_assert(c->write_success == false);
break;
case HTTP_SM_POST_UA_FAIL:
// UA quit - shutdown the SM
ink_assert(p->read_success == false);
terminate_sm = true;
break;
case HTTP_SM_POST_SUCCESS:
// The post succeeded
ink_assert(p->read_success == true);
ink_assert(p->consumer_list.head->write_success == true);
tunnel.deallocate_buffers();
tunnel.reset();
// When the ua completed sending it's data we must have
// removed it from the tunnel
ink_release_assert(ua_entry->in_tunnel == false);
server_entry->in_tunnel = false;
break;
default:
ink_release_assert(0);
}
}
// int HttpSM::tunnel_handler_post(int event, void* data)
//
// Handles completion of any http request body tunnel
// Having 'post' in its name is a misnomer
//
int
HttpSM::tunnel_handler_post(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_post, event);
HttpTunnelProducer *p = ua_session != nullptr ? tunnel.get_producer(ua_session) : tunnel.get_producer(HT_HTTP_CLIENT);
if (!p) {
return 0; // Cannot do anything if there is no producer
}
if (event != HTTP_TUNNEL_EVENT_DONE) {
if ((event == VC_EVENT_WRITE_COMPLETE) || (event == VC_EVENT_EOS)) {
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
}
if (p->handler_state == HTTP_SM_POST_UA_FAIL) {
Debug("http_tunnel", "cleanup tunnel in tunnel_handler_post");
hsm_release_assert(ua_entry->in_tunnel == true);
ink_assert((event == VC_EVENT_WRITE_COMPLETE) || (event == VC_EVENT_EOS));
vc_table.cleanup_all();
tunnel.chain_abort_all(p);
p->read_vio = nullptr;
p->vc->do_io_close(EHTTP_ERROR);
tunnel_handler_post_or_put(p);
tunnel.kill_tunnel();
return 0;
}
}
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// The tunnel calls this when it is done
int p_handler_state = p->handler_state;
tunnel_handler_post_or_put(p);
switch (p_handler_state) {
case HTTP_SM_POST_SERVER_FAIL:
handle_post_failure();
break;
case HTTP_SM_POST_UA_FAIL:
break;
case HTTP_SM_POST_SUCCESS:
// It's time to start reading the response
setup_server_read_response_header();
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::tunnel_handler_cache_fill(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_fill, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
ink_release_assert(cache_sm.cache_write_vc);
tunnel.deallocate_buffers();
tunnel.deallocate_redirect_postdata_buffers();
tunnel.reset();
setup_server_transfer_to_cache_only();
tunnel.tunnel_run();
return 0;
}
int
HttpSM::tunnel_handler_100_continue(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_100_continue, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// We're done sending the 100 continue. If we succeeded,
// we set up to parse the next server response. If we
// failed, shutdown the state machine
HttpTunnelConsumer *c = tunnel.get_consumer(ua_session);
if (c->write_success) {
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.client_response.destroy();
tunnel.deallocate_buffers();
tunnel.deallocate_redirect_postdata_buffers();
tunnel.reset();
if (server_entry->eos) {
// if the server closed while sending the
// 100 continue header, handle it here so we
// don't assert later
DebugSM("http", "[%" PRId64 "] tunnel_handler_100_continue - server already "
"closed, terminating connection",
sm_id);
// Since 100 isn't a final (loggable) response header
// kill the 100 continue header and create an empty one
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
handle_server_setup_error(VC_EVENT_EOS, server_entry->read_vio);
} else {
setup_server_read_response_header();
}
} else {
terminate_sm = true;
}
return 0;
}
int
HttpSM::tunnel_handler_push(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_push, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// Check to see if the client is still around
HttpTunnelProducer *ua = (ua_session) ? tunnel.get_producer(ua_session) : tunnel.get_producer(HT_HTTP_CLIENT);
if (ua && !ua->read_success) {
// Client failed to send the body, it's gone. Kill the
// state machine
terminate_sm = true;
return 0;
}
HttpTunnelConsumer *cache = ua->consumer_list.head;
ink_release_assert(cache->vc_type == HT_CACHE_WRITE);
bool cache_write_success = cache->write_success;
// Reset tunneling state since we need to send a response
// to client as whether we succeeded
tunnel.deallocate_buffers();
tunnel.deallocate_redirect_postdata_buffers();
tunnel.reset();
if (cache_write_success) {
call_transact_and_set_next_state(HttpTransact::HandlePushTunnelSuccess);
} else {
call_transact_and_set_next_state(HttpTransact::HandlePushTunnelFailure);
}
return 0;
}
int
HttpSM::tunnel_handler(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// The tunnel calls this when it is done
terminate_sm = true;
if (unlikely(t_state.is_websocket)) {
HTTP_DECREMENT_DYN_STAT(http_websocket_current_active_client_connections_stat);
}
return 0;
}
/****************************************************
TUNNELING HANDLERS
******************************************************/
bool
HttpSM::is_http_server_eos_truncation(HttpTunnelProducer *p)
{
if ((p->do_dechunking || p->do_chunked_passthru) && p->chunked_handler.truncation) {
// TS-3054 - In the chunked cases, chunked data that is incomplete
// should not be cached, but it should be passed onto the client
// This makes ATS more transparent in the case of non-standard
// servers. The cache aborts are dealt with in other checks
// on the truncation flag elsewhere in the code. This return value
// invalidates the current data being passed over to the client.
// So changing it from return true to return false, so the partial data
// is passed onto the client.
return false;
}
//////////////////////////////////////////////////////////////
// If we did not get or did not trust the origin server's //
// content-length, read_content_length is unset. The //
// only way the end of the document is signaled is the //
// origin server closing the connection. However, we //
// need to protect against the document getting truncated //
// because the origin server crashed. The following //
// tabled outlines when we mark the server read as failed //
// //
// No C-L : read success //
// Received byts < C-L : read failed (=> Cache Abort) //
// Received byts == C-L : read success //
// Received byts > C-L : read success //
//////////////////////////////////////////////////////////////
int64_t cl = t_state.hdr_info.server_response.get_content_length();
if (cl != UNDEFINED_COUNT && cl > server_response_body_bytes) {
DebugSM("http", "[%" PRId64 "] server EOS after %" PRId64 " bytes, expected %" PRId64, sm_id, server_response_body_bytes, cl);
return true;
} else {
return false;
}
}
int
HttpSM::tunnel_handler_server(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_server, event);
milestones[TS_MILESTONE_SERVER_CLOSE] = Thread::get_hrtime();
bool close_connection = false;
if (t_state.current.server->keep_alive == HTTP_KEEPALIVE && server_entry->eos == false &&
plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL && t_state.txn_conf->keep_alive_enabled_out == 1) {
close_connection = false;
} else {
close_connection = true;
}
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
t_state.squid_codes.log_code = SQUID_LOG_ERR_READ_TIMEOUT;
t_state.squid_codes.hier_code = SQUID_HIER_TIMEOUT_DIRECT;
/* fallthru */
case VC_EVENT_EOS:
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.current.server->state = HttpTransact::INACTIVE_TIMEOUT;
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.current.server->state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_ERROR:
t_state.current.server->state = HttpTransact::CONNECTION_ERROR;
break;
case VC_EVENT_EOS:
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
break;
}
close_connection = true;
ink_assert(p->vc_type == HT_HTTP_SERVER);
if (is_http_server_eos_truncation(p)) {
DebugSM("http", "[%" PRId64 "] [HttpSM::tunnel_handler_server] aborting HTTP tunnel due to server truncation", sm_id);
tunnel.chain_abort_all(p);
// UA session may not be in the tunnel yet, don't NULL out the pointer in that case.
// Note: This is a hack. The correct solution is for the UA session to signal back to the SM
// when the UA is about to be destroyed and clean up the pointer there. That should be done once
// the TS-3612 changes are in place (and similarly for the server session).
/*if (ua_entry->in_tunnel)
ua_session = NULL; */
t_state.current.server->abort = HttpTransact::ABORTED;
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
t_state.squid_codes.log_code = SQUID_LOG_ERR_READ_ERROR;
} else {
DebugSM("http", "[%" PRId64 "] [HttpSM::tunnel_handler_server] finishing HTTP tunnel", sm_id);
p->read_success = true;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
// Appending reason to a response without Content-Length will result in
// the reason string being written to the client and a bad CL when reading from cache.
// I didn't find anywhere this appended reason is being used, so commenting it out.
/*
if (t_state.negative_caching && p->bytes_read == 0) {
int reason_len;
const char *reason = t_state.hdr_info.server_response.reason_get(&reason_len);
if (reason == NULL)
tunnel.append_message_to_producer_buffer(p, "Negative Response", sizeof("Negative Response") - 1);
else
tunnel.append_message_to_producer_buffer(p, reason, reason_len);
}
*/
tunnel.local_finish_all(p);
}
break;
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case VC_EVENT_READ_COMPLETE:
//
// The transfer completed successfully
// If there is still data in the buffer, the server
// sent too much indicating a failed transfer
p->read_success = true;
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
if (p->do_dechunking || p->do_chunked_passthru) {
if (p->chunked_handler.truncation) {
tunnel.abort_cache_write_finish_others(p);
// We couldn't read all chunks successfully:
// Disable keep-alive.
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
} else {
tunnel.local_finish_all(p);
}
}
break;
case HTTP_TUNNEL_EVENT_CONSUMER_DETACH:
// All consumers are prematurely gone. Shutdown
// the server connection
p->read_success = true;
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
close_connection = true;
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
// turn off negative caching in case there are multiple server contacts
if (t_state.negative_caching) {
t_state.negative_caching = false;
}
// If we had a ground fill, check update our status
if (background_fill == BACKGROUND_FILL_STARTED) {
background_fill = p->read_success ? BACKGROUND_FILL_COMPLETED : BACKGROUND_FILL_ABORTED;
HTTP_DECREMENT_DYN_STAT(http_background_fill_current_count_stat);
}
// We handled the event. Now either shutdown the connection or
// setup it up for keep-alive
ink_assert(server_entry->vc == p->vc);
ink_assert(p->vc_type == HT_HTTP_SERVER);
ink_assert(p->vc == server_session);
if (close_connection) {
p->vc->do_io_close();
server_session = nullptr; // Because p->vc == server_session
p->read_vio = nullptr;
/* TS-1424: if we're outbound transparent and using the client
source port for the outbound connection we must effectively
propagate server closes back to the client. Part of that is
disabling KeepAlive if the server closes.
*/
if (ua_session && ua_session->is_outbound_transparent() && t_state.http_config_param->use_client_source_port) {
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
} else {
server_session->attach_hostname(t_state.current.server->name);
server_session->server_trans_stat--;
HTTP_DECREMENT_DYN_STAT(http_current_server_transactions_stat);
// If the option to attach the server session to the client session is set
// and if the client is still around and the client is keep-alive, attach the
// server session to so the next ka request can use it. Server sessions will
// be placed into the shared pool if the next incoming request is for a different
// origin server
if (t_state.txn_conf->attach_server_session_to_client == 1 && ua_session && t_state.client_info.keep_alive == HTTP_KEEPALIVE) {
Debug("http", "attaching server session to the client");
ua_session->attach_server_session(server_session);
} else {
// Release the session back into the shared session pool
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
server_session->release();
}
}
return 0;
}
// int HttpSM::tunnel_handler_100_continue_ua(int event, HttpTunnelConsumer* c)
//
// Used for tunneling the 100 continue response. The tunnel
// should not close or release the user agent unless there is
// an error since the real response is yet to come
//
int
HttpSM::tunnel_handler_100_continue_ua(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_100_continue_ua, event);
ink_assert(c->vc == ua_session);
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// FALL-THROUGH
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
set_ua_abort(HttpTransact::ABORTED, event);
c->vc->do_io_close();
break;
case VC_EVENT_WRITE_COMPLETE:
// mark the vc as no longer in tunnel
// so we don't get hosed if the ua abort before
// real response header is received
ua_entry->in_tunnel = false;
c->write_success = true;
}
return 0;
}
bool
HttpSM::is_bg_fill_necessary(HttpTunnelConsumer *c)
{
ink_assert(c->vc_type == HT_HTTP_CLIENT);
if (c->producer->alive && // something there to read
server_entry && server_entry->vc && // from an origin server
server_session && server_session->get_netvc() && // which is still open and valid
c->producer->num_consumers > 1 // with someone else reading it
) {
// If threshold is 0.0 or negative then do background
// fill regardless of the content length. Since this
// is floating point just make sure the number is near zero
if (t_state.txn_conf->background_fill_threshold <= 0.001) {
return true;
}
int64_t ua_cl = t_state.hdr_info.client_response.get_content_length();
if (ua_cl > 0) {
int64_t ua_body_done = c->bytes_written - client_response_hdr_bytes;
float pDone = (float)ua_body_done / ua_cl;
// If we got a good content length. Check to make sure that we haven't already
// done more the content length since that would indicate the content-length
// is bogus. If we've done more than the threshold, continue the background fill
if (pDone <= 1.0 && pDone > t_state.txn_conf->background_fill_threshold) {
return true;
} else {
DebugSM("http", "[%" PRId64 "] no background. Only %%%f of %%%f done [%" PRId64 " / %" PRId64 " ]", sm_id, pDone,
t_state.txn_conf->background_fill_threshold, ua_body_done, ua_cl);
}
}
}
return false;
}
int
HttpSM::tunnel_handler_ua(int event, HttpTunnelConsumer *c)
{
bool close_connection = true;
HttpTunnelProducer *p = nullptr;
HttpTunnelConsumer *selfc = nullptr;
STATE_ENTER(&HttpSM::tunnel_handler_ua, event);
ink_assert(c->vc == ua_session);
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// FALL-THROUGH
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
// The user agent died or aborted. Check to
// see if we should setup a background fill
set_ua_abort(HttpTransact::ABORTED, event);
if (is_bg_fill_necessary(c)) {
DebugSM("http", "[%" PRId64 "] Initiating background fill", sm_id);
background_fill = BACKGROUND_FILL_STARTED;
HTTP_INCREMENT_DYN_STAT(http_background_fill_current_count_stat);
// There is another consumer (cache write) so
// detach the user agent
ink_assert(server_entry->vc == server_session);
ink_assert(c->is_downstream_from(server_session));
server_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->background_fill_active_timeout));
} else {
// No background fill
p = c->producer;
tunnel.chain_abort_all(c->producer);
selfc = p->self_consumer;
if (selfc) {
// This is the case where there is a transformation between ua and os
p = selfc->producer;
// if producer is the cache or OS, close the producer.
// Otherwise in case of large docs, producer iobuffer gets filled up,
// waiting for a consumer to consume data and the connection is never closed.
if (p->alive && ((p->vc_type == HT_CACHE_READ) || (p->vc_type == HT_HTTP_SERVER))) {
tunnel.chain_abort_all(p);
}
}
}
break;
case VC_EVENT_WRITE_COMPLETE:
c->write_success = true;
t_state.client_info.abort = HttpTransact::DIDNOT_ABORT;
if (t_state.client_info.keep_alive == HTTP_KEEPALIVE) {
if (t_state.www_auth_content != HttpTransact::CACHE_AUTH_SERVE || ua_session->get_server_session()) {
// successful keep-alive
close_connection = false;
}
// else { the authenticated server connection (cache
// authenticated feature) closed during the serve-from-cache.
// We want the client to issue a new connection for the
// session based authenticated mechanism like NTLM, instead
// of still using the existing client connection. }
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
client_response_body_bytes = c->bytes_written - client_response_hdr_bytes;
if (client_response_body_bytes < 0) {
client_response_body_bytes = 0;
}
// attribute the size written to the client from various sources
// NOTE: responses that go through a range transform are attributed
// to their original sources
// all other transforms attribute the total number of input bytes
// to a source in HttpSM::tunnel_handler_transform_write
//
HttpTransact::Source_t original_source = t_state.source;
if (HttpTransact::SOURCE_TRANSFORM == original_source && t_state.range_setup != HttpTransact::RANGE_NONE) {
original_source = t_state.pre_transform_source;
}
switch (original_source) {
case HttpTransact::SOURCE_HTTP_ORIGIN_SERVER:
server_response_body_bytes = client_response_body_bytes;
break;
case HttpTransact::SOURCE_CACHE:
cache_response_body_bytes = client_response_body_bytes;
break;
default:
break;
}
ink_assert(ua_entry->vc == c->vc);
if (close_connection) {
// If the client could be pipelining or is doing a POST, we need to
// set the ua_session into half close mode
// only external POSTs should be subject to this logic; ruling out internal POSTs here
bool is_eligible_post_request = (t_state.method == HTTP_WKSIDX_POST);
if (is_eligible_post_request) {
NetVConnection *vc = ua_session->get_netvc();
if (vc) {
is_eligible_post_request &= !vc->get_is_internal_request();
}
}
if ((is_eligible_post_request || t_state.client_info.pipeline_possible == true) && c->producer->vc_type != HT_STATIC &&
event == VC_EVENT_WRITE_COMPLETE) {
ua_session->set_half_close_flag(true);
}
ua_session->do_io_close();
} else {
ink_assert(ua_buffer_reader != nullptr);
ua_session->release(ua_buffer_reader);
ua_buffer_reader = nullptr;
// ua_session = NULL;
}
return 0;
}
int
HttpSM::tunnel_handler_ua_push(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_ua_push, event);
pushed_response_body_bytes += p->bytes_read;
client_request_body_bytes += p->bytes_read;
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
// Transfer terminated. Bail on the cache write.
t_state.client_info.abort = HttpTransact::ABORTED;
p->vc->do_io_close(EHTTP_ERROR);
p->read_vio = nullptr;
tunnel.chain_abort_all(p);
break;
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case VC_EVENT_READ_COMPLETE:
//
// The transfer completed successfully
p->read_success = true;
ua_entry->in_tunnel = false;
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
return 0;
}
int
HttpSM::tunnel_handler_cache_read(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_read, event);
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
ink_assert(t_state.cache_info.object_read->valid());
if (t_state.cache_info.object_read->object_size_get() != INT64_MAX || event == VC_EVENT_ERROR) {
// Abnormal termination
t_state.squid_codes.log_code = SQUID_LOG_TCP_SWAPFAIL;
p->vc->do_io_close(EHTTP_ERROR);
p->read_vio = nullptr;
tunnel.chain_abort_all(p);
HTTP_INCREMENT_DYN_STAT(http_cache_read_errors);
break;
} else {
tunnel.local_finish_all(p);
// fall through for the case INT64_MAX read with VC_EVENT_EOS
// callback (read successful)
}
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case HTTP_TUNNEL_EVENT_CONSUMER_DETACH:
p->read_success = true;
p->vc->do_io_close();
p->read_vio = nullptr;
break;
default:
ink_release_assert(0);
break;
}
HTTP_DECREMENT_DYN_STAT(http_current_cache_connections_stat);
return 0;
}
int
HttpSM::tunnel_handler_cache_write(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_write, event);
HttpTransact::CacheWriteStatus_t *status_ptr =
(c->producer->vc_type == HT_TRANSFORM) ? &t_state.cache_info.transform_write_status : &t_state.cache_info.write_status;
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
// Abnormal termination
*status_ptr = HttpTransact::CACHE_WRITE_ERROR;
c->write_vio = nullptr;
c->vc->do_io_close(EHTTP_ERROR);
HTTP_INCREMENT_DYN_STAT(http_cache_write_errors);
DebugSM("http", "[%" PRId64 "] aborting cache write due %s event from cache", sm_id, HttpDebugNames::get_event_name(event));
// abort the producer if the cache_writevc is the only consumer.
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.chain_abort_all(c->producer);
}
break;
case VC_EVENT_WRITE_COMPLETE:
// if we've never initiated a cache write
// abort the cache since it's finicky about a close
// in this case. This case can only occur
// we got a truncated header from the origin server
// but decided to accept it anyways
if (c->write_vio == nullptr) {
*status_ptr = HttpTransact::CACHE_WRITE_ERROR;
c->write_success = false;
c->vc->do_io_close(EHTTP_ERROR);
} else {
*status_ptr = HttpTransact::CACHE_WRITE_COMPLETE;
c->write_success = true;
c->write_vio = c->vc->do_io(VIO::CLOSE);
}
break;
default:
// All other events indicate problems
ink_assert(0);
break;
}
HTTP_DECREMENT_DYN_STAT(http_current_cache_connections_stat);
return 0;
}
int
HttpSM::tunnel_handler_post_ua(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_post_ua, event);
client_request_body_bytes = p->init_bytes_done + p->bytes_read;
int64_t alloc_index, nbytes;
IOBufferReader *buf_start;
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
if (client_response_hdr_bytes == 0) {
p->handler_state = HTTP_SM_POST_UA_FAIL;
set_ua_abort(HttpTransact::ABORTED, event);
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
HttpTransact::build_error_response(&t_state, HTTP_STATUS_REQUEST_TIMEOUT, "POST Request timeout", "timeout#inactivity",
nullptr);
break;
case VC_EVENT_ACTIVE_TIMEOUT:
HttpTransact::build_error_response(&t_state, HTTP_STATUS_REQUEST_TIMEOUT, "POST Request timeout", "timeout#activity",
nullptr);
break;
}
// send back 408 request timeout
alloc_index = buffer_size_to_index(len_408_request_timeout_response + t_state.internal_msg_buffer_size);
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
ua_entry->write_buffer = new_MIOBuffer(alloc_index);
buf_start = ua_entry->write_buffer->alloc_reader();
DebugSM("http_tunnel", "send 408 response to client to vc %p, tunnel vc %p", ua_session->get_netvc(), p->vc);
nbytes = ua_entry->write_buffer->write(str_408_request_timeout_response, len_408_request_timeout_response);
nbytes += ua_entry->write_buffer->write(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size);
p->vc->do_io_write(this, nbytes, buf_start);
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
return 0;
}
// fall through
case VC_EVENT_EOS:
// My reading of spec says that user agents can not terminate
// posts with a half close so this is an error
case VC_EVENT_ERROR:
// Did not complete post tunneling. Abort the
// server and close the ua
p->handler_state = HTTP_SM_POST_UA_FAIL;
set_ua_abort(HttpTransact::ABORTED, event);
tunnel.chain_abort_all(p);
p->read_vio = nullptr;
p->vc->do_io_close(EHTTP_ERROR);
// the in_tunnel status on both the ua & and
// it's consumer must already be set to true. Previously
// we were setting it again to true but incorrectly in
// the case of a transform
hsm_release_assert(ua_entry->in_tunnel == true);
if (p->consumer_list.head->vc_type == HT_TRANSFORM) {
hsm_release_assert(post_transform_info.entry->in_tunnel == true);
} else if (server_entry != nullptr) {
hsm_release_assert(server_entry->in_tunnel == true);
}
break;
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
p->handler_state = HTTP_SM_POST_SUCCESS;
p->read_success = true;
ua_entry->in_tunnel = false;
if (p->do_dechunking || p->do_chunked_passthru) {
if (p->chunked_handler.truncation) {
tunnel.abort_cache_write_finish_others(p);
} else {
tunnel.local_finish_all(p);
}
}
// Initiate another read to watch catch aborts and
// timeouts
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = p->vc->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
break;
default:
ink_release_assert(0);
}
return 0;
}
// YTS Team, yamsat Plugin
// Tunnel handler to deallocate the tunnel buffers and
// set redirect_in_process=false
// Copy partial POST data to buffers. Check for the various parameters including
// the maximum configured post data size
int
HttpSM::tunnel_handler_for_partial_post(int event, void * /* data ATS_UNUSED */)
{
STATE_ENTER(&HttpSM::tunnel_handler_for_partial_post, event);
tunnel.deallocate_buffers();
tunnel.reset();
tunnel.allocate_redirect_postdata_producer_buffer();
t_state.redirect_info.redirect_in_process = false;
if (post_failed) {
post_failed = false;
handle_post_failure();
} else {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
return 0;
}
int
HttpSM::tunnel_handler_post_server(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_post_server, event);
server_request_body_bytes = c->bytes_written;
switch (event) {
case VC_EVENT_EOS:
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// Did not complete post tunneling
//
// In the http case, we don't want to close
// the connection because the
// destroys the header buffer which may
// a response even though the tunnel failed.
// Shutdown both sides of the connection. This prevents us
// from getting any further events and signals to client
// that POST data will not be forwarded to the server. Doing
// shutdown on the write side will likely generate a TCP
// reset to the client but if the proxy wasn't here this is
// exactly what would happen.
// we should wait to shutdown read side of the
// client to prevent sending a reset
server_entry->eos = true;
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
// We may be reading from a transform. In that case, we
// want to close the transform
HttpTunnelProducer *ua_producer;
if (c->producer->vc_type == HT_TRANSFORM) {
if (c->producer->handler_state == HTTP_SM_TRANSFORM_OPEN) {
ink_assert(c->producer->vc == post_transform_info.vc);
c->producer->vc->do_io_close();
c->producer->alive = false;
c->producer->self_consumer->alive = false;
}
ua_producer = c->producer->self_consumer->producer;
} else {
ua_producer = c->producer;
}
ink_assert(ua_producer->vc_type == HT_HTTP_CLIENT);
ink_assert(ua_producer->vc == ua_session);
ink_assert(ua_producer->vc == ua_entry->vc);
// Before shutting down, initiate another read
// on the user agent in order to get timeouts
// coming to the state machine and not the tunnel
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
// YTS Team, yamsat Plugin
// When event is VC_EVENT_ERROR,and when redirection is enabled
// do not shut down the client read
if (enable_redirection) {
if (ua_producer->vc_type == HT_STATIC && event != VC_EVENT_ERROR && event != VC_EVENT_EOS) {
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
// ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
t_state.client_info.pipeline_possible = false;
} else {
if (ua_producer->vc_type == HT_STATIC && t_state.redirect_info.redirect_in_process) {
post_failed = true;
}
}
} else {
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
// we should not shutdown read side of the client here to prevent sending a reset
// ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
t_state.client_info.pipeline_possible = false;
} // end of added logic
// We want to shutdown the tunnel here and see if there
// is a response on from the server. Mark the user
// agent as down so that tunnel concludes.
ua_producer->alive = false;
ua_producer->handler_state = HTTP_SM_POST_SERVER_FAIL;
ink_assert(tunnel.is_tunnel_alive() == false);
break;
case VC_EVENT_WRITE_COMPLETE:
// Completed successfully
c->write_success = true;
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::tunnel_handler_ssl_producer(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_ssl_producer, event);
switch (event) {
case VC_EVENT_EOS:
// The write side of this connection is still alive
// so half-close the read
if (p->self_consumer->alive) {
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
tunnel.local_finish_all(p);
break;
}
// FALL THROUGH - both sides of the tunnel are dea
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The other side of the connection is either already dead
// or rendered inoperative by the error on the connection
// Note: use tunnel close vc so the tunnel knows we are
// nuking the of the connection as well
tunnel.close_vc(p);
tunnel.local_finish_all(p);
// Because we've closed the net vc this error came in, it's write
// direction is now dead as well. If that side still being fed data,
// we need to kill that pipe as well
if (p->self_consumer->producer->alive) {
p->self_consumer->producer->alive = false;
if (p->self_consumer->producer->self_consumer->alive) {
p->self_consumer->producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
tunnel.close_vc(p->self_consumer->producer);
}
}
break;
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
// We should never get these event since we don't know
// how long the stream is
default:
ink_release_assert(0);
}
// Update stats
switch (p->vc_type) {
case HT_HTTP_SERVER:
server_response_body_bytes += p->bytes_read;
break;
case HT_HTTP_CLIENT:
client_request_body_bytes += p->bytes_read;
break;
default:
// Covered here:
// HT_CACHE_READ, HT_CACHE_WRITE,
// HT_TRANSFORM, HT_STATIC.
break;
}
return 0;
}
int
HttpSM::tunnel_handler_ssl_consumer(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_ssl_consumer, event);
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// we need to mark the producer dead
// otherwise it can stay alive forever.
if (c->producer->alive) {
c->producer->alive = false;
if (c->producer->self_consumer->alive) {
c->producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
tunnel.close_vc(c->producer);
}
}
// Since we are changing the state of the self_producer
// we must have the tunnel shutdown the vc
tunnel.close_vc(c);
tunnel.local_finish_all(c->self_producer);
break;
case VC_EVENT_WRITE_COMPLETE:
// If we get this event, it means that the producer
// has finished and we wrote the remaining data
// to the consumer
//
// If the read side of this connection has not yet
// closed, do a write half-close and then wait for
// read side to close so that we don't cut off
// pipelined responses with TCP resets
//
// ink_assert(c->producer->alive == false);
c->write_success = true;
if (c->self_producer->alive == true) {
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
} else {
c->vc->do_io_close();
}
break;
default:
ink_release_assert(0);
}
// Update stats
switch (c->vc_type) {
case HT_HTTP_SERVER:
server_request_body_bytes += c->bytes_written;
break;
case HT_HTTP_CLIENT:
client_response_body_bytes += c->bytes_written;
break;
default:
// Handled here:
// HT_CACHE_READ, HT_CACHE_WRITE, HT_TRANSFORM,
// HT_STATIC
break;
}
return 0;
}
int
HttpSM::tunnel_handler_transform_write(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_transform_write, event);
HttpTransformInfo *i;
// Figure out if this the request or response transform
// : use post_transform_info.entry because post_transform_info.vc
// is not set to NULL after the post transform is done.
if (post_transform_info.entry) {
i = &post_transform_info;
ink_assert(c->vc == i->entry->vc);
} else {
i = &transform_info;
ink_assert(c->vc == i->vc);
ink_assert(c->vc == i->entry->vc);
}
switch (event) {
case VC_EVENT_ERROR:
// Transform error
tunnel.chain_abort_all(c->producer);
c->handler_state = HTTP_SM_TRANSFORM_FAIL;
c->vc->do_io_close(EHTTP_ERROR);
break;
case VC_EVENT_EOS:
// It possible the transform quit
// before the producer finished. If this is true
// we need shut down the producer if it doesn't
// have other consumers to serve or else it will
// fill up buffer and get hung
if (c->producer->alive && c->producer->num_consumers == 1) {
// Send a tunnel detach event to the producer
// to shut it down but indicates it should not abort
// downstream (on the other side of the transform)
// cache writes
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
// FALLTHROUGH
case VC_EVENT_WRITE_COMPLETE:
// write to transform complete - shutdown the write side
c->write_success = true;
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
// If the read side has not started up yet, then the
// this transform_vc is no longer owned by the tunnel
if (c->self_producer == nullptr) {
i->entry->in_tunnel = false;
} else if (c->self_producer->alive == false) {
// The read side of the Transform
// has already completed (possible when the
// transform intentionally truncates the response).
// So close it
c->vc->do_io(VIO::CLOSE);
}
break;
default:
ink_release_assert(0);
}
// attribute the size written to the transform from various sources
// NOTE: the range transform is excluded from this accounting and
// is instead handled in HttpSM::tunnel_handler_ua
//
// the reasoning is that the range transform is internal functionality
// in support of HTTP 1.1 compliance, therefore part of "normal" operation
// all other transforms are plugin driven and the difference between
// source data and final data should represent the transformation delta
//
if (t_state.range_setup == HttpTransact::RANGE_NONE) {
switch (t_state.pre_transform_source) {
case HttpTransact::SOURCE_HTTP_ORIGIN_SERVER:
server_response_body_bytes = client_response_body_bytes;
break;
case HttpTransact::SOURCE_CACHE:
cache_response_body_bytes = client_response_body_bytes;
break;
default:
break;
}
}
return 0;
}
int
HttpSM::tunnel_handler_transform_read(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_transform_read, event);
ink_assert(p->vc == transform_info.vc || p->vc == post_transform_info.vc);
switch (event) {
case VC_EVENT_ERROR:
// Transform error
tunnel.chain_abort_all(p->self_consumer->producer);
break;
case VC_EVENT_EOS:
// If we did not get enough data from the transform abort the
// cache write otherwise fallthrough to the transform
// completing successfully
if (t_state.hdr_info.transform_response_cl != HTTP_UNDEFINED_CL &&
p->read_vio->nbytes < t_state.hdr_info.transform_response_cl) {
tunnel.abort_cache_write_finish_others(p);
break;
}
// FALL-THROUGH
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
// Transform complete
p->read_success = true;
tunnel.local_finish_all(p);
break;
default:
ink_release_assert(0);
}
// it's possible that the write side of the
// transform hasn't detached yet. If it is still alive,
// don't close the transform vc
if (p->self_consumer->alive == false) {
p->vc->do_io_close();
}
p->handler_state = HTTP_SM_TRANSFORM_CLOSED;
return 0;
}
int
HttpSM::tunnel_handler_plugin_agent(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_plugin_client, event);
switch (event) {
case VC_EVENT_ERROR:
c->vc->do_io_close(EHTTP_ERROR); // close up
// Signal producer if we're the last consumer.
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
break;
case VC_EVENT_EOS:
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
// FALLTHROUGH
case VC_EVENT_WRITE_COMPLETE:
c->write_success = true;
c->vc->do_io(VIO::CLOSE);
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::state_srv_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_srv_lookup, event);
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_SRV_LOOKUP:
pending_action = nullptr;
process_srv_info((HostDBInfo *)data);
break;
case EVENT_SRV_IP_REMOVED:
ink_assert(!"Unexpected SRV event from HostDB. What up, Eric?");
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
int
HttpSM::state_remap_request(int event, void * /* data ATS_UNUSED */)
{
STATE_ENTER(&HttpSM::state_remap_request, event);
switch (event) {
case EVENT_REMAP_ERROR: {
ink_assert(!"this doesn't happen");
pending_action = nullptr;
Error("error remapping request [see previous errors]");
call_transact_and_set_next_state(HttpTransact::HandleRequest); // HandleRequest skips EndRemapRequest
break;
}
case EVENT_REMAP_COMPLETE: {
pending_action = nullptr;
DebugSM("url_rewrite", "completed processor-based remapping request for [%" PRId64 "]", sm_id);
t_state.url_remap_success = remapProcessor.finish_remap(&t_state);
call_transact_and_set_next_state(nullptr);
break;
}
default:
ink_assert("Unexpected event inside state_remap_request");
break;
}
return 0;
}
void
HttpSM::do_remap_request(bool run_inline)
{
DebugSM("http_seq", "[HttpSM::do_remap_request] Remapping request");
DebugSM("url_rewrite", "Starting a possible remapping for request [%" PRId64 "]", sm_id);
SSLConfig::scoped_config params;
bool ret = false;
if (t_state.cop_test_page == false) {
ret = remapProcessor.setup_for_remap(&t_state);
}
// Preserve effective url before remap
t_state.unmapped_url.create(t_state.hdr_info.client_request.url_get()->m_heap);
t_state.unmapped_url.copy(t_state.hdr_info.client_request.url_get());
// Depending on a variety of factors the HOST field may or may not have been promoted to the
// client request URL. The unmapped URL should always have that promotion done. If the HOST field
// is not already there, promote it only in the unmapped_url. This avoids breaking any logic that
// depends on the lack of promotion in the client request URL.
if (!t_state.unmapped_url.m_url_impl->m_ptr_host) {
MIMEField *host_field = t_state.hdr_info.client_request.field_find(MIME_FIELD_HOST, MIME_LEN_HOST);
if (host_field) {
int host_len;
const char *host_name = host_field->value_get(&host_len);
if (host_name && host_len) {
t_state.unmapped_url.host_set(host_name, host_len);
}
}
}
if (!ret) {
DebugSM("url_rewrite", "Could not find a valid remapping entry for this request [%" PRId64 "]", sm_id);
if (!run_inline) {
handleEvent(EVENT_REMAP_COMPLETE, nullptr);
}
return;
}
DebugSM("url_rewrite", "Found a remap map entry for [%" PRId64 "], attempting to remap request and call any plugins", sm_id);
Action *remap_action_handle = remapProcessor.perform_remap(this, &t_state);
if (remap_action_handle != ACTION_RESULT_DONE) {
DebugSM("url_rewrite", "Still more remapping needed for [%" PRId64 "]", sm_id);
ink_assert(!pending_action);
pending_action = remap_action_handle;
}
// check if the overridden client cert filename is already attached to an existing ssl context
if (t_state.txn_conf->client_cert_filepath && t_state.txn_conf->client_cert_filename) {
ats_scoped_str clientCert(Layout::relative_to(t_state.txn_conf->client_cert_filepath, t_state.txn_conf->client_cert_filename));
if (clientCert != nullptr) {
auto tCTX = params->getCTX(clientCert);
if (tCTX == nullptr) {
// make new client ctx and add it to the ctx list
auto tctx = params->getNewCTX(clientCert);
params->InsertCTX(clientCert, tctx);
}
}
}
return;
}
void
HttpSM::do_hostdb_lookup()
{
/*
//////////////////////////////////////////
// if a connection to the origin server //
// is currently opened --- close it. //
//////////////////////////////////////////
if (m_origin_server_vc != 0) {
origin_server_close(CLOSE_CONNECTION);
if (m_response_body_tunnel_buffer_.buf() != 0)
m_response_body_tunnel_buffer_.reset();
}
*/
ink_assert(t_state.dns_info.lookup_name != nullptr);
ink_assert(pending_action == nullptr);
milestones[TS_MILESTONE_DNS_LOOKUP_BEGIN] = Thread::get_hrtime();
if (t_state.txn_conf->srv_enabled) {
char d[MAXDNAME];
// Look at the next_hop_scheme to determine what scheme to put in the SRV lookup
unsigned int scheme_len = sprintf(d, "_%s._tcp.", hdrtoken_index_to_wks(t_state.next_hop_scheme));
ink_strlcpy(d + scheme_len, t_state.server_info.name, sizeof(d) - scheme_len);
DebugSM("dns_srv", "Beginning lookup of SRV records for origin %s", d);
HostDBProcessor::Options opt;
if (t_state.api_txn_dns_timeout_value != -1) {
opt.timeout = t_state.api_txn_dns_timeout_value;
}
Action *srv_lookup_action_handle =
hostDBProcessor.getSRVbyname_imm(this, (process_srv_info_pfn)&HttpSM::process_srv_info, d, 0, opt);
if (srv_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = srv_lookup_action_handle;
} else {
char *host_name = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_hostname : t_state.dns_info.lookup_name;
opt.port = t_state.dns_info.srv_lookup_success ?
t_state.dns_info.srv_port :
t_state.server_info.dst_addr.isValid() ? t_state.server_info.dst_addr.host_order_port() :
t_state.hdr_info.client_request.port_get();
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ua_session->get_host_res_style();
Action *dns_lookup_action_handle =
hostDBProcessor.getbyname_imm(this, (process_hostdb_info_pfn)&HttpSM::process_hostdb_info, host_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
}
return;
} else { /* we aren't using SRV stuff... */
DebugSM("http_seq", "[HttpSM::do_hostdb_lookup] Doing DNS Lookup");
// If there is not a current server, we must be looking up the origin
// server at the beginning of the transaction
int server_port = t_state.current.server ?
t_state.current.server->dst_addr.host_order_port() :
t_state.server_info.dst_addr.isValid() ? t_state.server_info.dst_addr.host_order_port() :
t_state.hdr_info.client_request.port_get();
if (t_state.api_txn_dns_timeout_value != -1) {
DebugSM("http_timeout", "beginning DNS lookup. allowing %d mseconds for DNS lookup", t_state.api_txn_dns_timeout_value);
}
HostDBProcessor::Options opt;
opt.port = server_port;
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ua_session->get_host_res_style();
Action *dns_lookup_action_handle = hostDBProcessor.getbyname_imm(this, (process_hostdb_info_pfn)&HttpSM::process_hostdb_info,
t_state.dns_info.lookup_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
return;
}
ink_assert(!"not reached");
return;
}
void
HttpSM::do_hostdb_reverse_lookup()
{
ink_assert(t_state.dns_info.lookup_name != nullptr);
ink_assert(pending_action == nullptr);
DebugSM("http_seq", "[HttpSM::do_hostdb_reverse_lookup] Doing reverse DNS Lookup");
IpEndpoint addr;
ats_ip_pton(t_state.dns_info.lookup_name, &addr.sa);
Action *dns_lookup_action_handle = hostDBProcessor.getbyaddr_re(this, &addr.sa);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
}
return;
}
void
HttpSM::do_hostdb_update_if_necessary()
{
int issue_update = 0;
if (t_state.current.server == nullptr || plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL) {
// No server, so update is not necessary
return;
}
// If we failed back over to the origin server, we don't have our
// hostdb information anymore which means we shouldn't update the hostdb
if (!ats_ip_addr_eq(&t_state.current.server->dst_addr.sa, t_state.host_db_info.ip())) {
DebugSM("http", "[%" PRId64 "] skipping hostdb update due to server failover", sm_id);
return;
}
if (t_state.updated_server_version != HostDBApplicationInfo::HTTP_VERSION_UNDEFINED) {
// we may have incorrectly assumed that the hostdb had the wrong version of
// http for the server because our first few connect attempts to the server
// failed, causing us to downgrade our requests to a lower version and changing
// our information about the server version.
//
// This test therefore just issues the update only if the hostdb version is
// in fact different from the version we want the value to be updated to.
if (t_state.host_db_info.app.http_data.http_version != t_state.updated_server_version) {
t_state.host_db_info.app.http_data.http_version = t_state.updated_server_version;
issue_update |= 1;
}
t_state.updated_server_version = HostDBApplicationInfo::HTTP_VERSION_UNDEFINED;
}
// Check to see if we need to report or clear a connection failure
if (t_state.current.server->had_connect_fail()) {
issue_update |= 1;
mark_host_failure(&t_state.host_db_info, t_state.client_request_time);
} else {
if (t_state.host_db_info.app.http_data.last_failure != 0) {
t_state.host_db_info.app.http_data.last_failure = 0;
issue_update |= 1;
char addrbuf[INET6_ADDRPORTSTRLEN];
DebugSM("http", "[%" PRId64 "] hostdb update marking IP: %s as up", sm_id,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
if (t_state.dns_info.srv_lookup_success && t_state.dns_info.srv_app.http_data.last_failure != 0) {
t_state.dns_info.srv_app.http_data.last_failure = 0;
hostDBProcessor.setby_srv(t_state.dns_info.lookup_name, 0, t_state.dns_info.srv_hostname, &t_state.dns_info.srv_app);
DebugSM("http", "[%" PRId64 "] hostdb update marking SRV: %s as up", sm_id, t_state.dns_info.srv_hostname);
}
}
if (issue_update) {
hostDBProcessor.setby(t_state.current.server->name, strlen(t_state.current.server->name), &t_state.current.server->dst_addr.sa,
&t_state.host_db_info.app);
}
char addrbuf[INET6_ADDRPORTSTRLEN];
DebugSM("http", "server info = %s", ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
return;
}
/*
* range entry valid [a,b] (a >= 0 and b >= 0 and a <= b)
* HttpTransact::RANGE_NONE if the content length of cached copy is zero or
* no range entry
* HttpTransact::RANGE_NOT_SATISFIABLE iff all range entries are valid but
* none overlap the current extent of the cached copy
* HttpTransact::RANGE_NOT_HANDLED if out-of-order Range entries or
* the cached copy`s content_length is INT64_MAX (e.g. read_from_writer and trunked)
* HttpTransact::RANGE_REQUESTED if all sub range entries are valid and
* in order (remove the entries that not overlap the extent of cache copy)
*/
void
HttpSM::parse_range_and_compare(MIMEField *field, int64_t content_length)
{
int prev_good_range = -1;
const char *value;
int value_len;
int n_values;
int nr = 0; // number of valid ranges, also index to range array.
int not_satisfy = 0;
HdrCsvIter csv;
const char *s, *e, *tmp;
RangeRecord *ranges = nullptr;
int64_t start, end;
ink_assert(field != nullptr && t_state.range_setup == HttpTransact::RANGE_NONE && t_state.ranges == nullptr);
if (content_length <= 0) {
return;
}
// ToDo: Can this really happen?
if (content_length == INT64_MAX) {
t_state.range_setup = HttpTransact::RANGE_NOT_HANDLED;
return;
}
if (parse_range_done) {
Debug("http_range", "parse_range already done, t_state.range_setup %d", t_state.range_setup);
return;
}
parse_range_done = true;
n_values = 0;
value = csv.get_first(field, &value_len);
while (value) {
++n_values;
value = csv.get_next(&value_len);
}
value = csv.get_first(field, &value_len);
if (n_values <= 0 || ptr_len_ncmp(value, value_len, "bytes=", 6)) {
return;
}
ranges = new RangeRecord[n_values];
value += 6; // skip leading 'bytes='
value_len -= 6;
// assume range_in_cache
t_state.range_in_cache = true;
for (; value; value = csv.get_next(&value_len)) {
if (!(tmp = (const char *)memchr(value, '-', value_len))) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
// process start value
s = value;
e = tmp;
// skip leading white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s >= e) {
start = -1;
} else {
for (start = 0; s < e && *s >= '0' && *s <= '9'; ++s) {
start = start * 10 + (*s - '0');
}
// skip last white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s < e || start < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
}
// process end value
s = tmp + 1;
e = value + value_len;
// skip leading white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s >= e) {
if (start < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
} else if (start >= content_length) {
not_satisfy++;
continue;
}
end = content_length - 1;
} else {
for (end = 0; s < e && *s >= '0' && *s <= '9'; ++s) {
end = end * 10 + (*s - '0');
}
// skip last white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s < e || end < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
if (start < 0) {
if (end >= content_length) {
end = content_length;
}
start = content_length - end;
end = content_length - 1;
} else if (start >= content_length && start <= end) {
not_satisfy++;
continue;
}
if (end >= content_length) {
end = content_length - 1;
}
}
if (start > end) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
if (prev_good_range >= 0 && start <= ranges[prev_good_range]._end) {
t_state.range_setup = HttpTransact::RANGE_NOT_HANDLED;
goto Lfaild;
}
ink_assert(start >= 0 && end >= 0 && start < content_length && end < content_length);
prev_good_range = nr;
ranges[nr]._start = start;
ranges[nr]._end = end;
++nr;
if (!cache_sm.cache_read_vc->is_pread_capable() && cache_config_read_while_writer == 2) {
// write in progress, check if request range not in cache yet
HTTPInfo::FragOffset *frag_offset_tbl = t_state.cache_info.object_read->get_frag_table();
int frag_offset_cnt = t_state.cache_info.object_read->get_frag_offset_count();
if (!frag_offset_tbl || !frag_offset_cnt || (frag_offset_tbl[frag_offset_cnt - 1] < (uint64_t)end)) {
Debug("http_range", "request range in cache, end %" PRId64 ", frg_offset_cnt %d" PRId64, end, frag_offset_cnt);
t_state.range_in_cache = false;
}
}
}
if (nr > 0) {
t_state.range_setup = HttpTransact::RANGE_REQUESTED;
t_state.ranges = ranges;
t_state.num_range_fields = nr;
return;
}
if (not_satisfy) {
t_state.range_setup = HttpTransact::RANGE_NOT_SATISFIABLE;
}
Lfaild:
t_state.range_in_cache = false;
t_state.num_range_fields = -1;
delete[] ranges;
return;
}
void
HttpSM::calculate_output_cl(int64_t num_chars_for_ct, int64_t num_chars_for_cl)
{
int i;
if (t_state.range_setup != HttpTransact::RANGE_REQUESTED && t_state.range_setup != HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
return;
}
ink_assert(t_state.ranges);
if (t_state.num_range_fields == 1) {
t_state.range_output_cl = t_state.ranges[0]._end - t_state.ranges[0]._start + 1;
} else {
for (i = 0; i < t_state.num_range_fields; i++) {
if (t_state.ranges[i]._start >= 0) {
t_state.range_output_cl += boundary_size;
t_state.range_output_cl += sub_header_size + num_chars_for_ct;
t_state.range_output_cl +=
num_chars_for_int(t_state.ranges[i]._start) + num_chars_for_int(t_state.ranges[i]._end) + num_chars_for_cl + 2;
t_state.range_output_cl += t_state.ranges[i]._end - t_state.ranges[i]._start + 1;
t_state.range_output_cl += 2;
}
}
t_state.range_output_cl += boundary_size + 2;
}
Debug("http_range", "Pre-calculated Content-Length for Range response is %" PRId64, t_state.range_output_cl);
}
void
HttpSM::do_range_parse(MIMEField *range_field)
{
int num_chars_for_ct = 0;
t_state.cache_info.object_read->response_get()->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &num_chars_for_ct);
int64_t content_length = t_state.cache_info.object_read->object_size_get();
int64_t num_chars_for_cl = num_chars_for_int(content_length);
parse_range_and_compare(range_field, content_length);
calculate_output_cl(num_chars_for_ct, num_chars_for_cl);
}
// this function looks for any Range: headers, parses them and either
// sets up a transform processor to handle the request OR defers to the
// HttpTunnel
void
HttpSM::do_range_setup_if_necessary()
{
MIMEField *field;
INKVConnInternal *range_trans;
int field_content_type_len = -1;
const char *content_type;
ink_assert(t_state.cache_info.object_read != nullptr);
field = t_state.hdr_info.client_request.field_find(MIME_FIELD_RANGE, MIME_LEN_RANGE);
ink_assert(field != nullptr);
t_state.range_setup = HttpTransact::RANGE_NONE;
if (t_state.method == HTTP_WKSIDX_GET && t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 1)) {
do_range_parse(field);
if (t_state.range_setup == HttpTransact::RANGE_REQUESTED) {
if (!t_state.range_in_cache) {
Debug("http_range", "range can't be satisfied from cache, force origin request");
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_MISS;
return;
}
// if only one range entry and pread is capable, no need transform range
if (t_state.num_range_fields == 1 && cache_sm.cache_read_vc->is_pread_capable()) {
t_state.range_setup = HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED;
} else if (api_hooks.get(TS_HTTP_RESPONSE_TRANSFORM_HOOK) == nullptr) {
Debug("http_trans", "Unable to accelerate range request, fallback to transform");
content_type = t_state.cache_info.object_read->response_get()->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE,
&field_content_type_len);
// create a Range: transform processor for requests of type Range: bytes=1-2,4-5,10-100 (eg. multiple ranges)
range_trans = transformProcessor.range_transform(mutex.get(), t_state.ranges, t_state.num_range_fields,
&t_state.hdr_info.transform_response, content_type, field_content_type_len,
t_state.cache_info.object_read->object_size_get());
api_hooks.append(TS_HTTP_RESPONSE_TRANSFORM_HOOK, range_trans);
}
}
}
}
void
HttpSM::do_cache_lookup_and_read()
{
// TODO decide whether to uncomment after finish testing redirect
// ink_assert(server_session == NULL);
ink_assert(pending_action == nullptr);
HTTP_INCREMENT_DYN_STAT(http_cache_lookups_stat);
milestones[TS_MILESTONE_CACHE_OPEN_READ_BEGIN] = Thread::get_hrtime();
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.lookup_count++;
// YTS Team, yamsat Plugin
// Changed the lookup_url to c_url which enables even
// the new redirect url to perform a CACHE_LOOKUP
URL *c_url;
if (t_state.redirect_info.redirect_in_process && !t_state.txn_conf->redirect_use_orig_cache_key) {
c_url = t_state.hdr_info.client_request.url_get();
} else {
c_url = t_state.cache_info.lookup_url;
}
DebugSM("http_seq", "[HttpSM::do_cache_lookup_and_read] [%" PRId64 "] Issuing cache lookup for URL %s", sm_id,
c_url->string_get(&t_state.arena));
HttpCacheKey key;
Cache::generate_key(&key, c_url, t_state.txn_conf->cache_generation_number);
Action *cache_action_handle =
cache_sm.open_read(&key, c_url, &t_state.hdr_info.client_request, &(t_state.cache_info.config),
(time_t)((t_state.cache_control.pin_in_cache_for < 0) ? 0 : t_state.cache_control.pin_in_cache_for));
//
// pin_in_cache value is an open_write parameter.
// It is passed in open_read to allow the cluster to
// optimize the typical open_read/open_read failed/open_write
// sequence.
//
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
REMEMBER((long)pending_action, reentrancy_count);
return;
}
void
HttpSM::do_cache_delete_all_alts(Continuation *cont)
{
// Do not delete a non-existant object.
ink_assert(t_state.cache_info.object_read);
DebugSM("http_seq", "[HttpSM::do_cache_delete_all_alts] Issuing cache delete for %s",
t_state.cache_info.lookup_url->string_get_ref());
Action *cache_action_handle = nullptr;
HttpCacheKey key;
Cache::generate_key(&key, t_state.cache_info.lookup_url, t_state.txn_conf->cache_generation_number);
cache_action_handle = cacheProcessor.remove(cont, &key, t_state.cache_control.cluster_cache_local);
if (cont != nullptr) {
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
}
return;
}
inline void
HttpSM::do_cache_prepare_write()
{
// statistically no need to retry when we are trying to lock
// LOCK_URL_SECOND url because the server's behavior is unlikely to change
milestones[TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN] = Thread::get_hrtime();
bool retry = (t_state.api_lock_url == HttpTransact::LOCK_URL_FIRST);
do_cache_prepare_action(&cache_sm, t_state.cache_info.object_read, retry);
}
inline void
HttpSM::do_cache_prepare_write_transform()
{
if (cache_sm.cache_write_vc != nullptr || tunnel.has_cache_writer()) {
do_cache_prepare_action(&transform_cache_sm, nullptr, false, true);
} else {
do_cache_prepare_action(&transform_cache_sm, nullptr, false);
}
}
void
HttpSM::do_cache_prepare_update()
{
if (t_state.cache_info.object_read != nullptr && t_state.cache_info.object_read->valid() &&
t_state.cache_info.object_store.valid() && t_state.cache_info.object_store.response_get() != nullptr &&
t_state.cache_info.object_store.response_get()->valid() &&
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET) {
t_state.cache_info.object_store.request_set(t_state.cache_info.object_read->request_get());
// t_state.cache_info.object_read = NULL;
// cache_sm.close_read();
t_state.transact_return_point = HttpTransact::HandleUpdateCachedObject;
ink_assert(cache_sm.cache_write_vc == nullptr);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
// don't retry read for update
do_cache_prepare_action(&cache_sm, t_state.cache_info.object_read, false);
} else {
t_state.api_modifiable_cached_resp = false;
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
}
}
void
HttpSM::do_cache_prepare_action(HttpCacheSM *c_sm, CacheHTTPInfo *object_read_info, bool retry, bool allow_multiple)
{
URL *o_url, *c_url, *s_url;
bool restore_client_request = false;
ink_assert(!pending_action);
if (t_state.api_lock_url == HttpTransact::LOCK_URL_FIRST) {
if (t_state.redirect_info.redirect_in_process) {
o_url = &(t_state.redirect_info.original_url);
ink_assert(o_url->valid());
restore_client_request = true;
s_url = o_url;
} else {
o_url = &(t_state.cache_info.original_url);
if (o_url->valid()) {
s_url = o_url;
} else {
s_url = t_state.cache_info.lookup_url;
}
}
} else if (t_state.api_lock_url == HttpTransact::LOCK_URL_SECOND) {
s_url = &t_state.cache_info.lookup_url_storage;
} else {
ink_assert(t_state.api_lock_url == HttpTransact::LOCK_URL_ORIGINAL);
s_url = &(t_state.cache_info.original_url);
restore_client_request = true;
}
// modify client request to make it have the url we are going to
// store into the cache
if (restore_client_request) {
c_url = t_state.hdr_info.client_request.url_get();
s_url->copy(c_url);
}
ink_assert(s_url != nullptr && s_url->valid());
DebugSM("http_cache_write", "[%" PRId64 "] writing to cache with URL %s", sm_id, s_url->string_get(&t_state.arena));
HttpCacheKey key;
Cache::generate_key(&key, s_url, t_state.txn_conf->cache_generation_number);
Action *cache_action_handle = c_sm->open_write(
&key, s_url, &t_state.hdr_info.client_request, object_read_info,
(time_t)((t_state.cache_control.pin_in_cache_for < 0) ? 0 : t_state.cache_control.pin_in_cache_for), retry, allow_multiple);
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
}
void
HttpSM::send_origin_throttled_response()
{
t_state.current.attempts = t_state.txn_conf->connect_attempts_max_retries;
// t_state.current.state = HttpTransact::CONNECTION_ERROR;
t_state.current.state = HttpTransact::CONGEST_CONTROL_CONGESTED_ON_F;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::do_http_server_open()
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::do_http_server_open(bool raw)
{
int ip_family = t_state.current.server->dst_addr.sa.sa_family;
DebugSM("http_track", "entered inside do_http_server_open ][%s]", ats_ip_family_name(ip_family));
// Make sure we are on the "right" thread
if (ua_session) {
if ((pending_action = ua_session->adjust_thread(this, EVENT_INTERVAL, nullptr))) {
return; // Go away if we reschedule
}
}
pending_action = nullptr;
ink_assert(server_entry == nullptr);
// ua_entry can be null if a scheduled update is also a reverse proxy
// request. Added REVPROXY to the assert below, and then changed checks
// to be based on ua_session != NULL instead of req_flavor value.
ink_assert(ua_entry != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
ink_assert(pending_action == nullptr);
if (false == t_state.api_server_addr_set) {
ink_assert(t_state.current.server->dst_addr.host_order_port() > 0);
} else {
ink_assert(t_state.current.server->dst_addr.port() != 0); // verify the plugin set it to something.
}
char addrbuf[INET6_ADDRPORTSTRLEN];
DebugSM("http", "[%" PRId64 "] open connection to %s: %s", sm_id, t_state.current.server->name,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
if (plugin_tunnel) {
PluginVCCore *t = plugin_tunnel;
plugin_tunnel = nullptr;
Action *pvc_action_handle = t->connect_re(this);
// This connect call is always reentrant
ink_release_assert(pvc_action_handle == ACTION_RESULT_DONE);
return;
}
DebugSM("http_seq", "[HttpSM::do_http_server_open] Sending request to server");
milestones[TS_MILESTONE_SERVER_CONNECT] = Thread::get_hrtime();
if (milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] == 0) {
milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] = milestones[TS_MILESTONE_SERVER_CONNECT];
}
// Check for remap rule. If so, only apply ip_allow filter if it is activated (ip_allow_check_enabled_p set).
// Otherwise, if no remap rule is defined, apply the ip_allow filter.
if (!t_state.url_remap_success || t_state.url_map.getMapping()->ip_allow_check_enabled_p) {
// Method allowed on dest IP address check
sockaddr *server_ip = &t_state.current.server->dst_addr.sa;
IpAllow::scoped_config ip_allow;
if (ip_allow) {
const AclRecord *acl_record = ip_allow->match(server_ip, IpAllow::DEST_ADDR);
bool deny_request = false; // default is fail open.
int method = t_state.hdr_info.server_request.method_get_wksidx();
if (acl_record) {
// If empty, nothing is allowed, deny. Conversely if all methods are allowed it's OK, do not deny.
// Otherwise the method has to be checked specifically.
if (acl_record->isEmpty()) {
deny_request = true;
} else if (acl_record->_method_mask != AclRecord::ALL_METHOD_MASK) {
if (method != -1) {
deny_request = !acl_record->isMethodAllowed(method);
} else {
int method_str_len;
const char *method_str = t_state.hdr_info.server_request.method_get(&method_str_len);
deny_request = !acl_record->isNonstandardMethodAllowed(std::string(method_str, method_str_len));
}
}
}
if (deny_request) {
if (is_debug_tag_set("ip-allow")) {
ip_text_buffer ipb;
Warning("server '%s' prohibited by ip-allow policy", ats_ip_ntop(server_ip, ipb, sizeof(ipb)));
Debug("ip-allow", "Denial on %s:%s with mask %x", ats_ip_ntop(&t_state.current.server->dst_addr.sa, ipb, sizeof(ipb)),
hdrtoken_index_to_wks(method), acl_record ? acl_record->_method_mask : 0x0);
}
t_state.current.attempts = t_state.txn_conf->connect_attempts_max_retries; // prevent any more retries with this IP
call_transact_and_set_next_state(HttpTransact::Forbidden);
return;
}
}
}
// Congestion Check
if (t_state.pCongestionEntry != NULL) {
if (t_state.pCongestionEntry->F_congested() &&
(!t_state.pCongestionEntry->proxy_retry(milestones[TS_MILESTONE_SERVER_CONNECT]))) {
t_state.congestion_congested_or_failed = 1;
t_state.pCongestionEntry->stat_inc_F();
CONGEST_INCREMENT_DYN_STAT(congested_on_F_stat);
handleEvent(CONGESTION_EVENT_CONGESTED_ON_F, nullptr);
return;
} else if (t_state.pCongestionEntry->M_congested(ink_hrtime_to_sec(milestones[TS_MILESTONE_SERVER_CONNECT]))) {
t_state.pCongestionEntry->stat_inc_M();
t_state.congestion_congested_or_failed = 1;
CONGEST_INCREMENT_DYN_STAT(congested_on_M_stat);
handleEvent(CONGESTION_EVENT_CONGESTED_ON_M, nullptr);
return;
}
}
// If this is not a raw connection, we try to get a session from the
// shared session pool. Raw connections are for SSLs tunnel and
// require a new connection
//
// This problem with POST requests is a bug. Because of the issue of the
// race with us sending a request after server has closed but before the FIN
// gets to us, we should open a new connection for POST. I believe TS used
// to do this but as far I can tell the code that prevented keep-alive if
// there is a request body has been removed.
// If we are sending authorizations headers, mark the connection private
//
// We do this here because it means that we will not waste a connection from the pool if we already
// know that the session will be private. This is overridable meaning that if a plugin later decides
// it shouldn't be private it can still be returned to a shared pool.
//
if (t_state.txn_conf->auth_server_session_private == 1 &&
t_state.hdr_info.server_request.presence(MIME_PRESENCE_AUTHORIZATION | MIME_PRESENCE_PROXY_AUTHORIZATION |
MIME_PRESENCE_WWW_AUTHENTICATE)) {
DebugSM("http_ss_auth", "Setting server session to private for authorization header");
will_be_private_ss = true;
}
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
// don't share the session if keep-alive for post is not on
if (t_state.txn_conf->keep_alive_post_out == 0) {
DebugSM("http_ss", "Setting server session to private because of keep-alive post out");
will_be_private_ss = true;
}
}
// If there is already an attached server session mark it as private.
if (server_session != nullptr && will_be_private_ss) {
set_server_session_private(true);
}
if (raw == false && TS_SERVER_SESSION_SHARING_MATCH_NONE != t_state.txn_conf->server_session_sharing_match &&
(t_state.txn_conf->keep_alive_post_out == 1 || t_state.hdr_info.request_content_length == 0) && !is_private() &&
ua_session != nullptr) {
HSMresult_t shared_result;
shared_result = httpSessionManager.acquire_session(this, // state machine
&t_state.current.server->dst_addr.sa, // ip + port
t_state.current.server->name, // hostname
ua_session, // has ptr to bound ua sessions
this // sm
);
switch (shared_result) {
case HSM_DONE:
hsm_release_assert(server_session != nullptr);
handle_http_server_open();
return;
case HSM_NOT_FOUND:
hsm_release_assert(server_session == nullptr);
break;
case HSM_RETRY:
// Could not get shared pool lock
// FIX: should retry lock
break;
default:
hsm_release_assert(0);
}
}
// Avoid a problem where server session sharing is disabled and we have keep-alive, we are trying to open a new server
// session when we already have an attached server session.
else if ((TS_SERVER_SESSION_SHARING_MATCH_NONE == t_state.txn_conf->server_session_sharing_match || is_private()) &&
(ua_session != nullptr)) {
HttpServerSession *existing_ss = ua_session->get_server_session();
if (existing_ss) {
// [amc] Not sure if this is the best option, but we don't get here unless session sharing is disabled
// so there's no point in further checking on the match or pool values. But why check anything? The
// client has already exchanged a request with this specific origin server and has sent another one
// shouldn't we just automatically keep the association?
if (ats_ip_addr_port_eq(&existing_ss->get_server_ip().sa, &t_state.current.server->dst_addr.sa)) {
ua_session->attach_server_session(nullptr);
existing_ss->state = HSS_ACTIVE;
this->attach_server_session(existing_ss);
hsm_release_assert(server_session != nullptr);
handle_http_server_open();
return;
} else {
// As this is in the non-sharing configuration, we want to close
// the existing connection and call connect_re to get a new one
existing_ss->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
existing_ss->release();
ua_session->attach_server_session(nullptr);
}
}
}
// Otherwise, we release the existing connection and call connect_re
// to get a new one.
// ua_session is null when t_state.req_flavor == REQ_FLAVOR_SCHEDULED_UPDATE
else if (ua_session != nullptr) {
HttpServerSession *existing_ss = ua_session->get_server_session();
if (existing_ss) {
existing_ss->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
existing_ss->release();
ua_session->attach_server_session(nullptr);
}
}
// Check to see if we have reached the max number of connections.
// Atomically read the current number of connections and check to see
// if we have gone above the max allowed.
if (t_state.http_config_param->server_max_connections > 0) {
int64_t sum;
HTTP_READ_GLOBAL_DYN_SUM(http_current_server_connections_stat, sum);
// Note that there is a potential race condition here where
// the value of the http_current_server_connections_stat gets changed
// between the statement above and the check below.
// If this happens, we might go over the max by 1 but this is ok.
if (sum >= t_state.http_config_param->server_max_connections) {
httpSessionManager.purge_keepalives();
// Eventually may want to have a queue as the origin_max_connection does to allow for a combination
// of retries and errors. But at this point, we are just going to allow the error case.
t_state.current.state = HttpTransact::CONNECTION_ERROR;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return;
}
}
// Check to see if we have reached the max number of connections on this
// host.
if (t_state.txn_conf->origin_max_connections > 0) {
ConnectionCount *connections = ConnectionCount::getInstance();
INK_MD5 hostname_hash;
MD5Context md5_ctx;
md5_ctx.hash_immediate(hostname_hash, static_cast<const void *>(t_state.current.server->name),
strlen(t_state.current.server->name));
if (connections->getCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match) >=
t_state.txn_conf->origin_max_connections) {
ip_port_text_buffer addrbuf;
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf));
DebugSM("http", "[%" PRId64 "] over the number of connection for this host: %s", sm_id, addrbuf);
Warning("[%" PRId64 "] over the max number of connections for this host: %s", sm_id, addrbuf);
ink_assert(pending_action == nullptr);
// if we were previously queued, or the queue is disabled-- just reschedule
if (t_state.origin_request_queued || t_state.txn_conf->origin_max_connections_queue < 0) {
pending_action = eventProcessor.schedule_in(this, HRTIME_MSECONDS(100));
return;
} else if (t_state.txn_conf->origin_max_connections_queue > 0) { // If we have a queue, lets see if there is a slot
ConnectionCountQueue *waiting_connections = ConnectionCountQueue::getInstance();
// if there is space in the queue
if (waiting_connections->getCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match) <
t_state.txn_conf->origin_max_connections_queue) {
t_state.origin_request_queued = true;
Debug("http", "[%" PRId64 "] queued for this host: %s", sm_id,
ats_ip_ntop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
waiting_connections->incrementCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match, 1);
pending_action = eventProcessor.schedule_in(this, HRTIME_MSECONDS(100));
} else { // the queue is full
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
send_origin_throttled_response();
}
} else { // the queue is set to 0
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
send_origin_throttled_response();
}
return;
}
}
// We did not manage to get an existing session
// and need to open a new connection
Action *connect_action_handle;
NetVCOptions opt;
opt.f_blocking_connect = false;
opt.set_sock_param(t_state.txn_conf->sock_recv_buffer_size_out, t_state.txn_conf->sock_send_buffer_size_out,
t_state.txn_conf->sock_option_flag_out, t_state.txn_conf->sock_packet_mark_out,
t_state.txn_conf->sock_packet_tos_out);
opt.ip_family = ip_family;
if (ua_session) {
opt.local_port = ua_session->get_outbound_port();
const IpAddr &outbound_ip = AF_INET6 == ip_family ? ua_session->get_outbound_ip6() : ua_session->get_outbound_ip4();
if (outbound_ip.isValid()) {
opt.addr_binding = NetVCOptions::INTF_ADDR;
opt.local_ip = outbound_ip;
} else if (ua_session->is_outbound_transparent()) {
opt.addr_binding = NetVCOptions::FOREIGN_ADDR;
opt.local_ip = t_state.client_info.src_addr;
/* If the connection is server side transparent, we can bind to the
port that the client chose instead of randomly assigning one at
the proxy. This is controlled by the 'use_client_source_port'
configuration parameter.
*/
NetVConnection *client_vc = ua_session->get_netvc();
if (t_state.http_config_param->use_client_source_port && nullptr != client_vc) {
opt.local_port = client_vc->get_remote_port();
}
}
}
int scheme_to_use = t_state.scheme; // get initial scheme
if (!t_state.is_websocket) { // if not websocket, then get scheme from server request
int new_scheme_to_use = t_state.hdr_info.server_request.url_get()->scheme_get_wksidx();
// if the server_request url scheme was never set, try the client_request
if (new_scheme_to_use < 0) {
new_scheme_to_use = t_state.hdr_info.client_request.url_get()->scheme_get_wksidx();
}
if (new_scheme_to_use >= 0) { // found a new scheme, use it
scheme_to_use = new_scheme_to_use;
}
}
// draft-stenberg-httpbis-tcp recommends only enabling TFO on indempotent methods or
// those with intervening protocol layers (eg. TLS).
if (scheme_to_use == URL_WKSIDX_HTTPS || HttpTransactHeaders::is_method_idempotent(t_state.method)) {
opt.f_tcp_fastopen = (t_state.txn_conf->sock_option_flag_out & NetVCOptions::SOCK_OPT_TCP_FAST_OPEN);
}
if (scheme_to_use == URL_WKSIDX_HTTPS) {
DebugSM("http", "calling sslNetProcessor.connect_re");
int len = 0;
const char *host = t_state.hdr_info.server_request.host_get(&len);
if (host && len > 0) {
opt.set_sni_servername(host, len);
}
if (t_state.txn_conf->client_cert_filepath && t_state.txn_conf->client_cert_filename) {
ats_scoped_str clientCert(
(Layout::relative_to(t_state.txn_conf->client_cert_filepath, t_state.txn_conf->client_cert_filename)));
if (clientCert != nullptr) {
opt.set_client_certname(clientCert);
}
}
connect_action_handle = sslNetProcessor.connect_re(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
&opt);
} else if (t_state.method != HTTP_WKSIDX_CONNECT) {
DebugSM("http", "calling netProcessor.connect_re");
connect_action_handle = netProcessor.connect_re(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
&opt);
} else {
// CONNECT method
MgmtInt connect_timeout;
ink_assert(t_state.method == HTTP_WKSIDX_CONNECT);
// Set the inactivity timeout to the connect timeout so that we
// we fail this server if it doesn't start sending the response
// header
if (t_state.current.server == &t_state.parent_info) {
connect_timeout = t_state.http_config_param->parent_connect_timeout;
} else if (t_state.pCongestionEntry != nullptr) {
connect_timeout = t_state.pCongestionEntry->connect_timeout();
} else {
connect_timeout = t_state.txn_conf->connect_attempts_timeout;
}
DebugSM("http", "calling netProcessor.connect_s");
connect_action_handle = netProcessor.connect_s(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
connect_timeout, &opt);
}
if (connect_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = connect_action_handle;
}
return;
}
void
HttpSM::do_icp_lookup()
{
ink_assert(pending_action == nullptr);
URL *o_url = &t_state.cache_info.original_url;
Action *icp_lookup_action_handle = icpProcessor.ICPQuery(this, o_url->valid() ? o_url : t_state.cache_info.lookup_url);
if (icp_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = icp_lookup_action_handle;
}
return;
}
void
HttpSM::do_api_callout_internal()
{
if (t_state.backdoor_request) {
handle_api_return();
return;
}
switch (t_state.api_next_action) {
case HttpTransact::SM_ACTION_API_SM_START:
cur_hook_id = TS_HTTP_TXN_START_HOOK;
break;
case HttpTransact::SM_ACTION_API_PRE_REMAP:
cur_hook_id = TS_HTTP_PRE_REMAP_HOOK;
break;
case HttpTransact::SM_ACTION_API_POST_REMAP:
cur_hook_id = TS_HTTP_POST_REMAP_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
cur_hook_id = TS_HTTP_READ_REQUEST_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_OS_DNS:
cur_hook_id = TS_HTTP_OS_DNS_HOOK;
break;
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
cur_hook_id = TS_HTTP_SEND_REQUEST_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
cur_hook_id = TS_HTTP_READ_CACHE_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE:
cur_hook_id = TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
cur_hook_id = TS_HTTP_READ_RESPONSE_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
cur_hook_id = TS_HTTP_SEND_RESPONSE_HDR_HOOK;
milestones[TS_MILESTONE_UA_BEGIN_WRITE] = Thread::get_hrtime();
break;
case HttpTransact::SM_ACTION_API_SM_SHUTDOWN:
if (callout_state == HTTP_API_IN_CALLOUT || callout_state == HTTP_API_DEFERED_SERVER_ERROR) {
callout_state = HTTP_API_DEFERED_CLOSE;
return;
} else {
cur_hook_id = TS_HTTP_TXN_CLOSE_HOOK;
}
break;
default:
cur_hook_id = (TSHttpHookID)-1;
ink_assert(!"not reached");
}
cur_hook = nullptr;
cur_hooks = 0;
state_api_callout(0, nullptr);
}
VConnection *
HttpSM::do_post_transform_open()
{
ink_assert(post_transform_info.vc == nullptr);
if (is_action_tag_set("http_post_nullt")) {
txn_hook_prepend(TS_HTTP_REQUEST_TRANSFORM_HOOK, transformProcessor.null_transform(mutex.get()));
}
post_transform_info.vc = transformProcessor.open(this, api_hooks.get(TS_HTTP_REQUEST_TRANSFORM_HOOK));
if (post_transform_info.vc) {
// Record the transform VC in our table
post_transform_info.entry = vc_table.new_entry();
post_transform_info.entry->vc = post_transform_info.vc;
post_transform_info.entry->vc_type = HTTP_TRANSFORM_VC;
}
return post_transform_info.vc;
}
VConnection *
HttpSM::do_transform_open()
{
ink_assert(transform_info.vc == nullptr);
APIHook *hooks;
if (is_action_tag_set("http_nullt")) {
txn_hook_prepend(TS_HTTP_RESPONSE_TRANSFORM_HOOK, transformProcessor.null_transform(mutex.get()));
}
hooks = api_hooks.get(TS_HTTP_RESPONSE_TRANSFORM_HOOK);
if (hooks) {
transform_info.vc = transformProcessor.open(this, hooks);
// Record the transform VC in our table
transform_info.entry = vc_table.new_entry();
transform_info.entry->vc = transform_info.vc;
transform_info.entry->vc_type = HTTP_TRANSFORM_VC;
} else {
transform_info.vc = nullptr;
}
return transform_info.vc;
}
void
HttpSM::mark_host_failure(HostDBInfo *info, time_t time_down)
{
char addrbuf[INET6_ADDRPORTSTRLEN];
if (info->app.http_data.last_failure == 0) {
char *url_str = t_state.hdr_info.client_request.url_string_get(&t_state.arena, nullptr);
Log::error("CONNECT: could not connect to %s "
"for '%s' (setting last failure time)",
ats_ip_ntop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)), url_str ? url_str : "<none>");
if (url_str) {
t_state.arena.str_free(url_str);
}
}
info->app.http_data.last_failure = time_down;
#ifdef DEBUG
ink_assert(ink_cluster_time() + t_state.txn_conf->down_server_timeout > time_down);
#endif
DebugSM("http", "[%" PRId64 "] hostdb update marking IP: %s as down", sm_id,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
void
HttpSM::set_ua_abort(HttpTransact::AbortState_t ua_abort, int event)
{
t_state.client_info.abort = ua_abort;
switch (ua_abort) {
case HttpTransact::ABORTED:
case HttpTransact::MAYBE_ABORTED:
t_state.squid_codes.log_code = SQUID_LOG_ERR_CLIENT_ABORT;
break;
default:
// Handled here:
// HttpTransact::ABORT_UNDEFINED, HttpTransact::DIDNOT_ABORT
break;
}
// Set the connection attribute code for the client so that
// we log the client finish code correctly
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.client_info.state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.client_info.state = HttpTransact::INACTIVE_TIMEOUT;
break;
case VC_EVENT_ERROR:
t_state.client_info.state = HttpTransact::CONNECTION_ERROR;
break;
}
}
void
HttpSM::mark_server_down_on_client_abort()
{
/////////////////////////////////////////////////////
// Check see if the client aborted because the //
// origin server was too slow in sending the //
// response header. If so, mark that //
// server as down so other clients won't try to //
// for revalidation or select it from a round //
// robin set //
// //
// Note: we do not want to mark parent or icp //
// proxies as down with this metric because //
// that upstream proxy may be working but //
// the actual origin server is one that is hung //
/////////////////////////////////////////////////////
if (t_state.current.request_to == HttpTransact::ORIGIN_SERVER && t_state.hdr_info.request_content_length <= 0) {
if (milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] != 0 && milestones[TS_MILESTONE_SERVER_FIRST_READ] == 0) {
// Check to see if client waited for the threshold
// to declare the origin server as down
ink_hrtime wait = Thread::get_hrtime() - milestones[TS_MILESTONE_SERVER_FIRST_CONNECT];
if (wait < 0) {
wait = 0;
}
if (ink_hrtime_to_sec(wait) > t_state.txn_conf->client_abort_threshold) {
t_state.current.server->set_connect_fail(ETIMEDOUT);
do_hostdb_update_if_necessary();
}
}
}
}
// void HttpSM::release_server_session()
//
// Called when we are not tunneling a response from the
// server. If the session is keep alive, release it back to the
// shared pool, otherwise close it
//
void
HttpSM::release_server_session(bool serve_from_cache)
{
if (server_session == nullptr) {
return;
}
if (TS_SERVER_SESSION_SHARING_MATCH_NONE != t_state.txn_conf->server_session_sharing_match && t_state.current.server != nullptr &&
t_state.current.server->keep_alive == HTTP_KEEPALIVE && t_state.hdr_info.server_response.valid() &&
t_state.hdr_info.server_request.valid() && (t_state.hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED ||
(t_state.hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD &&
t_state.www_auth_content != HttpTransact::CACHE_AUTH_NONE)) &&
plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
HTTP_DECREMENT_DYN_STAT(http_current_server_transactions_stat);
server_session->server_trans_stat--;
server_session->attach_hostname(t_state.current.server->name);
if (t_state.www_auth_content == HttpTransact::CACHE_AUTH_NONE || serve_from_cache == false) {
// Must explicitly set the keep_alive_no_activity time before doing the release
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
server_session->release();
} else {
// an authenticated server connection - attach to the local client
// we are serving from cache for the current transaction
t_state.www_auth_content = HttpTransact::CACHE_AUTH_SERVE;
ua_session->attach_server_session(server_session, false);
}
} else {
server_session->do_io_close();
}
ink_assert(server_entry->vc == server_session);
server_entry->in_tunnel = true;
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
server_session = nullptr;
}
// void HttpSM::handle_post_failure()
//
// We failed in our attempt post (or put) a document
// to the server. Two cases happen here. The normal
// one is the server died, in which case we ought to
// return an error to the client. The second one is
// stupid. The server returned a response without reading
// all the post data. In order to be as transparent as
// possible process the server's response
void
HttpSM::handle_post_failure()
{
STATE_ENTER(&HttpSM::handle_post_failure, VC_EVENT_NONE);
ink_assert(ua_entry->vc == ua_session);
ink_assert(server_entry->eos == true);
// First order of business is to clean up from
// the tunnel
// note: since the tunnel is providing the buffer for a lingering
// client read (for abort watching purposes), we need to stop
// the read
if (false == t_state.redirect_info.redirect_in_process) {
ua_entry->read_vio = ua_session->do_io_read(this, 0, nullptr);
}
ua_entry->in_tunnel = false;
server_entry->in_tunnel = false;
// disable redirection in case we got a partial response and then EOS, because the buffer might not
// have the full post and it's deallocating the post buffers here
enable_redirection = false;
tunnel.deallocate_redirect_postdata_buffers();
// Don't even think about doing keep-alive after this debacle
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
if (server_buffer_reader->read_avail() > 0) {
tunnel.deallocate_buffers();
tunnel.reset();
// There's data from the server so try to read the header
setup_server_read_response_header();
} else {
tunnel.deallocate_buffers();
tunnel.reset();
// Server died
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
}
// void HttpSM::handle_http_server_open()
//
// The server connection is now open. If there is a POST or PUT,
// we need setup a transform is there is one otherwise we need
// to send the request header
//
void
HttpSM::handle_http_server_open()
{
// if we were a queued request, we need to decrement the queue size-- as we got a connection
if (t_state.origin_request_queued) {
INK_MD5 hostname_hash;
MD5Context md5_ctx;
md5_ctx.hash_immediate(hostname_hash, static_cast<const void *>(t_state.current.server->name),
strlen(t_state.current.server->name));
ConnectionCountQueue *waiting_connections = ConnectionCountQueue::getInstance();
waiting_connections->incrementCount(t_state.current.server->dst_addr, hostname_hash,
(TSServerSessionSharingMatchType)t_state.txn_conf->server_session_sharing_match, -1);
// The request is now not queued. This is important if the request will ever retry, the t_state is re-used
t_state.origin_request_queued = false;
}
// [bwyatt] applying per-transaction OS netVC options here
// IFF they differ from the netVC's current options.
// This should keep this from being redundant on a
// server session's first transaction.
if (nullptr != server_session) {
NetVConnection *vc = server_session->get_netvc();
if (vc != nullptr && (vc->options.sockopt_flags != t_state.txn_conf->sock_option_flag_out ||
vc->options.packet_mark != t_state.txn_conf->sock_packet_mark_out ||
vc->options.packet_tos != t_state.txn_conf->sock_packet_tos_out)) {
vc->options.sockopt_flags = t_state.txn_conf->sock_option_flag_out;
vc->options.packet_mark = t_state.txn_conf->sock_packet_mark_out;
vc->options.packet_tos = t_state.txn_conf->sock_packet_tos_out;
vc->apply_options();
}
}
if (t_state.pCongestionEntry != nullptr) {
if (t_state.congestion_connection_opened == 0) {
t_state.congestion_connection_opened = 1;
t_state.pCongestionEntry->connection_opened();
}
}
int method = t_state.hdr_info.server_request.method_get_wksidx();
if (method != HTTP_WKSIDX_TRACE &&
(t_state.hdr_info.request_content_length > 0 || t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) &&
do_post_transform_open()) {
do_setup_post_tunnel(HTTP_TRANSFORM_VC);
} else {
setup_server_send_request_api();
}
}
// void HttpSM::handle_server_setup_error(int event, void* data)
//
// Handles setting t_state.current.state and calling
// Transact in between opening an origin server connection
// and receiving the response header (in the case of the
// POST, a post tunnel happens in between the sending
// request header and reading the response header
//
void
HttpSM::handle_server_setup_error(int event, void *data)
{
VIO *vio = (VIO *)data;
ink_assert(vio != nullptr);
STATE_ENTER(&HttpSM::handle_server_setup_error, event);
// If there is POST or PUT tunnel wait for the tunnel
// to figure out that things have gone to hell
if (tunnel.is_tunnel_active()) {
ink_assert(server_entry->read_vio == data || server_entry->write_vio == data);
DebugSM("http", "[%" PRId64 "] [handle_server_setup_error] "
"forwarding event %s to post tunnel",
sm_id, HttpDebugNames::get_event_name(event));
HttpTunnelConsumer *c = tunnel.get_consumer(server_entry->vc);
// it is possible only user agent post->post transform is set up
// this happened for Linux iocore where NET_EVENT_OPEN was returned
// for a non-existing listening port. the hack is to pass the error
// event for server connection to post_transform_info
if (c == nullptr && post_transform_info.vc) {
c = tunnel.get_consumer(post_transform_info.vc);
// c->handler_state = HTTP_SM_TRANSFORM_FAIL;
// No point in proceeding if there is no consumer
// Do we need to do additional clean up in the c == NULL case?
if (c != nullptr) {
HttpTunnelProducer *ua_producer = c->producer;
ink_assert(ua_entry->vc == ua_producer->vc);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
ua_producer->alive = false;
ua_producer->handler_state = HTTP_SM_POST_SERVER_FAIL;
tunnel.handleEvent(VC_EVENT_ERROR, c->write_vio);
}
} else {
// c could be null here as well
if (c != nullptr) {
tunnel.handleEvent(event, c->write_vio);
}
}
return;
} else {
if (post_transform_info.vc) {
HttpTunnelConsumer *c = tunnel.get_consumer(post_transform_info.vc);
if (c && c->handler_state == HTTP_SM_TRANSFORM_OPEN) {
vc_table.cleanup_entry(post_transform_info.entry);
post_transform_info.entry = nullptr;
tunnel.deallocate_buffers();
tunnel.reset();
}
}
}
if (event == VC_EVENT_ERROR) {
t_state.cause_of_death_errno = server_session->get_netvc()->lerrno;
}
switch (event) {
case VC_EVENT_EOS:
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
break;
case VC_EVENT_ERROR:
t_state.current.state = HttpTransact::CONNECTION_ERROR;
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.current.state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
// If we're writing the request and get an inactivity timeout
// before any bytes are written, the connection to the
// server failed
// In case of TIMEOUT, the iocore sends back
// server_entry->read_vio instead of the write_vio
// if (vio->op == VIO::WRITE && vio->ndone == 0) {
if (server_entry->write_vio && server_entry->write_vio->nbytes > 0 && server_entry->write_vio->ndone == 0) {
t_state.current.state = HttpTransact::CONNECTION_ERROR;
} else {
t_state.current.state = HttpTransact::INACTIVE_TIMEOUT;
}
break;
default:
ink_release_assert(0);
}
// Closedown server connection and deallocate buffers
ink_assert(server_entry->in_tunnel == false);
// if we are waiting on a plugin callout for
// HTTP_API_SEND_REQUEST_HDR defer calling transact until
// after we've finished processing the plugin callout
switch (callout_state) {
case HTTP_API_NO_CALLOUT:
// Normal fast path case, no api callouts in progress
break;
case HTTP_API_IN_CALLOUT:
case HTTP_API_DEFERED_SERVER_ERROR:
// Callout in progress note that we are in deferring
// the server error
callout_state = HTTP_API_DEFERED_SERVER_ERROR;
return;
case HTTP_API_DEFERED_CLOSE:
// The user agent has shutdown killing the sm
// but we are stuck waiting for the server callout
// to finish so do nothing here. We don't care
// about the server connection at this and are
// just waiting till we can execute the close hook
return;
default:
ink_release_assert(0);
}
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
void
HttpSM::setup_transform_to_server_transfer()
{
ink_assert(post_transform_info.vc != nullptr);
ink_assert(post_transform_info.entry->vc == post_transform_info.vc);
int64_t nbytes = t_state.hdr_info.transform_request_cl;
int64_t alloc_index = buffer_size_to_index(nbytes);
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
HttpTunnelConsumer *c = tunnel.get_consumer(post_transform_info.vc);
HttpTunnelProducer *p = tunnel.add_producer(post_transform_info.vc, nbytes, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "post transform");
tunnel.chain(c, p);
post_transform_info.entry->in_tunnel = true;
tunnel.add_consumer(server_entry->vc, post_transform_info.vc, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER,
"http server post");
server_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
#ifdef PROXY_DRAIN
void
HttpSM::do_drain_request_body()
{
int64_t post_bytes = t_state.hdr_info.request_content_length;
int64_t avail = ua_buffer_reader->read_avail();
int64_t act_on = (avail < post_bytes) ? avail : post_bytes;
client_request_body_bytes = act_on;
ua_buffer_reader->consume(act_on);
ink_assert(client_request_body_bytes <= post_bytes);
if (client_request_body_bytes < post_bytes) {
ua_buffer_reader->mbuf->size_index = buffer_size_to_index(t_state.hdr_info.request_content_length);
ua_entry->vc_handler = &HttpSM::state_drain_client_request_body;
ua_entry->read_vio = ua_entry->vc->do_io_read(this, post_bytes - client_request_body_bytes, ua_buffer_reader->mbuf);
} else {
call_transact_and_set_next_state(NULL);
}
}
#endif /* PROXY_DRAIN */
void
HttpSM::do_setup_post_tunnel(HttpVC_t to_vc_type)
{
bool chunked = (t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING);
bool post_redirect = false;
HttpTunnelProducer *p = nullptr;
// YTS Team, yamsat Plugin
// if redirect_in_process and redirection is enabled add static producer
if (t_state.redirect_info.redirect_in_process && enable_redirection &&
(tunnel.postbuf && tunnel.postbuf->postdata_copy_buffer_start != nullptr &&
tunnel.postbuf->postdata_producer_buffer != nullptr)) {
post_redirect = true;
// copy the post data into a new producer buffer for static producer
tunnel.postbuf->postdata_producer_buffer->write(tunnel.postbuf->postdata_copy_buffer_start);
int64_t post_bytes = tunnel.postbuf->postdata_producer_reader->read_avail();
transfered_bytes = post_bytes;
p = tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, post_bytes, tunnel.postbuf->postdata_producer_reader,
(HttpProducerHandler) nullptr, HT_STATIC, "redirect static agent post");
// the tunnel has taken over the buffer and will free it
tunnel.postbuf->postdata_producer_buffer = nullptr;
tunnel.postbuf->postdata_producer_reader = nullptr;
} else {
int64_t alloc_index;
// content length is undefined, use default buffer size
if (t_state.hdr_info.request_content_length == HTTP_UNDEFINED_CL) {
alloc_index = (int)t_state.txn_conf->default_buffer_size_index;
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > MAX_BUFFER_SIZE_INDEX) {
alloc_index = DEFAULT_REQUEST_BUFFER_SIZE_INDEX;
}
} else {
alloc_index = buffer_size_to_index(t_state.hdr_info.request_content_length);
}
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
int64_t post_bytes = chunked ? INT64_MAX : t_state.hdr_info.request_content_length;
// Note: Many browsers, Netscape and IE included send two extra
// bytes (CRLF) at the end of the post. We just ignore those
// bytes since the sending them is not spec
// Next order of business if copy the remaining data from the
// header buffer into new buffer
client_request_body_bytes = post_buffer->write(ua_buffer_reader, chunked ? ua_buffer_reader->read_avail() : post_bytes);
ua_buffer_reader->consume(client_request_body_bytes);
p = tunnel.add_producer(ua_entry->vc, post_bytes - transfered_bytes, buf_start, &HttpSM::tunnel_handler_post_ua, HT_HTTP_CLIENT,
"user agent post");
}
ua_entry->in_tunnel = true;
switch (to_vc_type) {
case HTTP_TRANSFORM_VC:
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_request_wait_for_transform_read);
ink_assert(post_transform_info.entry != nullptr);
ink_assert(post_transform_info.entry->vc == post_transform_info.vc);
tunnel.add_consumer(post_transform_info.entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"post transform");
post_transform_info.entry->in_tunnel = true;
break;
case HTTP_SERVER_VC:
// YTS Team, yamsat Plugin
// When redirect in process is true and redirection is enabled
// add http server as the consumer
if (post_redirect) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_for_partial_post);
tunnel.add_consumer(server_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER,
"redirect http server post");
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
tunnel.add_consumer(server_entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER, "http server post");
}
server_entry->in_tunnel = true;
break;
default:
ink_release_assert(0);
break;
}
if (chunked) {
tunnel.set_producer_chunking_action(p, 0, TCA_PASSTHRU_CHUNKED_CONTENT);
}
ua_session->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
tunnel.tunnel_run(p);
// If we're half closed, we got a FIN from the client. Forward it on to the origin server
// now that we have the tunnel operational.
if (ua_session->get_half_close_flag()) {
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
}
}
// void HttpSM::perform_transform_cache_write_action()
//
// Called to do cache write from the transform
//
void
HttpSM::perform_transform_cache_write_action()
{
DebugSM("http", "[%" PRId64 "] perform_transform_cache_write_action %s", sm_id,
HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
if (t_state.range_setup) {
return;
}
switch (t_state.cache_info.transform_action) {
case HttpTransact::CACHE_DO_NO_ACTION: {
// Nothing to do
transform_cache_sm.end_both();
break;
}
case HttpTransact::CACHE_DO_WRITE: {
transform_cache_sm.close_read();
t_state.cache_info.transform_write_status = HttpTransact::CACHE_WRITE_IN_PROGRESS;
setup_cache_write_transfer(&transform_cache_sm, transform_info.entry->vc, &t_state.cache_info.transform_store,
client_response_hdr_bytes, "cache write t");
break;
}
default:
ink_release_assert(0);
break;
}
}
// void HttpSM::perform_cache_write_action()
//
// Called to do cache write, delete and updates based
// on s->cache_info.action. Does not setup cache
// read tunnels
//
void
HttpSM::perform_cache_write_action()
{
DebugSM("http", "[%" PRId64 "] perform_cache_write_action %s", sm_id,
HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
switch (t_state.cache_info.action) {
case HttpTransact::CACHE_DO_NO_ACTION:
{
// Nothing to do
cache_sm.end_both();
break;
}
case HttpTransact::CACHE_DO_SERVE: {
cache_sm.abort_write();
break;
}
case HttpTransact::CACHE_DO_DELETE: {
// Write close deletes the old alternate
cache_sm.close_write();
cache_sm.close_read();
break;
}
case HttpTransact::CACHE_DO_SERVE_AND_DELETE: {
// FIX ME: need to set up delete for after cache write has
// completed
break;
}
case HttpTransact::CACHE_DO_SERVE_AND_UPDATE: {
issue_cache_update();
break;
}
case HttpTransact::CACHE_DO_UPDATE: {
cache_sm.close_read();
issue_cache_update();
break;
}
case HttpTransact::CACHE_DO_WRITE:
case HttpTransact::CACHE_DO_REPLACE:
// Fix need to set up delete for after cache write has
// completed
if (transform_info.entry == nullptr || t_state.api_info.cache_untransformed == true) {
cache_sm.close_read();
t_state.cache_info.write_status = HttpTransact::CACHE_WRITE_IN_PROGRESS;
setup_cache_write_transfer(&cache_sm, server_entry->vc, &t_state.cache_info.object_store, client_response_hdr_bytes,
"cache write");
} else {
// We are not caching the untransformed. We might want to
// use the cache writevc to cache the transformed copy
ink_assert(transform_cache_sm.cache_write_vc == nullptr);
transform_cache_sm.cache_write_vc = cache_sm.cache_write_vc;
cache_sm.cache_write_vc = nullptr;
}
break;
default:
ink_release_assert(0);
break;
}
}
void
HttpSM::issue_cache_update()
{
ink_assert(cache_sm.cache_write_vc != nullptr);
if (cache_sm.cache_write_vc) {
t_state.cache_info.object_store.request_sent_time_set(t_state.request_sent_time);
t_state.cache_info.object_store.response_received_time_set(t_state.response_received_time);
ink_assert(t_state.cache_info.object_store.request_sent_time_get() > 0);
ink_assert(t_state.cache_info.object_store.response_received_time_get() > 0);
cache_sm.cache_write_vc->set_http_info(&t_state.cache_info.object_store);
t_state.cache_info.object_store.clear();
}
// Now close the write which commits the update
cache_sm.close_write();
}
int
HttpSM::write_header_into_buffer(HTTPHdr *h, MIOBuffer *b)
{
int bufindex;
int dumpoffset;
int done, tmp;
IOBufferBlock *block;
dumpoffset = 0;
do {
bufindex = 0;
tmp = dumpoffset;
block = b->get_current_block();
ink_assert(block->write_avail() > 0);
done = h->print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
ink_assert(bufindex > 0);
b->fill(bufindex);
if (!done) {
b->add_block();
}
} while (!done);
return dumpoffset;
}
void
HttpSM::attach_server_session(HttpServerSession *s)
{
hsm_release_assert(server_session == nullptr);
hsm_release_assert(server_entry == nullptr);
hsm_release_assert(s->state == HSS_ACTIVE);
server_session = s;
server_transact_count = server_session->transact_count++;
// Propagate the per client IP debugging
if (ua_session) {
s->get_netvc()->control_flags = get_cont_flags();
} else { // If there is no ua_session no sense in continuing to attach the server session
return;
}
// Set the mutex so that we have something to update
// stats with
server_session->mutex = this->mutex;
HTTP_INCREMENT_DYN_STAT(http_current_server_transactions_stat);
++s->server_trans_stat;
// Record the VC in our table
server_entry = vc_table.new_entry();
server_entry->vc = server_session;
server_entry->vc_type = HTTP_SERVER_VC;
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
// es - is this a concern here in HttpSM? Does it belong somewhere else?
// Get server and client connections
UnixNetVConnection *server_vc = dynamic_cast<UnixNetVConnection *>(server_session->get_netvc());
UnixNetVConnection *client_vc = (UnixNetVConnection *)(ua_session->get_netvc());
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(client_vc);
// Verifying that the user agent and server sessions/transactions are operating on the same thread.
ink_release_assert(!server_vc || !client_vc || server_vc->thread == client_vc->thread);
bool associated_connection = false;
if (server_vc) { // if server_vc isn't a PluginVC
if (ssl_vc) { // if incoming connection is SSL
bool client_trace = ssl_vc->getSSLTrace();
if (client_trace) {
// get remote address and port to mark corresponding traces
const sockaddr *remote_addr = ssl_vc->get_remote_addr();
uint16_t remote_port = ssl_vc->get_remote_port();
server_vc->setOriginTrace(true);
server_vc->setOriginTraceAddr(remote_addr);
server_vc->setOriginTracePort(remote_port);
associated_connection = true;
}
}
}
if (!associated_connection && server_vc) {
server_vc->setOriginTrace(false);
server_vc->setOriginTraceAddr(nullptr);
server_vc->setOriginTracePort(0);
}
// set flag for server session is SSL
SSLNetVConnection *server_ssl_vc = dynamic_cast<SSLNetVConnection *>(server_vc);
if (server_ssl_vc) {
server_connection_is_ssl = true;
}
// Initiate a read on the session so that the SM and not
// session manager will get called back if the timeout occurs
// or the server closes on us. The IO Core now requires us to
// do the read with a buffer and a size so preallocate the
// buffer
server_buffer_reader = server_session->get_reader();
// ts-3189 We are only setting up an empty read at this point. This
// is sufficient to have the timeout errors directed to the appropriate
// SM handler, but we don't want to read any data until the tunnel has
// been set up. This isn't such a big deal with GET results, since
// if no tunnels are set up, there is no danger of data being delivered
// to the wrong tunnel's consumer handler. But for post and other
// methods that send data after the request, two tunnels are created in
// series, and with a full read set up at this point, the EOS from the
// first tunnel was sometimes behind handled by the consumer of the
// first tunnel instead of the producer of the second tunnel.
// The real read is setup in setup_server_read_response_header()
//
server_entry->read_vio = server_session->do_io_read(this, 0, server_session->read_buffer);
// Transfer control of the write side as well
server_entry->write_vio = server_session->do_io_write(this, 0, nullptr);
// Setup the timeouts
// Set the inactivity timeout to the connect timeout so that we
// we fail this server if it doesn't start sending the response
// header
MgmtInt connect_timeout;
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
connect_timeout = t_state.txn_conf->post_connect_attempts_timeout;
} else if (t_state.current.server == &t_state.parent_info) {
connect_timeout = t_state.http_config_param->parent_connect_timeout;
} else {
connect_timeout = t_state.txn_conf->connect_attempts_timeout;
}
if (t_state.pCongestionEntry != nullptr) {
connect_timeout = t_state.pCongestionEntry->connect_timeout();
}
if (t_state.api_txn_connect_timeout_value != -1) {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_MSECONDS(t_state.api_txn_connect_timeout_value));
} else {
server_session->get_netvc()->set_inactivity_timeout(HRTIME_SECONDS(connect_timeout));
}
if (t_state.api_txn_active_timeout_value != -1) {
server_session->get_netvc()->set_active_timeout(HRTIME_MSECONDS(t_state.api_txn_active_timeout_value));
} else {
server_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_out));
}
if (plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL || will_be_private_ss) {
DebugSM("http_ss", "Setting server session to private");
set_server_session_private(true);
}
}
void
HttpSM::setup_server_send_request_api()
{
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR;
do_api_callout();
}
void
HttpSM::setup_server_send_request()
{
int hdr_length;
int64_t msg_len = 0; /* lv: just make gcc happy */
hsm_release_assert(server_entry != nullptr);
hsm_release_assert(server_session != nullptr);
hsm_release_assert(server_entry->vc == server_session);
// Send the request header
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
server_entry->write_buffer = new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
if (t_state.api_server_request_body_set) {
msg_len = t_state.internal_msg_buffer_size;
t_state.hdr_info.server_request.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, msg_len);
}
if (!t_state.cop_test_page) {
DUMP_HEADER("http_hdrs", &(t_state.hdr_info.server_request), t_state.state_machine_id, "Proxy's Request after hooks");
}
// We need a reader so bytes don't fall off the end of
// the buffer
IOBufferReader *buf_start = server_entry->write_buffer->alloc_reader();
server_request_hdr_bytes = hdr_length = write_header_into_buffer(&t_state.hdr_info.server_request, server_entry->write_buffer);
// the plugin decided to append a message to the request
if (t_state.api_server_request_body_set) {
DebugSM("http", "[%" PRId64 "] appending msg of %" PRId64 " bytes to request %s", sm_id, msg_len, t_state.internal_msg_buffer);
hdr_length += server_entry->write_buffer->write(t_state.internal_msg_buffer, msg_len);
server_request_body_bytes = msg_len;
}
milestones[TS_MILESTONE_SERVER_BEGIN_WRITE] = Thread::get_hrtime();
server_entry->write_vio = server_entry->vc->do_io_write(this, hdr_length, buf_start);
}
void
HttpSM::setup_server_read_response_header()
{
ink_assert(server_session != nullptr);
ink_assert(server_entry != nullptr);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed in REQ_FLAVOR_REVPROXY
ink_assert(ua_session != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
// We should have set the server_buffer_reader
// we sent the request header
ink_assert(server_buffer_reader != nullptr);
// Now that we've got the ability to read from the
// server, setup to read the response header
server_entry->vc_handler = &HttpSM::state_read_server_response_header;
t_state.current.state = HttpTransact::STATE_UNDEFINED;
t_state.current.server->state = HttpTransact::STATE_UNDEFINED;
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
server_response_hdr_bytes = 0;
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = 0;
// We already done the READ when we setup the connection to
// read the request header
ink_assert(server_entry->read_vio);
// The tunnel from OS to UA is now setup. Ready to read the response
server_entry->read_vio = server_session->do_io_read(this, INT64_MAX, server_buffer_reader->mbuf);
// If there is anything in the buffer call the parsing routines
// since if the response is finished, we won't get any
// additional callbacks
if (server_buffer_reader->read_avail() > 0) {
state_read_server_response_header((server_entry->eos) ? VC_EVENT_EOS : VC_EVENT_READ_READY, server_entry->read_vio);
}
}
HttpTunnelProducer *
HttpSM::setup_cache_read_transfer()
{
int64_t alloc_index, hdr_size;
int64_t doc_size;
ink_assert(cache_sm.cache_read_vc != nullptr);
doc_size = t_state.cache_info.object_read->object_size_get();
alloc_index = buffer_size_to_index(doc_size + index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX));
#ifndef USE_NEW_EMPTY_MIOBUFFER
MIOBuffer *buf = new_MIOBuffer(alloc_index);
#else
MIOBuffer *buf = new_empty_MIOBuffer(alloc_index);
buf->append_block(HTTP_HEADER_BUFFER_SIZE_INDEX);
#endif
buf->water_mark = (int)t_state.txn_conf->default_buffer_water_mark;
IOBufferReader *buf_start = buf->alloc_reader();
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = hdr_size = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
cache_response_hdr_bytes = client_response_hdr_bytes;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
if (doc_size != INT64_MAX) {
doc_size += hdr_size;
}
HttpTunnelProducer *p = tunnel.add_producer(cache_sm.cache_read_vc, doc_size, buf_start, &HttpSM::tunnel_handler_cache_read,
HT_CACHE_READ, "cache read");
tunnel.add_consumer(ua_entry->vc, cache_sm.cache_read_vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
// if size of a cached item is not known, we'll do chunking for keep-alive HTTP/1.1 clients
// this only applies to read-while-write cases where origin server sends a dynamically generated chunked content
// w/o providing a Content-Length header
if (t_state.client_info.receive_chunked_response) {
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_CHUNK_CONTENT);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
}
ua_entry->in_tunnel = true;
cache_sm.cache_read_vc = nullptr;
return p;
}
HttpTunnelProducer *
HttpSM::setup_cache_transfer_to_transform()
{
int64_t alloc_index;
int64_t doc_size;
ink_assert(cache_sm.cache_read_vc != nullptr);
ink_assert(transform_info.vc != nullptr);
ink_assert(transform_info.entry->vc == transform_info.vc);
// grab this here
cache_response_hdr_bytes = t_state.hdr_info.cache_response.length_get();
doc_size = t_state.cache_info.object_read->object_size_get();
alloc_index = buffer_size_to_index(doc_size);
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_response_wait_for_transform_read);
HttpTunnelProducer *p = tunnel.add_producer(cache_sm.cache_read_vc, doc_size, buf_start, &HttpSM::tunnel_handler_cache_read,
HT_CACHE_READ, "cache read");
tunnel.add_consumer(transform_info.vc, cache_sm.cache_read_vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"transform write");
transform_info.entry->in_tunnel = true;
cache_sm.cache_read_vc = nullptr;
return p;
}
void
HttpSM::setup_cache_write_transfer(HttpCacheSM *c_sm, VConnection *source_vc, HTTPInfo *store_info, int64_t skip_bytes,
const char *name)
{
ink_assert(c_sm->cache_write_vc != nullptr);
ink_assert(t_state.request_sent_time > 0);
ink_assert(t_state.response_received_time > 0);
store_info->request_sent_time_set(t_state.request_sent_time);
store_info->response_received_time_set(t_state.response_received_time);
c_sm->cache_write_vc->set_http_info(store_info);
store_info->clear();
tunnel.add_consumer(c_sm->cache_write_vc, source_vc, &HttpSM::tunnel_handler_cache_write, HT_CACHE_WRITE, name, skip_bytes);
c_sm->cache_write_vc = nullptr;
}
void
HttpSM::setup_100_continue_transfer()
{
MIOBuffer *buf = new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
IOBufferReader *buf_start = buf->alloc_reader();
// First write the client response header into the buffer
ink_assert(t_state.client_info.http_version != HTTPVersion(0, 9));
client_response_hdr_bytes = write_header_into_buffer(&t_state.hdr_info.client_response, buf);
ink_assert(client_response_hdr_bytes > 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_100_continue);
// Setup the tunnel to the client
HttpTunnelProducer *p = tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, client_response_hdr_bytes, buf_start,
(HttpProducerHandler) nullptr, HT_STATIC, "internal msg - 100 continue");
tunnel.add_consumer(ua_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_100_continue_ua, HT_HTTP_CLIENT,
"user agent");
// Make sure the half_close is not set.
ua_session->set_half_close_flag(false);
ua_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::setup_error_transfer()
//
// The proxy has generated an error message which it
// is sending to the client. For some cases, however,
// such as when the proxy is transparent, returning
// a proxy-generated error message exposes the proxy,
// destroying transparency. The HttpBodyFactory code,
// therefore, does not generate an error message body
// in such cases. This function checks for the presence
// of an error body. If its not present, it closes the
// connection to the user, else it simply calls
// setup_write_proxy_internal, which is the standard
// routine for setting up proxy-generated responses.
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::setup_error_transfer()
{
if (t_state.internal_msg_buffer) {
// Since we need to send the error message, call the API
// function
ink_assert(t_state.internal_msg_buffer_size > 0);
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
} else {
DebugSM("http", "[setup_error_transfer] Now closing connection ...");
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
// ua_session = NULL;
terminate_sm = true;
t_state.source = HttpTransact::SOURCE_INTERNAL;
}
}
void
HttpSM::setup_internal_transfer(HttpSMHandler handler_arg)
{
bool is_msg_buf_present;
if (t_state.internal_msg_buffer) {
is_msg_buf_present = true;
ink_assert(t_state.internal_msg_buffer_size > 0);
// Set the content length here since a plugin
// may have changed the error body
t_state.hdr_info.client_response.set_content_length(t_state.internal_msg_buffer_size);
t_state.hdr_info.client_response.field_delete(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
// set internal_msg_buffer_type if available
if (t_state.internal_msg_buffer_type) {
int len = strlen(t_state.internal_msg_buffer_type);
if (len > 0) {
t_state.hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, t_state.internal_msg_buffer_type,
len);
}
ats_free(t_state.internal_msg_buffer_type);
t_state.internal_msg_buffer_type = nullptr;
} else {
t_state.hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/html", 9);
}
} else {
is_msg_buf_present = false;
// If we are sending a response that can have a body
// but doesn't have a body add a content-length of zero.
// Needed for keep-alive on PURGE requests
if (!is_response_body_precluded(t_state.hdr_info.client_response.status_get(), t_state.method)) {
t_state.hdr_info.client_response.set_content_length(0);
t_state.hdr_info.client_response.field_delete(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
}
}
t_state.source = HttpTransact::SOURCE_INTERNAL;
int64_t buf_size =
index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX) + (is_msg_buf_present ? t_state.internal_msg_buffer_size : 0);
MIOBuffer *buf = new_MIOBuffer(buffer_size_to_index(buf_size));
IOBufferReader *buf_start = buf->alloc_reader();
// First write the client response header into the buffer
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
int64_t nbytes = client_response_hdr_bytes;
// Next append the message onto the MIOBuffer
// From HTTP/1.1 RFC:
// "The HEAD method is identical to GET except that the server
// MUST NOT return a message-body in the response. The metainformation
// in the HTTP headers in response to a HEAD request SHOULD be
// identical to the information sent in response to a GET request."
// --> do not append the message onto the MIOBuffer and keep our pointer
// to it so that it can be freed.
if (is_msg_buf_present && t_state.method != HTTP_WKSIDX_HEAD) {
nbytes += t_state.internal_msg_buffer_size;
if (t_state.internal_msg_buffer_fast_allocator_size < 0) {
buf->append_xmalloced(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size);
} else {
buf->append_fast_allocated(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size,
t_state.internal_msg_buffer_fast_allocator_size);
}
// The IOBufferBlock will free the msg buffer when necessary so
// eliminate our pointer to it
t_state.internal_msg_buffer = nullptr;
t_state.internal_msg_buffer_size = 0;
}
HTTP_SM_SET_DEFAULT_HANDLER(handler_arg);
// Clear the decks before we setup the new producers
// As things stand, we cannot have two static producers operating at
// once
tunnel.reset();
// Setup the tunnel to the client
HttpTunnelProducer *p =
tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, nbytes, buf_start, (HttpProducerHandler) nullptr, HT_STATIC, "internal msg");
tunnel.add_consumer(ua_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
ua_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
// int HttpSM::find_http_resp_buffer_size(int cl)
//
// Returns the allocation index for the buffer for
// a response based on the content length
//
int
HttpSM::find_http_resp_buffer_size(int64_t content_length)
{
int64_t buf_size;
int64_t alloc_index;
if (content_length == HTTP_UNDEFINED_CL) {
// Try use our configured default size. Otherwise pick
// the default size
alloc_index = (int)t_state.txn_conf->default_buffer_size_index;
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > DEFAULT_MAX_BUFFER_SIZE) {
alloc_index = DEFAULT_RESPONSE_BUFFER_SIZE_INDEX;
}
} else {
#ifdef WRITE_AND_TRANSFER
buf_size = HTTP_HEADER_BUFFER_SIZE + content_length - index_to_buffer_size(HTTP_SERVER_RESP_HDR_BUFFER_INDEX);
#else
buf_size = index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX) + content_length;
#endif
alloc_index = buffer_size_to_index(buf_size);
}
return alloc_index;
}
// int HttpSM::server_transfer_init()
//
// Moves data from the header buffer into the reply buffer
// and return the number of bytes we should use for initiating the
// tunnel
//
int64_t
HttpSM::server_transfer_init(MIOBuffer *buf, int hdr_size)
{
int64_t nbytes;
int64_t to_copy = INT64_MAX;
ink_assert(t_state.current.server != nullptr); // should have been set up if we're doing a transfer.
if (server_entry->eos == true) {
// The server has shutdown on us already so the only data
// we'll get is already in the buffer
nbytes = server_buffer_reader->read_avail() + hdr_size;
} else if (t_state.hdr_info.response_content_length == HTTP_UNDEFINED_CL) {
nbytes = -1;
} else {
// Set to copy to the number of bytes we want to write as
// if the server is sending us a bogus response we have to
// truncate it as we've already decided to trust the content
// length
to_copy = t_state.hdr_info.response_content_length;
nbytes = t_state.hdr_info.response_content_length + hdr_size;
}
// Next order of business if copy the remaining data from the
// header buffer into new buffer.
int64_t server_response_pre_read_bytes =
#ifdef WRITE_AND_TRANSFER
/* relinquish the space in server_buffer and let
the tunnel use the trailing space
*/
buf->write_and_transfer_left_over_space(server_buffer_reader, to_copy);
#else
buf->write(server_buffer_reader, to_copy);
#endif
server_buffer_reader->consume(server_response_pre_read_bytes);
// If we know the length & copied the entire body
// of the document out of the header buffer make
// sure the server isn't screwing us by having sent too
// much. If it did, we want to close the server connection
if (server_response_pre_read_bytes == to_copy && server_buffer_reader->read_avail() > 0) {
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
#ifdef LAZY_BUF_ALLOC
// reset the server session buffer
server_session->reset_read_buffer();
#endif
return nbytes;
}
HttpTunnelProducer *
HttpSM::setup_server_transfer_to_transform()
{
int64_t alloc_index;
int64_t nbytes;
alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
nbytes = server_transfer_init(buf, 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_response_wait_for_transform_read);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.add_consumer(transform_info.vc, server_entry->vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"transform write");
server_entry->in_tunnel = true;
transform_info.entry->in_tunnel = true;
if (t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
client_response_hdr_bytes = 0; // fixed by YTS Team, yamsat
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_DECHUNK_CONTENT);
}
return p;
}
HttpTunnelProducer *
HttpSM::setup_transfer_from_transform()
{
int64_t alloc_index = find_server_buffer_size();
// TODO change this call to new_empty_MIOBuffer()
MIOBuffer *buf = new_MIOBuffer(alloc_index);
buf->water_mark = (int)t_state.txn_conf->default_buffer_water_mark;
IOBufferReader *buf_start = buf->alloc_reader();
HttpTunnelConsumer *c = tunnel.get_consumer(transform_info.vc);
ink_assert(c != nullptr);
ink_assert(c->vc == transform_info.vc);
ink_assert(c->vc_type == HT_TRANSFORM);
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p = tunnel.add_producer(transform_info.vc, INT64_MAX, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "transform read");
tunnel.chain(c, p);
tunnel.add_consumer(ua_entry->vc, transform_info.vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
transform_info.entry->in_tunnel = true;
ua_entry->in_tunnel = true;
this->setup_plugin_agents(p);
if (t_state.client_info.receive_chunked_response) {
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_CHUNK_CONTENT);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
}
return p;
}
HttpTunnelProducer *
HttpSM::setup_transfer_from_transform_to_cache_only()
{
int64_t alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
HttpTunnelConsumer *c = tunnel.get_consumer(transform_info.vc);
ink_assert(c != nullptr);
ink_assert(c->vc == transform_info.vc);
ink_assert(c->vc_type == HT_TRANSFORM);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p = tunnel.add_producer(transform_info.vc, INT64_MAX, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "transform read");
tunnel.chain(c, p);
transform_info.entry->in_tunnel = true;
ink_assert(t_state.cache_info.transform_action == HttpTransact::CACHE_DO_WRITE);
perform_transform_cache_write_action();
return p;
}
void
HttpSM::setup_server_transfer_to_cache_only()
{
TunnelChunkingAction_t action;
int64_t alloc_index;
int64_t nbytes;
alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
action = (t_state.current.server && t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) ?
TCA_DECHUNK_CONTENT :
TCA_PASSTHRU_DECHUNKED_CONTENT;
nbytes = server_transfer_init(buf, 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.set_producer_chunking_action(p, 0, action);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
setup_cache_write_transfer(&cache_sm, server_entry->vc, &t_state.cache_info.object_store, 0, "cache write");
server_entry->in_tunnel = true;
}
HttpTunnelProducer *
HttpSM::setup_server_transfer()
{
DebugSM("http", "Setup Server Transfer");
int64_t alloc_index, hdr_size;
int64_t nbytes;
alloc_index = find_server_buffer_size();
#ifndef USE_NEW_EMPTY_MIOBUFFER
MIOBuffer *buf = new_MIOBuffer(alloc_index);
#else
MIOBuffer *buf = new_empty_MIOBuffer(alloc_index);
buf->append_block(HTTP_HEADER_BUFFER_SIZE_INDEX);
#endif
buf->water_mark = (int)t_state.txn_conf->default_buffer_water_mark;
IOBufferReader *buf_start = buf->alloc_reader();
// we need to know if we are going to chunk the response or not
// before we write the response header into buffer
TunnelChunkingAction_t action;
if (t_state.client_info.receive_chunked_response == false) {
if (t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
action = TCA_DECHUNK_CONTENT;
} else {
action = TCA_PASSTHRU_DECHUNKED_CONTENT;
}
} else {
if (t_state.current.server->transfer_encoding != HttpTransact::CHUNKED_ENCODING) {
if (t_state.client_info.http_version == HTTPVersion(0, 9)) {
action = TCA_PASSTHRU_DECHUNKED_CONTENT; // send as-is
} else {
action = TCA_CHUNK_CONTENT;
}
} else {
action = TCA_PASSTHRU_CHUNKED_CONTENT;
}
}
if (action == TCA_CHUNK_CONTENT || action == TCA_PASSTHRU_CHUNKED_CONTENT) { // remove Content-Length
t_state.hdr_info.client_response.field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
}
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = hdr_size = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
nbytes = server_transfer_init(buf, hdr_size);
if (t_state.negative_caching && t_state.hdr_info.server_response.status_get() == HTTP_STATUS_NO_CONTENT) {
int s = sizeof("No Content") - 1;
buf->write("No Content", s);
nbytes += s;
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.add_consumer(ua_entry->vc, server_entry->vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
ua_entry->in_tunnel = true;
server_entry->in_tunnel = true;
this->setup_plugin_agents(p);
// If the incoming server response is chunked and the client does not
// expect a chunked response, then dechunk it. Otherwise, if the
// incoming response is not chunked and the client expects a chunked
// response, then chunk it.
/*
// this block is moved up so that we know if we need to remove
// Content-Length field from response header before writing the
// response header into buffer bz50730
TunnelChunkingAction_t action;
if (t_state.client_info.receive_chunked_response == false) {
if (t_state.current.server->transfer_encoding ==
HttpTransact::CHUNKED_ENCODING)
action = TCA_DECHUNK_CONTENT;
else action = TCA_PASSTHRU_DECHUNKED_CONTENT;
}
else {
if (t_state.current.server->transfer_encoding !=
HttpTransact::CHUNKED_ENCODING)
action = TCA_CHUNK_CONTENT;
else action = TCA_PASSTHRU_CHUNKED_CONTENT;
}
*/
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, action);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
return p;
}
HttpTunnelProducer *
HttpSM::setup_push_transfer_to_cache()
{
int64_t nbytes, alloc_index;
alloc_index = find_http_resp_buffer_size(t_state.hdr_info.request_content_length);
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
ink_release_assert(t_state.hdr_info.request_content_length != HTTP_UNDEFINED_CL);
nbytes = t_state.hdr_info.request_content_length - pushed_response_hdr_bytes;
ink_release_assert(nbytes >= 0);
if (ua_entry->eos == true) {
// The ua has shutdown on us already so the only data
// we'll get is already in the buffer. Make sure it
// fulfills the stated length
int64_t avail = ua_buffer_reader->read_avail();
if (avail < nbytes) {
// Client failed to send the body, it's gone. Kill the
// state machine
terminate_sm = true;
return nullptr;
}
}
// Next order of business is copy the remaining data from the
// header buffer into new buffer.
pushed_response_body_bytes = buf->write(ua_buffer_reader, nbytes);
ua_buffer_reader->consume(pushed_response_body_bytes);
client_request_body_bytes += pushed_response_body_bytes;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_push);
HttpTunnelProducer *p =
tunnel.add_producer(ua_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_ua_push, HT_HTTP_CLIENT, "user_agent");
setup_cache_write_transfer(&cache_sm, ua_entry->vc, &t_state.cache_info.object_store, 0, "cache write");
ua_entry->in_tunnel = true;
return p;
}
void
HttpSM::setup_blind_tunnel(bool send_response_hdr)
{
HttpTunnelConsumer *c_ua;
HttpTunnelConsumer *c_os;
HttpTunnelProducer *p_ua;
HttpTunnelProducer *p_os;
MIOBuffer *from_ua_buf = new_MIOBuffer(BUFFER_SIZE_INDEX_32K);
MIOBuffer *to_ua_buf = new_MIOBuffer(BUFFER_SIZE_INDEX_32K);
IOBufferReader *r_from = from_ua_buf->alloc_reader();
IOBufferReader *r_to = to_ua_buf->alloc_reader();
milestones[TS_MILESTONE_SERVER_BEGIN_WRITE] = Thread::get_hrtime();
if (send_response_hdr) {
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, to_ua_buf);
} else {
client_response_hdr_bytes = 0;
}
client_request_body_bytes = 0;
if (ua_raw_buffer_reader != nullptr) {
client_request_body_bytes += from_ua_buf->write(ua_raw_buffer_reader, client_request_hdr_bytes);
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
// Next order of business if copy the remaining data from the
// header buffer into new buffer
client_request_body_bytes += from_ua_buf->write(ua_buffer_reader);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
p_os =
tunnel.add_producer(server_entry->vc, -1, r_to, &HttpSM::tunnel_handler_ssl_producer, HT_HTTP_SERVER, "http server - tunnel");
c_ua = tunnel.add_consumer(ua_entry->vc, server_entry->vc, &HttpSM::tunnel_handler_ssl_consumer, HT_HTTP_CLIENT,
"user agent - tunnel");
p_ua = tunnel.add_producer(ua_entry->vc, -1, r_from, &HttpSM::tunnel_handler_ssl_producer, HT_HTTP_CLIENT, "user agent - tunnel");
c_os = tunnel.add_consumer(server_entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_ssl_consumer, HT_HTTP_SERVER,
"http server - tunnel");
// Make the tunnel aware that the entries are bi-directional
tunnel.chain(c_os, p_os);
tunnel.chain(c_ua, p_ua);
ua_entry->in_tunnel = true;
server_entry->in_tunnel = true;
tunnel.tunnel_run();
// If we're half closed, we got a FIN from the client. Forward it on to the origin server
// now that we have the tunnel operational.
if (ua_session->get_half_close_flag()) {
p_ua->vc->do_io_shutdown(IO_SHUTDOWN_READ);
}
}
void
HttpSM::setup_plugin_agents(HttpTunnelProducer *p)
{
APIHook *agent = txn_hook_get(TS_HTTP_RESPONSE_CLIENT_HOOK);
has_active_plugin_agents = agent != nullptr;
while (agent) {
INKVConnInternal *contp = static_cast<INKVConnInternal *>(agent->m_cont);
tunnel.add_consumer(contp, p->vc, &HttpSM::tunnel_handler_plugin_agent, HT_HTTP_CLIENT, "plugin agent");
// We don't put these in the SM VC table because the tunnel
// will clean them up in do_io_close().
agent = agent->next();
}
}
inline void
HttpSM::transform_cleanup(TSHttpHookID hook, HttpTransformInfo *info)
{
APIHook *t_hook = api_hooks.get(hook);
if (t_hook && info->vc == nullptr) {
do {
VConnection *t_vcon = t_hook->m_cont;
t_vcon->do_io_close();
t_hook = t_hook->m_link.next;
} while (t_hook != nullptr);
}
}
void
HttpSM::plugin_agents_cleanup()
{
// If this is set then all of the plugin agent VCs were put in
// the VC table and cleaned up there. This handles the case where
// something went wrong early.
if (!has_active_plugin_agents) {
APIHook *agent = txn_hook_get(TS_HTTP_RESPONSE_CLIENT_HOOK);
while (agent) {
INKVConnInternal *contp = static_cast<INKVConnInternal *>(agent->m_cont);
contp->do_io_close();
agent = agent->next();
}
}
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::kill_this()
//
// This function has two phases. One before we call the asynchronous
// clean up routines (api and list removal) and one after.
// The state about which phase we are in is kept in
// HttpSM::kill_this_async_done
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::kill_this()
{
ink_release_assert(reentrancy_count == 1);
tunnel.deallocate_redirect_postdata_buffers();
enable_redirection = false;
if (kill_this_async_done == false) {
////////////////////////////////
// cancel uncompleted actions //
////////////////////////////////
// The action should be cancelled only if
// the state machine is in HTTP_API_NO_CALLOUT
// state. This is because we are depending on the
// callout to complete for the state machine to
// get killed.
if (callout_state == HTTP_API_NO_CALLOUT && pending_action) {
pending_action->cancel();
pending_action = nullptr;
}
cache_sm.end_both();
if (second_cache_sm) {
second_cache_sm->end_both();
}
transform_cache_sm.end_both();
vc_table.cleanup_all();
// tunnel.deallocate_buffers();
// Why don't we just kill the tunnel? Might still be
// active if the state machine is going down hard,
// and we should clean it up.
tunnel.kill_tunnel();
// It possible that a plugin added transform hook
// but the hook never executed due to a client abort
// In that case, we need to manually close all the
// transforms to prevent memory leaks (INKqa06147)
if (hooks_set) {
transform_cleanup(TS_HTTP_RESPONSE_TRANSFORM_HOOK, &transform_info);
transform_cleanup(TS_HTTP_REQUEST_TRANSFORM_HOOK, &post_transform_info);
plugin_agents_cleanup();
}
// It's also possible that the plugin_tunnel vc was never
// executed due to not contacting the server
if (plugin_tunnel) {
plugin_tunnel->kill_no_connect();
plugin_tunnel = nullptr;
}
server_session = nullptr;
// So we don't try to nuke the state machine
// if the plugin receives event we must reset
// the terminate_flag
terminate_sm = false;
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_SHUTDOWN;
do_api_callout();
}
// The reentrancy_count is still valid up to this point since
// the api shutdown hook is asynchronous and double frees can
// happen if the reentrancy count is not still valid until
// after all asynch callouts have completed
//
// Once we get to this point, we could be waiting for async
// completion in which case we need to decrement the reentrancy
// count since the entry points can't do it for us since they
// don't know if the state machine has been destroyed. In the
// case we really are done with asynch callouts, decrement the
// reentrancy count since it seems tacky to destruct a state
// machine with non-zero count
reentrancy_count--;
ink_release_assert(reentrancy_count == 0);
// If the api shutdown & list removal was synchronous
// then the value of kill_this_async_done has changed so
// we must check it again
if (kill_this_async_done == true) {
if (t_state.http_config_param->enable_http_stats) {
update_stats();
}
if (ua_session) {
ua_session->transaction_done();
}
// In the async state, the plugin could have been
// called resulting in the creation of a plugin_tunnel.
// So it needs to be deleted now.
if (plugin_tunnel) {
plugin_tunnel->kill_no_connect();
plugin_tunnel = nullptr;
}
if (t_state.pCongestionEntry != nullptr) {
if (t_state.congestion_congested_or_failed != 1) {
t_state.pCongestionEntry->go_alive();
}
}
ink_assert(pending_action == nullptr);
ink_release_assert(vc_table.is_table_clear() == true);
ink_release_assert(tunnel.is_tunnel_active() == false);
HTTP_SM_SET_DEFAULT_HANDLER(nullptr);
if (!t_state.cop_test_page || t_state.http_config_param->record_cop_page) {
//////////////
// Log Data //
//////////////
DebugSM("http_seq", "[HttpSM::update_stats] Logging transaction");
if (Log::transaction_logging_enabled() && t_state.api_info.logging_enabled) {
LogAccessHttp accessor(this);
int ret = Log::access(&accessor);
if (ret & Log::FULL) {
DebugSM("http", "[update_stats] Logging system indicates FULL.");
}
if (ret & Log::FAIL) {
Log::error("failed to log transaction for at least one log object");
}
}
}
if (redirect_url != nullptr) {
ats_free((void *)redirect_url);
redirect_url = nullptr;
redirect_url_len = 0;
}
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.remove(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
DebugSM("http", "[%" PRId64 "] deallocating sm", sm_id);
// authAdapter.destroyState();
HTTP_DECREMENT_DYN_STAT(http_current_client_transactions_stat);
destroy();
}
}
void
HttpSM::update_stats()
{
milestones[TS_MILESTONE_SM_FINISH] = Thread::get_hrtime();
if (t_state.cop_test_page && !t_state.http_config_param->record_cop_page) {
DebugSM("http_seq", "Skipping cop heartbeat logging & stats due to config");
return;
}
if (is_action_tag_set("bad_length_state_dump")) {
if (t_state.hdr_info.client_response.valid() && t_state.hdr_info.client_response.status_get() == HTTP_STATUS_OK) {
int64_t p_resp_cl = t_state.hdr_info.client_response.get_content_length();
int64_t resp_size = client_response_body_bytes;
if (!((p_resp_cl == -1 || p_resp_cl == resp_size || resp_size == 0))) {
Error("[%" PRId64 "] Truncated content detected", sm_id);
dump_state_on_assert();
}
} else if (client_request_hdr_bytes == 0) {
Error("[%" PRId64 "] Zero length request header received", sm_id);
dump_state_on_assert();
}
}
if (is_action_tag_set("assert_jtest_length")) {
if (t_state.hdr_info.client_response.valid() && t_state.hdr_info.client_response.status_get() == HTTP_STATUS_OK) {
int64_t p_resp_cl = t_state.hdr_info.client_response.get_content_length();
int64_t resp_size = client_response_body_bytes;
ink_release_assert(p_resp_cl == -1 || p_resp_cl == resp_size || resp_size == 0);
}
}
ink_hrtime total_time = milestones.elapsed(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH);
// ua_close will not be assigned properly in some exceptional situation.
// TODO: Assign ua_close with suitable value when HttpTunnel terminates abnormally.
if (milestones[TS_MILESTONE_UA_CLOSE] == 0 && milestones[TS_MILESTONE_UA_READ_HEADER_DONE] > 0) {
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
}
// request_process_time = The time after the header is parsed to the completion of the transaction
ink_hrtime request_process_time = milestones[TS_MILESTONE_UA_CLOSE] - milestones[TS_MILESTONE_UA_READ_HEADER_DONE];
HttpTransact::client_result_stat(&t_state, total_time, request_process_time);
ink_hrtime ua_write_time;
if (milestones[TS_MILESTONE_UA_BEGIN_WRITE] != 0 && milestones[TS_MILESTONE_UA_CLOSE] != 0) {
ua_write_time = milestones.elapsed(TS_MILESTONE_UA_BEGIN_WRITE, TS_MILESTONE_UA_CLOSE);
} else {
ua_write_time = -1;
}
ink_hrtime os_read_time;
if (milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] != 0 && milestones[TS_MILESTONE_SERVER_CLOSE] != 0) {
os_read_time = milestones.elapsed(TS_MILESTONE_SERVER_READ_HEADER_DONE, TS_MILESTONE_SERVER_CLOSE);
} else {
os_read_time = -1;
}
HttpTransact::update_size_and_time_stats(
&t_state, total_time, ua_write_time, os_read_time, client_request_hdr_bytes, client_request_body_bytes,
client_response_hdr_bytes, client_response_body_bytes, server_request_hdr_bytes, server_request_body_bytes,
server_response_hdr_bytes, server_response_body_bytes, pushed_response_hdr_bytes, pushed_response_body_bytes, milestones);
/*
if (is_action_tag_set("http_handler_times")) {
print_all_http_handler_times();
}
*/
// print slow requests if the threshold is set (> 0) and if we are over the time threshold
if (t_state.txn_conf->slow_log_threshold != 0 && ink_hrtime_from_msec(t_state.txn_conf->slow_log_threshold) < total_time) {
URL *url = t_state.hdr_info.client_request.url_get();
char url_string[256] = "";
int offset = 0;
int skip = 0;
t_state.hdr_info.client_request.url_print(url_string, sizeof(url_string) - 1, &offset, &skip);
url_string[offset] = 0; // NULL terminate the string
// unique id
char unique_id_string[128] = "";
// [amc] why do we check the URL to get a MIME field?
if (nullptr != url && url->valid()) {
int length = 0;
const char *field = t_state.hdr_info.client_request.value_get(MIME_FIELD_X_ID, MIME_LEN_X_ID, &length);
if (field != nullptr) {
ink_strlcpy(unique_id_string, field, sizeof(unique_id_string));
}
}
// set the fd for the request
int fd = 0;
NetVConnection *vc = nullptr;
if (ua_session != nullptr) {
vc = ua_session->get_netvc();
if (vc != nullptr) {
fd = vc->get_socket();
} else {
fd = -1;
}
}
// get the status code, lame that we have to check to see if it is valid or we will assert in the method call
int status = 0;
if (t_state.hdr_info.client_response.valid()) {
status = t_state.hdr_info.client_response.status_get();
}
char client_ip[INET6_ADDRSTRLEN];
ats_ip_ntop(&t_state.client_info.src_addr, client_ip, sizeof(client_ip));
Error("[%" PRId64 "] Slow Request: "
"client_ip: %s:%u "
"protocol: %s "
"url: %s "
"status: %d "
"unique id: %s "
"redirection_tries: %d "
"bytes: %" PRId64 " "
"fd: %d "
"client state: %d "
"server state: %d "
"ua_begin: %.3f "
"ua_first_read: %.3f "
"ua_read_header_done: %.3f "
"cache_open_read_begin: %.3f "
"cache_open_read_end: %.3f "
"dns_lookup_begin: %.3f "
"dns_lookup_end: %.3f "
"server_connect: %.3f "
"server_connect_end: %.3f "
"server_first_read: %.3f "
"server_read_header_done: %.3f "
"server_close: %.3f "
"ua_write: %.3f "
"ua_close: %.3f "
"sm_finish: %.3f "
"plugin_active: %.3f "
"plugin_total: %.3f",
sm_id, client_ip, t_state.client_info.src_addr.host_order_port(), ua_session ? ua_session->get_protocol_string() : "-1",
url_string, status, unique_id_string, redirection_tries, client_response_body_bytes, fd, t_state.client_info.state,
t_state.server_info.state, milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_FIRST_READ),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_READ_HEADER_DONE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_READ),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_READ_HEADER_DONE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CLOSE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN_WRITE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_CLOSE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_PLUGIN_ACTIVE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_PLUGIN_TOTAL));
}
}
//
// void HttpSM::dump_state_on_assert
// Debugging routine to dump the state machine's history
// and other state on an assertion failure
// We use Diags::Status instead of stderr since
// Diags works both on UNIX & NT
//
void
HttpSM::dump_state_on_assert()
{
Error("[%" PRId64 "] ------- begin http state dump -------", sm_id);
int hist_size = this->history_pos;
if (this->history_pos > HISTORY_SIZE) {
hist_size = HISTORY_SIZE;
Error(" History Wrap around. history_pos: %d", this->history_pos);
}
// Loop through the history and dump it
for (int i = 0; i < hist_size; i++) {
int r = history[i].reentrancy;
int e = history[i].event;
Error("%d %d %s", e, r, history[i].fileline);
}
// Dump the via string
Error("Via String: [%s]\n", t_state.via_string);
// Dump header info
dump_state_hdr(&t_state.hdr_info.client_request, "Client Request");
dump_state_hdr(&t_state.hdr_info.server_request, "Server Request");
dump_state_hdr(&t_state.hdr_info.server_response, "Server Response");
dump_state_hdr(&t_state.hdr_info.transform_response, "Transform Response");
dump_state_hdr(&t_state.hdr_info.client_response, "Client Response");
Error("[%" PRId64 "] ------- end http state dump ---------", sm_id);
}
void
HttpSM::dump_state_hdr(HTTPHdr *h, const char *s)
{
// Dump the client request if available
if (h->valid()) {
int l = h->length_get();
char *hdr_buf = (char *)ats_malloc(l + 1);
int index = 0;
int offset = 0;
h->print(hdr_buf, l, &index, &offset);
hdr_buf[l] = '\0';
Error(" ---- %s [%" PRId64 "] ----\n%s\n", s, sm_id, hdr_buf);
ats_free(hdr_buf);
}
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact Interface ****
**** ****
*****************************************************************************
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::call_transact_and_set_next_state(f)
//
// This routine takes an HttpTransact function <f>, calls the function
// to perform some actions on the current HttpTransact::State, and
// then uses the HttpTransact return action code to set the next
// handler (state) for the state machine. HttpTransact could have
// returned the handler directly, but returns action codes in hopes of
// making a cleaner separation between the state machine and the
// HttpTransact logic.
//
//////////////////////////////////////////////////////////////////////////
// Where is the goatherd?
void
HttpSM::call_transact_and_set_next_state(TransactEntryFunc_t f)
{
last_action = t_state.next_action; // remember where we were
// The callee can either specify a method to call in to Transact,
// or call with NULL which indicates that Transact should use
// its stored entry point.
if (f == nullptr) {
ink_release_assert(t_state.transact_return_point != nullptr);
t_state.transact_return_point(&t_state);
} else {
f(&t_state);
}
DebugSM("http", "[%" PRId64 "] State Transition: %s -> %s", sm_id, HttpDebugNames::get_action_name(last_action),
HttpDebugNames::get_action_name(t_state.next_action));
set_next_state();
return;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::set_next_state()
//
// call_transact_and_set_next_state() was broken into two parts, one
// which calls the HttpTransact method and the second which sets the
// next state. In a case which set_next_state() was not completed,
// the state function calls set_next_state() to retry setting the
// state.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpSM::set_next_state()
{
///////////////////////////////////////////////////////////////////////
// Use the returned "next action" code to set the next state handler //
///////////////////////////////////////////////////////////////////////
switch (t_state.next_action) {
case HttpTransact::SM_ACTION_API_PRE_REMAP:
case HttpTransact::SM_ACTION_API_POST_REMAP:
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_OS_DNS:
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE: {
t_state.api_next_action = t_state.next_action;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_POST_REMAP_SKIP: {
call_transact_and_set_next_state(nullptr);
break;
}
case HttpTransact::SM_ACTION_REMAP_REQUEST: {
if (!remapProcessor.using_separate_thread()) {
do_remap_request(true); /* run inline */
DebugSM("url_rewrite", "completed inline remapping request for [%" PRId64 "]", sm_id);
t_state.url_remap_success = remapProcessor.finish_remap(&t_state);
if (t_state.next_action == HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP && t_state.transact_return_point == nullptr) {
// It appears that we can now set the next_action to error and transact_return_point to nullptr when
// going through do_remap_request presumably due to a plugin setting an error. In that case, it seems
// that the error message has already been setup, so we can just return and avoid the further
// call_transact_and_set_next_state
} else {
call_transact_and_set_next_state(nullptr);
}
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_remap_request);
do_remap_request(false); /* dont run inline (iow on another thread) */
}
break;
}
case HttpTransact::SM_ACTION_DNS_LOOKUP: {
sockaddr const *addr;
if (t_state.api_server_addr_set) {
/* If the API has set the server address before the OS DNS lookup
* then we can skip the lookup
*/
ip_text_buffer ipb;
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup for API supplied target %s.",
ats_ip_ntop(&t_state.server_info.dst_addr, ipb, sizeof(ipb)));
// this seems wasteful as we will just copy it right back
ats_ip_copy(t_state.host_db_info.ip(), &t_state.server_info.dst_addr);
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
} else if (0 == ats_ip_pton(t_state.dns_info.lookup_name, t_state.host_db_info.ip()) &&
ats_is_ip_loopback(t_state.host_db_info.ip())) {
// If it's 127.0.0.1 or ::1 don't bother with hostdb
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup for %s because it's loopback",
t_state.dns_info.lookup_name);
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(NULL);
break;
} else if (url_remap_mode == HttpTransact::URL_REMAP_FOR_OS && t_state.first_dns_lookup) {
DebugSM("cdn", "Skipping DNS Lookup");
// skip the DNS lookup
t_state.first_dns_lookup = false;
call_transact_and_set_next_state(HttpTransact::HandleFiltering);
break;
} else if (t_state.http_config_param->use_client_target_addr == 2 && !t_state.url_remap_success &&
t_state.parent_result.result != PARENT_SPECIFIED && t_state.client_info.is_transparent &&
t_state.dns_info.os_addr_style == HttpTransact::DNSLookupInfo::OS_ADDR_TRY_DEFAULT &&
ats_is_ip(addr = t_state.state_machine->ua_session->get_netvc()->get_local_addr())) {
/* If the connection is client side transparent and the URL
* was not remapped/directed to parent proxy, we can use the
* client destination IP address instead of doing a DNS
* lookup. This is controlled by the 'use_client_target_addr'
* configuration parameter.
*/
if (is_debug_tag_set("dns")) {
ip_text_buffer ipb;
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup for client supplied target %s.",
ats_ip_ntop(addr, ipb, sizeof(ipb)));
}
ats_ip_copy(t_state.host_db_info.ip(), addr);
if (t_state.hdr_info.client_request.version_get() == HTTPVersion(0, 9)) {
t_state.host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_09;
} else if (t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 0)) {
t_state.host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_10;
} else {
t_state.host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_11;
}
t_state.dns_info.lookup_success = true;
// cache this result so we don't have to unreliably duplicate the
// logic later if the connect fails.
t_state.dns_info.os_addr_style = HttpTransact::DNSLookupInfo::OS_ADDR_TRY_CLIENT;
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.parent_result.result == PARENT_UNDEFINED && t_state.dns_info.lookup_success) {
// Already set, and we don't have a parent proxy to lookup
ink_assert(ats_is_ip(t_state.host_db_info.ip()));
DebugSM("dns", "[HttpTransact::HandleRequest] Skipping DNS lookup, provided by plugin");
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.dns_info.looking_up == HttpTransact::ORIGIN_SERVER && t_state.http_config_param->no_dns_forward_to_parent &&
t_state.parent_result.result != PARENT_UNDEFINED) {
if (t_state.cop_test_page) {
NetVConnection *vc = t_state.state_machine->ua_session->get_netvc();
if (vc) {
ats_ip_copy(t_state.host_db_info.ip(), vc->get_local_addr());
}
}
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_hostdb_lookup);
ink_assert(t_state.dns_info.looking_up != HttpTransact::UNDEFINED_LOOKUP);
do_hostdb_lookup();
break;
}
case HttpTransact::SM_ACTION_DNS_REVERSE_LOOKUP: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_hostdb_reverse_lookup);
do_hostdb_reverse_lookup();
break;
}
case HttpTransact::SM_ACTION_CACHE_LOOKUP: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_read);
do_cache_lookup_and_read();
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN: {
if (congestionControlEnabled && (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_UNDEFINED)) {
t_state.congest_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_congestion_control_lookup);
if (!do_congestion_control_lookup()) {
break;
}
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_http_server_open);
// We need to close the previous attempt
if (server_entry) {
ink_assert(server_entry->vc_type == HTTP_SERVER_VC);
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
server_session = nullptr;
} else {
// Now that we have gotten the user agent request, we can cancel
// the inactivity timeout associated with it. Note, however, that
// we must not cancel the inactivity timeout if the message
// contains a body (as indicated by the non-zero request_content_length
// field). This indicates that a POST operation is taking place and
// that the client is still sending data to the origin server. The
// origin server cannot reply until the entire request is received. In
// light of this dependency, TS must ensure that the client finishes
// sending its request and for this reason, the inactivity timeout
// cannot be cancelled.
if (ua_session && !t_state.hdr_info.request_content_length) {
ua_session->cancel_inactivity_timeout();
} else if (!ua_session) {
terminate_sm = true;
return; // Give up if there is no session
}
}
do_http_server_open();
break;
}
case HttpTransact::SM_ACTION_SERVER_PARSE_NEXT_HDR: {
setup_server_read_response_header();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_100_RESPONSE: {
setup_100_continue_transfer();
break;
}
case HttpTransact::SM_ACTION_SERVER_READ: {
t_state.source = HttpTransact::SOURCE_HTTP_ORIGIN_SERVER;
if (transform_info.vc) {
ink_assert(t_state.hdr_info.client_response.valid() == 0);
ink_assert((t_state.hdr_info.transform_response.valid() ? true : false) == true);
HttpTunnelProducer *p = setup_server_transfer_to_transform();
perform_cache_write_action();
tunnel.tunnel_run(p);
} else {
ink_assert((t_state.hdr_info.client_response.valid() ? true : false) == true);
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
// check to see if we are going to handle the redirection from server response and if there is a plugin hook set
if (hooks_set && is_redirect_required() == false) {
do_api_callout_internal();
} else {
do_redirect();
handle_api_return();
}
}
break;
}
case HttpTransact::SM_ACTION_SERVE_FROM_CACHE: {
ink_assert(t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE ||
t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE_AND_DELETE ||
t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE_AND_UPDATE);
release_server_session(true);
t_state.source = HttpTransact::SOURCE_CACHE;
if (transform_info.vc) {
ink_assert(t_state.hdr_info.client_response.valid() == 0);
ink_assert((t_state.hdr_info.transform_response.valid() ? true : false) == true);
t_state.hdr_info.cache_response.create(HTTP_TYPE_RESPONSE);
t_state.hdr_info.cache_response.copy(&t_state.hdr_info.transform_response);
HttpTunnelProducer *p = setup_cache_transfer_to_transform();
perform_cache_write_action();
tunnel.tunnel_run(p);
} else {
ink_assert((t_state.hdr_info.client_response.valid() ? true : false) == true);
t_state.hdr_info.cache_response.create(HTTP_TYPE_RESPONSE);
t_state.hdr_info.cache_response.copy(&t_state.hdr_info.client_response);
perform_cache_write_action();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
// check to see if we are going to handle the redirection from server response and if there is a plugin hook set
if (hooks_set && is_redirect_required() == false) {
do_api_callout_internal();
} else {
do_redirect();
handle_api_return();
}
}
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE: {
ink_assert((cache_sm.cache_write_vc == nullptr) || t_state.redirect_info.redirect_in_process);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
do_cache_prepare_write();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_WRITE: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_NOOP: {
if (server_entry != nullptr && server_entry->in_tunnel == false) {
release_server_session();
}
// If we're in state SEND_API_RESPONSE_HDR, it means functions
// registered to hook SEND_RESPONSE_HDR have already been called. So we do not
// need to call do_api_callout. Otherwise TS loops infinitely in this state !
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR) {
handle_api_return();
} else {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
}
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE: {
// Nuke all the alternates since this is mostly likely
// the result of a delete method
cache_sm.end_both();
do_cache_delete_all_alts(nullptr);
release_server_session();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS: {
issue_cache_update();
cache_sm.close_read();
release_server_session();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP: {
setup_error_transfer();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_REQUEST: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_handle_stat_page);
Action *action_handle = statPagesManager.handle_http(this, &t_state.hdr_info.client_request);
if (action_handle != ACTION_RESULT_DONE) {
pending_action = action_handle;
}
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_RR_MARK_DOWN: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_mark_os_down);
ink_assert(t_state.dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
// TODO: This might not be optimal (or perhaps even correct), but it will
// effectively mark the host as down. What's odd is that state_mark_os_down
// above isn't triggering.
HttpSM::do_hostdb_update_if_necessary();
do_hostdb_lookup();
break;
}
case HttpTransact::SM_ACTION_SSL_TUNNEL: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN: {
if (congestionControlEnabled && (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_UNDEFINED)) {
t_state.congest_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_congestion_control_lookup);
if (!do_congestion_control_lookup()) {
break;
}
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_raw_http_server_open);
ink_assert(server_entry == nullptr);
do_http_server_open(true);
break;
}
case HttpTransact::SM_ACTION_ICP_QUERY: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_icp_lookup);
do_icp_lookup();
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM: {
ink_assert(t_state.cache_info.transform_action == HttpTransact::CACHE_PREPARE_TO_WRITE);
if (transform_cache_sm.cache_write_vc) {
// We've already got the write_vc that
// didn't use for the untransformed copy
ink_assert(cache_sm.cache_write_vc == nullptr);
ink_assert(t_state.api_info.cache_untransformed == false);
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_SUCCESS;
call_transact_and_set_next_state(nullptr);
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
do_cache_prepare_write_transform();
}
break;
}
case HttpTransact::SM_ACTION_TRANSFORM_READ: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_READ_PUSH_HDR: {
setup_push_read_response_header();
break;
}
case HttpTransact::SM_ACTION_STORE_PUSH_BODY: {
// This can return NULL - do we really want to run the tunnel in that case?
// But that's how it was before this change.
HttpTunnelProducer *p = setup_push_transfer_to_cache();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_CACHE_PREPARE_UPDATE: {
ink_assert(t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE);
do_cache_prepare_update();
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_UPDATE: {
if (t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_ERROR) {
t_state.cache_info.object_read = nullptr;
cache_sm.close_read();
}
issue_cache_update();
call_transact_and_set_next_state(nullptr);
break;
}
#ifdef PROXY_DRAIN
case HttpTransact::SM_ACTION_DRAIN_REQUEST_BODY: {
do_drain_request_body();
break;
}
#endif /* PROXY_DRAIN */
case HttpTransact::SM_ACTION_CONTINUE: {
ink_release_assert(!"Not implemented");
}
default: {
ink_release_assert("!Unknown next action");
}
}
}
void
clear_http_handler_times()
{
}
bool
HttpSM::do_congestion_control_lookup()
{
ink_assert(pending_action == nullptr);
Action *congestion_control_action_handle = get_congest_entry(this, &t_state.request_data, &t_state.pCongestionEntry);
if (congestion_control_action_handle != ACTION_RESULT_DONE) {
pending_action = congestion_control_action_handle;
return false;
}
return true;
}
int
HttpSM::state_congestion_control_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_congestion_control_lookup, event);
if (event == CONGESTION_EVENT_CONTROL_LOOKUP_DONE) {
pending_action = nullptr;
t_state.next_action = t_state.congest_saved_next_action;
t_state.transact_return_point = nullptr;
set_next_state();
} else {
if (pending_action != nullptr) {
pending_action->cancel();
pending_action = nullptr;
}
if (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN) {
return state_http_server_open(event, data);
} else if (t_state.congest_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
return state_raw_http_server_open(event, data);
}
}
return 0;
}
// YTS Team, yamsat Plugin
void
HttpSM::do_redirect()
{
DebugSM("http_redirect", "[HttpSM::do_redirect]");
if (!enable_redirection || redirection_tries >= t_state.txn_conf->number_of_redirections) {
tunnel.deallocate_redirect_postdata_buffers();
return;
}
// if redirect_url is set by an user's plugin, yts will redirect to this url anyway.
if (is_redirect_required()) {
if (redirect_url != nullptr || t_state.hdr_info.client_response.field_find(MIME_FIELD_LOCATION, MIME_LEN_LOCATION)) {
if (Log::transaction_logging_enabled() && t_state.api_info.logging_enabled) {
LogAccessHttp accessor(this);
if (redirect_url == nullptr) {
if (t_state.squid_codes.log_code == SQUID_LOG_TCP_HIT) {
t_state.squid_codes.log_code = SQUID_LOG_TCP_HIT_REDIRECT;
} else {
t_state.squid_codes.log_code = SQUID_LOG_TCP_MISS_REDIRECT;
}
} else {
if (t_state.squid_codes.log_code == SQUID_LOG_TCP_HIT) {
t_state.squid_codes.log_code = SQUID_LOG_TCP_HIT_X_REDIRECT;
} else {
t_state.squid_codes.log_code = SQUID_LOG_TCP_MISS_X_REDIRECT;
}
}
int ret = Log::access(&accessor);
if (ret & Log::FULL) {
DebugSM("http", "[update_stats] Logging system indicates FULL.");
}
if (ret & Log::FAIL) {
Log::error("failed to log transaction for at least one log object");
}
}
if (redirect_url != nullptr) {
redirect_request(redirect_url, redirect_url_len);
ats_free((void *)redirect_url);
redirect_url = nullptr;
redirect_url_len = 0;
HTTP_INCREMENT_DYN_STAT(http_total_x_redirect_stat);
} else {
// get the location header and setup the redirect
int redir_len;
char *redir_url = (char *)t_state.hdr_info.client_response.value_get(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, &redir_len);
redirect_request(redir_url, redir_len);
}
} else {
enable_redirection = false;
}
} else {
enable_redirection = false;
}
}
void
HttpSM::redirect_request(const char *redirect_url, const int redirect_len)
{
DebugSM("http_redirect", "[HttpSM::redirect_request]");
// get a reference to the client request header and client url and check to see if the url is valid
HTTPHdr &clientRequestHeader = t_state.hdr_info.client_request;
URL &clientUrl = *clientRequestHeader.url_get();
if (!clientUrl.valid()) {
return;
}
bool valid_origHost = true;
int origHost_len, origMethod_len;
char origHost[MAXDNAME];
char origMethod[255];
int origPort = 80;
if (t_state.hdr_info.server_request.valid()) {
char *tmpOrigHost;
origPort = t_state.hdr_info.server_request.port_get();
tmpOrigHost = (char *)t_state.hdr_info.server_request.value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &origHost_len);
if (tmpOrigHost) {
memcpy(origHost, tmpOrigHost, origHost_len);
origHost[origHost_len] = '\0';
} else {
valid_origHost = false;
}
char *tmpOrigMethod = (char *)t_state.hdr_info.server_request.method_get(&origMethod_len);
if (tmpOrigMethod) {
memcpy(origMethod, tmpOrigMethod, origMethod_len);
} else {
valid_origHost = false;
}
} else {
DebugSM("http_redir_error", "t_state.hdr_info.server_request not valid");
valid_origHost = false;
}
t_state.redirect_info.redirect_in_process = true;
// set the passed in location url and parse it
URL &redirectUrl = t_state.redirect_info.redirect_url;
if (!redirectUrl.valid()) {
redirectUrl.create(nullptr);
}
// reset the path from previous redirects (if any)
t_state.redirect_info.redirect_url.path_set(nullptr, 0);
// redirectUrl.user_set(redirect_url, redirect_len);
redirectUrl.parse(redirect_url, redirect_len);
// copy the client url to the original url
URL &origUrl = t_state.redirect_info.original_url;
if (!origUrl.valid()) {
origUrl.create(nullptr);
origUrl.copy(&clientUrl);
}
// copy the redirect url to the client url
clientUrl.copy(&redirectUrl);
//(bug 2540703) Clear the previous response if we will attempt the redirect
if (t_state.hdr_info.client_response.valid()) {
// XXX - doing a destroy() for now, we can do a fileds_clear() if we have performance issue
t_state.hdr_info.client_response.destroy();
}
int scheme = t_state.next_hop_scheme;
int scheme_len = hdrtoken_index_to_length(scheme);
const char *next_hop_scheme = hdrtoken_index_to_wks(scheme);
char scheme_str[scheme_len + 1];
if (next_hop_scheme) {
memcpy(scheme_str, next_hop_scheme, scheme_len);
} else {
valid_origHost = false;
}
t_state.hdr_info.server_request.destroy();
// we want to close the server session
// will do that in handle_api_return under the
// HttpTransact::SM_ACTION_REDIRECT_READ state
t_state.parent_result.reset();
t_state.request_sent_time = 0;
t_state.response_received_time = 0;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_INIT;
t_state.next_action = HttpTransact::SM_ACTION_REDIRECT_READ;
// we have a new OS and need to have DNS lookup the new OS
t_state.dns_info.lookup_success = false;
t_state.force_dns = false;
if (t_state.txn_conf->cache_http) {
t_state.cache_info.object_read = nullptr;
}
bool noPortInHost = HttpConfig::m_master.redirection_host_no_port;
// check to see if the client request passed a host header, if so copy the host and port from the redirect url and
// make a new host header
if (t_state.hdr_info.client_request.presence(MIME_PRESENCE_HOST)) {
int host_len;
const char *host = clientUrl.host_get(&host_len);
if (host != nullptr) {
int port = clientUrl.port_get();
int redirectSchemeLen;
const char *redirectScheme = clientUrl.scheme_get(&redirectSchemeLen);
if (redirectScheme == nullptr) {
clientUrl.scheme_set(scheme_str, scheme_len);
DebugSM("http_redirect", "[HttpSM::redirect_request] URL without scheme %.*s", redirectSchemeLen, redirectScheme);
}
if (noPortInHost) {
int redirectSchemeIdx = clientUrl.scheme_get_wksidx();
bool defaultPort =
(((redirectSchemeIdx == URL_WKSIDX_HTTP) && (port == 80)) || ((redirectSchemeIdx == URL_WKSIDX_HTTPS) && (port == 443)));
if (!defaultPort) {
noPortInHost = false;
}
}
if (!noPortInHost) {
char buf[host_len + 7]; // 5 + 1 + 1 ("12345" + ':' + '\0')
host_len = snprintf(buf, host_len + 7, "%.*s:%d", host_len, host, port);
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
t_state.hdr_info.client_request.m_target_cached = false;
t_state.hdr_info.server_request.m_target_cached = false;
} else {
// the client request didn't have a host, so use the current origin host
if (valid_origHost) {
char *saveptr = nullptr;
// the client request didn't have a host, so use the current origin host
DebugSM("http_redirect", "[HttpSM::redirect_request] keeping client request host %s://%s", next_hop_scheme, origHost);
char *origHostNoPort = strtok_r(origHost, ":", &saveptr);
if (origHostNoPort == nullptr) {
goto LhostError;
}
host_len = strlen(origHostNoPort);
if (noPortInHost) {
int redirectSchemeIdx = t_state.next_hop_scheme;
bool defaultPort = (((redirectSchemeIdx == URL_WKSIDX_HTTP) && (origPort == 80)) ||
((redirectSchemeIdx == URL_WKSIDX_HTTPS) && (origPort == 443)));
if (!defaultPort) {
noPortInHost = false;
}
}
if (!noPortInHost) {
char buf[host_len + 7]; // 5 + 1 + 1 ("12345" + ':' + '\0')
host_len = snprintf(buf, host_len + 7, "%s:%d", origHostNoPort, origPort);
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, origHostNoPort, host_len);
}
// Cleanup of state etc.
url_nuke_proxy_stuff(clientUrl.m_url_impl);
url_nuke_proxy_stuff(t_state.hdr_info.client_request.m_url_cached.m_url_impl);
t_state.hdr_info.client_request.method_set(origMethod, origMethod_len);
t_state.hdr_info.client_request.m_target_cached = false;
t_state.hdr_info.server_request.m_target_cached = false;
clientUrl.scheme_set(scheme_str, scheme_len);
} else {
LhostError:
// the server request didn't have a host, so remove it from the headers
t_state.hdr_info.client_request.field_delete(MIME_FIELD_HOST, MIME_LEN_HOST);
}
}
}
if (!t_state.cop_test_page) {
DUMP_HEADER("http_hdrs", &t_state.hdr_info.client_request, sm_id, "Framed Client Request..checking");
}
}
void
HttpSM::set_http_schedule(Continuation *contp)
{
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::get_http_schedule);
schedule_cont = contp;
}
int
HttpSM::get_http_schedule(int event, void * /* data ATS_UNUSED */)
{
bool plugin_lock;
Ptr<ProxyMutex> plugin_mutex;
if (schedule_cont->mutex) {
plugin_mutex = schedule_cont->mutex;
plugin_lock = MUTEX_TAKE_TRY_LOCK(schedule_cont->mutex, mutex->thread_holding);
if (!plugin_lock) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::get_http_schedule);
ink_assert(pending_action == nullptr);
pending_action = mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
return 0;
} else {
pending_action = nullptr; // if there was a pending action, it'll get freed after this returns so clear it.
}
} else {
plugin_lock = false;
}
// handle Mutex;
schedule_cont->handleEvent(event, this);
if (plugin_lock) {
Mutex_unlock(plugin_mutex, mutex->thread_holding);
}
return 0;
}
bool
HttpSM::set_server_session_private(bool private_session)
{
if (server_session != nullptr) {
server_session->private_session = private_session;
return true;
}
return false;
}
inline bool
HttpSM::is_private()
{
bool res = false;
if (server_session) {
res = server_session->private_session;
} else if (ua_session) {
HttpServerSession *ss = ua_session->get_server_session();
if (ss) {
res = ss->private_session;
} else if (will_be_private_ss) {
res = will_be_private_ss;
}
}
return res;
}
// check to see if redirection is enabled and less than max redirections tries or if a plugin enabled redirection
inline bool
HttpSM::is_redirect_required()
{
bool redirect_required = (enable_redirection && (redirection_tries <= t_state.txn_conf->number_of_redirections));
DebugSM("http_redirect", "is_redirect_required %u", redirect_required);
if (redirect_required == true) {
HTTPStatus status = t_state.hdr_info.client_response.status_get();
// check to see if the response from the orgin was a 301, 302, or 303
switch (status) {
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
case HTTP_STATUS_MOVED_TEMPORARILY: // 302
case HTTP_STATUS_SEE_OTHER: // 303
case HTTP_STATUS_USE_PROXY: // 305
case HTTP_STATUS_TEMPORARY_REDIRECT: // 307
redirect_required = true;
break;
default:
redirect_required = false;
break;
}
// if redirect_url is set by an user's plugin, ats will redirect to this url anyway.
if (redirect_url != nullptr) {
redirect_required = true;
}
}
return redirect_required;
}
// Fill in the client protocols used. Return the number of entries returned
int
HttpSM::populate_client_protocol(const char **result, int n) const
{
int retval = 0;
if (n > 0) {
const char *proto = HttpSM::find_proto_string(t_state.hdr_info.client_request.version_get());
if (proto) {
result[0] = proto;
retval = 1;
if (n > retval && ua_session) {
retval += ua_session->populate_protocol(result + retval, n - retval);
}
}
}
return retval;
}
// Look for a specific protocol
const char *
HttpSM::client_protocol_contains(const char *tag_prefix) const
{
const char *retval = nullptr;
const char *proto = HttpSM::find_proto_string(t_state.hdr_info.client_request.version_get());
if (proto) {
unsigned int tag_prefix_len = strlen(tag_prefix);
if (tag_prefix_len <= strlen(proto) && strncmp(tag_prefix, proto, tag_prefix_len) == 0) {
retval = proto;
} else if (ua_session) {
retval = ua_session->protocol_contains(tag_prefix);
}
}
return retval;
}
const char *
HttpSM::find_proto_string(HTTPVersion version) const
{
if (version == HTTPVersion(1, 1)) {
return TS_PROTO_TAG_HTTP_1_1;
} else if (version == HTTPVersion(1, 0)) {
return TS_PROTO_TAG_HTTP_1_0;
} else {
return nullptr;
}
}
|
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include "talk/base/common.h"
#include "talk/base/logging.h"
#include "talk/base/openssladapter.h"
#include "talk/base/stringutils.h"
#include "talk/base/Equifax_Secure_Global_eBusiness_CA-1.h"
//////////////////////////////////////////////////////////////////////
// StreamBIO
//////////////////////////////////////////////////////////////////////
#if 0
static int stream_write(BIO* h, const char* buf, int num);
static int stream_read(BIO* h, char* buf, int size);
static int stream_puts(BIO* h, const char* str);
static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
static int stream_new(BIO* h);
static int stream_free(BIO* data);
static BIO_METHOD methods_stream = {
BIO_TYPE_BIO,
"stream",
stream_write,
stream_read,
stream_puts,
0,
stream_ctrl,
stream_new,
stream_free,
NULL,
};
BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
BIO* BIO_new_stream(StreamInterface* stream) {
BIO* ret = BIO_new(BIO_s_stream());
if (ret == NULL)
return NULL;
ret->ptr = stream;
return ret;
}
static int stream_new(BIO* b) {
b->shutdown = 0;
b->init = 1;
b->num = 0; // 1 means end-of-stream
b->ptr = 0;
return 1;
}
static int stream_free(BIO* b) {
if (b == NULL)
return 0;
return 1;
}
static int stream_read(BIO* b, char* out, int outl) {
if (!out)
return -1;
StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
BIO_clear_retry_flags(b);
size_t read;
int error;
StreamResult result = stream->Read(out, outl, &read, &error);
if (result == SR_SUCCESS) {
return read;
} else if (result == SR_EOS) {
b->num = 1;
} else if (result == SR_BLOCK) {
BIO_set_retry_read(b);
}
return -1;
}
static int stream_write(BIO* b, const char* in, int inl) {
if (!in)
return -1;
StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
BIO_clear_retry_flags(b);
size_t written;
int error;
StreamResult result = stream->Write(in, inl, &written, &error);
if (result == SR_SUCCESS) {
return written;
} else if (result == SR_BLOCK) {
BIO_set_retry_write(b);
}
return -1;
}
static int stream_puts(BIO* b, const char* str) {
return stream_write(b, str, strlen(str));
}
static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
UNUSED(num);
UNUSED(ptr);
switch (cmd) {
case BIO_CTRL_RESET:
return 0;
case BIO_CTRL_EOF:
return b->num;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
return 0;
case BIO_CTRL_FLUSH:
return 1;
default:
return 0;
}
}
#endif
//////////////////////////////////////////////////////////////////////
// SocketBIO
//////////////////////////////////////////////////////////////////////
static int socket_write(BIO* h, const char* buf, int num);
static int socket_read(BIO* h, char* buf, int size);
static int socket_puts(BIO* h, const char* str);
static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2);
static int socket_new(BIO* h);
static int socket_free(BIO* data);
static BIO_METHOD methods_socket = {
BIO_TYPE_BIO,
"socket",
socket_write,
socket_read,
socket_puts,
0,
socket_ctrl,
socket_new,
socket_free,
NULL,
};
BIO_METHOD* BIO_s_socket2() { return(&methods_socket); }
BIO* BIO_new_socket(talk_base::AsyncSocket* socket) {
BIO* ret = BIO_new(BIO_s_socket2());
if (ret == NULL) {
return NULL;
}
ret->ptr = socket;
return ret;
}
static int socket_new(BIO* b) {
b->shutdown = 0;
b->init = 1;
b->num = 0; // 1 means socket closed
b->ptr = 0;
return 1;
}
static int socket_free(BIO* b) {
if (b == NULL)
return 0;
return 1;
}
static int socket_read(BIO* b, char* out, int outl) {
if (!out)
return -1;
talk_base::AsyncSocket* socket = static_cast<talk_base::AsyncSocket*>(b->ptr);
BIO_clear_retry_flags(b);
int result = socket->Recv(out, outl);
if (result > 0) {
return result;
} else if (result == 0) {
b->num = 1;
} else if (socket->IsBlocking()) {
BIO_set_retry_read(b);
}
return -1;
}
static int socket_write(BIO* b, const char* in, int inl) {
if (!in)
return -1;
talk_base::AsyncSocket* socket = static_cast<talk_base::AsyncSocket*>(b->ptr);
BIO_clear_retry_flags(b);
int result = socket->Send(in, inl);
if (result > 0) {
return result;
} else if (socket->IsBlocking()) {
BIO_set_retry_write(b);
}
return -1;
}
static int socket_puts(BIO* b, const char* str) {
return socket_write(b, str, strlen(str));
}
static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) {
UNUSED(num);
UNUSED(ptr);
switch (cmd) {
case BIO_CTRL_RESET:
return 0;
case BIO_CTRL_EOF:
return b->num;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
return 0;
case BIO_CTRL_FLUSH:
return 1;
default:
return 0;
}
}
/////////////////////////////////////////////////////////////////////////////
// OpenSSLAdapter
/////////////////////////////////////////////////////////////////////////////
namespace talk_base {
OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket)
: SSLAdapter(socket),
state_(SSL_NONE),
ssl_read_needs_write_(false),
ssl_write_needs_read_(false),
restartable_(false),
ssl_(NULL), ssl_ctx_(NULL) {
}
OpenSSLAdapter::~OpenSSLAdapter() {
Cleanup();
}
int
OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
if (state_ != SSL_NONE)
return -1;
ssl_host_name_ = hostname;
restartable_ = restartable;
if (socket_->GetState() != Socket::CS_CONNECTED) {
state_ = SSL_WAIT;
return 0;
}
state_ = SSL_CONNECTING;
if (int err = BeginSSL()) {
Error("BeginSSL", err, false);
return err;
}
LOG(LS_VERBOSE) << "OpenSSLAdapter::StartSSL() returns 0";
return 0;
}
int
OpenSSLAdapter::BeginSSL() {
LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_;
ASSERT(state_ == SSL_CONNECTING);
int err = 0;
BIO* bio = NULL;
// First set up the context
if (!ssl_ctx_)
ssl_ctx_ = SetupSSLContext();
if (!ssl_ctx_) {
err = -1;
goto ssl_error;
}
bio = BIO_new_socket(static_cast<talk_base::AsyncSocketAdapter*>(socket_));
if (!bio) {
err = -1;
goto ssl_error;
}
ssl_ = SSL_new(ssl_ctx_);
if (!ssl_) {
err = -1;
goto ssl_error;
}
SSL_set_app_data(ssl_, this);
SSL_set_bio(ssl_, bio, bio);
SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
// the SSL object owns the bio now
bio = NULL;
// Do the connect
err = ContinueSSL();
if (err != 0)
goto ssl_error;
return err;
ssl_error:
Cleanup();
if (bio)
BIO_free(bio);
return err;
}
int
OpenSSLAdapter::ContinueSSL() {
LOG(LS_INFO) << "ContinueSSL";
ASSERT(state_ == SSL_CONNECTING);
int code = SSL_connect(ssl_);
int err = SSL_get_error(ssl_, code);
if (err != SSL_ERROR_NONE)
{
LOG(LS_WARNING) << "!!! SSL_connect() returned " << err;
}
switch (err) {
case SSL_ERROR_NONE:
LOG(LS_INFO) << " -- success";
if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) {
LOG(LS_ERROR) << "TLS post connection check failed";
// make sure we close the socket
Cleanup();
// The connect failed so return -1 to shut down the socket
return -1;
}
state_ = SSL_CONNECTED;
AsyncSocketAdapter::OnConnectEvent(this);
#if 0 // TODO: worry about this
// Don't let ourselves go away during the callbacks
PRefPtr<OpenSSLAdapter> lock(this);
LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(this);
LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(this);
#endif
break;
case SSL_ERROR_WANT_READ:
LOG(LS_INFO) << " -- error want read";
break;
case SSL_ERROR_WANT_WRITE:
LOG(LS_INFO) << " -- error want write";
break;
case SSL_ERROR_ZERO_RETURN:
default:
LOG(LS_INFO) << " -- error " << code;
return (code != 0) ? code : -1;
}
LOG(LS_VERBOSE) << "OpenSSLAdapter::ContinueSSL() returns 0";
return 0;
}
void
OpenSSLAdapter::Error(const char* context, int err, bool signal) {
LOG(LS_WARNING) << "SChannelAdapter::Error("
<< context << ", " << err << ")";
state_ = SSL_ERROR;
SetError(err);
if (signal)
AsyncSocketAdapter::OnCloseEvent(this, err);
}
void
OpenSSLAdapter::Cleanup() {
LOG(LS_INFO) << "Cleanup";
state_ = SSL_NONE;
ssl_read_needs_write_ = false;
ssl_write_needs_read_ = false;
if (ssl_) {
SSL_free(ssl_);
ssl_ = NULL;
}
if (ssl_ctx_) {
SSL_CTX_free(ssl_ctx_);
ssl_ctx_ = NULL;
}
}
//
// AsyncSocket Implementation
//
int
OpenSSLAdapter::Send(const void* pv, size_t cb) {
//LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")";
switch (state_) {
case SSL_NONE:
return AsyncSocketAdapter::Send(pv, cb);
case SSL_WAIT:
case SSL_CONNECTING:
SetError(EWOULDBLOCK);
return SOCKET_ERROR;
case SSL_CONNECTED:
break;
case SSL_ERROR:
default:
return SOCKET_ERROR;
}
// OpenSSL will return an error if we try to write zero bytes
if (cb == 0)
return 0;
ssl_write_needs_read_ = false;
int code = SSL_write(ssl_, pv, cb);
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
//LOG(LS_INFO) << " -- success";
return code;
case SSL_ERROR_WANT_READ:
//LOG(LS_INFO) << " -- error want read";
ssl_write_needs_read_ = true;
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_WANT_WRITE:
//LOG(LS_INFO) << " -- error want write";
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_ZERO_RETURN:
//LOG(LS_INFO) << " -- remote side closed";
SetError(EWOULDBLOCK);
// do we need to signal closure?
break;
default:
//LOG(LS_INFO) << " -- error " << code;
Error("SSL_write", (code ? code : -1), false);
break;
}
return SOCKET_ERROR;
}
int
OpenSSLAdapter::Recv(void* pv, size_t cb) {
//LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")";
switch (state_) {
case SSL_NONE:
return AsyncSocketAdapter::Recv(pv, cb);
case SSL_WAIT:
case SSL_CONNECTING:
SetError(EWOULDBLOCK);
return SOCKET_ERROR;
case SSL_CONNECTED:
break;
case SSL_ERROR:
default:
return SOCKET_ERROR;
}
// Don't trust OpenSSL with zero byte reads
if (cb == 0)
return 0;
ssl_read_needs_write_ = false;
int code = SSL_read(ssl_, pv, cb);
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
//LOG(LS_INFO) << " -- success";
return code;
case SSL_ERROR_WANT_READ:
//LOG(LS_INFO) << " -- error want read";
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_WANT_WRITE:
//LOG(LS_INFO) << " -- error want write";
ssl_read_needs_write_ = true;
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_ZERO_RETURN:
//LOG(LS_INFO) << " -- remote side closed";
SetError(EWOULDBLOCK);
// do we need to signal closure?
break;
default:
//LOG(LS_INFO) << " -- error " << code;
Error("SSL_read", (code ? code : -1), false);
break;
}
return SOCKET_ERROR;
}
int
OpenSSLAdapter::Close() {
Cleanup();
state_ = restartable_ ? SSL_WAIT : SSL_NONE;
return AsyncSocketAdapter::Close();
}
Socket::ConnState
OpenSSLAdapter::GetState() const {
//if (signal_close_)
// return CS_CONNECTED;
ConnState state = socket_->GetState();
if ((state == CS_CONNECTED)
&& ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
state = CS_CONNECTING;
return state;
}
void
OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
if (state_ != SSL_WAIT) {
ASSERT(state_ == SSL_NONE);
AsyncSocketAdapter::OnConnectEvent(socket);
return;
}
state_ = SSL_CONNECTING;
if (int err = BeginSSL()) {
AsyncSocketAdapter::OnCloseEvent(socket, err);
}
}
void
OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
//LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent";
if (state_ == SSL_NONE) {
AsyncSocketAdapter::OnReadEvent(socket);
return;
}
if (state_ == SSL_CONNECTING) {
if (int err = ContinueSSL()) {
Error("ContinueSSL", err);
}
return;
}
if (state_ != SSL_CONNECTED)
return;
// Don't let ourselves go away during the callbacks
//PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
if (ssl_write_needs_read_) {
//LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(socket);
}
//LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(socket);
}
void
OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
//LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent";
if (state_ == SSL_NONE) {
AsyncSocketAdapter::OnWriteEvent(socket);
return;
}
if (state_ == SSL_CONNECTING) {
if (int err = ContinueSSL()) {
Error("ContinueSSL", err);
}
return;
}
if (state_ != SSL_CONNECTED)
return;
// Don't let ourselves go away during the callbacks
//PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
if (ssl_read_needs_write_) {
//LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(socket);
}
//LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(socket);
}
void
OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
AsyncSocketAdapter::OnCloseEvent(socket, err);
}
// This code is taken from the "Network Security with OpenSSL"
// sample in chapter 5
bool
OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) {
if (!host)
return false;
// Checking the return from SSL_get_peer_certificate here is not strictly
// necessary. With our setup, it is not possible for it to return
// NULL. However, it is good form to check the return.
X509* certificate = SSL_get_peer_certificate(ssl);
if (!certificate)
return false;
#ifdef _DEBUG
{
LOG(LS_INFO) << "Certificate from server:";
BIO* mem = BIO_new(BIO_s_mem());
X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER);
BIO_write(mem, "\0", 1);
char* buffer;
BIO_get_mem_data(mem, &buffer);
LOG(LS_INFO) << buffer;
BIO_free(mem);
char* cipher_description =
SSL_CIPHER_description(SSL_get_current_cipher(ssl), NULL, 128);
LOG(LS_INFO) << "Cipher: " << cipher_description;
OPENSSL_free(cipher_description);
}
#endif
bool ok = false;
int extension_count = X509_get_ext_count(certificate);
for (int i = 0; i < extension_count; ++i) {
X509_EXTENSION* extension = X509_get_ext(certificate, i);
int extension_nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension));
if (extension_nid == NID_subject_alt_name) {
const X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension);
if (!meth)
break;
void* ext_str = NULL;
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
const unsigned char **ext_value_data = (const_cast<const unsigned char **>
(&extension->value->data));
#else
unsigned char **ext_value_data = &extension->value->data;
#endif
if (meth->it) {
ext_str = ASN1_item_d2i(NULL, ext_value_data, extension->value->length,
ASN1_ITEM_ptr(meth->it));
} else {
ext_str = meth->d2i(NULL, ext_value_data, extension->value->length);
}
STACK_OF(CONF_VALUE)* value = meth->i2v(meth, ext_str, NULL);
for (int j = 0; j < sk_CONF_VALUE_num(value); ++j) {
CONF_VALUE* nval = sk_CONF_VALUE_value(value, j);
if (!strcmp(nval->name, "DNS") && !strcmp(nval->value, host)) {
ok = true;
break;
}
}
}
if (ok)
break;
}
char data[256];
X509_name_st* subject;
if (!ok
&& (subject = X509_get_subject_name(certificate))
&& (X509_NAME_get_text_by_NID(subject, NID_commonName,
data, sizeof(data)) > 0)) {
data[sizeof(data)-1] = 0;
if (_stricmp(data, host) == 0)
ok = true;
}
X509_free(certificate);
if (!ok && ignore_bad_cert()) {
LOG(LS_WARNING) << "TLS certificate check FAILED. "
<< "Allowing connection anyway.";
ok = true;
}
if (ok)
ok = (SSL_get_verify_result(ssl) == X509_V_OK);
if (!ok && ignore_bad_cert()) {
LOG(LS_INFO) << "Other TLS post connection checks failed.";
ok = true;
}
return ok;
}
#if _DEBUG
// We only use this for tracing and so it is only needed in debug mode
void
OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
const char* str = "undefined";
int w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
}
if (where & SSL_CB_LOOP) {
LOG(LS_INFO) << str << ":" << SSL_state_string_long(s);
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
LOG(LS_INFO) << "SSL3 alert " << str
<< ":" << SSL_alert_type_string_long(ret)
<< ":" << SSL_alert_desc_string_long(ret);
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
} else if (ret < 0) {
LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
}
}
}
#endif // _DEBUG
int
OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
#if _DEBUG
if (!ok) {
char data[256];
X509* cert = X509_STORE_CTX_get_current_cert(store);
int depth = X509_STORE_CTX_get_error_depth(store);
int err = X509_STORE_CTX_get_error(store);
LOG(LS_INFO) << "Error with certificate at depth: " << depth;
X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
LOG(LS_INFO) << " issuer = " << data;
X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
LOG(LS_INFO) << " subject = " << data;
LOG(LS_INFO) << " err = " << err
<< ":" << X509_verify_cert_error_string(err);
}
#endif
// Get our stream pointer from the store
SSL* ssl = reinterpret_cast<SSL*>(
X509_STORE_CTX_get_ex_data(store,
SSL_get_ex_data_X509_STORE_CTX_idx()));
OpenSSLAdapter* stream =
reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
if (!ok && stream->ignore_bad_cert()) {
LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
ok = 1;
}
return ok;
}
SSL_CTX*
OpenSSLAdapter::SetupSSLContext() {
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx == NULL)
{
LOG(LS_ERROR) << "OpenSSLAdapter::SetupSSLContext() error: ctx == NULL";
return NULL;
}
// Add the root cert to the SSL context
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
const unsigned char* cert_buffer
#else
unsigned char* cert_buffer
#endif
= EquifaxSecureGlobalEBusinessCA1_certificate;
size_t cert_buffer_len = sizeof(EquifaxSecureGlobalEBusinessCA1_certificate);
X509* cert = d2i_X509(NULL, &cert_buffer, cert_buffer_len);
if (cert == NULL) {
SSL_CTX_free(ctx);
return NULL;
}
if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert)) {
X509_free(cert);
SSL_CTX_free(ctx);
return NULL;
}
#ifdef _DEBUG
SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
#endif
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
SSL_CTX_set_verify_depth(ctx, 4);
SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
return ctx;
}
} // namespace talk_base
also compile with openssl < 1.0.0
svn path=/trunk/KDE/kdenetwork/kopete/; revision=1123701
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include "talk/base/common.h"
#include "talk/base/logging.h"
#include "talk/base/openssladapter.h"
#include "talk/base/stringutils.h"
#include "talk/base/Equifax_Secure_Global_eBusiness_CA-1.h"
//////////////////////////////////////////////////////////////////////
// StreamBIO
//////////////////////////////////////////////////////////////////////
#if 0
static int stream_write(BIO* h, const char* buf, int num);
static int stream_read(BIO* h, char* buf, int size);
static int stream_puts(BIO* h, const char* str);
static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
static int stream_new(BIO* h);
static int stream_free(BIO* data);
static BIO_METHOD methods_stream = {
BIO_TYPE_BIO,
"stream",
stream_write,
stream_read,
stream_puts,
0,
stream_ctrl,
stream_new,
stream_free,
NULL,
};
BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
BIO* BIO_new_stream(StreamInterface* stream) {
BIO* ret = BIO_new(BIO_s_stream());
if (ret == NULL)
return NULL;
ret->ptr = stream;
return ret;
}
static int stream_new(BIO* b) {
b->shutdown = 0;
b->init = 1;
b->num = 0; // 1 means end-of-stream
b->ptr = 0;
return 1;
}
static int stream_free(BIO* b) {
if (b == NULL)
return 0;
return 1;
}
static int stream_read(BIO* b, char* out, int outl) {
if (!out)
return -1;
StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
BIO_clear_retry_flags(b);
size_t read;
int error;
StreamResult result = stream->Read(out, outl, &read, &error);
if (result == SR_SUCCESS) {
return read;
} else if (result == SR_EOS) {
b->num = 1;
} else if (result == SR_BLOCK) {
BIO_set_retry_read(b);
}
return -1;
}
static int stream_write(BIO* b, const char* in, int inl) {
if (!in)
return -1;
StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
BIO_clear_retry_flags(b);
size_t written;
int error;
StreamResult result = stream->Write(in, inl, &written, &error);
if (result == SR_SUCCESS) {
return written;
} else if (result == SR_BLOCK) {
BIO_set_retry_write(b);
}
return -1;
}
static int stream_puts(BIO* b, const char* str) {
return stream_write(b, str, strlen(str));
}
static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
UNUSED(num);
UNUSED(ptr);
switch (cmd) {
case BIO_CTRL_RESET:
return 0;
case BIO_CTRL_EOF:
return b->num;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
return 0;
case BIO_CTRL_FLUSH:
return 1;
default:
return 0;
}
}
#endif
//////////////////////////////////////////////////////////////////////
// SocketBIO
//////////////////////////////////////////////////////////////////////
static int socket_write(BIO* h, const char* buf, int num);
static int socket_read(BIO* h, char* buf, int size);
static int socket_puts(BIO* h, const char* str);
static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2);
static int socket_new(BIO* h);
static int socket_free(BIO* data);
static BIO_METHOD methods_socket = {
BIO_TYPE_BIO,
"socket",
socket_write,
socket_read,
socket_puts,
0,
socket_ctrl,
socket_new,
socket_free,
NULL,
};
BIO_METHOD* BIO_s_socket2() { return(&methods_socket); }
BIO* BIO_new_socket(talk_base::AsyncSocket* socket) {
BIO* ret = BIO_new(BIO_s_socket2());
if (ret == NULL) {
return NULL;
}
ret->ptr = socket;
return ret;
}
static int socket_new(BIO* b) {
b->shutdown = 0;
b->init = 1;
b->num = 0; // 1 means socket closed
b->ptr = 0;
return 1;
}
static int socket_free(BIO* b) {
if (b == NULL)
return 0;
return 1;
}
static int socket_read(BIO* b, char* out, int outl) {
if (!out)
return -1;
talk_base::AsyncSocket* socket = static_cast<talk_base::AsyncSocket*>(b->ptr);
BIO_clear_retry_flags(b);
int result = socket->Recv(out, outl);
if (result > 0) {
return result;
} else if (result == 0) {
b->num = 1;
} else if (socket->IsBlocking()) {
BIO_set_retry_read(b);
}
return -1;
}
static int socket_write(BIO* b, const char* in, int inl) {
if (!in)
return -1;
talk_base::AsyncSocket* socket = static_cast<talk_base::AsyncSocket*>(b->ptr);
BIO_clear_retry_flags(b);
int result = socket->Send(in, inl);
if (result > 0) {
return result;
} else if (socket->IsBlocking()) {
BIO_set_retry_write(b);
}
return -1;
}
static int socket_puts(BIO* b, const char* str) {
return socket_write(b, str, strlen(str));
}
static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) {
UNUSED(num);
UNUSED(ptr);
switch (cmd) {
case BIO_CTRL_RESET:
return 0;
case BIO_CTRL_EOF:
return b->num;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
return 0;
case BIO_CTRL_FLUSH:
return 1;
default:
return 0;
}
}
/////////////////////////////////////////////////////////////////////////////
// OpenSSLAdapter
/////////////////////////////////////////////////////////////////////////////
namespace talk_base {
OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket)
: SSLAdapter(socket),
state_(SSL_NONE),
ssl_read_needs_write_(false),
ssl_write_needs_read_(false),
restartable_(false),
ssl_(NULL), ssl_ctx_(NULL) {
}
OpenSSLAdapter::~OpenSSLAdapter() {
Cleanup();
}
int
OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
if (state_ != SSL_NONE)
return -1;
ssl_host_name_ = hostname;
restartable_ = restartable;
if (socket_->GetState() != Socket::CS_CONNECTED) {
state_ = SSL_WAIT;
return 0;
}
state_ = SSL_CONNECTING;
if (int err = BeginSSL()) {
Error("BeginSSL", err, false);
return err;
}
LOG(LS_VERBOSE) << "OpenSSLAdapter::StartSSL() returns 0";
return 0;
}
int
OpenSSLAdapter::BeginSSL() {
LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_;
ASSERT(state_ == SSL_CONNECTING);
int err = 0;
BIO* bio = NULL;
// First set up the context
if (!ssl_ctx_)
ssl_ctx_ = SetupSSLContext();
if (!ssl_ctx_) {
err = -1;
goto ssl_error;
}
bio = BIO_new_socket(static_cast<talk_base::AsyncSocketAdapter*>(socket_));
if (!bio) {
err = -1;
goto ssl_error;
}
ssl_ = SSL_new(ssl_ctx_);
if (!ssl_) {
err = -1;
goto ssl_error;
}
SSL_set_app_data(ssl_, this);
SSL_set_bio(ssl_, bio, bio);
SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
// the SSL object owns the bio now
bio = NULL;
// Do the connect
err = ContinueSSL();
if (err != 0)
goto ssl_error;
return err;
ssl_error:
Cleanup();
if (bio)
BIO_free(bio);
return err;
}
int
OpenSSLAdapter::ContinueSSL() {
LOG(LS_INFO) << "ContinueSSL";
ASSERT(state_ == SSL_CONNECTING);
int code = SSL_connect(ssl_);
int err = SSL_get_error(ssl_, code);
if (err != SSL_ERROR_NONE)
{
LOG(LS_WARNING) << "!!! SSL_connect() returned " << err;
}
switch (err) {
case SSL_ERROR_NONE:
LOG(LS_INFO) << " -- success";
if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) {
LOG(LS_ERROR) << "TLS post connection check failed";
// make sure we close the socket
Cleanup();
// The connect failed so return -1 to shut down the socket
return -1;
}
state_ = SSL_CONNECTED;
AsyncSocketAdapter::OnConnectEvent(this);
#if 0 // TODO: worry about this
// Don't let ourselves go away during the callbacks
PRefPtr<OpenSSLAdapter> lock(this);
LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(this);
LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(this);
#endif
break;
case SSL_ERROR_WANT_READ:
LOG(LS_INFO) << " -- error want read";
break;
case SSL_ERROR_WANT_WRITE:
LOG(LS_INFO) << " -- error want write";
break;
case SSL_ERROR_ZERO_RETURN:
default:
LOG(LS_INFO) << " -- error " << code;
return (code != 0) ? code : -1;
}
LOG(LS_VERBOSE) << "OpenSSLAdapter::ContinueSSL() returns 0";
return 0;
}
void
OpenSSLAdapter::Error(const char* context, int err, bool signal) {
LOG(LS_WARNING) << "SChannelAdapter::Error("
<< context << ", " << err << ")";
state_ = SSL_ERROR;
SetError(err);
if (signal)
AsyncSocketAdapter::OnCloseEvent(this, err);
}
void
OpenSSLAdapter::Cleanup() {
LOG(LS_INFO) << "Cleanup";
state_ = SSL_NONE;
ssl_read_needs_write_ = false;
ssl_write_needs_read_ = false;
if (ssl_) {
SSL_free(ssl_);
ssl_ = NULL;
}
if (ssl_ctx_) {
SSL_CTX_free(ssl_ctx_);
ssl_ctx_ = NULL;
}
}
//
// AsyncSocket Implementation
//
int
OpenSSLAdapter::Send(const void* pv, size_t cb) {
//LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")";
switch (state_) {
case SSL_NONE:
return AsyncSocketAdapter::Send(pv, cb);
case SSL_WAIT:
case SSL_CONNECTING:
SetError(EWOULDBLOCK);
return SOCKET_ERROR;
case SSL_CONNECTED:
break;
case SSL_ERROR:
default:
return SOCKET_ERROR;
}
// OpenSSL will return an error if we try to write zero bytes
if (cb == 0)
return 0;
ssl_write_needs_read_ = false;
int code = SSL_write(ssl_, pv, cb);
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
//LOG(LS_INFO) << " -- success";
return code;
case SSL_ERROR_WANT_READ:
//LOG(LS_INFO) << " -- error want read";
ssl_write_needs_read_ = true;
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_WANT_WRITE:
//LOG(LS_INFO) << " -- error want write";
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_ZERO_RETURN:
//LOG(LS_INFO) << " -- remote side closed";
SetError(EWOULDBLOCK);
// do we need to signal closure?
break;
default:
//LOG(LS_INFO) << " -- error " << code;
Error("SSL_write", (code ? code : -1), false);
break;
}
return SOCKET_ERROR;
}
int
OpenSSLAdapter::Recv(void* pv, size_t cb) {
//LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")";
switch (state_) {
case SSL_NONE:
return AsyncSocketAdapter::Recv(pv, cb);
case SSL_WAIT:
case SSL_CONNECTING:
SetError(EWOULDBLOCK);
return SOCKET_ERROR;
case SSL_CONNECTED:
break;
case SSL_ERROR:
default:
return SOCKET_ERROR;
}
// Don't trust OpenSSL with zero byte reads
if (cb == 0)
return 0;
ssl_read_needs_write_ = false;
int code = SSL_read(ssl_, pv, cb);
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
//LOG(LS_INFO) << " -- success";
return code;
case SSL_ERROR_WANT_READ:
//LOG(LS_INFO) << " -- error want read";
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_WANT_WRITE:
//LOG(LS_INFO) << " -- error want write";
ssl_read_needs_write_ = true;
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_ZERO_RETURN:
//LOG(LS_INFO) << " -- remote side closed";
SetError(EWOULDBLOCK);
// do we need to signal closure?
break;
default:
//LOG(LS_INFO) << " -- error " << code;
Error("SSL_read", (code ? code : -1), false);
break;
}
return SOCKET_ERROR;
}
int
OpenSSLAdapter::Close() {
Cleanup();
state_ = restartable_ ? SSL_WAIT : SSL_NONE;
return AsyncSocketAdapter::Close();
}
Socket::ConnState
OpenSSLAdapter::GetState() const {
//if (signal_close_)
// return CS_CONNECTED;
ConnState state = socket_->GetState();
if ((state == CS_CONNECTED)
&& ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
state = CS_CONNECTING;
return state;
}
void
OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
if (state_ != SSL_WAIT) {
ASSERT(state_ == SSL_NONE);
AsyncSocketAdapter::OnConnectEvent(socket);
return;
}
state_ = SSL_CONNECTING;
if (int err = BeginSSL()) {
AsyncSocketAdapter::OnCloseEvent(socket, err);
}
}
void
OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
//LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent";
if (state_ == SSL_NONE) {
AsyncSocketAdapter::OnReadEvent(socket);
return;
}
if (state_ == SSL_CONNECTING) {
if (int err = ContinueSSL()) {
Error("ContinueSSL", err);
}
return;
}
if (state_ != SSL_CONNECTED)
return;
// Don't let ourselves go away during the callbacks
//PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
if (ssl_write_needs_read_) {
//LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(socket);
}
//LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(socket);
}
void
OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
//LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent";
if (state_ == SSL_NONE) {
AsyncSocketAdapter::OnWriteEvent(socket);
return;
}
if (state_ == SSL_CONNECTING) {
if (int err = ContinueSSL()) {
Error("ContinueSSL", err);
}
return;
}
if (state_ != SSL_CONNECTED)
return;
// Don't let ourselves go away during the callbacks
//PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
if (ssl_read_needs_write_) {
//LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(socket);
}
//LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(socket);
}
void
OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
AsyncSocketAdapter::OnCloseEvent(socket, err);
}
// This code is taken from the "Network Security with OpenSSL"
// sample in chapter 5
bool
OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) {
if (!host)
return false;
// Checking the return from SSL_get_peer_certificate here is not strictly
// necessary. With our setup, it is not possible for it to return
// NULL. However, it is good form to check the return.
X509* certificate = SSL_get_peer_certificate(ssl);
if (!certificate)
return false;
#ifdef _DEBUG
{
LOG(LS_INFO) << "Certificate from server:";
BIO* mem = BIO_new(BIO_s_mem());
X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER);
BIO_write(mem, "\0", 1);
char* buffer;
BIO_get_mem_data(mem, &buffer);
LOG(LS_INFO) << buffer;
BIO_free(mem);
char* cipher_description =
SSL_CIPHER_description(SSL_get_current_cipher(ssl), NULL, 128);
LOG(LS_INFO) << "Cipher: " << cipher_description;
OPENSSL_free(cipher_description);
}
#endif
bool ok = false;
int extension_count = X509_get_ext_count(certificate);
for (int i = 0; i < extension_count; ++i) {
X509_EXTENSION* extension = X509_get_ext(certificate, i);
int extension_nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension));
if (extension_nid == NID_subject_alt_name) {
#if OPENSSL_VERSION_NUMBER >= 0x1000000fL
const X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension);
#else
X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension);
#endif
if (!meth)
break;
void* ext_str = NULL;
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
const unsigned char **ext_value_data = (const_cast<const unsigned char **>
(&extension->value->data));
#else
unsigned char **ext_value_data = &extension->value->data;
#endif
if (meth->it) {
ext_str = ASN1_item_d2i(NULL, ext_value_data, extension->value->length,
ASN1_ITEM_ptr(meth->it));
} else {
ext_str = meth->d2i(NULL, ext_value_data, extension->value->length);
}
STACK_OF(CONF_VALUE)* value = meth->i2v(meth, ext_str, NULL);
for (int j = 0; j < sk_CONF_VALUE_num(value); ++j) {
CONF_VALUE* nval = sk_CONF_VALUE_value(value, j);
if (!strcmp(nval->name, "DNS") && !strcmp(nval->value, host)) {
ok = true;
break;
}
}
}
if (ok)
break;
}
char data[256];
X509_name_st* subject;
if (!ok
&& (subject = X509_get_subject_name(certificate))
&& (X509_NAME_get_text_by_NID(subject, NID_commonName,
data, sizeof(data)) > 0)) {
data[sizeof(data)-1] = 0;
if (_stricmp(data, host) == 0)
ok = true;
}
X509_free(certificate);
if (!ok && ignore_bad_cert()) {
LOG(LS_WARNING) << "TLS certificate check FAILED. "
<< "Allowing connection anyway.";
ok = true;
}
if (ok)
ok = (SSL_get_verify_result(ssl) == X509_V_OK);
if (!ok && ignore_bad_cert()) {
LOG(LS_INFO) << "Other TLS post connection checks failed.";
ok = true;
}
return ok;
}
#if _DEBUG
// We only use this for tracing and so it is only needed in debug mode
void
OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
const char* str = "undefined";
int w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
}
if (where & SSL_CB_LOOP) {
LOG(LS_INFO) << str << ":" << SSL_state_string_long(s);
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
LOG(LS_INFO) << "SSL3 alert " << str
<< ":" << SSL_alert_type_string_long(ret)
<< ":" << SSL_alert_desc_string_long(ret);
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
} else if (ret < 0) {
LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
}
}
}
#endif // _DEBUG
int
OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
#if _DEBUG
if (!ok) {
char data[256];
X509* cert = X509_STORE_CTX_get_current_cert(store);
int depth = X509_STORE_CTX_get_error_depth(store);
int err = X509_STORE_CTX_get_error(store);
LOG(LS_INFO) << "Error with certificate at depth: " << depth;
X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
LOG(LS_INFO) << " issuer = " << data;
X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
LOG(LS_INFO) << " subject = " << data;
LOG(LS_INFO) << " err = " << err
<< ":" << X509_verify_cert_error_string(err);
}
#endif
// Get our stream pointer from the store
SSL* ssl = reinterpret_cast<SSL*>(
X509_STORE_CTX_get_ex_data(store,
SSL_get_ex_data_X509_STORE_CTX_idx()));
OpenSSLAdapter* stream =
reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
if (!ok && stream->ignore_bad_cert()) {
LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
ok = 1;
}
return ok;
}
SSL_CTX*
OpenSSLAdapter::SetupSSLContext() {
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx == NULL)
{
LOG(LS_ERROR) << "OpenSSLAdapter::SetupSSLContext() error: ctx == NULL";
return NULL;
}
// Add the root cert to the SSL context
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
const unsigned char* cert_buffer
#else
unsigned char* cert_buffer
#endif
= EquifaxSecureGlobalEBusinessCA1_certificate;
size_t cert_buffer_len = sizeof(EquifaxSecureGlobalEBusinessCA1_certificate);
X509* cert = d2i_X509(NULL, &cert_buffer, cert_buffer_len);
if (cert == NULL) {
SSL_CTX_free(ctx);
return NULL;
}
if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert)) {
X509_free(cert);
SSL_CTX_free(ctx);
return NULL;
}
#ifdef _DEBUG
SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
#endif
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
SSL_CTX_set_verify_depth(ctx, 4);
SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
return ctx;
}
} // namespace talk_base
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include <android/bitmap.h>
#include "base/android/build_info.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/threading/worker_pool.h"
#include "cc/base/latency_info_swap_promise.h"
#include "cc/layers/delegated_frame_provider.h"
#include "cc/layers/delegated_renderer_layer.h"
#include "cc/layers/layer.h"
#include "cc/output/compositor_frame.h"
#include "cc/output/compositor_frame_ack.h"
#include "cc/output/copy_output_request.h"
#include "cc/output/copy_output_result.h"
#include "cc/output/viewport_selection_bound.h"
#include "cc/resources/single_release_callback.h"
#include "cc/trees/layer_tree_host.h"
#include "content/browser/accessibility/browser_accessibility_manager_android.h"
#include "content/browser/android/composited_touch_handle_drawable.h"
#include "content/browser/android/content_view_core_impl.h"
#include "content/browser/android/edge_effect.h"
#include "content/browser/android/edge_effect_l.h"
#include "content/browser/android/in_process/synchronous_compositor_impl.h"
#include "content/browser/android/overscroll_controller_android.h"
#include "content/browser/devtools/render_view_devtools_agent_host.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_process_host_ui_shim.h"
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "content/browser/media/media_web_contents_observer.h"
#include "content/browser/renderer_host/compositor_impl_android.h"
#include "content/browser/renderer_host/dip_util.h"
#include "content/browser/renderer_host/input/synthetic_gesture_target_android.h"
#include "content/browser/renderer_host/input/web_input_event_builders_android.h"
#include "content/browser/renderer_host/input/web_input_event_util.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/common/gpu/gpu_process_launch_causes.h"
#include "content/common/input/did_overscroll_params.h"
#include "content/common/input_messages.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "skia/ext/image_operations.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/base/android/window_android.h"
#include "ui/base/android/window_android_compositor.h"
#include "ui/events/gesture_detection/gesture_provider_config_helper.h"
#include "ui/events/gesture_detection/motion_event.h"
#include "ui/gfx/android/device_display_info.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/android/view_configuration.h"
#include "ui/gfx/display.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/size_conversions.h"
#include "ui/touch_selection/touch_selection_controller.h"
namespace content {
namespace {
const int kUndefinedOutputSurfaceId = -1;
// Used to accomodate finite precision when comparing scaled viewport and
// content widths. While this value may seem large, width=device-width on an N7
// V1 saw errors of ~0.065 between computed window and content widths.
const float kMobileViewportWidthEpsilon = 0.15f;
static const char kAsyncReadBackString[] = "Compositing.CopyFromSurfaceTime";
// Sends an acknowledgement to the renderer of a processed IME event.
void SendImeEventAck(RenderWidgetHostImpl* host) {
host->Send(new ViewMsg_ImeEventAck(host->GetRoutingID()));
}
class GLHelperHolder
: public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
public:
static GLHelperHolder* Create();
~GLHelperHolder() override;
void Initialize();
// WebGraphicsContextLostCallback implementation.
virtual void onContextLost() override;
GLHelper* GetGLHelper() { return gl_helper_.get(); }
bool IsLost() { return !context_.get() || context_->isContextLost(); }
private:
GLHelperHolder();
static scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateContext3D();
scoped_ptr<GLHelper> gl_helper_;
scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
DISALLOW_COPY_AND_ASSIGN(GLHelperHolder);
};
GLHelperHolder* GLHelperHolder::Create() {
GLHelperHolder* holder = new GLHelperHolder;
holder->Initialize();
return holder;
}
GLHelperHolder::GLHelperHolder() {
}
GLHelperHolder::~GLHelperHolder() {
}
void GLHelperHolder::Initialize() {
context_ = CreateContext3D();
if (context_) {
context_->setContextLostCallback(this);
gl_helper_.reset(new GLHelper(context_->GetImplementation(),
context_->GetContextSupport()));
}
}
void GLHelperHolder::onContextLost() {
// Need to post a task because the command buffer client cannot be deleted
// from within this callback.
LOG(ERROR) << "Context lost.";
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&RenderWidgetHostViewAndroid::OnContextLost));
}
scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
GLHelperHolder::CreateContext3D() {
BrowserGpuChannelHostFactory* factory =
BrowserGpuChannelHostFactory::instance();
scoped_refptr<GpuChannelHost> gpu_channel_host(factory->GetGpuChannel());
// GLHelper can only be used in asynchronous APIs for postprocessing after
// Browser Compositor operations (i.e. readback).
DCHECK(gpu_channel_host.get()) << "Illegal access to GPU channel at startup";
if (gpu_channel_host->IsLost()) {
// The Browser Compositor is in charge of reestablishing the channel.
return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
}
blink::WebGraphicsContext3D::Attributes attrs;
attrs.shareResources = true;
GURL url("chrome://gpu/RenderWidgetHostViewAndroid");
static const size_t kBytesPerPixel = 4;
gfx::DeviceDisplayInfo display_info;
size_t full_screen_texture_size_in_bytes = display_info.GetDisplayHeight() *
display_info.GetDisplayWidth() *
kBytesPerPixel;
WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
limits.command_buffer_size = 64 * 1024;
limits.start_transfer_buffer_size = 64 * 1024;
limits.min_transfer_buffer_size = 64 * 1024;
limits.max_transfer_buffer_size = std::min(
3 * full_screen_texture_size_in_bytes, kDefaultMaxTransferBufferSize);
limits.mapped_memory_reclaim_limit =
WebGraphicsContext3DCommandBufferImpl::kNoLimit;
bool lose_context_when_out_of_memory = false;
scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
new WebGraphicsContext3DCommandBufferImpl(
0, // offscreen
url, gpu_channel_host.get(), attrs, lose_context_when_out_of_memory,
limits, nullptr));
if (context->InitializeOnCurrentThread()) {
context->pushGroupMarkerEXT(
base::StringPrintf("CmdBufferImageTransportFactory-%p",
context.get()).c_str());
} else {
context.reset();
}
return context.Pass();
}
// This can only be used for readback postprocessing. It may return null if the
// channel was lost and not reestablished yet.
GLHelper* GetPostReadbackGLHelper() {
static GLHelperHolder* g_readback_helper_holder = nullptr;
if (g_readback_helper_holder && g_readback_helper_holder->IsLost()) {
delete g_readback_helper_holder;
g_readback_helper_holder = nullptr;
}
if (!g_readback_helper_holder)
g_readback_helper_holder = GLHelperHolder::Create();
return g_readback_helper_holder->GetGLHelper();
}
void CopyFromCompositingSurfaceFinished(
ReadbackRequestCallback& callback,
scoped_ptr<cc::SingleReleaseCallback> release_callback,
scoped_ptr<SkBitmap> bitmap,
const base::TimeTicks& start_time,
scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock,
bool result) {
TRACE_EVENT0(
"cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceFinished");
bitmap_pixels_lock.reset();
uint32 sync_point = 0;
if (result) {
GLHelper* gl_helper = GetPostReadbackGLHelper();
if (gl_helper)
sync_point = gl_helper->InsertSyncPoint();
}
bool lost_resource = sync_point == 0;
release_callback->Run(sync_point, lost_resource);
UMA_HISTOGRAM_TIMES(kAsyncReadBackString,
base::TimeTicks::Now() - start_time);
ReadbackResponse response = result ? READBACK_SUCCESS : READBACK_FAILED;
callback.Run(*bitmap, response);
}
ui::LatencyInfo CreateLatencyInfo(const blink::WebInputEvent& event) {
ui::LatencyInfo latency_info;
// The latency number should only be added if the timestamp is valid.
if (event.timeStampSeconds) {
const int64 time_micros = static_cast<int64>(
event.timeStampSeconds * base::Time::kMicrosecondsPerSecond);
latency_info.AddLatencyNumberWithTimestamp(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
0,
0,
base::TimeTicks() + base::TimeDelta::FromMicroseconds(time_micros),
1);
}
return latency_info;
}
scoped_ptr<ui::TouchSelectionController> CreateSelectionController(
ui::TouchSelectionControllerClient* client,
ContentViewCore* content_view_core) {
DCHECK(client);
DCHECK(content_view_core);
int tap_timeout_ms = gfx::ViewConfiguration::GetTapTimeoutInMs();
int touch_slop_pixels = gfx::ViewConfiguration::GetTouchSlopInPixels();
return make_scoped_ptr(new ui::TouchSelectionController(
client,
base::TimeDelta::FromMilliseconds(tap_timeout_ms),
touch_slop_pixels / content_view_core->GetDpiScale()));
}
scoped_ptr<OverscrollControllerAndroid> CreateOverscrollController(
ContentViewCore* content_view_core) {
DCHECK(content_view_core);
ui::WindowAndroid* window = content_view_core->GetWindowAndroid();
DCHECK(window);
ui::WindowAndroidCompositor* compositor = window->GetCompositor();
DCHECK(compositor);
return make_scoped_ptr(new OverscrollControllerAndroid(
content_view_core->GetWebContents(),
compositor,
content_view_core->GetDpiScale()));
}
ui::GestureProvider::Config CreateGestureProviderConfig() {
ui::GestureProvider::Config config = ui::DefaultGestureProviderConfig();
config.disable_click_delay =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableClickDelay);
return config;
}
bool HasFixedPageScale(const cc::CompositorFrameMetadata& frame_metadata) {
return frame_metadata.min_page_scale_factor ==
frame_metadata.max_page_scale_factor;
}
bool HasMobileViewport(const cc::CompositorFrameMetadata& frame_metadata) {
float window_width_dip =
frame_metadata.page_scale_factor *
frame_metadata.scrollable_viewport_size.width();
float content_width_css = frame_metadata.root_layer_size.width();
return content_width_css <= window_width_dip + kMobileViewportWidthEpsilon;
}
} // anonymous namespace
ReadbackRequest::ReadbackRequest(float scale,
SkColorType color_type,
gfx::Rect src_subrect,
ReadbackRequestCallback& result_callback)
: scale_(scale),
color_type_(color_type),
src_subrect_(src_subrect),
result_callback_(result_callback) {
}
ReadbackRequest::ReadbackRequest() {
}
ReadbackRequest::~ReadbackRequest() {
}
RenderWidgetHostViewAndroid::LastFrameInfo::LastFrameInfo(
uint32 output_id,
scoped_ptr<cc::CompositorFrame> output_frame)
: output_surface_id(output_id), frame(output_frame.Pass()) {}
RenderWidgetHostViewAndroid::LastFrameInfo::~LastFrameInfo() {}
void RenderWidgetHostViewAndroid::OnContextLost() {
scoped_ptr<RenderWidgetHostIterator> widgets(
RenderWidgetHostImpl::GetAllRenderWidgetHosts());
while (RenderWidgetHost* widget = widgets->GetNextHost()) {
if (widget->GetView()) {
static_cast<RenderWidgetHostViewAndroid*>(widget->GetView())
->OnLostResources();
}
}
}
RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
ContentViewCoreImpl* content_view_core)
: host_(widget_host),
outstanding_vsync_requests_(0),
is_showing_(!widget_host->is_hidden()),
content_view_core_(NULL),
ime_adapter_android_(this),
cached_background_color_(SK_ColorWHITE),
last_output_surface_id_(kUndefinedOutputSurfaceId),
gesture_provider_(CreateGestureProviderConfig(), this),
stylus_text_selector_(this),
accelerated_surface_route_id_(0),
using_browser_compositor_(CompositorImpl::IsInitialized()),
frame_evictor_(new DelegatedFrameEvictor(this)),
locks_on_frame_count_(0),
observing_root_window_(false),
weak_ptr_factory_(this) {
host_->SetView(this);
SetContentViewCore(content_view_core);
}
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
SetContentViewCore(NULL);
DCHECK(ack_callbacks_.empty());
DCHECK(readbacks_waiting_for_frame_.empty());
if (resource_collection_.get())
resource_collection_->SetClient(NULL);
}
bool RenderWidgetHostViewAndroid::OnMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewAndroid, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_StartContentIntent, OnStartContentIntent)
IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeBodyBackgroundColor,
OnDidChangeBodyBackgroundColor)
IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
OnSetNeedsBeginFrames)
IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
OnTextInputStateChanged)
IPC_MESSAGE_HANDLER(ViewHostMsg_SmartClipDataExtracted,
OnSmartClipDataExtracted)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewAndroid::InitAsPopup(
RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewAndroid::InitAsFullscreen(
RenderWidgetHostView* reference_host_view) {
NOTIMPLEMENTED();
}
RenderWidgetHost*
RenderWidgetHostViewAndroid::GetRenderWidgetHost() const {
return host_;
}
void RenderWidgetHostViewAndroid::WasShown() {
if (!host_ || !host_->is_hidden())
return;
host_->WasShown(ui::LatencyInfo());
if (content_view_core_) {
StartObservingRootWindow();
RequestVSyncUpdate(BEGIN_FRAME);
}
}
void RenderWidgetHostViewAndroid::WasHidden() {
RunAckCallbacks();
if (!host_ || host_->is_hidden())
return;
// Inform the renderer that we are being hidden so it can reduce its resource
// utilization.
host_->WasHidden();
StopObservingRootWindow();
}
void RenderWidgetHostViewAndroid::WasResized() {
host_->WasResized();
}
void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) {
// Ignore the given size as only the Java code has the power to
// resize the view on Android.
default_size_ = size;
}
void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) {
SetSize(rect.size());
}
void RenderWidgetHostViewAndroid::AbortPendingReadbackRequests() {
while (!readbacks_waiting_for_frame_.empty()) {
ReadbackRequest& readback_request = readbacks_waiting_for_frame_.front();
readback_request.GetResultCallback().Run(SkBitmap(), READBACK_FAILED);
readbacks_waiting_for_frame_.pop();
}
}
void RenderWidgetHostViewAndroid::GetScaledContentBitmap(
float scale,
SkColorType color_type,
gfx::Rect src_subrect,
ReadbackRequestCallback& result_callback) {
if (!host_ || host_->is_hidden()) {
result_callback.Run(SkBitmap(), READBACK_NOT_SUPPORTED);
return;
}
if (!IsSurfaceAvailableForCopy()) {
// The view is visible, probably the frame has not yet arrived.
// Just add the ReadbackRequest to queue and wait for frame arrival
// to get this request processed.
readbacks_waiting_for_frame_.push(
ReadbackRequest(scale, color_type, src_subrect, result_callback));
return;
}
gfx::Size bounds = layer_->bounds();
if (src_subrect.IsEmpty())
src_subrect = gfx::Rect(bounds);
DCHECK_LE(src_subrect.width() + src_subrect.x(), bounds.width());
DCHECK_LE(src_subrect.height() + src_subrect.y(), bounds.height());
const gfx::Display& display =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
float device_scale_factor = display.device_scale_factor();
DCHECK_GT(device_scale_factor, 0);
gfx::Size dst_size(
gfx::ToCeiledSize(gfx::ScaleSize(bounds, scale / device_scale_factor)));
CopyFromCompositingSurface(
src_subrect, dst_size, result_callback, color_type);
}
scoped_refptr<cc::DelegatedRendererLayer>
RenderWidgetHostViewAndroid::CreateDelegatedLayerForFrameProvider() const {
DCHECK(frame_provider_.get());
scoped_refptr<cc::DelegatedRendererLayer> delegated_layer =
cc::DelegatedRendererLayer::Create(frame_provider_);
delegated_layer->SetBounds(content_size_in_layer_);
delegated_layer->SetIsDrawable(true);
delegated_layer->SetContentsOpaque(true);
return delegated_layer;
}
bool RenderWidgetHostViewAndroid::HasValidFrame() const {
if (!content_view_core_)
return false;
if (!layer_.get())
return false;
if (texture_size_in_layer_.IsEmpty())
return false;
// This tell us whether a valid frame has arrived or not.
if (!frame_evictor_->HasFrame())
return false;
return true;
}
gfx::Vector2dF RenderWidgetHostViewAndroid::GetLastScrollOffset() const {
return last_scroll_offset_;
}
gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const {
return content_view_core_->GetViewAndroid();
}
gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const {
return reinterpret_cast<gfx::NativeViewId>(
const_cast<RenderWidgetHostViewAndroid*>(this));
}
gfx::NativeViewAccessible
RenderWidgetHostViewAndroid::GetNativeViewAccessible() {
NOTIMPLEMENTED();
return NULL;
}
void RenderWidgetHostViewAndroid::MovePluginWindows(
const std::vector<WebPluginGeometry>& moves) {
// We don't have plugin windows on Android. Do nothing. Note: this is called
// from RenderWidgetHost::OnUpdateRect which is itself invoked while
// processing the corresponding message from Renderer.
}
void RenderWidgetHostViewAndroid::Focus() {
host_->Focus();
host_->SetInputMethodActive(true);
if (overscroll_controller_)
overscroll_controller_->Enable();
}
void RenderWidgetHostViewAndroid::Blur() {
host_->SetInputMethodActive(false);
host_->Blur();
if (overscroll_controller_)
overscroll_controller_->Disable();
}
bool RenderWidgetHostViewAndroid::HasFocus() const {
if (!content_view_core_)
return false; // ContentViewCore not created yet.
return content_view_core_->HasFocus();
}
bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() const {
return HasValidFrame();
}
void RenderWidgetHostViewAndroid::Show() {
if (is_showing_)
return;
is_showing_ = true;
if (layer_.get())
layer_->SetHideLayerAndSubtree(false);
frame_evictor_->SetVisible(true);
WasShown();
}
void RenderWidgetHostViewAndroid::Hide() {
if (!is_showing_)
return;
is_showing_ = false;
if (layer_.get() && locks_on_frame_count_ == 0)
layer_->SetHideLayerAndSubtree(true);
frame_evictor_->SetVisible(false);
// We don't know if we will ever get a frame if we are hiding the renderer, so
// we need to cancel all requests
AbortPendingReadbackRequests();
WasHidden();
}
bool RenderWidgetHostViewAndroid::IsShowing() {
// ContentViewCoreImpl represents the native side of the Java
// ContentViewCore. It being NULL means that it is not attached
// to the View system yet, so we treat this RWHVA as hidden.
return is_showing_ && content_view_core_;
}
void RenderWidgetHostViewAndroid::LockCompositingSurface() {
DCHECK(HasValidFrame());
DCHECK(host_);
DCHECK(frame_evictor_->HasFrame());
frame_evictor_->LockFrame();
locks_on_frame_count_++;
}
void RenderWidgetHostViewAndroid::UnlockCompositingSurface() {
if (!frame_evictor_->HasFrame() || locks_on_frame_count_ == 0)
return;
DCHECK(HasValidFrame());
frame_evictor_->UnlockFrame();
locks_on_frame_count_--;
if (locks_on_frame_count_ == 0) {
if (last_frame_info_) {
InternalSwapCompositorFrame(last_frame_info_->output_surface_id,
last_frame_info_->frame.Pass());
last_frame_info_.reset();
}
if (!is_showing_ && layer_.get())
layer_->SetHideLayerAndSubtree(true);
}
}
void RenderWidgetHostViewAndroid::SetTextSurroundingSelectionCallback(
const TextSurroundingSelectionCallback& callback) {
// Only one outstanding request is allowed at any given time.
DCHECK(!callback.is_null());
text_surrounding_selection_callback_ = callback;
}
void RenderWidgetHostViewAndroid::OnTextSurroundingSelectionResponse(
const base::string16& content,
size_t start_offset,
size_t end_offset) {
if (text_surrounding_selection_callback_.is_null())
return;
text_surrounding_selection_callback_.Run(content, start_offset, end_offset);
text_surrounding_selection_callback_.Reset();
}
void RenderWidgetHostViewAndroid::ReleaseLocksOnSurface() {
if (!frame_evictor_->HasFrame()) {
DCHECK_EQ(locks_on_frame_count_, 0u);
return;
}
while (locks_on_frame_count_ > 0) {
UnlockCompositingSurface();
}
RunAckCallbacks();
}
gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const {
if (!content_view_core_)
return gfx::Rect(default_size_);
return gfx::Rect(content_view_core_->GetViewSize());
}
gfx::Size RenderWidgetHostViewAndroid::GetPhysicalBackingSize() const {
if (!content_view_core_)
return gfx::Size();
return content_view_core_->GetPhysicalBackingSize();
}
bool RenderWidgetHostViewAndroid::DoTopControlsShrinkBlinkSize() const {
if (!content_view_core_)
return false;
// Whether or not Blink's viewport size should be shrunk by the height of the
// URL-bar.
return content_view_core_->DoTopControlsShrinkBlinkSize();
}
float RenderWidgetHostViewAndroid::GetTopControlsHeight() const {
if (!content_view_core_)
return 0.f;
// The height of the top controls.
return content_view_core_->GetTopControlsHeightDip();
}
void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) {
// There are no cursors on Android.
}
void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) {
// Do nothing. The UI notification is handled through ContentViewClient which
// is TabContentsDelegate.
}
void RenderWidgetHostViewAndroid::TextInputTypeChanged(
ui::TextInputType type,
ui::TextInputMode input_mode,
bool can_compose_inline,
int flags) {
// Unused on Android, which uses OnTextInputChanged instead.
}
long RenderWidgetHostViewAndroid::GetNativeImeAdapter() {
return reinterpret_cast<intptr_t>(&ime_adapter_android_);
}
void RenderWidgetHostViewAndroid::OnTextInputStateChanged(
const ViewHostMsg_TextInputState_Params& params) {
if (selection_controller_) {
// This call is semi-redundant with that in |OnFocusedNodeChanged|. The
// latter is guaranteed to be called before |OnSelectionBoundsChanged|,
// while this call is present to ensure consistency with IME after
// navigation and tab focus changes
const bool is_editable_node = params.type != ui::TEXT_INPUT_TYPE_NONE;
selection_controller_->OnSelectionEditable(is_editable_node);
}
// If the change is not originated from IME (e.g. Javascript, autofill),
// send back the renderer an acknowledgement, regardless of how we exit from
// this method.
base::ScopedClosureRunner ack_caller;
if (params.is_non_ime_change)
ack_caller.Reset(base::Bind(&SendImeEventAck, host_));
if (!IsShowing())
return;
content_view_core_->UpdateImeAdapter(
GetNativeImeAdapter(),
static_cast<int>(params.type), params.flags,
params.value, params.selection_start, params.selection_end,
params.composition_start, params.composition_end,
params.show_ime_if_needed, params.is_non_ime_change);
}
void RenderWidgetHostViewAndroid::OnDidChangeBodyBackgroundColor(
SkColor color) {
if (cached_background_color_ == color)
return;
cached_background_color_ = color;
if (content_view_core_)
content_view_core_->OnBackgroundColorChanged(color);
}
void RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames(bool enabled) {
DCHECK(using_browser_compositor_);
TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames",
"enabled", enabled);
if (enabled)
RequestVSyncUpdate(PERSISTENT_BEGIN_FRAME);
else
outstanding_vsync_requests_ &= ~PERSISTENT_BEGIN_FRAME;
}
void RenderWidgetHostViewAndroid::OnStartContentIntent(
const GURL& content_url) {
if (content_view_core_)
content_view_core_->StartContentIntent(content_url);
}
void RenderWidgetHostViewAndroid::OnSmartClipDataExtracted(
const base::string16& text,
const base::string16& html,
const gfx::Rect rect) {
if (content_view_core_)
content_view_core_->OnSmartClipDataExtracted(text, html, rect);
}
bool RenderWidgetHostViewAndroid::OnTouchEvent(
const ui::MotionEvent& event) {
if (!host_)
return false;
if (selection_controller_ &&
selection_controller_->WillHandleTouchEvent(event))
return true;
if (stylus_text_selector_.OnTouchEvent(event))
return true;
if (!gesture_provider_.OnTouchEvent(event))
return false;
if (host_->ShouldForwardTouchEvent()) {
blink::WebTouchEvent web_event = CreateWebTouchEventFromMotionEvent(event);
host_->ForwardTouchEventWithLatencyInfo(web_event,
CreateLatencyInfo(web_event));
} else {
const bool event_consumed = false;
gesture_provider_.OnTouchEventAck(event_consumed);
}
// Send a proactive BeginFrame on the next vsync to reduce latency.
// This is good enough as long as the first touch event has Begin semantics
// and the actual scroll happens on the next vsync.
if (observing_root_window_)
RequestVSyncUpdate(BEGIN_FRAME);
return true;
}
bool RenderWidgetHostViewAndroid::OnTouchHandleEvent(
const ui::MotionEvent& event) {
return selection_controller_ &&
selection_controller_->WillHandleTouchEvent(event);
}
void RenderWidgetHostViewAndroid::ResetGestureDetection() {
const ui::MotionEvent* current_down_event =
gesture_provider_.GetCurrentDownEvent();
if (current_down_event) {
scoped_ptr<ui::MotionEvent> cancel_event = current_down_event->Cancel();
OnTouchEvent(*cancel_event);
}
// A hard reset ensures prevention of any timer-based events.
gesture_provider_.ResetDetection();
}
void RenderWidgetHostViewAndroid::SetDoubleTapSupportEnabled(bool enabled) {
gesture_provider_.SetDoubleTapSupportForPlatformEnabled(enabled);
}
void RenderWidgetHostViewAndroid::SetMultiTouchZoomSupportEnabled(
bool enabled) {
gesture_provider_.SetMultiTouchZoomSupportEnabled(enabled);
}
void RenderWidgetHostViewAndroid::ImeCancelComposition() {
ime_adapter_android_.CancelComposition();
}
void RenderWidgetHostViewAndroid::ImeCompositionRangeChanged(
const gfx::Range& range,
const std::vector<gfx::Rect>& character_bounds) {
ime_adapter_android_.SetCharacterBounds(character_bounds);
}
void RenderWidgetHostViewAndroid::FocusedNodeChanged(bool is_editable_node) {
ime_adapter_android_.FocusedNodeChanged(is_editable_node);
if (selection_controller_)
selection_controller_->OnSelectionEditable(is_editable_node);
}
void RenderWidgetHostViewAndroid::RenderProcessGone(
base::TerminationStatus status, int error_code) {
Destroy();
}
void RenderWidgetHostViewAndroid::Destroy() {
RemoveLayers();
SetContentViewCore(NULL);
// The RenderWidgetHost's destruction led here, so don't call it.
host_ = NULL;
delete this;
}
void RenderWidgetHostViewAndroid::SetTooltipText(
const base::string16& tooltip_text) {
// Tooltips don't makes sense on Android.
}
void RenderWidgetHostViewAndroid::SelectionChanged(const base::string16& text,
size_t offset,
const gfx::Range& range) {
RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
if (selection_controller_)
selection_controller_->OnSelectionEmpty(text.empty());
if (!content_view_core_)
return;
if (range.is_empty()) {
content_view_core_->OnSelectionChanged("");
return;
}
DCHECK(!text.empty());
size_t pos = range.GetMin() - offset;
size_t n = range.length();
DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
if (pos >= text.length()) {
NOTREACHED() << "The text can not cover range.";
return;
}
std::string utf8_selection = base::UTF16ToUTF8(text.substr(pos, n));
content_view_core_->OnSelectionChanged(utf8_selection);
}
void RenderWidgetHostViewAndroid::SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params& params) {
NOTREACHED() << "Selection bounds should be routed through the compositor.";
}
void RenderWidgetHostViewAndroid::SetBackgroundColor(SkColor color) {
RenderWidgetHostViewBase::SetBackgroundColor(color);
host_->SetBackgroundOpaque(GetBackgroundOpaque());
OnDidChangeBodyBackgroundColor(color);
}
void RenderWidgetHostViewAndroid::CopyFromCompositingSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
ReadbackRequestCallback& callback,
const SkColorType color_type) {
TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurface");
if (!host_ || host_->is_hidden()) {
callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
return;
}
base::TimeTicks start_time = base::TimeTicks::Now();
if (using_browser_compositor_ && !IsSurfaceAvailableForCopy()) {
callback.Run(SkBitmap(), READBACK_NOT_SUPPORTED);
return;
}
const gfx::Display& display =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
float device_scale_factor = display.device_scale_factor();
gfx::Size dst_size_in_pixel =
gfx::ConvertRectToPixel(device_scale_factor, gfx::Rect(dst_size)).size();
gfx::Rect src_subrect_in_pixel =
gfx::ConvertRectToPixel(device_scale_factor, src_subrect);
if (!using_browser_compositor_) {
SynchronousCopyContents(src_subrect_in_pixel, dst_size_in_pixel, callback,
color_type);
UMA_HISTOGRAM_TIMES("Compositing.CopyFromSurfaceTimeSynchronous",
base::TimeTicks::Now() - start_time);
return;
}
scoped_ptr<cc::CopyOutputRequest> request;
scoped_refptr<cc::Layer> readback_layer;
DCHECK(content_view_core_);
DCHECK(content_view_core_->GetWindowAndroid());
ui::WindowAndroidCompositor* compositor =
content_view_core_->GetWindowAndroid()->GetCompositor();
DCHECK(compositor);
DCHECK(frame_provider_.get());
scoped_refptr<cc::DelegatedRendererLayer> delegated_layer =
CreateDelegatedLayerForFrameProvider();
delegated_layer->SetHideLayerAndSubtree(true);
compositor->AttachLayerForReadback(delegated_layer);
readback_layer = delegated_layer;
request = cc::CopyOutputRequest::CreateRequest(
base::Bind(&RenderWidgetHostViewAndroid::
PrepareTextureCopyOutputResultForDelegatedReadback,
dst_size_in_pixel,
color_type,
start_time,
readback_layer,
callback));
request->set_area(src_subrect_in_pixel);
readback_layer->RequestCopyOfOutput(request.Pass());
}
void RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceToVideoFrame(
const gfx::Rect& src_subrect,
const scoped_refptr<media::VideoFrame>& target,
const base::Callback<void(bool)>& callback) {
NOTIMPLEMENTED();
callback.Run(false);
}
bool RenderWidgetHostViewAndroid::CanCopyToVideoFrame() const {
return false;
}
void RenderWidgetHostViewAndroid::ShowDisambiguationPopup(
const gfx::Rect& rect_pixels, const SkBitmap& zoomed_bitmap) {
if (!content_view_core_)
return;
content_view_core_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
}
scoped_ptr<SyntheticGestureTarget>
RenderWidgetHostViewAndroid::CreateSyntheticGestureTarget() {
return scoped_ptr<SyntheticGestureTarget>(new SyntheticGestureTargetAndroid(
host_, content_view_core_->CreateTouchEventSynthesizer()));
}
void RenderWidgetHostViewAndroid::SendDelegatedFrameAck(
uint32 output_surface_id) {
DCHECK(host_);
cc::CompositorFrameAck ack;
if (resource_collection_.get())
resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
RenderWidgetHostImpl::SendSwapCompositorFrameAck(host_->GetRoutingID(),
output_surface_id,
host_->GetProcess()->GetID(),
ack);
}
void RenderWidgetHostViewAndroid::SendReturnedDelegatedResources(
uint32 output_surface_id) {
DCHECK(resource_collection_.get());
cc::CompositorFrameAck ack;
resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
DCHECK(!ack.resources.empty());
RenderWidgetHostImpl::SendReclaimCompositorResources(
host_->GetRoutingID(),
output_surface_id,
host_->GetProcess()->GetID(),
ack);
}
void RenderWidgetHostViewAndroid::UnusedResourcesAreAvailable() {
if (ack_callbacks_.size())
return;
SendReturnedDelegatedResources(last_output_surface_id_);
}
void RenderWidgetHostViewAndroid::DestroyDelegatedContent() {
RemoveLayers();
frame_provider_ = NULL;
layer_ = NULL;
// This gets called when ever any eviction, loosing resources, swapping
// problems are encountered and so we abort any pending readbacks here.
AbortPendingReadbackRequests();
}
void RenderWidgetHostViewAndroid::SwapDelegatedFrame(
uint32 output_surface_id,
scoped_ptr<cc::DelegatedFrameData> frame_data) {
bool has_content = !texture_size_in_layer_.IsEmpty();
if (output_surface_id != last_output_surface_id_) {
// Drop the cc::DelegatedFrameResourceCollection so that we will not return
// any resources from the old output surface with the new output surface id.
if (resource_collection_.get()) {
resource_collection_->SetClient(NULL);
if (resource_collection_->LoseAllResources())
SendReturnedDelegatedResources(last_output_surface_id_);
resource_collection_ = NULL;
}
DestroyDelegatedContent();
last_output_surface_id_ = output_surface_id;
}
// DelegatedRendererLayerImpl applies the inverse device_scale_factor of the
// renderer frame, assuming that the browser compositor will scale
// it back up to device scale. But on Android we put our browser layers in
// physical pixels and set our browser CC device_scale_factor to 1, so this
// suppresses the transform. This line may need to be removed when fixing
// http://crbug.com/384134 or http://crbug.com/310763
frame_data->device_scale_factor = 1.0f;
if (!has_content) {
DestroyDelegatedContent();
} else {
if (!resource_collection_.get()) {
resource_collection_ = new cc::DelegatedFrameResourceCollection;
resource_collection_->SetClient(this);
}
if (!frame_provider_.get() ||
texture_size_in_layer_ != frame_provider_->frame_size()) {
RemoveLayers();
frame_provider_ = new cc::DelegatedFrameProvider(
resource_collection_.get(), frame_data.Pass());
layer_ = cc::DelegatedRendererLayer::Create(frame_provider_);
AttachLayers();
} else {
frame_provider_->SetFrameData(frame_data.Pass());
}
}
if (layer_.get()) {
layer_->SetIsDrawable(true);
layer_->SetContentsOpaque(true);
layer_->SetBounds(content_size_in_layer_);
layer_->SetNeedsDisplay();
}
base::Closure ack_callback =
base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
weak_ptr_factory_.GetWeakPtr(),
output_surface_id);
ack_callbacks_.push(ack_callback);
if (host_->is_hidden())
RunAckCallbacks();
}
void RenderWidgetHostViewAndroid::ComputeContentsSize(
const cc::CompositorFrameMetadata& frame_metadata) {
// Calculate the content size. This should be 0 if the texture_size is 0.
gfx::Vector2dF offset;
if (texture_size_in_layer_.IsEmpty())
content_size_in_layer_ = gfx::Size();
content_size_in_layer_ = gfx::ToCeiledSize(gfx::ScaleSize(
frame_metadata.scrollable_viewport_size,
frame_metadata.device_scale_factor * frame_metadata.page_scale_factor));
}
void RenderWidgetHostViewAndroid::InternalSwapCompositorFrame(
uint32 output_surface_id,
scoped_ptr<cc::CompositorFrame> frame) {
last_scroll_offset_ = frame->metadata.root_scroll_offset;
if (!frame->delegated_frame_data) {
LOG(ERROR) << "Non-delegated renderer path no longer supported";
return;
}
if (locks_on_frame_count_ > 0) {
DCHECK(HasValidFrame());
RetainFrame(output_surface_id, frame.Pass());
return;
}
if (layer_.get() && layer_->layer_tree_host()) {
for (size_t i = 0; i < frame->metadata.latency_info.size(); i++) {
scoped_ptr<cc::SwapPromise> swap_promise(
new cc::LatencyInfoSwapPromise(frame->metadata.latency_info[i]));
layer_->layer_tree_host()->QueueSwapPromise(swap_promise.Pass());
}
}
DCHECK(!frame->delegated_frame_data->render_pass_list.empty());
cc::RenderPass* root_pass =
frame->delegated_frame_data->render_pass_list.back();
texture_size_in_layer_ = root_pass->output_rect.size();
ComputeContentsSize(frame->metadata);
SwapDelegatedFrame(output_surface_id, frame->delegated_frame_data.Pass());
frame_evictor_->SwappedFrame(!host_->is_hidden());
// As the metadata update may trigger view invalidation, always call it after
// any potential compositor scheduling.
OnFrameMetadataUpdated(frame->metadata);
// Check if we have any pending readbacks, see if we have a frame available
// and process them here.
if (!readbacks_waiting_for_frame_.empty()) {
while (!readbacks_waiting_for_frame_.empty()) {
ReadbackRequest& readback_request = readbacks_waiting_for_frame_.front();
GetScaledContentBitmap(readback_request.GetScale(),
readback_request.GetColorFormat(),
readback_request.GetCaptureRect(),
readback_request.GetResultCallback());
readbacks_waiting_for_frame_.pop();
}
}
}
void RenderWidgetHostViewAndroid::OnSwapCompositorFrame(
uint32 output_surface_id,
scoped_ptr<cc::CompositorFrame> frame) {
InternalSwapCompositorFrame(output_surface_id, frame.Pass());
}
void RenderWidgetHostViewAndroid::RetainFrame(
uint32 output_surface_id,
scoped_ptr<cc::CompositorFrame> frame) {
DCHECK(locks_on_frame_count_);
// Store the incoming frame so that it can be swapped when all the locks have
// been released. If there is already a stored frame, then replace and skip
// the previous one but make sure we still eventually send the ACK. Holding
// the ACK also blocks the renderer when its max_frames_pending is reached.
if (last_frame_info_) {
base::Closure ack_callback =
base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
weak_ptr_factory_.GetWeakPtr(),
last_frame_info_->output_surface_id);
ack_callbacks_.push(ack_callback);
}
last_frame_info_.reset(new LastFrameInfo(output_surface_id, frame.Pass()));
}
void RenderWidgetHostViewAndroid::SynchronousFrameMetadata(
const cc::CompositorFrameMetadata& frame_metadata) {
if (!content_view_core_)
return;
// This is a subset of OnSwapCompositorFrame() used in the synchronous
// compositor flow.
OnFrameMetadataUpdated(frame_metadata);
ComputeContentsSize(frame_metadata);
// DevTools ScreenCast support for Android WebView.
WebContents* web_contents = content_view_core_->GetWebContents();
if (DevToolsAgentHost::HasFor(web_contents)) {
scoped_refptr<DevToolsAgentHost> dtah =
DevToolsAgentHost::GetOrCreateFor(web_contents);
// Unblock the compositor.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&RenderViewDevToolsAgentHost::SynchronousSwapCompositorFrame,
static_cast<RenderViewDevToolsAgentHost*>(dtah.get()),
frame_metadata));
}
}
void RenderWidgetHostViewAndroid::SetOverlayVideoMode(bool enabled) {
if (layer_.get())
layer_->SetContentsOpaque(!enabled);
}
bool RenderWidgetHostViewAndroid::SupportsAnimation() const {
// The synchronous (WebView) compositor does not have a proper browser
// compositor with which to drive animations.
return using_browser_compositor_;
}
void RenderWidgetHostViewAndroid::SetNeedsAnimate() {
DCHECK(content_view_core_);
DCHECK(using_browser_compositor_);
content_view_core_->GetWindowAndroid()->SetNeedsAnimate();
}
void RenderWidgetHostViewAndroid::MoveCaret(const gfx::PointF& position) {
MoveCaret(gfx::Point(position.x(), position.y()));
}
void RenderWidgetHostViewAndroid::MoveRangeSelectionExtent(
const gfx::PointF& extent) {
DCHECK(content_view_core_);
content_view_core_->MoveRangeSelectionExtent(extent);
}
void RenderWidgetHostViewAndroid::SelectBetweenCoordinates(
const gfx::PointF& base,
const gfx::PointF& extent) {
DCHECK(content_view_core_);
content_view_core_->SelectBetweenCoordinates(base, extent);
}
void RenderWidgetHostViewAndroid::OnSelectionEvent(
ui::SelectionEventType event,
const gfx::PointF& position) {
DCHECK(content_view_core_);
// Showing the selection action bar can alter the current View coordinates in
// such a way that the current MotionEvent stream is suddenly shifted in
// space. Avoid the associated scroll jump by pre-emptively cancelling gesture
// detection; scrolling after the selection is activated is unnecessary.
if (event == ui::SelectionEventType::SELECTION_SHOWN)
ResetGestureDetection();
content_view_core_->OnSelectionEvent(event, position);
}
scoped_ptr<ui::TouchHandleDrawable>
RenderWidgetHostViewAndroid::CreateDrawable() {
DCHECK(content_view_core_);
if (!using_browser_compositor_)
return content_view_core_->CreatePopupTouchHandleDrawable();
return scoped_ptr<ui::TouchHandleDrawable>(new CompositedTouchHandleDrawable(
content_view_core_->GetLayer().get(),
content_view_core_->GetDpiScale(),
// Use the activity context (instead of the application context) to ensure
// proper handle theming.
content_view_core_->GetContext().obj()));
}
void RenderWidgetHostViewAndroid::SynchronousCopyContents(
const gfx::Rect& src_subrect_in_pixel,
const gfx::Size& dst_size_in_pixel,
ReadbackRequestCallback& callback,
const SkColorType color_type) {
SynchronousCompositor* compositor =
SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
host_->GetRoutingID());
if (!compositor) {
callback.Run(SkBitmap(), READBACK_FAILED);
return;
}
SkBitmap bitmap;
bitmap.allocPixels(SkImageInfo::Make(dst_size_in_pixel.width(),
dst_size_in_pixel.height(),
color_type,
kPremul_SkAlphaType));
SkCanvas canvas(bitmap);
canvas.scale(
(float)dst_size_in_pixel.width() / (float)src_subrect_in_pixel.width(),
(float)dst_size_in_pixel.height() / (float)src_subrect_in_pixel.height());
compositor->DemandDrawSw(&canvas);
callback.Run(bitmap, READBACK_SUCCESS);
}
void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
const cc::CompositorFrameMetadata& frame_metadata) {
// Disable double tap zoom for pages that have a width=device-width or
// narrower viewport (indicating that this is a mobile-optimized or responsive
// web design, so text will be legible without zooming). Also disable
// double tap and pinch for pages that prevent zooming in or out.
bool has_mobile_viewport = HasMobileViewport(frame_metadata);
bool has_fixed_page_scale = HasFixedPageScale(frame_metadata);
gesture_provider_.SetDoubleTapSupportForPageEnabled(
!has_fixed_page_scale && !has_mobile_viewport);
if (!content_view_core_)
return;
if (overscroll_controller_)
overscroll_controller_->OnFrameMetadataUpdated(frame_metadata);
if (selection_controller_) {
selection_controller_->OnSelectionBoundsChanged(
ui::SelectionBound(frame_metadata.selection_start),
ui::SelectionBound(frame_metadata.selection_end));
}
// All offsets and sizes are in CSS pixels.
content_view_core_->UpdateFrameInfo(
frame_metadata.root_scroll_offset,
frame_metadata.page_scale_factor,
gfx::Vector2dF(frame_metadata.min_page_scale_factor,
frame_metadata.max_page_scale_factor),
frame_metadata.root_layer_size,
frame_metadata.scrollable_viewport_size,
frame_metadata.location_bar_offset,
frame_metadata.location_bar_content_translation);
#if defined(VIDEO_HOLE)
if (host_ && host_->IsRenderView()) {
RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(
RenderViewHost::From(host_));
rvhi->media_web_contents_observer()->OnFrameInfoUpdated();
}
#endif // defined(VIDEO_HOLE)
}
void RenderWidgetHostViewAndroid::AcceleratedSurfaceInitialized(int route_id) {
// TODO: remove need for the surface id here
accelerated_surface_route_id_ = route_id;
}
void RenderWidgetHostViewAndroid::AttachLayers() {
if (!content_view_core_)
return;
if (!layer_.get())
return;
content_view_core_->AttachLayer(layer_);
if (overscroll_controller_)
overscroll_controller_->Enable();
layer_->SetHideLayerAndSubtree(!is_showing_);
}
void RenderWidgetHostViewAndroid::RemoveLayers() {
if (!content_view_core_)
return;
if (!layer_.get())
return;
content_view_core_->RemoveLayer(layer_);
if (overscroll_controller_)
overscroll_controller_->Disable();
}
void RenderWidgetHostViewAndroid::RequestVSyncUpdate(uint32 requests) {
// The synchronous compositor does not requre BeginFrame messages.
if (!using_browser_compositor_)
requests &= FLUSH_INPUT;
bool should_request_vsync = !outstanding_vsync_requests_ && requests;
outstanding_vsync_requests_ |= requests;
// Note that if we're not currently observing the root window, outstanding
// vsync requests will be pushed if/when we resume observing in
// |StartObservingRootWindow()|.
if (observing_root_window_ && should_request_vsync)
content_view_core_->GetWindowAndroid()->RequestVSyncUpdate();
}
void RenderWidgetHostViewAndroid::StartObservingRootWindow() {
DCHECK(content_view_core_);
if (observing_root_window_)
return;
observing_root_window_ = true;
content_view_core_->GetWindowAndroid()->AddObserver(this);
// Clear existing vsync requests to allow a request to the new window.
uint32 outstanding_vsync_requests = outstanding_vsync_requests_;
outstanding_vsync_requests_ = 0;
RequestVSyncUpdate(outstanding_vsync_requests);
}
void RenderWidgetHostViewAndroid::StopObservingRootWindow() {
if (!content_view_core_) {
DCHECK(!observing_root_window_);
return;
}
if (!observing_root_window_)
return;
observing_root_window_ = false;
content_view_core_->GetWindowAndroid()->RemoveObserver(this);
}
void RenderWidgetHostViewAndroid::SendBeginFrame(base::TimeTicks frame_time,
base::TimeDelta vsync_period) {
TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::SendBeginFrame",
"frame_time_us", frame_time.ToInternalValue());
base::TimeTicks display_time = frame_time + vsync_period;
// TODO(brianderson): Use adaptive draw-time estimation.
base::TimeDelta estimated_browser_composite_time =
base::TimeDelta::FromMicroseconds(
(1.0f * base::Time::kMicrosecondsPerSecond) / (3.0f * 60));
base::TimeTicks deadline = display_time - estimated_browser_composite_time;
host_->Send(new ViewMsg_BeginFrame(
host_->GetRoutingID(),
cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE, frame_time, deadline,
vsync_period, cc::BeginFrameArgs::NORMAL)));
}
bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) {
bool needs_animate = false;
if (overscroll_controller_) {
needs_animate |= overscroll_controller_->Animate(
frame_time, content_view_core_->GetLayer().get());
}
if (selection_controller_)
needs_animate |= selection_controller_->Animate(frame_time);
return needs_animate;
}
void RenderWidgetHostViewAndroid::EvictDelegatedFrame() {
if (layer_.get())
DestroyDelegatedContent();
frame_evictor_->DiscardedFrame();
// We are evicting the delegated frame,
// so there should be no pending readback requests
DCHECK(readbacks_waiting_for_frame_.empty());
}
bool RenderWidgetHostViewAndroid::HasAcceleratedSurface(
const gfx::Size& desired_size) {
NOTREACHED();
return false;
}
void RenderWidgetHostViewAndroid::GetScreenInfo(blink::WebScreenInfo* result) {
// ScreenInfo isn't tied to the widget on Android. Always return the default.
RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
}
// TODO(jrg): Find out the implications and answer correctly here,
// as we are returning the WebView and not root window bounds.
gfx::Rect RenderWidgetHostViewAndroid::GetBoundsInRootWindow() {
return GetViewBounds();
}
gfx::GLSurfaceHandle RenderWidgetHostViewAndroid::GetCompositingSurface() {
gfx::GLSurfaceHandle handle =
gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
if (using_browser_compositor_) {
handle.parent_client_id =
BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
}
return handle;
}
void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent(
const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
const bool event_consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
gesture_provider_.OnTouchEventAck(event_consumed);
}
void RenderWidgetHostViewAndroid::GestureEventAck(
const blink::WebGestureEvent& event,
InputEventAckState ack_result) {
if (overscroll_controller_)
overscroll_controller_->OnGestureEventAck(event, ack_result);
if (content_view_core_)
content_view_core_->OnGestureEventAck(event, ack_result);
}
InputEventAckState RenderWidgetHostViewAndroid::FilterInputEvent(
const blink::WebInputEvent& input_event) {
if (selection_controller_) {
switch (input_event.type) {
case blink::WebInputEvent::GestureLongPress:
selection_controller_->OnLongPressEvent();
break;
case blink::WebInputEvent::GestureTap:
selection_controller_->OnTapEvent();
break;
default:
break;
}
}
if (overscroll_controller_ &&
blink::WebInputEvent::isGestureEventType(input_event.type) &&
overscroll_controller_->WillHandleGestureEvent(
static_cast<const blink::WebGestureEvent&>(input_event))) {
return INPUT_EVENT_ACK_STATE_CONSUMED;
}
if (content_view_core_ &&
content_view_core_->FilterInputEvent(input_event))
return INPUT_EVENT_ACK_STATE_CONSUMED;
if (!host_)
return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
if (input_event.type == blink::WebInputEvent::GestureTapDown ||
input_event.type == blink::WebInputEvent::TouchStart) {
GpuDataManagerImpl* gpu_data = GpuDataManagerImpl::GetInstance();
GpuProcessHostUIShim* shim = GpuProcessHostUIShim::GetOneInstance();
if (shim && gpu_data && accelerated_surface_route_id_ &&
gpu_data->IsDriverBugWorkaroundActive(gpu::WAKE_UP_GPU_BEFORE_DRAWING))
shim->Send(
new AcceleratedSurfaceMsg_WakeUpGpu(accelerated_surface_route_id_));
}
SynchronousCompositorImpl* compositor =
SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
host_->GetRoutingID());
if (compositor)
return compositor->HandleInputEvent(input_event);
return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
}
void RenderWidgetHostViewAndroid::OnSetNeedsFlushInput() {
TRACE_EVENT0("input", "RenderWidgetHostViewAndroid::OnSetNeedsFlushInput");
RequestVSyncUpdate(FLUSH_INPUT);
}
BrowserAccessibilityManager*
RenderWidgetHostViewAndroid::CreateBrowserAccessibilityManager(
BrowserAccessibilityDelegate* delegate) {
// TODO(dmazzoni): Currently there can only be one
// BrowserAccessibilityManager per ContentViewCore, so return NULL
// if there's already a BrowserAccessibilityManager for the main
// frame. Eventually, in order to support cross-process iframes on
// Android we'll need to add support for a
// BrowserAccessibilityManager for a child frame.
// http://crbug.com/423846
if (!host_ || host_->GetRootBrowserAccessibilityManager())
return NULL;
base::android::ScopedJavaLocalRef<jobject> obj;
if (content_view_core_)
obj = content_view_core_->GetJavaObject();
return new BrowserAccessibilityManagerAndroid(
obj,
BrowserAccessibilityManagerAndroid::GetEmptyDocument(),
delegate);
}
bool RenderWidgetHostViewAndroid::LockMouse() {
NOTIMPLEMENTED();
return false;
}
void RenderWidgetHostViewAndroid::UnlockMouse() {
NOTIMPLEMENTED();
}
// Methods called from the host to the render
void RenderWidgetHostViewAndroid::SendKeyEvent(
const NativeWebKeyboardEvent& event) {
if (host_)
host_->ForwardKeyboardEvent(event);
}
void RenderWidgetHostViewAndroid::SendMouseEvent(
const blink::WebMouseEvent& event) {
if (host_)
host_->ForwardMouseEvent(event);
}
void RenderWidgetHostViewAndroid::SendMouseWheelEvent(
const blink::WebMouseWheelEvent& event) {
if (host_)
host_->ForwardWheelEvent(event);
}
void RenderWidgetHostViewAndroid::SendGestureEvent(
const blink::WebGestureEvent& event) {
// Sending a gesture that may trigger overscroll should resume the effect.
if (overscroll_controller_)
overscroll_controller_->Enable();
if (host_)
host_->ForwardGestureEventWithLatencyInfo(event, CreateLatencyInfo(event));
}
void RenderWidgetHostViewAndroid::MoveCaret(const gfx::Point& point) {
if (host_)
host_->MoveCaret(point);
}
void RenderWidgetHostViewAndroid::DismissTextHandles() {
if (selection_controller_)
selection_controller_->HideAndDisallowShowingAutomatically();
}
void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden(bool hidden) {
if (selection_controller_)
selection_controller_->SetTemporarilyHidden(hidden);
}
void RenderWidgetHostViewAndroid::OnShowingPastePopup(
const gfx::PointF& point) {
if (!selection_controller_)
return;
// As the paste popup may be triggered *before* the bounds and editability
// of the region have been updated, explicitly set the properties now.
// TODO(jdduke): Remove this workaround when auxiliary paste popup
// notifications are no longer required, crbug.com/398170.
ui::SelectionBound insertion_bound;
insertion_bound.set_type(ui::SelectionBound::CENTER);
insertion_bound.set_visible(true);
insertion_bound.SetEdge(point, point);
selection_controller_->HideAndDisallowShowingAutomatically();
selection_controller_->OnSelectionEditable(true);
selection_controller_->OnSelectionEmpty(true);
selection_controller_->OnSelectionBoundsChanged(insertion_bound,
insertion_bound);
selection_controller_->AllowShowingFromCurrentSelection();
}
SkColor RenderWidgetHostViewAndroid::GetCachedBackgroundColor() const {
return cached_background_color_;
}
void RenderWidgetHostViewAndroid::DidOverscroll(
const DidOverscrollParams& params) {
if (!content_view_core_ || !layer_.get() || !is_showing_)
return;
if (overscroll_controller_)
overscroll_controller_->OnOverscrolled(params);
}
void RenderWidgetHostViewAndroid::DidStopFlinging() {
if (content_view_core_)
content_view_core_->DidStopFlinging();
}
void RenderWidgetHostViewAndroid::SetContentViewCore(
ContentViewCoreImpl* content_view_core) {
RemoveLayers();
StopObservingRootWindow();
bool resize = false;
if (content_view_core != content_view_core_) {
overscroll_controller_.reset();
selection_controller_.reset();
ReleaseLocksOnSurface();
resize = true;
}
content_view_core_ = content_view_core;
BrowserAccessibilityManager* manager = NULL;
if (host_)
manager = host_->GetRootBrowserAccessibilityManager();
if (manager) {
base::android::ScopedJavaLocalRef<jobject> obj;
if (content_view_core_)
obj = content_view_core_->GetJavaObject();
manager->ToBrowserAccessibilityManagerAndroid()->SetContentViewCore(obj);
}
AttachLayers();
if (!content_view_core_)
return;
StartObservingRootWindow();
if (resize)
WasResized();
if (!selection_controller_)
selection_controller_ = CreateSelectionController(this, content_view_core_);
if (!overscroll_controller_ &&
content_view_core_->GetWindowAndroid()->GetCompositor()) {
overscroll_controller_ = CreateOverscrollController(content_view_core_);
}
}
void RenderWidgetHostViewAndroid::RunAckCallbacks() {
while (!ack_callbacks_.empty()) {
ack_callbacks_.front().Run();
ack_callbacks_.pop();
}
}
void RenderWidgetHostViewAndroid::OnGestureEvent(
const ui::GestureEventData& gesture) {
SendGestureEvent(CreateWebGestureEventFromGestureEventData(gesture));
}
void RenderWidgetHostViewAndroid::OnCompositingDidCommit() {
RunAckCallbacks();
}
void RenderWidgetHostViewAndroid::OnAttachCompositor() {
DCHECK(content_view_core_);
if (!overscroll_controller_)
overscroll_controller_ = CreateOverscrollController(content_view_core_);
}
void RenderWidgetHostViewAndroid::OnDetachCompositor() {
DCHECK(content_view_core_);
DCHECK(using_browser_compositor_);
RunAckCallbacks();
overscroll_controller_.reset();
}
void RenderWidgetHostViewAndroid::OnVSync(base::TimeTicks frame_time,
base::TimeDelta vsync_period) {
TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::OnVSync");
if (!host_)
return;
const uint32 current_vsync_requests = outstanding_vsync_requests_;
outstanding_vsync_requests_ = 0;
if (current_vsync_requests & FLUSH_INPUT)
host_->FlushInput();
if (current_vsync_requests & BEGIN_FRAME ||
current_vsync_requests & PERSISTENT_BEGIN_FRAME) {
SendBeginFrame(frame_time, vsync_period);
}
if (current_vsync_requests & PERSISTENT_BEGIN_FRAME)
RequestVSyncUpdate(PERSISTENT_BEGIN_FRAME);
}
void RenderWidgetHostViewAndroid::OnAnimate(base::TimeTicks begin_frame_time) {
if (Animate(begin_frame_time))
SetNeedsAnimate();
}
void RenderWidgetHostViewAndroid::OnLostResources() {
ReleaseLocksOnSurface();
if (layer_.get())
DestroyDelegatedContent();
DCHECK(ack_callbacks_.empty());
// We should not loose a frame if we have readback requests pending.
DCHECK(readbacks_waiting_for_frame_.empty());
}
// static
void
RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResultForDelegatedReadback(
const gfx::Size& dst_size_in_pixel,
const SkColorType color_type,
const base::TimeTicks& start_time,
scoped_refptr<cc::Layer> readback_layer,
ReadbackRequestCallback& callback,
scoped_ptr<cc::CopyOutputResult> result) {
readback_layer->RemoveFromParent();
PrepareTextureCopyOutputResult(
dst_size_in_pixel, color_type, start_time, callback, result.Pass());
}
// static
void RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult(
const gfx::Size& dst_size_in_pixel,
const SkColorType color_type,
const base::TimeTicks& start_time,
ReadbackRequestCallback& callback,
scoped_ptr<cc::CopyOutputResult> result) {
base::ScopedClosureRunner scoped_callback_runner(
base::Bind(callback, SkBitmap(), READBACK_FAILED));
TRACE_EVENT0("cc",
"RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult");
if (!result->HasTexture() || result->IsEmpty() || result->size().IsEmpty())
return;
scoped_ptr<SkBitmap> bitmap(new SkBitmap);
if (!bitmap->tryAllocPixels(SkImageInfo::Make(dst_size_in_pixel.width(),
dst_size_in_pixel.height(),
color_type,
kOpaque_SkAlphaType))) {
return;
}
GLHelper* gl_helper = GetPostReadbackGLHelper();
if (!gl_helper || !gl_helper->IsReadbackConfigSupported(color_type))
return;
scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock(
new SkAutoLockPixels(*bitmap));
uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
cc::TextureMailbox texture_mailbox;
scoped_ptr<cc::SingleReleaseCallback> release_callback;
result->TakeTexture(&texture_mailbox, &release_callback);
DCHECK(texture_mailbox.IsTexture());
if (!texture_mailbox.IsTexture())
return;
ignore_result(scoped_callback_runner.Release());
gl_helper->CropScaleReadbackAndCleanMailbox(
texture_mailbox.mailbox(),
texture_mailbox.sync_point(),
result->size(),
gfx::Rect(result->size()),
dst_size_in_pixel,
pixels,
color_type,
base::Bind(&CopyFromCompositingSurfaceFinished,
callback,
base::Passed(&release_callback),
base::Passed(&bitmap),
start_time,
base::Passed(&bitmap_pixels_lock)),
GLHelper::SCALER_QUALITY_GOOD);
}
SkColorType RenderWidgetHostViewAndroid::PreferredReadbackFormat() {
// Define the criteria here. If say the 16 texture readback is
// supported we should go with that (this degrades quality)
// or stick back to the default format.
if (base::SysInfo::IsLowEndDevice()) {
// TODO(sievers): Cannot use GLHelper here. Instead remove this API
// and have CopyFromCompositingSurface() fall back to RGB8 if 565 was
// requested but is not supported.
GLHelper* gl_helper = GetPostReadbackGLHelper();
if (gl_helper && gl_helper->IsReadbackConfigSupported(kRGB_565_SkColorType))
return kRGB_565_SkColorType;
}
return kN32_SkColorType;
}
void RenderWidgetHostViewAndroid::OnStylusSelectBegin(float x0,
float y0,
float x1,
float y1) {
SelectBetweenCoordinates(gfx::PointF(x0, y0), gfx::PointF(x1, y1));
}
void RenderWidgetHostViewAndroid::OnStylusSelectUpdate(float x, float y) {
MoveRangeSelectionExtent(gfx::PointF(x, y));
}
void RenderWidgetHostViewAndroid::OnStylusSelectEnd() {
if (selection_controller_)
selection_controller_->AllowShowingFromCurrentSelection();
}
void RenderWidgetHostViewAndroid::OnStylusSelectTap(base::TimeTicks time,
float x,
float y) {
// Treat the stylus tap as a long press, activating either a word selection or
// context menu depending on the targetted content.
blink::WebGestureEvent long_press = WebGestureEventBuilder::Build(
blink::WebInputEvent::GestureLongPress,
(time - base::TimeTicks()).InSecondsF(), x, y);
SendGestureEvent(long_press);
}
// static
void RenderWidgetHostViewBase::GetDefaultScreenInfo(
blink::WebScreenInfo* results) {
const gfx::Display& display =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
results->rect = display.bounds();
// TODO(husky): Remove any system controls from availableRect.
results->availableRect = display.work_area();
results->deviceScaleFactor = display.device_scale_factor();
results->orientationAngle = display.RotationAsDegree();
results->orientationType =
RenderWidgetHostViewBase::GetOrientationTypeForMobile(display);
gfx::DeviceDisplayInfo info;
results->depth = info.GetBitsPerPixel();
results->depthPerComponent = info.GetBitsPerComponent();
results->isMonochrome = (results->depthPerComponent == 0);
}
} // namespace content
Android: Destroy GLHelper before the context
The scaling stages will try to delete GL resources during
destruction.
BUG=440017
NOTRY=True
Review URL: https://codereview.chromium.org/792533003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#307531}
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include <android/bitmap.h>
#include "base/android/build_info.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/threading/worker_pool.h"
#include "cc/base/latency_info_swap_promise.h"
#include "cc/layers/delegated_frame_provider.h"
#include "cc/layers/delegated_renderer_layer.h"
#include "cc/layers/layer.h"
#include "cc/output/compositor_frame.h"
#include "cc/output/compositor_frame_ack.h"
#include "cc/output/copy_output_request.h"
#include "cc/output/copy_output_result.h"
#include "cc/output/viewport_selection_bound.h"
#include "cc/resources/single_release_callback.h"
#include "cc/trees/layer_tree_host.h"
#include "content/browser/accessibility/browser_accessibility_manager_android.h"
#include "content/browser/android/composited_touch_handle_drawable.h"
#include "content/browser/android/content_view_core_impl.h"
#include "content/browser/android/edge_effect.h"
#include "content/browser/android/edge_effect_l.h"
#include "content/browser/android/in_process/synchronous_compositor_impl.h"
#include "content/browser/android/overscroll_controller_android.h"
#include "content/browser/devtools/render_view_devtools_agent_host.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_process_host_ui_shim.h"
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "content/browser/media/media_web_contents_observer.h"
#include "content/browser/renderer_host/compositor_impl_android.h"
#include "content/browser/renderer_host/dip_util.h"
#include "content/browser/renderer_host/input/synthetic_gesture_target_android.h"
#include "content/browser/renderer_host/input/web_input_event_builders_android.h"
#include "content/browser/renderer_host/input/web_input_event_util.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/common/gpu/gpu_process_launch_causes.h"
#include "content/common/input/did_overscroll_params.h"
#include "content/common/input_messages.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "skia/ext/image_operations.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/base/android/window_android.h"
#include "ui/base/android/window_android_compositor.h"
#include "ui/events/gesture_detection/gesture_provider_config_helper.h"
#include "ui/events/gesture_detection/motion_event.h"
#include "ui/gfx/android/device_display_info.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/android/view_configuration.h"
#include "ui/gfx/display.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/size_conversions.h"
#include "ui/touch_selection/touch_selection_controller.h"
namespace content {
namespace {
const int kUndefinedOutputSurfaceId = -1;
// Used to accomodate finite precision when comparing scaled viewport and
// content widths. While this value may seem large, width=device-width on an N7
// V1 saw errors of ~0.065 between computed window and content widths.
const float kMobileViewportWidthEpsilon = 0.15f;
static const char kAsyncReadBackString[] = "Compositing.CopyFromSurfaceTime";
// Sends an acknowledgement to the renderer of a processed IME event.
void SendImeEventAck(RenderWidgetHostImpl* host) {
host->Send(new ViewMsg_ImeEventAck(host->GetRoutingID()));
}
class GLHelperHolder
: public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
public:
static GLHelperHolder* Create();
~GLHelperHolder() override;
void Initialize();
// WebGraphicsContextLostCallback implementation.
virtual void onContextLost() override;
GLHelper* GetGLHelper() { return gl_helper_.get(); }
bool IsLost() { return !context_.get() || context_->isContextLost(); }
private:
GLHelperHolder();
static scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateContext3D();
scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
scoped_ptr<GLHelper> gl_helper_;
DISALLOW_COPY_AND_ASSIGN(GLHelperHolder);
};
GLHelperHolder* GLHelperHolder::Create() {
GLHelperHolder* holder = new GLHelperHolder;
holder->Initialize();
return holder;
}
GLHelperHolder::GLHelperHolder() {
}
GLHelperHolder::~GLHelperHolder() {
}
void GLHelperHolder::Initialize() {
context_ = CreateContext3D();
if (context_) {
context_->setContextLostCallback(this);
gl_helper_.reset(new GLHelper(context_->GetImplementation(),
context_->GetContextSupport()));
}
}
void GLHelperHolder::onContextLost() {
// Need to post a task because the command buffer client cannot be deleted
// from within this callback.
LOG(ERROR) << "Context lost.";
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&RenderWidgetHostViewAndroid::OnContextLost));
}
scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
GLHelperHolder::CreateContext3D() {
BrowserGpuChannelHostFactory* factory =
BrowserGpuChannelHostFactory::instance();
scoped_refptr<GpuChannelHost> gpu_channel_host(factory->GetGpuChannel());
// GLHelper can only be used in asynchronous APIs for postprocessing after
// Browser Compositor operations (i.e. readback).
DCHECK(gpu_channel_host.get()) << "Illegal access to GPU channel at startup";
if (gpu_channel_host->IsLost()) {
// The Browser Compositor is in charge of reestablishing the channel.
return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
}
blink::WebGraphicsContext3D::Attributes attrs;
attrs.shareResources = true;
GURL url("chrome://gpu/RenderWidgetHostViewAndroid");
static const size_t kBytesPerPixel = 4;
gfx::DeviceDisplayInfo display_info;
size_t full_screen_texture_size_in_bytes = display_info.GetDisplayHeight() *
display_info.GetDisplayWidth() *
kBytesPerPixel;
WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
limits.command_buffer_size = 64 * 1024;
limits.start_transfer_buffer_size = 64 * 1024;
limits.min_transfer_buffer_size = 64 * 1024;
limits.max_transfer_buffer_size = std::min(
3 * full_screen_texture_size_in_bytes, kDefaultMaxTransferBufferSize);
limits.mapped_memory_reclaim_limit =
WebGraphicsContext3DCommandBufferImpl::kNoLimit;
bool lose_context_when_out_of_memory = false;
scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
new WebGraphicsContext3DCommandBufferImpl(
0, // offscreen
url, gpu_channel_host.get(), attrs, lose_context_when_out_of_memory,
limits, nullptr));
if (context->InitializeOnCurrentThread()) {
context->pushGroupMarkerEXT(
base::StringPrintf("CmdBufferImageTransportFactory-%p",
context.get()).c_str());
} else {
context.reset();
}
return context.Pass();
}
// This can only be used for readback postprocessing. It may return null if the
// channel was lost and not reestablished yet.
GLHelper* GetPostReadbackGLHelper() {
static GLHelperHolder* g_readback_helper_holder = nullptr;
if (g_readback_helper_holder && g_readback_helper_holder->IsLost()) {
delete g_readback_helper_holder;
g_readback_helper_holder = nullptr;
}
if (!g_readback_helper_holder)
g_readback_helper_holder = GLHelperHolder::Create();
return g_readback_helper_holder->GetGLHelper();
}
void CopyFromCompositingSurfaceFinished(
ReadbackRequestCallback& callback,
scoped_ptr<cc::SingleReleaseCallback> release_callback,
scoped_ptr<SkBitmap> bitmap,
const base::TimeTicks& start_time,
scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock,
bool result) {
TRACE_EVENT0(
"cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceFinished");
bitmap_pixels_lock.reset();
uint32 sync_point = 0;
if (result) {
GLHelper* gl_helper = GetPostReadbackGLHelper();
if (gl_helper)
sync_point = gl_helper->InsertSyncPoint();
}
bool lost_resource = sync_point == 0;
release_callback->Run(sync_point, lost_resource);
UMA_HISTOGRAM_TIMES(kAsyncReadBackString,
base::TimeTicks::Now() - start_time);
ReadbackResponse response = result ? READBACK_SUCCESS : READBACK_FAILED;
callback.Run(*bitmap, response);
}
ui::LatencyInfo CreateLatencyInfo(const blink::WebInputEvent& event) {
ui::LatencyInfo latency_info;
// The latency number should only be added if the timestamp is valid.
if (event.timeStampSeconds) {
const int64 time_micros = static_cast<int64>(
event.timeStampSeconds * base::Time::kMicrosecondsPerSecond);
latency_info.AddLatencyNumberWithTimestamp(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
0,
0,
base::TimeTicks() + base::TimeDelta::FromMicroseconds(time_micros),
1);
}
return latency_info;
}
scoped_ptr<ui::TouchSelectionController> CreateSelectionController(
ui::TouchSelectionControllerClient* client,
ContentViewCore* content_view_core) {
DCHECK(client);
DCHECK(content_view_core);
int tap_timeout_ms = gfx::ViewConfiguration::GetTapTimeoutInMs();
int touch_slop_pixels = gfx::ViewConfiguration::GetTouchSlopInPixels();
return make_scoped_ptr(new ui::TouchSelectionController(
client,
base::TimeDelta::FromMilliseconds(tap_timeout_ms),
touch_slop_pixels / content_view_core->GetDpiScale()));
}
scoped_ptr<OverscrollControllerAndroid> CreateOverscrollController(
ContentViewCore* content_view_core) {
DCHECK(content_view_core);
ui::WindowAndroid* window = content_view_core->GetWindowAndroid();
DCHECK(window);
ui::WindowAndroidCompositor* compositor = window->GetCompositor();
DCHECK(compositor);
return make_scoped_ptr(new OverscrollControllerAndroid(
content_view_core->GetWebContents(),
compositor,
content_view_core->GetDpiScale()));
}
ui::GestureProvider::Config CreateGestureProviderConfig() {
ui::GestureProvider::Config config = ui::DefaultGestureProviderConfig();
config.disable_click_delay =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableClickDelay);
return config;
}
bool HasFixedPageScale(const cc::CompositorFrameMetadata& frame_metadata) {
return frame_metadata.min_page_scale_factor ==
frame_metadata.max_page_scale_factor;
}
bool HasMobileViewport(const cc::CompositorFrameMetadata& frame_metadata) {
float window_width_dip =
frame_metadata.page_scale_factor *
frame_metadata.scrollable_viewport_size.width();
float content_width_css = frame_metadata.root_layer_size.width();
return content_width_css <= window_width_dip + kMobileViewportWidthEpsilon;
}
} // anonymous namespace
ReadbackRequest::ReadbackRequest(float scale,
SkColorType color_type,
gfx::Rect src_subrect,
ReadbackRequestCallback& result_callback)
: scale_(scale),
color_type_(color_type),
src_subrect_(src_subrect),
result_callback_(result_callback) {
}
ReadbackRequest::ReadbackRequest() {
}
ReadbackRequest::~ReadbackRequest() {
}
RenderWidgetHostViewAndroid::LastFrameInfo::LastFrameInfo(
uint32 output_id,
scoped_ptr<cc::CompositorFrame> output_frame)
: output_surface_id(output_id), frame(output_frame.Pass()) {}
RenderWidgetHostViewAndroid::LastFrameInfo::~LastFrameInfo() {}
void RenderWidgetHostViewAndroid::OnContextLost() {
scoped_ptr<RenderWidgetHostIterator> widgets(
RenderWidgetHostImpl::GetAllRenderWidgetHosts());
while (RenderWidgetHost* widget = widgets->GetNextHost()) {
if (widget->GetView()) {
static_cast<RenderWidgetHostViewAndroid*>(widget->GetView())
->OnLostResources();
}
}
}
RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
ContentViewCoreImpl* content_view_core)
: host_(widget_host),
outstanding_vsync_requests_(0),
is_showing_(!widget_host->is_hidden()),
content_view_core_(NULL),
ime_adapter_android_(this),
cached_background_color_(SK_ColorWHITE),
last_output_surface_id_(kUndefinedOutputSurfaceId),
gesture_provider_(CreateGestureProviderConfig(), this),
stylus_text_selector_(this),
accelerated_surface_route_id_(0),
using_browser_compositor_(CompositorImpl::IsInitialized()),
frame_evictor_(new DelegatedFrameEvictor(this)),
locks_on_frame_count_(0),
observing_root_window_(false),
weak_ptr_factory_(this) {
host_->SetView(this);
SetContentViewCore(content_view_core);
}
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
SetContentViewCore(NULL);
DCHECK(ack_callbacks_.empty());
DCHECK(readbacks_waiting_for_frame_.empty());
if (resource_collection_.get())
resource_collection_->SetClient(NULL);
}
bool RenderWidgetHostViewAndroid::OnMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewAndroid, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_StartContentIntent, OnStartContentIntent)
IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeBodyBackgroundColor,
OnDidChangeBodyBackgroundColor)
IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
OnSetNeedsBeginFrames)
IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
OnTextInputStateChanged)
IPC_MESSAGE_HANDLER(ViewHostMsg_SmartClipDataExtracted,
OnSmartClipDataExtracted)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewAndroid::InitAsPopup(
RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewAndroid::InitAsFullscreen(
RenderWidgetHostView* reference_host_view) {
NOTIMPLEMENTED();
}
RenderWidgetHost*
RenderWidgetHostViewAndroid::GetRenderWidgetHost() const {
return host_;
}
void RenderWidgetHostViewAndroid::WasShown() {
if (!host_ || !host_->is_hidden())
return;
host_->WasShown(ui::LatencyInfo());
if (content_view_core_) {
StartObservingRootWindow();
RequestVSyncUpdate(BEGIN_FRAME);
}
}
void RenderWidgetHostViewAndroid::WasHidden() {
RunAckCallbacks();
if (!host_ || host_->is_hidden())
return;
// Inform the renderer that we are being hidden so it can reduce its resource
// utilization.
host_->WasHidden();
StopObservingRootWindow();
}
void RenderWidgetHostViewAndroid::WasResized() {
host_->WasResized();
}
void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) {
// Ignore the given size as only the Java code has the power to
// resize the view on Android.
default_size_ = size;
}
void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) {
SetSize(rect.size());
}
void RenderWidgetHostViewAndroid::AbortPendingReadbackRequests() {
while (!readbacks_waiting_for_frame_.empty()) {
ReadbackRequest& readback_request = readbacks_waiting_for_frame_.front();
readback_request.GetResultCallback().Run(SkBitmap(), READBACK_FAILED);
readbacks_waiting_for_frame_.pop();
}
}
void RenderWidgetHostViewAndroid::GetScaledContentBitmap(
float scale,
SkColorType color_type,
gfx::Rect src_subrect,
ReadbackRequestCallback& result_callback) {
if (!host_ || host_->is_hidden()) {
result_callback.Run(SkBitmap(), READBACK_NOT_SUPPORTED);
return;
}
if (!IsSurfaceAvailableForCopy()) {
// The view is visible, probably the frame has not yet arrived.
// Just add the ReadbackRequest to queue and wait for frame arrival
// to get this request processed.
readbacks_waiting_for_frame_.push(
ReadbackRequest(scale, color_type, src_subrect, result_callback));
return;
}
gfx::Size bounds = layer_->bounds();
if (src_subrect.IsEmpty())
src_subrect = gfx::Rect(bounds);
DCHECK_LE(src_subrect.width() + src_subrect.x(), bounds.width());
DCHECK_LE(src_subrect.height() + src_subrect.y(), bounds.height());
const gfx::Display& display =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
float device_scale_factor = display.device_scale_factor();
DCHECK_GT(device_scale_factor, 0);
gfx::Size dst_size(
gfx::ToCeiledSize(gfx::ScaleSize(bounds, scale / device_scale_factor)));
CopyFromCompositingSurface(
src_subrect, dst_size, result_callback, color_type);
}
scoped_refptr<cc::DelegatedRendererLayer>
RenderWidgetHostViewAndroid::CreateDelegatedLayerForFrameProvider() const {
DCHECK(frame_provider_.get());
scoped_refptr<cc::DelegatedRendererLayer> delegated_layer =
cc::DelegatedRendererLayer::Create(frame_provider_);
delegated_layer->SetBounds(content_size_in_layer_);
delegated_layer->SetIsDrawable(true);
delegated_layer->SetContentsOpaque(true);
return delegated_layer;
}
bool RenderWidgetHostViewAndroid::HasValidFrame() const {
if (!content_view_core_)
return false;
if (!layer_.get())
return false;
if (texture_size_in_layer_.IsEmpty())
return false;
// This tell us whether a valid frame has arrived or not.
if (!frame_evictor_->HasFrame())
return false;
return true;
}
gfx::Vector2dF RenderWidgetHostViewAndroid::GetLastScrollOffset() const {
return last_scroll_offset_;
}
gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const {
return content_view_core_->GetViewAndroid();
}
gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const {
return reinterpret_cast<gfx::NativeViewId>(
const_cast<RenderWidgetHostViewAndroid*>(this));
}
gfx::NativeViewAccessible
RenderWidgetHostViewAndroid::GetNativeViewAccessible() {
NOTIMPLEMENTED();
return NULL;
}
void RenderWidgetHostViewAndroid::MovePluginWindows(
const std::vector<WebPluginGeometry>& moves) {
// We don't have plugin windows on Android. Do nothing. Note: this is called
// from RenderWidgetHost::OnUpdateRect which is itself invoked while
// processing the corresponding message from Renderer.
}
void RenderWidgetHostViewAndroid::Focus() {
host_->Focus();
host_->SetInputMethodActive(true);
if (overscroll_controller_)
overscroll_controller_->Enable();
}
void RenderWidgetHostViewAndroid::Blur() {
host_->SetInputMethodActive(false);
host_->Blur();
if (overscroll_controller_)
overscroll_controller_->Disable();
}
bool RenderWidgetHostViewAndroid::HasFocus() const {
if (!content_view_core_)
return false; // ContentViewCore not created yet.
return content_view_core_->HasFocus();
}
bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() const {
return HasValidFrame();
}
void RenderWidgetHostViewAndroid::Show() {
if (is_showing_)
return;
is_showing_ = true;
if (layer_.get())
layer_->SetHideLayerAndSubtree(false);
frame_evictor_->SetVisible(true);
WasShown();
}
void RenderWidgetHostViewAndroid::Hide() {
if (!is_showing_)
return;
is_showing_ = false;
if (layer_.get() && locks_on_frame_count_ == 0)
layer_->SetHideLayerAndSubtree(true);
frame_evictor_->SetVisible(false);
// We don't know if we will ever get a frame if we are hiding the renderer, so
// we need to cancel all requests
AbortPendingReadbackRequests();
WasHidden();
}
bool RenderWidgetHostViewAndroid::IsShowing() {
// ContentViewCoreImpl represents the native side of the Java
// ContentViewCore. It being NULL means that it is not attached
// to the View system yet, so we treat this RWHVA as hidden.
return is_showing_ && content_view_core_;
}
void RenderWidgetHostViewAndroid::LockCompositingSurface() {
DCHECK(HasValidFrame());
DCHECK(host_);
DCHECK(frame_evictor_->HasFrame());
frame_evictor_->LockFrame();
locks_on_frame_count_++;
}
void RenderWidgetHostViewAndroid::UnlockCompositingSurface() {
if (!frame_evictor_->HasFrame() || locks_on_frame_count_ == 0)
return;
DCHECK(HasValidFrame());
frame_evictor_->UnlockFrame();
locks_on_frame_count_--;
if (locks_on_frame_count_ == 0) {
if (last_frame_info_) {
InternalSwapCompositorFrame(last_frame_info_->output_surface_id,
last_frame_info_->frame.Pass());
last_frame_info_.reset();
}
if (!is_showing_ && layer_.get())
layer_->SetHideLayerAndSubtree(true);
}
}
void RenderWidgetHostViewAndroid::SetTextSurroundingSelectionCallback(
const TextSurroundingSelectionCallback& callback) {
// Only one outstanding request is allowed at any given time.
DCHECK(!callback.is_null());
text_surrounding_selection_callback_ = callback;
}
void RenderWidgetHostViewAndroid::OnTextSurroundingSelectionResponse(
const base::string16& content,
size_t start_offset,
size_t end_offset) {
if (text_surrounding_selection_callback_.is_null())
return;
text_surrounding_selection_callback_.Run(content, start_offset, end_offset);
text_surrounding_selection_callback_.Reset();
}
void RenderWidgetHostViewAndroid::ReleaseLocksOnSurface() {
if (!frame_evictor_->HasFrame()) {
DCHECK_EQ(locks_on_frame_count_, 0u);
return;
}
while (locks_on_frame_count_ > 0) {
UnlockCompositingSurface();
}
RunAckCallbacks();
}
gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const {
if (!content_view_core_)
return gfx::Rect(default_size_);
return gfx::Rect(content_view_core_->GetViewSize());
}
gfx::Size RenderWidgetHostViewAndroid::GetPhysicalBackingSize() const {
if (!content_view_core_)
return gfx::Size();
return content_view_core_->GetPhysicalBackingSize();
}
bool RenderWidgetHostViewAndroid::DoTopControlsShrinkBlinkSize() const {
if (!content_view_core_)
return false;
// Whether or not Blink's viewport size should be shrunk by the height of the
// URL-bar.
return content_view_core_->DoTopControlsShrinkBlinkSize();
}
float RenderWidgetHostViewAndroid::GetTopControlsHeight() const {
if (!content_view_core_)
return 0.f;
// The height of the top controls.
return content_view_core_->GetTopControlsHeightDip();
}
void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) {
// There are no cursors on Android.
}
void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) {
// Do nothing. The UI notification is handled through ContentViewClient which
// is TabContentsDelegate.
}
void RenderWidgetHostViewAndroid::TextInputTypeChanged(
ui::TextInputType type,
ui::TextInputMode input_mode,
bool can_compose_inline,
int flags) {
// Unused on Android, which uses OnTextInputChanged instead.
}
long RenderWidgetHostViewAndroid::GetNativeImeAdapter() {
return reinterpret_cast<intptr_t>(&ime_adapter_android_);
}
void RenderWidgetHostViewAndroid::OnTextInputStateChanged(
const ViewHostMsg_TextInputState_Params& params) {
if (selection_controller_) {
// This call is semi-redundant with that in |OnFocusedNodeChanged|. The
// latter is guaranteed to be called before |OnSelectionBoundsChanged|,
// while this call is present to ensure consistency with IME after
// navigation and tab focus changes
const bool is_editable_node = params.type != ui::TEXT_INPUT_TYPE_NONE;
selection_controller_->OnSelectionEditable(is_editable_node);
}
// If the change is not originated from IME (e.g. Javascript, autofill),
// send back the renderer an acknowledgement, regardless of how we exit from
// this method.
base::ScopedClosureRunner ack_caller;
if (params.is_non_ime_change)
ack_caller.Reset(base::Bind(&SendImeEventAck, host_));
if (!IsShowing())
return;
content_view_core_->UpdateImeAdapter(
GetNativeImeAdapter(),
static_cast<int>(params.type), params.flags,
params.value, params.selection_start, params.selection_end,
params.composition_start, params.composition_end,
params.show_ime_if_needed, params.is_non_ime_change);
}
void RenderWidgetHostViewAndroid::OnDidChangeBodyBackgroundColor(
SkColor color) {
if (cached_background_color_ == color)
return;
cached_background_color_ = color;
if (content_view_core_)
content_view_core_->OnBackgroundColorChanged(color);
}
void RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames(bool enabled) {
DCHECK(using_browser_compositor_);
TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames",
"enabled", enabled);
if (enabled)
RequestVSyncUpdate(PERSISTENT_BEGIN_FRAME);
else
outstanding_vsync_requests_ &= ~PERSISTENT_BEGIN_FRAME;
}
void RenderWidgetHostViewAndroid::OnStartContentIntent(
const GURL& content_url) {
if (content_view_core_)
content_view_core_->StartContentIntent(content_url);
}
void RenderWidgetHostViewAndroid::OnSmartClipDataExtracted(
const base::string16& text,
const base::string16& html,
const gfx::Rect rect) {
if (content_view_core_)
content_view_core_->OnSmartClipDataExtracted(text, html, rect);
}
bool RenderWidgetHostViewAndroid::OnTouchEvent(
const ui::MotionEvent& event) {
if (!host_)
return false;
if (selection_controller_ &&
selection_controller_->WillHandleTouchEvent(event))
return true;
if (stylus_text_selector_.OnTouchEvent(event))
return true;
if (!gesture_provider_.OnTouchEvent(event))
return false;
if (host_->ShouldForwardTouchEvent()) {
blink::WebTouchEvent web_event = CreateWebTouchEventFromMotionEvent(event);
host_->ForwardTouchEventWithLatencyInfo(web_event,
CreateLatencyInfo(web_event));
} else {
const bool event_consumed = false;
gesture_provider_.OnTouchEventAck(event_consumed);
}
// Send a proactive BeginFrame on the next vsync to reduce latency.
// This is good enough as long as the first touch event has Begin semantics
// and the actual scroll happens on the next vsync.
if (observing_root_window_)
RequestVSyncUpdate(BEGIN_FRAME);
return true;
}
bool RenderWidgetHostViewAndroid::OnTouchHandleEvent(
const ui::MotionEvent& event) {
return selection_controller_ &&
selection_controller_->WillHandleTouchEvent(event);
}
void RenderWidgetHostViewAndroid::ResetGestureDetection() {
const ui::MotionEvent* current_down_event =
gesture_provider_.GetCurrentDownEvent();
if (current_down_event) {
scoped_ptr<ui::MotionEvent> cancel_event = current_down_event->Cancel();
OnTouchEvent(*cancel_event);
}
// A hard reset ensures prevention of any timer-based events.
gesture_provider_.ResetDetection();
}
void RenderWidgetHostViewAndroid::SetDoubleTapSupportEnabled(bool enabled) {
gesture_provider_.SetDoubleTapSupportForPlatformEnabled(enabled);
}
void RenderWidgetHostViewAndroid::SetMultiTouchZoomSupportEnabled(
bool enabled) {
gesture_provider_.SetMultiTouchZoomSupportEnabled(enabled);
}
void RenderWidgetHostViewAndroid::ImeCancelComposition() {
ime_adapter_android_.CancelComposition();
}
void RenderWidgetHostViewAndroid::ImeCompositionRangeChanged(
const gfx::Range& range,
const std::vector<gfx::Rect>& character_bounds) {
ime_adapter_android_.SetCharacterBounds(character_bounds);
}
void RenderWidgetHostViewAndroid::FocusedNodeChanged(bool is_editable_node) {
ime_adapter_android_.FocusedNodeChanged(is_editable_node);
if (selection_controller_)
selection_controller_->OnSelectionEditable(is_editable_node);
}
void RenderWidgetHostViewAndroid::RenderProcessGone(
base::TerminationStatus status, int error_code) {
Destroy();
}
void RenderWidgetHostViewAndroid::Destroy() {
RemoveLayers();
SetContentViewCore(NULL);
// The RenderWidgetHost's destruction led here, so don't call it.
host_ = NULL;
delete this;
}
void RenderWidgetHostViewAndroid::SetTooltipText(
const base::string16& tooltip_text) {
// Tooltips don't makes sense on Android.
}
void RenderWidgetHostViewAndroid::SelectionChanged(const base::string16& text,
size_t offset,
const gfx::Range& range) {
RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
if (selection_controller_)
selection_controller_->OnSelectionEmpty(text.empty());
if (!content_view_core_)
return;
if (range.is_empty()) {
content_view_core_->OnSelectionChanged("");
return;
}
DCHECK(!text.empty());
size_t pos = range.GetMin() - offset;
size_t n = range.length();
DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
if (pos >= text.length()) {
NOTREACHED() << "The text can not cover range.";
return;
}
std::string utf8_selection = base::UTF16ToUTF8(text.substr(pos, n));
content_view_core_->OnSelectionChanged(utf8_selection);
}
void RenderWidgetHostViewAndroid::SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params& params) {
NOTREACHED() << "Selection bounds should be routed through the compositor.";
}
void RenderWidgetHostViewAndroid::SetBackgroundColor(SkColor color) {
RenderWidgetHostViewBase::SetBackgroundColor(color);
host_->SetBackgroundOpaque(GetBackgroundOpaque());
OnDidChangeBodyBackgroundColor(color);
}
void RenderWidgetHostViewAndroid::CopyFromCompositingSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
ReadbackRequestCallback& callback,
const SkColorType color_type) {
TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurface");
if (!host_ || host_->is_hidden()) {
callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
return;
}
base::TimeTicks start_time = base::TimeTicks::Now();
if (using_browser_compositor_ && !IsSurfaceAvailableForCopy()) {
callback.Run(SkBitmap(), READBACK_NOT_SUPPORTED);
return;
}
const gfx::Display& display =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
float device_scale_factor = display.device_scale_factor();
gfx::Size dst_size_in_pixel =
gfx::ConvertRectToPixel(device_scale_factor, gfx::Rect(dst_size)).size();
gfx::Rect src_subrect_in_pixel =
gfx::ConvertRectToPixel(device_scale_factor, src_subrect);
if (!using_browser_compositor_) {
SynchronousCopyContents(src_subrect_in_pixel, dst_size_in_pixel, callback,
color_type);
UMA_HISTOGRAM_TIMES("Compositing.CopyFromSurfaceTimeSynchronous",
base::TimeTicks::Now() - start_time);
return;
}
scoped_ptr<cc::CopyOutputRequest> request;
scoped_refptr<cc::Layer> readback_layer;
DCHECK(content_view_core_);
DCHECK(content_view_core_->GetWindowAndroid());
ui::WindowAndroidCompositor* compositor =
content_view_core_->GetWindowAndroid()->GetCompositor();
DCHECK(compositor);
DCHECK(frame_provider_.get());
scoped_refptr<cc::DelegatedRendererLayer> delegated_layer =
CreateDelegatedLayerForFrameProvider();
delegated_layer->SetHideLayerAndSubtree(true);
compositor->AttachLayerForReadback(delegated_layer);
readback_layer = delegated_layer;
request = cc::CopyOutputRequest::CreateRequest(
base::Bind(&RenderWidgetHostViewAndroid::
PrepareTextureCopyOutputResultForDelegatedReadback,
dst_size_in_pixel,
color_type,
start_time,
readback_layer,
callback));
request->set_area(src_subrect_in_pixel);
readback_layer->RequestCopyOfOutput(request.Pass());
}
void RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceToVideoFrame(
const gfx::Rect& src_subrect,
const scoped_refptr<media::VideoFrame>& target,
const base::Callback<void(bool)>& callback) {
NOTIMPLEMENTED();
callback.Run(false);
}
bool RenderWidgetHostViewAndroid::CanCopyToVideoFrame() const {
return false;
}
void RenderWidgetHostViewAndroid::ShowDisambiguationPopup(
const gfx::Rect& rect_pixels, const SkBitmap& zoomed_bitmap) {
if (!content_view_core_)
return;
content_view_core_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
}
scoped_ptr<SyntheticGestureTarget>
RenderWidgetHostViewAndroid::CreateSyntheticGestureTarget() {
return scoped_ptr<SyntheticGestureTarget>(new SyntheticGestureTargetAndroid(
host_, content_view_core_->CreateTouchEventSynthesizer()));
}
void RenderWidgetHostViewAndroid::SendDelegatedFrameAck(
uint32 output_surface_id) {
DCHECK(host_);
cc::CompositorFrameAck ack;
if (resource_collection_.get())
resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
RenderWidgetHostImpl::SendSwapCompositorFrameAck(host_->GetRoutingID(),
output_surface_id,
host_->GetProcess()->GetID(),
ack);
}
void RenderWidgetHostViewAndroid::SendReturnedDelegatedResources(
uint32 output_surface_id) {
DCHECK(resource_collection_.get());
cc::CompositorFrameAck ack;
resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
DCHECK(!ack.resources.empty());
RenderWidgetHostImpl::SendReclaimCompositorResources(
host_->GetRoutingID(),
output_surface_id,
host_->GetProcess()->GetID(),
ack);
}
void RenderWidgetHostViewAndroid::UnusedResourcesAreAvailable() {
if (ack_callbacks_.size())
return;
SendReturnedDelegatedResources(last_output_surface_id_);
}
void RenderWidgetHostViewAndroid::DestroyDelegatedContent() {
RemoveLayers();
frame_provider_ = NULL;
layer_ = NULL;
// This gets called when ever any eviction, loosing resources, swapping
// problems are encountered and so we abort any pending readbacks here.
AbortPendingReadbackRequests();
}
void RenderWidgetHostViewAndroid::SwapDelegatedFrame(
uint32 output_surface_id,
scoped_ptr<cc::DelegatedFrameData> frame_data) {
bool has_content = !texture_size_in_layer_.IsEmpty();
if (output_surface_id != last_output_surface_id_) {
// Drop the cc::DelegatedFrameResourceCollection so that we will not return
// any resources from the old output surface with the new output surface id.
if (resource_collection_.get()) {
resource_collection_->SetClient(NULL);
if (resource_collection_->LoseAllResources())
SendReturnedDelegatedResources(last_output_surface_id_);
resource_collection_ = NULL;
}
DestroyDelegatedContent();
last_output_surface_id_ = output_surface_id;
}
// DelegatedRendererLayerImpl applies the inverse device_scale_factor of the
// renderer frame, assuming that the browser compositor will scale
// it back up to device scale. But on Android we put our browser layers in
// physical pixels and set our browser CC device_scale_factor to 1, so this
// suppresses the transform. This line may need to be removed when fixing
// http://crbug.com/384134 or http://crbug.com/310763
frame_data->device_scale_factor = 1.0f;
if (!has_content) {
DestroyDelegatedContent();
} else {
if (!resource_collection_.get()) {
resource_collection_ = new cc::DelegatedFrameResourceCollection;
resource_collection_->SetClient(this);
}
if (!frame_provider_.get() ||
texture_size_in_layer_ != frame_provider_->frame_size()) {
RemoveLayers();
frame_provider_ = new cc::DelegatedFrameProvider(
resource_collection_.get(), frame_data.Pass());
layer_ = cc::DelegatedRendererLayer::Create(frame_provider_);
AttachLayers();
} else {
frame_provider_->SetFrameData(frame_data.Pass());
}
}
if (layer_.get()) {
layer_->SetIsDrawable(true);
layer_->SetContentsOpaque(true);
layer_->SetBounds(content_size_in_layer_);
layer_->SetNeedsDisplay();
}
base::Closure ack_callback =
base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
weak_ptr_factory_.GetWeakPtr(),
output_surface_id);
ack_callbacks_.push(ack_callback);
if (host_->is_hidden())
RunAckCallbacks();
}
void RenderWidgetHostViewAndroid::ComputeContentsSize(
const cc::CompositorFrameMetadata& frame_metadata) {
// Calculate the content size. This should be 0 if the texture_size is 0.
gfx::Vector2dF offset;
if (texture_size_in_layer_.IsEmpty())
content_size_in_layer_ = gfx::Size();
content_size_in_layer_ = gfx::ToCeiledSize(gfx::ScaleSize(
frame_metadata.scrollable_viewport_size,
frame_metadata.device_scale_factor * frame_metadata.page_scale_factor));
}
void RenderWidgetHostViewAndroid::InternalSwapCompositorFrame(
uint32 output_surface_id,
scoped_ptr<cc::CompositorFrame> frame) {
last_scroll_offset_ = frame->metadata.root_scroll_offset;
if (!frame->delegated_frame_data) {
LOG(ERROR) << "Non-delegated renderer path no longer supported";
return;
}
if (locks_on_frame_count_ > 0) {
DCHECK(HasValidFrame());
RetainFrame(output_surface_id, frame.Pass());
return;
}
if (layer_.get() && layer_->layer_tree_host()) {
for (size_t i = 0; i < frame->metadata.latency_info.size(); i++) {
scoped_ptr<cc::SwapPromise> swap_promise(
new cc::LatencyInfoSwapPromise(frame->metadata.latency_info[i]));
layer_->layer_tree_host()->QueueSwapPromise(swap_promise.Pass());
}
}
DCHECK(!frame->delegated_frame_data->render_pass_list.empty());
cc::RenderPass* root_pass =
frame->delegated_frame_data->render_pass_list.back();
texture_size_in_layer_ = root_pass->output_rect.size();
ComputeContentsSize(frame->metadata);
SwapDelegatedFrame(output_surface_id, frame->delegated_frame_data.Pass());
frame_evictor_->SwappedFrame(!host_->is_hidden());
// As the metadata update may trigger view invalidation, always call it after
// any potential compositor scheduling.
OnFrameMetadataUpdated(frame->metadata);
// Check if we have any pending readbacks, see if we have a frame available
// and process them here.
if (!readbacks_waiting_for_frame_.empty()) {
while (!readbacks_waiting_for_frame_.empty()) {
ReadbackRequest& readback_request = readbacks_waiting_for_frame_.front();
GetScaledContentBitmap(readback_request.GetScale(),
readback_request.GetColorFormat(),
readback_request.GetCaptureRect(),
readback_request.GetResultCallback());
readbacks_waiting_for_frame_.pop();
}
}
}
void RenderWidgetHostViewAndroid::OnSwapCompositorFrame(
uint32 output_surface_id,
scoped_ptr<cc::CompositorFrame> frame) {
InternalSwapCompositorFrame(output_surface_id, frame.Pass());
}
void RenderWidgetHostViewAndroid::RetainFrame(
uint32 output_surface_id,
scoped_ptr<cc::CompositorFrame> frame) {
DCHECK(locks_on_frame_count_);
// Store the incoming frame so that it can be swapped when all the locks have
// been released. If there is already a stored frame, then replace and skip
// the previous one but make sure we still eventually send the ACK. Holding
// the ACK also blocks the renderer when its max_frames_pending is reached.
if (last_frame_info_) {
base::Closure ack_callback =
base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
weak_ptr_factory_.GetWeakPtr(),
last_frame_info_->output_surface_id);
ack_callbacks_.push(ack_callback);
}
last_frame_info_.reset(new LastFrameInfo(output_surface_id, frame.Pass()));
}
void RenderWidgetHostViewAndroid::SynchronousFrameMetadata(
const cc::CompositorFrameMetadata& frame_metadata) {
if (!content_view_core_)
return;
// This is a subset of OnSwapCompositorFrame() used in the synchronous
// compositor flow.
OnFrameMetadataUpdated(frame_metadata);
ComputeContentsSize(frame_metadata);
// DevTools ScreenCast support for Android WebView.
WebContents* web_contents = content_view_core_->GetWebContents();
if (DevToolsAgentHost::HasFor(web_contents)) {
scoped_refptr<DevToolsAgentHost> dtah =
DevToolsAgentHost::GetOrCreateFor(web_contents);
// Unblock the compositor.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&RenderViewDevToolsAgentHost::SynchronousSwapCompositorFrame,
static_cast<RenderViewDevToolsAgentHost*>(dtah.get()),
frame_metadata));
}
}
void RenderWidgetHostViewAndroid::SetOverlayVideoMode(bool enabled) {
if (layer_.get())
layer_->SetContentsOpaque(!enabled);
}
bool RenderWidgetHostViewAndroid::SupportsAnimation() const {
// The synchronous (WebView) compositor does not have a proper browser
// compositor with which to drive animations.
return using_browser_compositor_;
}
void RenderWidgetHostViewAndroid::SetNeedsAnimate() {
DCHECK(content_view_core_);
DCHECK(using_browser_compositor_);
content_view_core_->GetWindowAndroid()->SetNeedsAnimate();
}
void RenderWidgetHostViewAndroid::MoveCaret(const gfx::PointF& position) {
MoveCaret(gfx::Point(position.x(), position.y()));
}
void RenderWidgetHostViewAndroid::MoveRangeSelectionExtent(
const gfx::PointF& extent) {
DCHECK(content_view_core_);
content_view_core_->MoveRangeSelectionExtent(extent);
}
void RenderWidgetHostViewAndroid::SelectBetweenCoordinates(
const gfx::PointF& base,
const gfx::PointF& extent) {
DCHECK(content_view_core_);
content_view_core_->SelectBetweenCoordinates(base, extent);
}
void RenderWidgetHostViewAndroid::OnSelectionEvent(
ui::SelectionEventType event,
const gfx::PointF& position) {
DCHECK(content_view_core_);
// Showing the selection action bar can alter the current View coordinates in
// such a way that the current MotionEvent stream is suddenly shifted in
// space. Avoid the associated scroll jump by pre-emptively cancelling gesture
// detection; scrolling after the selection is activated is unnecessary.
if (event == ui::SelectionEventType::SELECTION_SHOWN)
ResetGestureDetection();
content_view_core_->OnSelectionEvent(event, position);
}
scoped_ptr<ui::TouchHandleDrawable>
RenderWidgetHostViewAndroid::CreateDrawable() {
DCHECK(content_view_core_);
if (!using_browser_compositor_)
return content_view_core_->CreatePopupTouchHandleDrawable();
return scoped_ptr<ui::TouchHandleDrawable>(new CompositedTouchHandleDrawable(
content_view_core_->GetLayer().get(),
content_view_core_->GetDpiScale(),
// Use the activity context (instead of the application context) to ensure
// proper handle theming.
content_view_core_->GetContext().obj()));
}
void RenderWidgetHostViewAndroid::SynchronousCopyContents(
const gfx::Rect& src_subrect_in_pixel,
const gfx::Size& dst_size_in_pixel,
ReadbackRequestCallback& callback,
const SkColorType color_type) {
SynchronousCompositor* compositor =
SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
host_->GetRoutingID());
if (!compositor) {
callback.Run(SkBitmap(), READBACK_FAILED);
return;
}
SkBitmap bitmap;
bitmap.allocPixels(SkImageInfo::Make(dst_size_in_pixel.width(),
dst_size_in_pixel.height(),
color_type,
kPremul_SkAlphaType));
SkCanvas canvas(bitmap);
canvas.scale(
(float)dst_size_in_pixel.width() / (float)src_subrect_in_pixel.width(),
(float)dst_size_in_pixel.height() / (float)src_subrect_in_pixel.height());
compositor->DemandDrawSw(&canvas);
callback.Run(bitmap, READBACK_SUCCESS);
}
void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
const cc::CompositorFrameMetadata& frame_metadata) {
// Disable double tap zoom for pages that have a width=device-width or
// narrower viewport (indicating that this is a mobile-optimized or responsive
// web design, so text will be legible without zooming). Also disable
// double tap and pinch for pages that prevent zooming in or out.
bool has_mobile_viewport = HasMobileViewport(frame_metadata);
bool has_fixed_page_scale = HasFixedPageScale(frame_metadata);
gesture_provider_.SetDoubleTapSupportForPageEnabled(
!has_fixed_page_scale && !has_mobile_viewport);
if (!content_view_core_)
return;
if (overscroll_controller_)
overscroll_controller_->OnFrameMetadataUpdated(frame_metadata);
if (selection_controller_) {
selection_controller_->OnSelectionBoundsChanged(
ui::SelectionBound(frame_metadata.selection_start),
ui::SelectionBound(frame_metadata.selection_end));
}
// All offsets and sizes are in CSS pixels.
content_view_core_->UpdateFrameInfo(
frame_metadata.root_scroll_offset,
frame_metadata.page_scale_factor,
gfx::Vector2dF(frame_metadata.min_page_scale_factor,
frame_metadata.max_page_scale_factor),
frame_metadata.root_layer_size,
frame_metadata.scrollable_viewport_size,
frame_metadata.location_bar_offset,
frame_metadata.location_bar_content_translation);
#if defined(VIDEO_HOLE)
if (host_ && host_->IsRenderView()) {
RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(
RenderViewHost::From(host_));
rvhi->media_web_contents_observer()->OnFrameInfoUpdated();
}
#endif // defined(VIDEO_HOLE)
}
void RenderWidgetHostViewAndroid::AcceleratedSurfaceInitialized(int route_id) {
// TODO: remove need for the surface id here
accelerated_surface_route_id_ = route_id;
}
void RenderWidgetHostViewAndroid::AttachLayers() {
if (!content_view_core_)
return;
if (!layer_.get())
return;
content_view_core_->AttachLayer(layer_);
if (overscroll_controller_)
overscroll_controller_->Enable();
layer_->SetHideLayerAndSubtree(!is_showing_);
}
void RenderWidgetHostViewAndroid::RemoveLayers() {
if (!content_view_core_)
return;
if (!layer_.get())
return;
content_view_core_->RemoveLayer(layer_);
if (overscroll_controller_)
overscroll_controller_->Disable();
}
void RenderWidgetHostViewAndroid::RequestVSyncUpdate(uint32 requests) {
// The synchronous compositor does not requre BeginFrame messages.
if (!using_browser_compositor_)
requests &= FLUSH_INPUT;
bool should_request_vsync = !outstanding_vsync_requests_ && requests;
outstanding_vsync_requests_ |= requests;
// Note that if we're not currently observing the root window, outstanding
// vsync requests will be pushed if/when we resume observing in
// |StartObservingRootWindow()|.
if (observing_root_window_ && should_request_vsync)
content_view_core_->GetWindowAndroid()->RequestVSyncUpdate();
}
void RenderWidgetHostViewAndroid::StartObservingRootWindow() {
DCHECK(content_view_core_);
if (observing_root_window_)
return;
observing_root_window_ = true;
content_view_core_->GetWindowAndroid()->AddObserver(this);
// Clear existing vsync requests to allow a request to the new window.
uint32 outstanding_vsync_requests = outstanding_vsync_requests_;
outstanding_vsync_requests_ = 0;
RequestVSyncUpdate(outstanding_vsync_requests);
}
void RenderWidgetHostViewAndroid::StopObservingRootWindow() {
if (!content_view_core_) {
DCHECK(!observing_root_window_);
return;
}
if (!observing_root_window_)
return;
observing_root_window_ = false;
content_view_core_->GetWindowAndroid()->RemoveObserver(this);
}
void RenderWidgetHostViewAndroid::SendBeginFrame(base::TimeTicks frame_time,
base::TimeDelta vsync_period) {
TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::SendBeginFrame",
"frame_time_us", frame_time.ToInternalValue());
base::TimeTicks display_time = frame_time + vsync_period;
// TODO(brianderson): Use adaptive draw-time estimation.
base::TimeDelta estimated_browser_composite_time =
base::TimeDelta::FromMicroseconds(
(1.0f * base::Time::kMicrosecondsPerSecond) / (3.0f * 60));
base::TimeTicks deadline = display_time - estimated_browser_composite_time;
host_->Send(new ViewMsg_BeginFrame(
host_->GetRoutingID(),
cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE, frame_time, deadline,
vsync_period, cc::BeginFrameArgs::NORMAL)));
}
bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) {
bool needs_animate = false;
if (overscroll_controller_) {
needs_animate |= overscroll_controller_->Animate(
frame_time, content_view_core_->GetLayer().get());
}
if (selection_controller_)
needs_animate |= selection_controller_->Animate(frame_time);
return needs_animate;
}
void RenderWidgetHostViewAndroid::EvictDelegatedFrame() {
if (layer_.get())
DestroyDelegatedContent();
frame_evictor_->DiscardedFrame();
// We are evicting the delegated frame,
// so there should be no pending readback requests
DCHECK(readbacks_waiting_for_frame_.empty());
}
bool RenderWidgetHostViewAndroid::HasAcceleratedSurface(
const gfx::Size& desired_size) {
NOTREACHED();
return false;
}
void RenderWidgetHostViewAndroid::GetScreenInfo(blink::WebScreenInfo* result) {
// ScreenInfo isn't tied to the widget on Android. Always return the default.
RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
}
// TODO(jrg): Find out the implications and answer correctly here,
// as we are returning the WebView and not root window bounds.
gfx::Rect RenderWidgetHostViewAndroid::GetBoundsInRootWindow() {
return GetViewBounds();
}
gfx::GLSurfaceHandle RenderWidgetHostViewAndroid::GetCompositingSurface() {
gfx::GLSurfaceHandle handle =
gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
if (using_browser_compositor_) {
handle.parent_client_id =
BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
}
return handle;
}
void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent(
const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
const bool event_consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
gesture_provider_.OnTouchEventAck(event_consumed);
}
void RenderWidgetHostViewAndroid::GestureEventAck(
const blink::WebGestureEvent& event,
InputEventAckState ack_result) {
if (overscroll_controller_)
overscroll_controller_->OnGestureEventAck(event, ack_result);
if (content_view_core_)
content_view_core_->OnGestureEventAck(event, ack_result);
}
InputEventAckState RenderWidgetHostViewAndroid::FilterInputEvent(
const blink::WebInputEvent& input_event) {
if (selection_controller_) {
switch (input_event.type) {
case blink::WebInputEvent::GestureLongPress:
selection_controller_->OnLongPressEvent();
break;
case blink::WebInputEvent::GestureTap:
selection_controller_->OnTapEvent();
break;
default:
break;
}
}
if (overscroll_controller_ &&
blink::WebInputEvent::isGestureEventType(input_event.type) &&
overscroll_controller_->WillHandleGestureEvent(
static_cast<const blink::WebGestureEvent&>(input_event))) {
return INPUT_EVENT_ACK_STATE_CONSUMED;
}
if (content_view_core_ &&
content_view_core_->FilterInputEvent(input_event))
return INPUT_EVENT_ACK_STATE_CONSUMED;
if (!host_)
return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
if (input_event.type == blink::WebInputEvent::GestureTapDown ||
input_event.type == blink::WebInputEvent::TouchStart) {
GpuDataManagerImpl* gpu_data = GpuDataManagerImpl::GetInstance();
GpuProcessHostUIShim* shim = GpuProcessHostUIShim::GetOneInstance();
if (shim && gpu_data && accelerated_surface_route_id_ &&
gpu_data->IsDriverBugWorkaroundActive(gpu::WAKE_UP_GPU_BEFORE_DRAWING))
shim->Send(
new AcceleratedSurfaceMsg_WakeUpGpu(accelerated_surface_route_id_));
}
SynchronousCompositorImpl* compositor =
SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
host_->GetRoutingID());
if (compositor)
return compositor->HandleInputEvent(input_event);
return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
}
void RenderWidgetHostViewAndroid::OnSetNeedsFlushInput() {
TRACE_EVENT0("input", "RenderWidgetHostViewAndroid::OnSetNeedsFlushInput");
RequestVSyncUpdate(FLUSH_INPUT);
}
BrowserAccessibilityManager*
RenderWidgetHostViewAndroid::CreateBrowserAccessibilityManager(
BrowserAccessibilityDelegate* delegate) {
// TODO(dmazzoni): Currently there can only be one
// BrowserAccessibilityManager per ContentViewCore, so return NULL
// if there's already a BrowserAccessibilityManager for the main
// frame. Eventually, in order to support cross-process iframes on
// Android we'll need to add support for a
// BrowserAccessibilityManager for a child frame.
// http://crbug.com/423846
if (!host_ || host_->GetRootBrowserAccessibilityManager())
return NULL;
base::android::ScopedJavaLocalRef<jobject> obj;
if (content_view_core_)
obj = content_view_core_->GetJavaObject();
return new BrowserAccessibilityManagerAndroid(
obj,
BrowserAccessibilityManagerAndroid::GetEmptyDocument(),
delegate);
}
bool RenderWidgetHostViewAndroid::LockMouse() {
NOTIMPLEMENTED();
return false;
}
void RenderWidgetHostViewAndroid::UnlockMouse() {
NOTIMPLEMENTED();
}
// Methods called from the host to the render
void RenderWidgetHostViewAndroid::SendKeyEvent(
const NativeWebKeyboardEvent& event) {
if (host_)
host_->ForwardKeyboardEvent(event);
}
void RenderWidgetHostViewAndroid::SendMouseEvent(
const blink::WebMouseEvent& event) {
if (host_)
host_->ForwardMouseEvent(event);
}
void RenderWidgetHostViewAndroid::SendMouseWheelEvent(
const blink::WebMouseWheelEvent& event) {
if (host_)
host_->ForwardWheelEvent(event);
}
void RenderWidgetHostViewAndroid::SendGestureEvent(
const blink::WebGestureEvent& event) {
// Sending a gesture that may trigger overscroll should resume the effect.
if (overscroll_controller_)
overscroll_controller_->Enable();
if (host_)
host_->ForwardGestureEventWithLatencyInfo(event, CreateLatencyInfo(event));
}
void RenderWidgetHostViewAndroid::MoveCaret(const gfx::Point& point) {
if (host_)
host_->MoveCaret(point);
}
void RenderWidgetHostViewAndroid::DismissTextHandles() {
if (selection_controller_)
selection_controller_->HideAndDisallowShowingAutomatically();
}
void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden(bool hidden) {
if (selection_controller_)
selection_controller_->SetTemporarilyHidden(hidden);
}
void RenderWidgetHostViewAndroid::OnShowingPastePopup(
const gfx::PointF& point) {
if (!selection_controller_)
return;
// As the paste popup may be triggered *before* the bounds and editability
// of the region have been updated, explicitly set the properties now.
// TODO(jdduke): Remove this workaround when auxiliary paste popup
// notifications are no longer required, crbug.com/398170.
ui::SelectionBound insertion_bound;
insertion_bound.set_type(ui::SelectionBound::CENTER);
insertion_bound.set_visible(true);
insertion_bound.SetEdge(point, point);
selection_controller_->HideAndDisallowShowingAutomatically();
selection_controller_->OnSelectionEditable(true);
selection_controller_->OnSelectionEmpty(true);
selection_controller_->OnSelectionBoundsChanged(insertion_bound,
insertion_bound);
selection_controller_->AllowShowingFromCurrentSelection();
}
SkColor RenderWidgetHostViewAndroid::GetCachedBackgroundColor() const {
return cached_background_color_;
}
void RenderWidgetHostViewAndroid::DidOverscroll(
const DidOverscrollParams& params) {
if (!content_view_core_ || !layer_.get() || !is_showing_)
return;
if (overscroll_controller_)
overscroll_controller_->OnOverscrolled(params);
}
void RenderWidgetHostViewAndroid::DidStopFlinging() {
if (content_view_core_)
content_view_core_->DidStopFlinging();
}
void RenderWidgetHostViewAndroid::SetContentViewCore(
ContentViewCoreImpl* content_view_core) {
RemoveLayers();
StopObservingRootWindow();
bool resize = false;
if (content_view_core != content_view_core_) {
overscroll_controller_.reset();
selection_controller_.reset();
ReleaseLocksOnSurface();
resize = true;
}
content_view_core_ = content_view_core;
BrowserAccessibilityManager* manager = NULL;
if (host_)
manager = host_->GetRootBrowserAccessibilityManager();
if (manager) {
base::android::ScopedJavaLocalRef<jobject> obj;
if (content_view_core_)
obj = content_view_core_->GetJavaObject();
manager->ToBrowserAccessibilityManagerAndroid()->SetContentViewCore(obj);
}
AttachLayers();
if (!content_view_core_)
return;
StartObservingRootWindow();
if (resize)
WasResized();
if (!selection_controller_)
selection_controller_ = CreateSelectionController(this, content_view_core_);
if (!overscroll_controller_ &&
content_view_core_->GetWindowAndroid()->GetCompositor()) {
overscroll_controller_ = CreateOverscrollController(content_view_core_);
}
}
void RenderWidgetHostViewAndroid::RunAckCallbacks() {
while (!ack_callbacks_.empty()) {
ack_callbacks_.front().Run();
ack_callbacks_.pop();
}
}
void RenderWidgetHostViewAndroid::OnGestureEvent(
const ui::GestureEventData& gesture) {
SendGestureEvent(CreateWebGestureEventFromGestureEventData(gesture));
}
void RenderWidgetHostViewAndroid::OnCompositingDidCommit() {
RunAckCallbacks();
}
void RenderWidgetHostViewAndroid::OnAttachCompositor() {
DCHECK(content_view_core_);
if (!overscroll_controller_)
overscroll_controller_ = CreateOverscrollController(content_view_core_);
}
void RenderWidgetHostViewAndroid::OnDetachCompositor() {
DCHECK(content_view_core_);
DCHECK(using_browser_compositor_);
RunAckCallbacks();
overscroll_controller_.reset();
}
void RenderWidgetHostViewAndroid::OnVSync(base::TimeTicks frame_time,
base::TimeDelta vsync_period) {
TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::OnVSync");
if (!host_)
return;
const uint32 current_vsync_requests = outstanding_vsync_requests_;
outstanding_vsync_requests_ = 0;
if (current_vsync_requests & FLUSH_INPUT)
host_->FlushInput();
if (current_vsync_requests & BEGIN_FRAME ||
current_vsync_requests & PERSISTENT_BEGIN_FRAME) {
SendBeginFrame(frame_time, vsync_period);
}
if (current_vsync_requests & PERSISTENT_BEGIN_FRAME)
RequestVSyncUpdate(PERSISTENT_BEGIN_FRAME);
}
void RenderWidgetHostViewAndroid::OnAnimate(base::TimeTicks begin_frame_time) {
if (Animate(begin_frame_time))
SetNeedsAnimate();
}
void RenderWidgetHostViewAndroid::OnLostResources() {
ReleaseLocksOnSurface();
if (layer_.get())
DestroyDelegatedContent();
DCHECK(ack_callbacks_.empty());
// We should not loose a frame if we have readback requests pending.
DCHECK(readbacks_waiting_for_frame_.empty());
}
// static
void
RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResultForDelegatedReadback(
const gfx::Size& dst_size_in_pixel,
const SkColorType color_type,
const base::TimeTicks& start_time,
scoped_refptr<cc::Layer> readback_layer,
ReadbackRequestCallback& callback,
scoped_ptr<cc::CopyOutputResult> result) {
readback_layer->RemoveFromParent();
PrepareTextureCopyOutputResult(
dst_size_in_pixel, color_type, start_time, callback, result.Pass());
}
// static
void RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult(
const gfx::Size& dst_size_in_pixel,
const SkColorType color_type,
const base::TimeTicks& start_time,
ReadbackRequestCallback& callback,
scoped_ptr<cc::CopyOutputResult> result) {
base::ScopedClosureRunner scoped_callback_runner(
base::Bind(callback, SkBitmap(), READBACK_FAILED));
TRACE_EVENT0("cc",
"RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult");
if (!result->HasTexture() || result->IsEmpty() || result->size().IsEmpty())
return;
scoped_ptr<SkBitmap> bitmap(new SkBitmap);
if (!bitmap->tryAllocPixels(SkImageInfo::Make(dst_size_in_pixel.width(),
dst_size_in_pixel.height(),
color_type,
kOpaque_SkAlphaType))) {
return;
}
GLHelper* gl_helper = GetPostReadbackGLHelper();
if (!gl_helper || !gl_helper->IsReadbackConfigSupported(color_type))
return;
scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock(
new SkAutoLockPixels(*bitmap));
uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
cc::TextureMailbox texture_mailbox;
scoped_ptr<cc::SingleReleaseCallback> release_callback;
result->TakeTexture(&texture_mailbox, &release_callback);
DCHECK(texture_mailbox.IsTexture());
if (!texture_mailbox.IsTexture())
return;
ignore_result(scoped_callback_runner.Release());
gl_helper->CropScaleReadbackAndCleanMailbox(
texture_mailbox.mailbox(),
texture_mailbox.sync_point(),
result->size(),
gfx::Rect(result->size()),
dst_size_in_pixel,
pixels,
color_type,
base::Bind(&CopyFromCompositingSurfaceFinished,
callback,
base::Passed(&release_callback),
base::Passed(&bitmap),
start_time,
base::Passed(&bitmap_pixels_lock)),
GLHelper::SCALER_QUALITY_GOOD);
}
SkColorType RenderWidgetHostViewAndroid::PreferredReadbackFormat() {
// Define the criteria here. If say the 16 texture readback is
// supported we should go with that (this degrades quality)
// or stick back to the default format.
if (base::SysInfo::IsLowEndDevice()) {
// TODO(sievers): Cannot use GLHelper here. Instead remove this API
// and have CopyFromCompositingSurface() fall back to RGB8 if 565 was
// requested but is not supported.
GLHelper* gl_helper = GetPostReadbackGLHelper();
if (gl_helper && gl_helper->IsReadbackConfigSupported(kRGB_565_SkColorType))
return kRGB_565_SkColorType;
}
return kN32_SkColorType;
}
void RenderWidgetHostViewAndroid::OnStylusSelectBegin(float x0,
float y0,
float x1,
float y1) {
SelectBetweenCoordinates(gfx::PointF(x0, y0), gfx::PointF(x1, y1));
}
void RenderWidgetHostViewAndroid::OnStylusSelectUpdate(float x, float y) {
MoveRangeSelectionExtent(gfx::PointF(x, y));
}
void RenderWidgetHostViewAndroid::OnStylusSelectEnd() {
if (selection_controller_)
selection_controller_->AllowShowingFromCurrentSelection();
}
void RenderWidgetHostViewAndroid::OnStylusSelectTap(base::TimeTicks time,
float x,
float y) {
// Treat the stylus tap as a long press, activating either a word selection or
// context menu depending on the targetted content.
blink::WebGestureEvent long_press = WebGestureEventBuilder::Build(
blink::WebInputEvent::GestureLongPress,
(time - base::TimeTicks()).InSecondsF(), x, y);
SendGestureEvent(long_press);
}
// static
void RenderWidgetHostViewBase::GetDefaultScreenInfo(
blink::WebScreenInfo* results) {
const gfx::Display& display =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
results->rect = display.bounds();
// TODO(husky): Remove any system controls from availableRect.
results->availableRect = display.work_area();
results->deviceScaleFactor = display.device_scale_factor();
results->orientationAngle = display.RotationAsDegree();
results->orientationType =
RenderWidgetHostViewBase::GetOrientationTypeForMobile(display);
gfx::DeviceDisplayInfo info;
results->depth = info.GetBitsPerPixel();
results->depthPerComponent = info.GetBitsPerComponent();
results->isMonochrome = (results->depthPerComponent == 0);
}
} // namespace content
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// (C) Copyright 1994-2015 Hewlett-Packard Development Company, L.P.
//
// 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.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
*****************************************************************************
*
* File: CmpSeabaseDDLview.cpp
* Description: Implements ddl views for SQL/seabase tables.
*
*
* Created: 6/30/2013
* Language: C++
*
*
*****************************************************************************
*/
#define SQLPARSERGLOBALS_FLAGS // must precede all #include's
#define SQLPARSERGLOBALS_NADEFAULTS
#include "ComObjectName.h"
#include "ComUser.h"
#include "StmtDDLCreateView.h"
#include "StmtDDLDropView.h"
#include "ElemDDLColDefArray.h"
#include "ElemDDLColRefArray.h"
#include "SchemaDB.h"
#include "CmpSeabaseDDLincludes.h"
#include "ExpHbaseInterface.h"
#include "ExExeUtilCli.h"
#include "Generator.h"
#include "desc.h"
// for privilege checking
#include "PrivMgrCommands.h"
#include "PrivMgrDefs.h"
#include "PrivMgrPrivileges.h"
#include <bitset>
#include "ComCextdecs.h"
short CmpSeabaseDDL::buildViewText(StmtDDLCreateView * createViewParseNode,
NAString &viewText)
{
const ParNameLocList &nameLocList = createViewParseNode->getNameLocList();
const char *pInputStr = nameLocList.getInputStringPtr();
StringPos inputStrPos = createViewParseNode->getStartPosition();
for (CollIndex i = 0; i < nameLocList.entries(); i++)
{
const ParNameLoc &nameLoc = nameLocList[i];
const NAString &nameExpanded = nameLoc.getExpandedName(FALSE/*no assert*/);
size_t nameAsIs = 0;
size_t nameLenInBytes = 0;
size_t nameLenInNAWchars = 0;
//
// When the character set of the input string is a variable-length/width
// multi-byte characters set, the value returned by getNameLength()
// may not be numerically equal to the number of bytes in the original
// input string that we need to skip. So, we get the character
// conversion routines to tell us how many bytes we need to skip.
//
CMPASSERT(nameLocList.getInputStringCharSet() EQU CharInfo::UTF8);
enum cnv_charset eCnvCS = convertCharsetEnum(nameLocList.getInputStringCharSet());
const char *str_to_test = (const char *) &pInputStr[nameLoc.getNamePosition()];
const Int32 max_bytes2cnv = createViewParseNode->getEndPosition()
- nameLoc.getNamePosition() + 1;
const char *tmp_out_bufr = new (STMTHEAP) char[max_bytes2cnv * 4 + 10 /* Ensure big enough! */ ];
char * p1stUnstranslatedChar = NULL;
UInt32 iTransCharCountInChars = 0;
Int32 cnvErrStatus = LocaleToUTF16(
cnv_version1 // in - const enum cnv_version version
, str_to_test // in - const char *in_bufr
, max_bytes2cnv // in - const int in_len
, tmp_out_bufr // out - const char *out_bufr
, max_bytes2cnv * 4 + 1 // in - const int out_len
, eCnvCS // in - enum cnv_charset charset
, p1stUnstranslatedChar // out - char * & first_untranslated_char
, NULL // out - unsigned int *output_data_len_p
, 0 // in - const int cnv_flags
, (Int32)TRUE // in - const int addNullAtEnd_flag
, &iTransCharCountInChars // out - unsigned int * translated_char_cnt_p
, nameLoc.getNameLength() // in - unsigned int max_NAWchars_to_convert
);
// NOTE: No errors should be possible -- string has been converted before.
NADELETEBASIC (tmp_out_bufr, STMTHEAP);
nameLenInBytes = p1stUnstranslatedChar - str_to_test;
// If name not expanded, then use the original name as is
if (nameExpanded.isNull())
nameAsIs = nameLenInBytes;
// Copy from (last position in) input string up to current name
viewText += NAString(&pInputStr[inputStrPos],
nameLoc.getNamePosition() - inputStrPos +
nameAsIs);
if (NOT nameAsIs) // original name to be replaced with expanded
{
size_t namePos = nameLoc.getNamePosition();
size_t nameLen = nameLoc.getNameLength();
if ( ( /* case #1 */ pInputStr[namePos] EQU '*' OR
/* case #2 */ pInputStr[namePos] EQU '"' )
AND nameExpanded.data()[0] NEQ '"'
AND namePos > 1
AND ( pInputStr[namePos - 1] EQU '_' OR
isAlNumIsoMapCS((unsigned char)pInputStr[namePos - 1]) )
)
{
// insert a blank separator to avoid syntax error
// WITHOUT FIX
// ex#1: CREATE VIEW C.S.V AS SELECTC.S.T.COL FROM C.S.T
// ex#2: CREATE VIEW C.S.V AS SELECTC.S.T.COL FROM C.S.T
viewText += " "; // the FIX
// WITH FIX
// ex#1: CREATE VIEW C.S.V AS SELECT C.S.T.COL FROM C.S.T
// ex#2: CREATE VIEW C.S.V AS SELECT C.S.T.COL FROM C.S.T
}
// Add the expanded (fully qualified) name (if exists)
viewText += nameExpanded;
if ( ( /* case #3 */ ( pInputStr[namePos] EQU '*' AND nameLen EQU 1 ) OR
/* case #4 */ pInputStr[namePos + nameLen - 1] EQU '"' )
AND nameExpanded.data()[nameExpanded.length() - 1] NEQ '"'
AND pInputStr[namePos + nameLen] NEQ '\0'
AND ( pInputStr[namePos + nameLen] EQU '_' OR
isAlNumIsoMapCS((unsigned char)pInputStr[namePos + nameLen]) )
)
{
// insert a blank separator to avoid syntax error
// WITHOUT FIX
// ex: CREATE VIEW C.S.V AS SELECT C.S.T.COLFROM C.S.T
viewText += " "; // the FIX
// WITH FIX
// ex: CREATE VIEW C.S.V AS SELECT C.S.T.COL FROM C.S.T
}
} // if (NOT nameAsIs)
// Advance input pointer beyond original name in input string
inputStrPos = nameLoc.getNamePosition() + nameLenInBytes /* same as nameLenInNAWchars */;
} // for
if (createViewParseNode->getEndPosition() >= inputStrPos)
{
viewText += NAString(&pInputStr[inputStrPos],
createViewParseNode->getEndPosition()
+ 1 - inputStrPos);
}
else
CMPASSERT(createViewParseNode->getEndPosition() == inputStrPos-1);
PrettifySqlText(viewText,
CharType::getCharSetAsPrefix(SqlParser_NATIONAL_CHARSET));
return 0;
} // CmpSeabaseDDL::buildViewText()
short CmpSeabaseDDL::buildViewColInfo(StmtDDLCreateView * createViewParseNode,
ElemDDLColDefArray *colDefArray)
{
// Builds the list of ElemDDLColDef parse nodes from the list of
// NAType parse nodes derived from the query expression parse sub-tree
// and the list of ElemDDLColViewDef parse nodes from the parse tree.
// This extra step is needed to invoke (reuse) global func CatBuildColumnList.
CMPASSERT(createViewParseNode->getQueryExpression()->
getOperatorType() EQU REL_ROOT);
RelRoot * pQueryExpr = (RelRoot *)createViewParseNode->getQueryExpression();
const ValueIdList &valIdList = pQueryExpr->compExpr(); // select-list
CMPASSERT(valIdList.entries() > 0);
CollIndex numOfCols(createViewParseNode->getViewColDefArray().entries());
if (numOfCols NEQ valIdList.entries())
{
*CmpCommon::diags() << DgSqlCode(-1108) //CAT_NUM_OF_VIEW_COLS_NOT_MATCHED
<< DgInt0(numOfCols)
<< DgInt1(valIdList.entries());
return -1;
}
const ElemDDLColViewDefArray &viewColDefArray = createViewParseNode->
getViewColDefArray();
for (CollIndex i = 0; i < numOfCols; i++)
{
// ANSI 11.19 SR8
if (viewColDefArray[i]->getColumnName().isNull())
{
*CmpCommon::diags() << DgSqlCode(-1099) //CAT_VIEW_COLUMN_UNNAMED
<< DgInt0(i+1);
return -1;
}
colDefArray->insert(new (STMTHEAP) ElemDDLColDef
( viewColDefArray[i]->getColumnName()
, (NAType *)&valIdList[i].getType()
, NULL // default value (n/a for view def)
, NULL // col attr list (not needed)
, STMTHEAP));
if (viewColDefArray[i]->isHeadingSpecified())
{
(*colDefArray)[i]->setIsHeadingSpecified(TRUE);
(*colDefArray)[i]->setHeading(viewColDefArray[i]->getHeading());
}
}
return 0;
}
const char *
CmpSeabaseDDL::computeCheckOption(StmtDDLCreateView * createViewParseNode)
{
if (createViewParseNode->isWithCheckOptionSpecified())
{
switch (createViewParseNode->getCheckOptionLevel())
{
case COM_CASCADED_LEVEL :
return COM_CASCADE_CHECK_OPTION_LIT;
break;
case COM_LOCAL_LEVEL:
return COM_LOCAL_CHECK_OPTION_LIT;
break;
case COM_UNKNOWN_LEVEL :
return COM_UNKNOWN_CHECK_OPTION_LIT;
break;
default:
return COM_NONE_CHECK_OPTION_LIT;
break;
} // switch
}
else
{
return COM_NONE_CHECK_OPTION_LIT;
}
return NULL;
} // CmpSeabaseDDL::computeCheckOption()
short CmpSeabaseDDL::updateViewUsage(StmtDDLCreateView * createViewParseNode,
Int64 viewUID,
ExeCliInterface * cliInterface)
{
const ParViewUsages &vu = createViewParseNode->getViewUsages();
const ParTableUsageList &vtul = vu.getViewTableUsageList();
for (CollIndex i = 0; i < vtul.entries(); i++)
{
ComObjectName usedObjName(vtul[i].getQualifiedNameObj()
.getQualifiedNameAsAnsiString(),
vtul[i].getAnsiNameSpace());
const NAString catalogNamePart = usedObjName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = usedObjName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = usedObjName.getObjectNamePartAsAnsiString(TRUE);
const NAString extUsedObjName = usedObjName.getExternalName(TRUE);
char objType[10];
Int64 usedObjUID = getObjectUID(cliInterface,
catalogNamePart.data(), schemaNamePart.data(),
objectNamePart.data(),
NULL,
NULL,
objType);
if (usedObjUID < 0)
{
return -1;
}
char query[1000];
str_sprintf(query, "upsert into %s.\"%s\".%s values (%Ld, %Ld, '%s', 0 )",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS_USAGE,
viewUID,
usedObjUID,
objType);
Lng32 cliRC = cliInterface->executeImmediate(query);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
return -1;
}
} // for
// Views can also reference functions. Add the list of functions
// referenced to the VIEWS_USAGE table.
const LIST(OptUDFInfo *) & uul = createViewParseNode->getUDFList();
for (CollIndex u = 0; u < uul.entries(); u++)
{
char query[1000];
str_sprintf(query, "upsert into %s.\"%s\".%s values (%Ld, %Ld, '%s', 0 )",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS_USAGE,
viewUID,
uul[u]->getUDFUID(),
COM_USER_DEFINED_ROUTINE_OBJECT_LIT);
Lng32 cliRC = cliInterface->executeImmediate(query);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
return -1;
}
} // for
return 0;
}
// ****************************************************************************
// method: gatherViewPrivileges
//
// For each referenced object (table or view) directly associated with the new
// view, combine privilege and grantable bitmaps together. The list of
// privileges gathered will be assigned as default privileges as the privilege
// owner values.
//
// TBD: when column privileges are added, need to check only the affected
// columns
//
// Parameters:
// createViewNode - for list of objects and isUpdatable/isInsertable flags
// cliInterface - used to get UID of referenced object
// privilegeBitmap - returns privileges this user has on the view
// grantableBitmap - returns privileges this user can grant
//
// returns:
// 0 - successful
// -1 - user does not have the privilege
// ****************************************************************************
short CmpSeabaseDDL::gatherViewPrivileges (const StmtDDLCreateView * createViewNode,
ExeCliInterface * cliInterface,
PrivMgrBitmap &privilegesBitmap,
PrivMgrBitmap &grantableBitmap)
{
// set all bits to true initially, we will be ANDing with privileges
// from all referenced objects
// default table and view privileges are the same, set up default values
PrivMgrPrivileges::setTablePrivs(privilegesBitmap);
PrivMgrPrivileges::setTablePrivs(grantableBitmap);
if (!isAuthorizationEnabled())
return 0;
const ParViewUsages &vu = createViewNode->getViewUsages();
const ParTableUsageList &vtul = vu.getViewTableUsageList();
// If DB__ROOT, no need to gather privileges
if (!ComUser::isRootUserID())
{
// generate the lists of privileges and grantable privileges
// a side effect is to return an error if basic privileges are not granted
for (CollIndex i = 0; i < vtul.entries(); i++)
{
ComObjectName usedObjName(vtul[i].getQualifiedNameObj()
.getQualifiedNameAsAnsiString(),
vtul[i].getAnsiNameSpace());
const NAString catalogNamePart = usedObjName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = usedObjName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = usedObjName.getObjectNamePartAsAnsiString(TRUE);
const NAString extUsedObjName = usedObjName.getExternalName(TRUE);
CorrName cn(objectNamePart, STMTHEAP, schemaNamePart, catalogNamePart);
// Grab privileges from the NATable structure
BindWA bindWA(ActiveSchemaDB(), CmpCommon::context(), FALSE/*inDDL*/);
NATable *naTable = bindWA.getNATable(cn);
if (naTable == NULL)
{
SEABASEDDL_INTERNAL_ERROR("Bad NATable pointer in gather view privileges");
return -1;
}
PrivMgrUserPrivs *privs = naTable->getPrivInfo();
if (privs == NULL)
{
*CmpCommon::diags() << DgSqlCode(-CAT_UNABLE_TO_RETRIEVE_PRIVS);
return -1;
}
// Requester must have at least select privilege
if ( !privs->hasSelectPriv() )
{
*CmpCommon::diags() << DgSqlCode( -4481 )
<< DgString0( "SELECT" )
<< DgString1( extUsedObjName.data());
return -1;
}
// Summarize privileges
privilegesBitmap &= privs->getObjectBitmap();
grantableBitmap &= privs->getGrantableBitmap();
}
}
// If view is not updatable or insertable, turn off privs in bitmaps
if (!createViewNode->getIsUpdatable())
{
privilegesBitmap.set(UPDATE_PRIV,false);
grantableBitmap.set(UPDATE_PRIV, false);
privilegesBitmap.set(DELETE_PRIV,false);
grantableBitmap.set(DELETE_PRIV, false);
}
if (!createViewNode->getIsInsertable())
{
privilegesBitmap.set(INSERT_PRIV,false);
grantableBitmap.set(INSERT_PRIV, false);
}
return 0;
}
// ****************************************************************************
// method: getListOfReferencedTables
//
// Returns a list of all tables that are being referenced by the passed in
// view UID
//
// Parameters:
// cliInterface - used to get the list of object usages
// objectUID - the UID being processed
// tableList - a list of objectRefdByMe structures describing each usage
//
// returns:
// 0 - successful
// -1 - unexpected error occurred
// ****************************************************************************
short CmpSeabaseDDL::getListOfReferencedTables(
ExeCliInterface * cliInterface,
const Int64 objectUID,
NAList<objectRefdByMe> &tablesList )
{
Lng32 retcode = 0;
NAList <objectRefdByMe> tempRefdList;
retcode = getListOfDirectlyReferencedObjects (cliInterface, objectUID, tempRefdList);
// If unexpected error - return
if (retcode < 0)
{
if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
SEABASEDDL_INTERNAL_ERROR("getting list of referenced tables");
return -1;
}
// For each view in the list, call getReferencedTables recursively
for (CollIndex i = 0; i < tempRefdList.entries(); i++)
{
objectRefdByMe objectRefd = tempRefdList[i];
// views should only be referencing tables, other views, or functions
CMPASSERT(objectRefd.objectType == COM_BASE_TABLE_OBJECT_LIT ||
objectRefd.objectType == COM_USER_DEFINED_ROUTINE_OBJECT_LIT ||
objectRefd.objectType == COM_VIEW_OBJECT_LIT);
// found a table, add to list
if (objectRefd.objectType == COM_BASE_TABLE_OBJECT_LIT)
{
// First make sure it has not already been added to the list
NABoolean foundEntry = FALSE;
for (CollIndex j = 0; j < tablesList.entries(); j++)
{
if (tablesList[j].objectUID == objectRefd.objectUID)
foundEntry = TRUE;
}
if (!foundEntry)
tablesList.insert(objectRefd);
}
// found a view, get objects associated with the view
if (objectRefd.objectType == COM_VIEW_OBJECT_LIT)
getListOfReferencedTables(cliInterface, objectRefd.objectUID, tablesList);
}
return 0;
}
// ****************************************************************************
// method: getListOfDirectlyReferencedObjects
//
// Returns a list of objects that are being directly referenced by the passed
// in objectUID
//
// Parameters:
// cliInterface - used to get the list of object usages
// objectUID - the UID being processed
// objectList - a list of objectRefdByMe structures describing each usage
//
// returns:
// 0 - successful
// -1 - unexpected error occurred
// ****************************************************************************
short CmpSeabaseDDL::getListOfDirectlyReferencedObjects (
ExeCliInterface *cliInterface,
const Int64 objectUID,
NAList<objectRefdByMe> &objectsList)
{
// Select all the rows from views_usage associated with the passed in
// objectUID
Lng32 cliRC = 0;
char buf[4000];
str_sprintf(buf, "select object_type, object_uid, catalog_name,"
"schema_name, object_name from %s.\"%s\".%s T, %s.\"%s\".%s VU "
"where VU.using_view_uid = %Ld "
"and T.object_uid = VU.used_object_uid",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_OBJECTS,
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS_USAGE,
objectUID);
Queue * usingObjectsQueue = NULL;
cliRC = cliInterface->fetchAllRows(usingObjectsQueue, buf, 0, FALSE, FALSE, TRUE);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
return -1;
}
// set up an objectRefdByMe struct for each returned row
usingObjectsQueue->position();
for (int idx = 0; idx < usingObjectsQueue->numEntries(); idx++)
{
OutputInfo * oi = (OutputInfo*)usingObjectsQueue->getNext();
objectRefdByMe objectInfo;
objectInfo.objectType = NAString(oi->get(0));
objectInfo.objectUID = *(Int64*)oi->get(1);
objectInfo.catalogName = NAString(oi->get(2));
objectInfo.schemaName = NAString(oi->get(3));
objectInfo.objectName = NAString(oi->get(4));
objectsList.insert(objectInfo);
}
return 0;
}
void CmpSeabaseDDL::createSeabaseView(
StmtDDLCreateView * createViewNode,
NAString &currCatName, NAString &currSchName)
{
Lng32 retcode = 0;
Lng32 cliRC = 0;
ComObjectName viewName(createViewNode->getViewName());
ComAnsiNamePart currCatAnsiName(currCatName);
ComAnsiNamePart currSchAnsiName(currSchName);
viewName.applyDefaults(currCatAnsiName, currSchAnsiName);
const NAString catalogNamePart = viewName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = viewName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = viewName.getObjectNamePartAsAnsiString(TRUE);
const NAString extViewName = viewName.getExternalName(TRUE);
const NAString extNameForHbase = catalogNamePart + "." + schemaNamePart + "." + objectNamePart;
ExeCliInterface cliInterface(STMTHEAP, NULL, NULL,
CmpCommon::context()->sqlSession()->getParentQid());
Int32 objectOwnerID = SUPER_USER;
Int32 schemaOwnerID = SUPER_USER;
ComSchemaClass schemaClass;
retcode = verifyDDLCreateOperationAuthorized(&cliInterface,
SQLOperation::CREATE_VIEW,
catalogNamePart,
schemaNamePart,
schemaClass,
objectOwnerID,
schemaOwnerID);
if (retcode != 0)
{
handleDDLCreateAuthorizationError(retcode,catalogNamePart,schemaNamePart);
return;
}
ExpHbaseInterface * ehi = NULL;
ehi = allocEHI();
if (ehi == NULL)
{
processReturn();
return;
}
if ((isSeabaseReservedSchema(viewName)) &&
(!Get_SqlParser_Flags(INTERNAL_QUERY_FROM_EXEUTIL)))
{
*CmpCommon::diags() << DgSqlCode(-1118)
<< DgTableName(extViewName);
deallocEHI(ehi);
return;
}
//if metadata views are being created and seabase is uninitialized, then this
//indicates that these views are being created during 'initialize trafodion'
//and this compiler contains stale version.
//Reload version info.
//
if ((isSeabaseMD(viewName)) &&
(CmpCommon::context()->isUninitializedSeabase()))
{
CmpCommon::context()->setIsUninitializedSeabase(FALSE);
CmpCommon::context()->uninitializedSeabaseErrNum() = 0;
}
retcode = existsInSeabaseMDTable(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_UNKNOWN_OBJECT, FALSE, FALSE);
if (retcode < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
if (retcode == 1) // already exists
{
if (NOT ((createViewNode->isCreateOrReplaceViewCascade())||
(createViewNode->isCreateOrReplaceView())))
{
*CmpCommon::diags() << DgSqlCode(-1390)
<< DgString0(extViewName);
deallocEHI(ehi);
processReturn();
return;
}
}
char * query = NULL;
int64_t objectUID = -1;
std::vector<ObjectPrivsRow> viewPrivsRows;
bool replacingView = false;
if ((retcode == 1) && // exists
((createViewNode->isCreateOrReplaceViewCascade())||
(createViewNode->isCreateOrReplaceView())))
{
// Replace view. Drop this view and recreate it.
Int32 objectOwnerID = 0;
Int32 schemaOwnerID = 0;
Int64 objUID = getObjectUIDandOwners(&cliInterface,
catalogNamePart.data(), schemaNamePart.data(),
objectNamePart.data(),
COM_VIEW_OBJECT,
objectOwnerID,schemaOwnerID);
if (objUID < 0 || objectOwnerID == 0)
{
if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
SEABASEDDL_INTERNAL_ERROR("getting object UID and owner for create or replace view");
deallocEHI(ehi);
processReturn();
return;
}
if (isAuthorizationEnabled())
{
// Verify user can perform operation
if (!isDDLOperationAuthorized(SQLOperation::ALTER_VIEW,objectOwnerID,schemaOwnerID))
{
*CmpCommon::diags() << DgSqlCode(-CAT_NOT_AUTHORIZED);
deallocEHI(ehi);
processReturn ();
return;
}
// Initiate the privilege manager interface class
NAString privMgrMDLoc;
CONCAT_CATSCH(privMgrMDLoc,getSystemCatalog(),SEABASE_PRIVMGR_SCHEMA);
PrivMgrCommands privInterface(std::string(privMgrMDLoc.data()),
CmpCommon::diags());
PrivStatus privStatus = privInterface.getPrivRowsForObject(objUID,viewPrivsRows);
if (privStatus != PrivStatus::STATUS_GOOD)
{
SEABASEDDL_INTERNAL_ERROR("Unable to retrieve privileges for replaced view");
deallocEHI(ehi);
processReturn();
return;
}
}
if (dropOneTableorView(cliInterface,extViewName.data(),COM_VIEW_OBJECT,false))
{
deallocEHI(ehi);
processReturn();
return;
}
replacingView = true;
}
// Gather the object and grantable privileges that the view creator has.
// This code also verifies that the current user has the necessary
// privileges to create the view.
PrivMgrBitmap privilegesBitmap;
PrivMgrBitmap grantableBitmap;
privilegesBitmap.set();
grantableBitmap.set();
if (gatherViewPrivileges(createViewNode,
&cliInterface,
privilegesBitmap,
grantableBitmap))
{
processReturn();
deallocEHI(ehi);
return;
}
NAString viewText(STMTHEAP);
buildViewText(createViewNode, viewText);
NAString newViewText(STMTHEAP);
for (Lng32 i = 0; i < viewText.length(); i++)
{
if (viewText.data()[i] == '\'')
newViewText += "''";
else
newViewText += viewText.data()[i];
}
ElemDDLColDefArray colDefArray(STMTHEAP);
if (buildViewColInfo(createViewNode, &colDefArray))
{
deallocEHI(ehi);
processReturn();
return;
}
Lng32 numCols = colDefArray.entries();
ComTdbVirtTableColumnInfo * colInfoArray =
new(STMTHEAP) ComTdbVirtTableColumnInfo[numCols];
if (buildColInfoArray(&colDefArray, colInfoArray, FALSE, 0, FALSE))
{
deallocEHI(ehi);
processReturn();
return;
}
Int64 objUID = -1;
if (updateSeabaseMDTable(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_VIEW_OBJECT,
"N",
NULL,
numCols,
colInfoArray,
0, NULL,
0, NULL,
objectOwnerID,
schemaOwnerID,
objUID))
{
deallocEHI(ehi);
processReturn();
return;
}
if (objUID < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
// grant privileges for view
if (isAuthorizationEnabled())
{
char authName[MAX_AUTHNAME_LEN+1];
Int32 lActualLen = 0;
Int16 status = ComUser::getAuthNameFromAuthID( (Int32) objectOwnerID
, (char *)&authName
, MAX_AUTHNAME_LEN
, lActualLen );
if (status != FEOK)
{
*CmpCommon::diags() << DgSqlCode(-20235)
<< DgInt0(status)
<< DgInt1(objectOwnerID);
deallocEHI(ehi);
processReturn();
return;
}
// Initiate the privilege manager interface class
NAString privMgrMDLoc;
CONCAT_CATSCH(privMgrMDLoc, getSystemCatalog(), SEABASE_PRIVMGR_SCHEMA);
PrivMgrCommands privInterface(std::string(privMgrMDLoc.data()),
CmpCommon::diags());
retcode = privInterface.grantObjectPrivilege
(objUID, std::string(extViewName.data()), COM_VIEW_OBJECT,
objectOwnerID, std::string(authName),
privilegesBitmap, grantableBitmap);
if (retcode != STATUS_GOOD && retcode != STATUS_WARNING)
{
deallocEHI(ehi);
processReturn();
return;
}
if (replacingView)
{
PrivStatus privStatus = privInterface.insertPrivRowsForObject(objUID,viewPrivsRows);
if (privStatus != PrivStatus::STATUS_GOOD)
{
SEABASEDDL_INTERNAL_ERROR("Unable to restore privileges for replaced view");
deallocEHI(ehi);
processReturn();
return;
}
}
}
query = new(STMTHEAP) char[newViewText.length() + 1000];
str_sprintf(query, "upsert into %s.\"%s\".%s values (%Ld, '%s', %d, %d, 0)",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS,
objUID,
computeCheckOption(createViewNode),
(createViewNode->getIsUpdatable() ? 1 : 0),
(createViewNode->getIsInsertable() ? 1 : 0));
cliRC = cliInterface.executeImmediate(query);
NADELETEBASIC(query, STMTHEAP);
if (cliRC < 0)
{
if (cliRC == -8402)
// string overflow, view text does not fit into metadata table
*CmpCommon::diags() << DgSqlCode(-1198);
else
cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
deallocEHI(ehi);
processReturn();
return;
}
if (updateTextTable(&cliInterface, objUID, COM_VIEW_TEXT, 0, newViewText))
{
deallocEHI(ehi);
processReturn();
return;
}
if (updateViewUsage(createViewNode, objUID, &cliInterface))
{
deallocEHI(ehi);
processReturn();
return;
}
if (updateObjectValidDef(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_VIEW_OBJECT_LIT,
"Y"))
{
deallocEHI(ehi);
processReturn();
return;
}
CorrName cn(objectNamePart, STMTHEAP, schemaNamePart, catalogNamePart);
ActiveSchemaDB()->getNATableDB()->removeNATable(cn,
NATableDB::REMOVE_MINE_ONLY, COM_VIEW_OBJECT);
deallocEHI(ehi);
processReturn();
return;
}
void CmpSeabaseDDL::dropSeabaseView(
StmtDDLDropView * dropViewNode,
NAString &currCatName, NAString &currSchName)
{
Lng32 cliRC = 0;
Lng32 retcode = 0;
const NAString &tabName = dropViewNode->getViewName();
ComObjectName viewName(tabName);
ComAnsiNamePart currCatAnsiName(currCatName);
ComAnsiNamePart currSchAnsiName(currSchName);
viewName.applyDefaults(currCatAnsiName, currSchAnsiName);
const NAString catalogNamePart = viewName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = viewName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = viewName.getObjectNamePartAsAnsiString(TRUE);
const NAString extViewName = viewName.getExternalName(TRUE);
ExeCliInterface cliInterface(STMTHEAP, NULL, NULL,
CmpCommon::context()->sqlSession()->getParentQid());
ExpHbaseInterface * ehi = allocEHI();
if (ehi == NULL)
return;
if ((isSeabaseReservedSchema(viewName)) &&
(!Get_SqlParser_Flags(INTERNAL_QUERY_FROM_EXEUTIL)))
{
*CmpCommon::diags() << DgSqlCode(-1119)
<< DgTableName(extViewName);
deallocEHI(ehi);
processReturn();
return;
}
retcode = existsInSeabaseMDTable(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_VIEW_OBJECT, TRUE, FALSE);
if (retcode < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
if (retcode == 0) // does not exist
{
*CmpCommon::diags() << DgSqlCode(-1389)
<< DgString0(extViewName);
deallocEHI(ehi);
processReturn();
return;
}
Int32 objectOwnerID = 0;
Int32 schemaOwnerID = 0;
Int64 objUID = getObjectUIDandOwners(&cliInterface,
catalogNamePart.data(), schemaNamePart.data(),
objectNamePart.data(),
COM_VIEW_OBJECT,
objectOwnerID,schemaOwnerID);
if (objUID < 0 || objectOwnerID == 0)
{
if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
SEABASEDDL_INTERNAL_ERROR("getting object UID and owner for drop view");
deallocEHI(ehi);
processReturn();
return;
}
// Verify user can perform operation
if (!isDDLOperationAuthorized(SQLOperation::DROP_VIEW,objectOwnerID,schemaOwnerID))
{
*CmpCommon::diags() << DgSqlCode(-CAT_NOT_AUTHORIZED);
deallocEHI(ehi);
processReturn ();
return;
}
Queue * usingViewsQueue = NULL;
if (dropViewNode->getDropBehavior() == COM_RESTRICT_DROP_BEHAVIOR)
{
NAString usingObjName;
cliRC = getUsingObject(&cliInterface, objUID, usingObjName);
if (cliRC < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
if (cliRC != 100) // found an object
{
*CmpCommon::diags() << DgSqlCode(-1047)
<< DgTableName(usingObjName);
deallocEHI(ehi);
processReturn();
return;
}
}
else if (dropViewNode->getDropBehavior() == COM_CASCADE_DROP_BEHAVIOR)
{
cliRC = getUsingViews(&cliInterface, objUID, usingViewsQueue);
if (cliRC < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
}
// get the list of all tables referenced by the view. Save this list so
// referenced tables can be removed from cache later
NAList<objectRefdByMe> tablesRefdList;
short status = getListOfReferencedTables(&cliInterface, objUID, tablesRefdList);
if (usingViewsQueue)
{
usingViewsQueue->position();
for (int idx = 0; idx < usingViewsQueue->numEntries(); idx++)
{
OutputInfo * vi = (OutputInfo*)usingViewsQueue->getNext();
char * viewName = vi->get(0);
if (dropSeabaseObject(ehi, viewName,
currCatName, currSchName, COM_VIEW_OBJECT))
{
deallocEHI(ehi);
processReturn();
return;
}
}
}
if (dropSeabaseObject(ehi, tabName,
currCatName, currSchName, COM_VIEW_OBJECT))
{
deallocEHI(ehi);
processReturn();
return;
}
// clear view definition from my cache only.
CorrName cn(objectNamePart, STMTHEAP, schemaNamePart, catalogNamePart);
ActiveSchemaDB()->getNATableDB()->removeNATable(cn,
NATableDB::REMOVE_MINE_ONLY, COM_VIEW_OBJECT);
// clear view from all other caches here. This compensates for a
// scenario where the object UID is not available in removeNATable,
// and the look up failed too. Solution is just to use the objectUID
// here.
SQL_QIKEY qiKey;
qiKey.operation[0] = 'O';
qiKey.operation[1] = 'R';
qiKey.ddlObjectUID = objUID;
SQL_EXEC_SetSecInvalidKeys(1, &qiKey);
// Now remove referenced tables from cache.
// When a query that references a view is compiled, all views are converted
// to the underlying base tables. Query plans are generated to access the
// tables, and the views are no longer relevant.
// When dropping a view, query plans that reference the dropped view will
// continue to work if the plans are cached. This code removes the
// referenced tables from caches to force recompilations so dropped views
// are noticed.
for (CollIndex i = 0; i < tablesRefdList.entries(); i++)
{
CorrName cn(tablesRefdList[i].objectName,
STMTHEAP,
tablesRefdList[i].schemaName,
tablesRefdList[i].catalogName);
ActiveSchemaDB()->getNATableDB()->removeNATable(cn,
NATableDB::REMOVE_FROM_ALL_USERS, COM_BASE_TABLE_OBJECT);
}
deallocEHI(ehi);
processReturn();
return;
}
void CmpSeabaseDDL::glueQueryFragments(Lng32 queryArraySize,
const QString * queryArray,
char * &gluedQuery,
Lng32 &gluedQuerySize)
{
Int32 i = 0;
gluedQuerySize = 0;
gluedQuery = NULL;
for (i = 0; i < queryArraySize; i++)
{
UInt32 j = 0;
const char * partn_frag = queryArray[i].str;
while ((j < strlen(queryArray[i].str)) &&
(partn_frag[j] == ' '))
j++;
if (j < strlen(queryArray[i].str))
gluedQuerySize += strlen(&partn_frag[j]);
}
gluedQuery =
new(STMTHEAP) char[gluedQuerySize + 100];
gluedQuery[0] = 0;
for (i = 0; i < queryArraySize; i++)
{
UInt32 j = 0;
const char * partn_frag = queryArray[i].str;
while ((j < strlen(queryArray[i].str)) &&
(partn_frag[j] == ' '))
j++;
if (j < strlen(queryArray[i].str))
strcat(gluedQuery, &partn_frag[j]);
}
}
short CmpSeabaseDDL::createMetadataViews(ExeCliInterface * cliInterface)
{
Lng32 cliRC = 0;
Lng32 retcode = 0;
char queryBuf[5000];
for (Int32 i = 0; i < sizeof(allMDviewsInfo)/sizeof(MDViewInfo); i++)
{
const MDViewInfo &mdi = allMDviewsInfo[i];
if (! mdi.viewName)
continue;
for (Int32 j = 0; j < NUM_MAX_PARAMS; j++)
{
param_[j] = NULL;
}
const QString * qs = NULL;
Int32 sizeOfqs = 0;
qs = mdi.viewDefnQuery;
sizeOfqs = mdi.sizeOfDefnArr;
Int32 qryArraySize = sizeOfqs / sizeof(QString);
char * gluedQuery;
Lng32 gluedQuerySize;
glueQueryFragments(qryArraySize, qs,
gluedQuery, gluedQuerySize);
if (strcmp(mdi.viewName, TRAF_TABLES_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_TABLES;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_BASE_TABLE_OBJECT_LIT;
}
else if (strcmp(mdi.viewName, TRAF_COLUMNS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_COLUMNS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_BASE_TABLE_OBJECT_LIT;
}
else if (strcmp(mdi.viewName, TRAF_INDEXES_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_INDEXES;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_OBJECTS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = SEABASE_OBJECTS;
param_[11] = getSystemCatalog();
param_[12] = SEABASE_MD_SCHEMA;
}
else if (strcmp(mdi.viewName, TRAF_KEYS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_TABLE_CONSTRAINTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_OBJECTS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = SEABASE_OBJECTS;
param_[11] = getSystemCatalog();
param_[12] = SEABASE_MD_SCHEMA;
param_[13] = SEABASE_KEYS;
param_[14] = getSystemCatalog();
param_[15] = SEABASE_MD_SCHEMA;
}
else if (strcmp(mdi.viewName, TRAF_REF_CONSTRAINTS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_REF_CONSTRAINTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_OBJECTS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = SEABASE_OBJECTS;
param_[11] = getSystemCatalog();
param_[12] = SEABASE_MD_SCHEMA;
param_[13] = SEABASE_OBJECTS;
param_[14] = getSystemCatalog();
param_[15] = SEABASE_MD_SCHEMA;
param_[16] = SEABASE_TABLE_CONSTRAINTS;
param_[17] = getSystemCatalog();
param_[18] = SEABASE_MD_SCHEMA;
}
else if (strcmp(mdi.viewName, TRAF_SEQUENCES_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_SEQ_GEN;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_SEQUENCE_GENERATOR_OBJECT_LIT;
}
else if (strcmp(mdi.viewName, TRAF_VIEWS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_VIEWS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_VIEW_OBJECT_LIT;
}
else
{
NADELETEBASIC(gluedQuery, STMTHEAP);
continue;
}
str_sprintf(queryBuf, gluedQuery,
param_[0], param_[1], param_[2], param_[3], param_[4],
param_[5], param_[6], param_[7], param_[8], param_[9],
param_[10], param_[11], param_[12], param_[13], param_[14],
param_[15], param_[16], param_[17], param_[18]);
NADELETEBASIC(gluedQuery, STMTHEAP);
NABoolean xnWasStartedHere = FALSE;
if (beginXnIfNotInProgress(cliInterface, xnWasStartedHere))
return -1;
cliRC = cliInterface->executeImmediate(queryBuf);
if (cliRC == -1390) // view already exists
{
// ignore the error.
cliRC = 0;
}
else if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
}
if (endXnIfStartedHere(cliInterface, xnWasStartedHere, cliRC) < 0)
return -1;
} // for
return 0;
}
short CmpSeabaseDDL::dropMetadataViews(ExeCliInterface * cliInterface)
{
Lng32 cliRC = 0;
Lng32 retcode = 0;
char queryBuf[5000];
for (Int32 i = 0; i < sizeof(allMDviewsInfo)/sizeof(MDViewInfo); i++)
{
const MDViewInfo &mdi = allMDviewsInfo[i];
if (! mdi.viewName)
continue;
str_sprintf(queryBuf, "drop view %s.\"%s\".%s",
getSystemCatalog(), SEABASE_MD_SCHEMA,
mdi.viewName);
NABoolean xnWasStartedHere = FALSE;
if (beginXnIfNotInProgress(cliInterface, xnWasStartedHere))
return -1;
cliRC = cliInterface->executeImmediate(queryBuf);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
}
if (endXnIfStartedHere(cliInterface, xnWasStartedHere, cliRC) < 0)
return -1;
} // for
return 0;
}
Drop view that references a sequence generator
Fixes a problem where a view that referenced a sequence generator
could not be dropped. Code handling objects referenced by views
was not prepared for sequences. Launchpad bug 1439319.
There are many other problems related to views referencing
sequences (e.g. see 1439316); this change only
corrects the problem of not being able to drop the view.
Change-Id: I8fbb8cbf565f9e6eef649152a0cec8e85d73afa4
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// (C) Copyright 1994-2015 Hewlett-Packard Development Company, L.P.
//
// 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.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
*****************************************************************************
*
* File: CmpSeabaseDDLview.cpp
* Description: Implements ddl views for SQL/seabase tables.
*
*
* Created: 6/30/2013
* Language: C++
*
*
*****************************************************************************
*/
#define SQLPARSERGLOBALS_FLAGS // must precede all #include's
#define SQLPARSERGLOBALS_NADEFAULTS
#include "ComObjectName.h"
#include "ComUser.h"
#include "StmtDDLCreateView.h"
#include "StmtDDLDropView.h"
#include "ElemDDLColDefArray.h"
#include "ElemDDLColRefArray.h"
#include "SchemaDB.h"
#include "CmpSeabaseDDLincludes.h"
#include "ExpHbaseInterface.h"
#include "ExExeUtilCli.h"
#include "Generator.h"
#include "desc.h"
// for privilege checking
#include "PrivMgrCommands.h"
#include "PrivMgrDefs.h"
#include "PrivMgrPrivileges.h"
#include <bitset>
#include "ComCextdecs.h"
short CmpSeabaseDDL::buildViewText(StmtDDLCreateView * createViewParseNode,
NAString &viewText)
{
const ParNameLocList &nameLocList = createViewParseNode->getNameLocList();
const char *pInputStr = nameLocList.getInputStringPtr();
StringPos inputStrPos = createViewParseNode->getStartPosition();
for (CollIndex i = 0; i < nameLocList.entries(); i++)
{
const ParNameLoc &nameLoc = nameLocList[i];
const NAString &nameExpanded = nameLoc.getExpandedName(FALSE/*no assert*/);
size_t nameAsIs = 0;
size_t nameLenInBytes = 0;
size_t nameLenInNAWchars = 0;
//
// When the character set of the input string is a variable-length/width
// multi-byte characters set, the value returned by getNameLength()
// may not be numerically equal to the number of bytes in the original
// input string that we need to skip. So, we get the character
// conversion routines to tell us how many bytes we need to skip.
//
CMPASSERT(nameLocList.getInputStringCharSet() EQU CharInfo::UTF8);
enum cnv_charset eCnvCS = convertCharsetEnum(nameLocList.getInputStringCharSet());
const char *str_to_test = (const char *) &pInputStr[nameLoc.getNamePosition()];
const Int32 max_bytes2cnv = createViewParseNode->getEndPosition()
- nameLoc.getNamePosition() + 1;
const char *tmp_out_bufr = new (STMTHEAP) char[max_bytes2cnv * 4 + 10 /* Ensure big enough! */ ];
char * p1stUnstranslatedChar = NULL;
UInt32 iTransCharCountInChars = 0;
Int32 cnvErrStatus = LocaleToUTF16(
cnv_version1 // in - const enum cnv_version version
, str_to_test // in - const char *in_bufr
, max_bytes2cnv // in - const int in_len
, tmp_out_bufr // out - const char *out_bufr
, max_bytes2cnv * 4 + 1 // in - const int out_len
, eCnvCS // in - enum cnv_charset charset
, p1stUnstranslatedChar // out - char * & first_untranslated_char
, NULL // out - unsigned int *output_data_len_p
, 0 // in - const int cnv_flags
, (Int32)TRUE // in - const int addNullAtEnd_flag
, &iTransCharCountInChars // out - unsigned int * translated_char_cnt_p
, nameLoc.getNameLength() // in - unsigned int max_NAWchars_to_convert
);
// NOTE: No errors should be possible -- string has been converted before.
NADELETEBASIC (tmp_out_bufr, STMTHEAP);
nameLenInBytes = p1stUnstranslatedChar - str_to_test;
// If name not expanded, then use the original name as is
if (nameExpanded.isNull())
nameAsIs = nameLenInBytes;
// Copy from (last position in) input string up to current name
viewText += NAString(&pInputStr[inputStrPos],
nameLoc.getNamePosition() - inputStrPos +
nameAsIs);
if (NOT nameAsIs) // original name to be replaced with expanded
{
size_t namePos = nameLoc.getNamePosition();
size_t nameLen = nameLoc.getNameLength();
if ( ( /* case #1 */ pInputStr[namePos] EQU '*' OR
/* case #2 */ pInputStr[namePos] EQU '"' )
AND nameExpanded.data()[0] NEQ '"'
AND namePos > 1
AND ( pInputStr[namePos - 1] EQU '_' OR
isAlNumIsoMapCS((unsigned char)pInputStr[namePos - 1]) )
)
{
// insert a blank separator to avoid syntax error
// WITHOUT FIX
// ex#1: CREATE VIEW C.S.V AS SELECTC.S.T.COL FROM C.S.T
// ex#2: CREATE VIEW C.S.V AS SELECTC.S.T.COL FROM C.S.T
viewText += " "; // the FIX
// WITH FIX
// ex#1: CREATE VIEW C.S.V AS SELECT C.S.T.COL FROM C.S.T
// ex#2: CREATE VIEW C.S.V AS SELECT C.S.T.COL FROM C.S.T
}
// Add the expanded (fully qualified) name (if exists)
viewText += nameExpanded;
if ( ( /* case #3 */ ( pInputStr[namePos] EQU '*' AND nameLen EQU 1 ) OR
/* case #4 */ pInputStr[namePos + nameLen - 1] EQU '"' )
AND nameExpanded.data()[nameExpanded.length() - 1] NEQ '"'
AND pInputStr[namePos + nameLen] NEQ '\0'
AND ( pInputStr[namePos + nameLen] EQU '_' OR
isAlNumIsoMapCS((unsigned char)pInputStr[namePos + nameLen]) )
)
{
// insert a blank separator to avoid syntax error
// WITHOUT FIX
// ex: CREATE VIEW C.S.V AS SELECT C.S.T.COLFROM C.S.T
viewText += " "; // the FIX
// WITH FIX
// ex: CREATE VIEW C.S.V AS SELECT C.S.T.COL FROM C.S.T
}
} // if (NOT nameAsIs)
// Advance input pointer beyond original name in input string
inputStrPos = nameLoc.getNamePosition() + nameLenInBytes /* same as nameLenInNAWchars */;
} // for
if (createViewParseNode->getEndPosition() >= inputStrPos)
{
viewText += NAString(&pInputStr[inputStrPos],
createViewParseNode->getEndPosition()
+ 1 - inputStrPos);
}
else
CMPASSERT(createViewParseNode->getEndPosition() == inputStrPos-1);
PrettifySqlText(viewText,
CharType::getCharSetAsPrefix(SqlParser_NATIONAL_CHARSET));
return 0;
} // CmpSeabaseDDL::buildViewText()
short CmpSeabaseDDL::buildViewColInfo(StmtDDLCreateView * createViewParseNode,
ElemDDLColDefArray *colDefArray)
{
// Builds the list of ElemDDLColDef parse nodes from the list of
// NAType parse nodes derived from the query expression parse sub-tree
// and the list of ElemDDLColViewDef parse nodes from the parse tree.
// This extra step is needed to invoke (reuse) global func CatBuildColumnList.
CMPASSERT(createViewParseNode->getQueryExpression()->
getOperatorType() EQU REL_ROOT);
RelRoot * pQueryExpr = (RelRoot *)createViewParseNode->getQueryExpression();
const ValueIdList &valIdList = pQueryExpr->compExpr(); // select-list
CMPASSERT(valIdList.entries() > 0);
CollIndex numOfCols(createViewParseNode->getViewColDefArray().entries());
if (numOfCols NEQ valIdList.entries())
{
*CmpCommon::diags() << DgSqlCode(-1108) //CAT_NUM_OF_VIEW_COLS_NOT_MATCHED
<< DgInt0(numOfCols)
<< DgInt1(valIdList.entries());
return -1;
}
const ElemDDLColViewDefArray &viewColDefArray = createViewParseNode->
getViewColDefArray();
for (CollIndex i = 0; i < numOfCols; i++)
{
// ANSI 11.19 SR8
if (viewColDefArray[i]->getColumnName().isNull())
{
*CmpCommon::diags() << DgSqlCode(-1099) //CAT_VIEW_COLUMN_UNNAMED
<< DgInt0(i+1);
return -1;
}
colDefArray->insert(new (STMTHEAP) ElemDDLColDef
( viewColDefArray[i]->getColumnName()
, (NAType *)&valIdList[i].getType()
, NULL // default value (n/a for view def)
, NULL // col attr list (not needed)
, STMTHEAP));
if (viewColDefArray[i]->isHeadingSpecified())
{
(*colDefArray)[i]->setIsHeadingSpecified(TRUE);
(*colDefArray)[i]->setHeading(viewColDefArray[i]->getHeading());
}
}
return 0;
}
const char *
CmpSeabaseDDL::computeCheckOption(StmtDDLCreateView * createViewParseNode)
{
if (createViewParseNode->isWithCheckOptionSpecified())
{
switch (createViewParseNode->getCheckOptionLevel())
{
case COM_CASCADED_LEVEL :
return COM_CASCADE_CHECK_OPTION_LIT;
break;
case COM_LOCAL_LEVEL:
return COM_LOCAL_CHECK_OPTION_LIT;
break;
case COM_UNKNOWN_LEVEL :
return COM_UNKNOWN_CHECK_OPTION_LIT;
break;
default:
return COM_NONE_CHECK_OPTION_LIT;
break;
} // switch
}
else
{
return COM_NONE_CHECK_OPTION_LIT;
}
return NULL;
} // CmpSeabaseDDL::computeCheckOption()
short CmpSeabaseDDL::updateViewUsage(StmtDDLCreateView * createViewParseNode,
Int64 viewUID,
ExeCliInterface * cliInterface)
{
const ParViewUsages &vu = createViewParseNode->getViewUsages();
const ParTableUsageList &vtul = vu.getViewTableUsageList();
for (CollIndex i = 0; i < vtul.entries(); i++)
{
ComObjectName usedObjName(vtul[i].getQualifiedNameObj()
.getQualifiedNameAsAnsiString(),
vtul[i].getAnsiNameSpace());
const NAString catalogNamePart = usedObjName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = usedObjName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = usedObjName.getObjectNamePartAsAnsiString(TRUE);
const NAString extUsedObjName = usedObjName.getExternalName(TRUE);
char objType[10];
Int64 usedObjUID = getObjectUID(cliInterface,
catalogNamePart.data(), schemaNamePart.data(),
objectNamePart.data(),
NULL,
NULL,
objType);
if (usedObjUID < 0)
{
return -1;
}
char query[1000];
str_sprintf(query, "upsert into %s.\"%s\".%s values (%Ld, %Ld, '%s', 0 )",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS_USAGE,
viewUID,
usedObjUID,
objType);
Lng32 cliRC = cliInterface->executeImmediate(query);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
return -1;
}
} // for
// Views can also reference functions. Add the list of functions
// referenced to the VIEWS_USAGE table.
const LIST(OptUDFInfo *) & uul = createViewParseNode->getUDFList();
for (CollIndex u = 0; u < uul.entries(); u++)
{
char query[1000];
str_sprintf(query, "upsert into %s.\"%s\".%s values (%Ld, %Ld, '%s', 0 )",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS_USAGE,
viewUID,
uul[u]->getUDFUID(),
COM_USER_DEFINED_ROUTINE_OBJECT_LIT);
Lng32 cliRC = cliInterface->executeImmediate(query);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
return -1;
}
} // for
return 0;
}
// ****************************************************************************
// method: gatherViewPrivileges
//
// For each referenced object (table or view) directly associated with the new
// view, combine privilege and grantable bitmaps together. The list of
// privileges gathered will be assigned as default privileges as the privilege
// owner values.
//
// TBD: when column privileges are added, need to check only the affected
// columns
//
// Parameters:
// createViewNode - for list of objects and isUpdatable/isInsertable flags
// cliInterface - used to get UID of referenced object
// privilegeBitmap - returns privileges this user has on the view
// grantableBitmap - returns privileges this user can grant
//
// returns:
// 0 - successful
// -1 - user does not have the privilege
// ****************************************************************************
short CmpSeabaseDDL::gatherViewPrivileges (const StmtDDLCreateView * createViewNode,
ExeCliInterface * cliInterface,
PrivMgrBitmap &privilegesBitmap,
PrivMgrBitmap &grantableBitmap)
{
// set all bits to true initially, we will be ANDing with privileges
// from all referenced objects
// default table and view privileges are the same, set up default values
PrivMgrPrivileges::setTablePrivs(privilegesBitmap);
PrivMgrPrivileges::setTablePrivs(grantableBitmap);
if (!isAuthorizationEnabled())
return 0;
const ParViewUsages &vu = createViewNode->getViewUsages();
const ParTableUsageList &vtul = vu.getViewTableUsageList();
// If DB__ROOT, no need to gather privileges
if (!ComUser::isRootUserID())
{
// generate the lists of privileges and grantable privileges
// a side effect is to return an error if basic privileges are not granted
for (CollIndex i = 0; i < vtul.entries(); i++)
{
ComObjectName usedObjName(vtul[i].getQualifiedNameObj()
.getQualifiedNameAsAnsiString(),
vtul[i].getAnsiNameSpace());
const NAString catalogNamePart = usedObjName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = usedObjName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = usedObjName.getObjectNamePartAsAnsiString(TRUE);
const NAString extUsedObjName = usedObjName.getExternalName(TRUE);
CorrName cn(objectNamePart, STMTHEAP, schemaNamePart, catalogNamePart);
// Grab privileges from the NATable structure
BindWA bindWA(ActiveSchemaDB(), CmpCommon::context(), FALSE/*inDDL*/);
NATable *naTable = bindWA.getNATable(cn);
if (naTable == NULL)
{
SEABASEDDL_INTERNAL_ERROR("Bad NATable pointer in gather view privileges");
return -1;
}
PrivMgrUserPrivs *privs = naTable->getPrivInfo();
if (privs == NULL)
{
*CmpCommon::diags() << DgSqlCode(-CAT_UNABLE_TO_RETRIEVE_PRIVS);
return -1;
}
// Requester must have at least select privilege
if ( !privs->hasSelectPriv() )
{
*CmpCommon::diags() << DgSqlCode( -4481 )
<< DgString0( "SELECT" )
<< DgString1( extUsedObjName.data());
return -1;
}
// Summarize privileges
privilegesBitmap &= privs->getObjectBitmap();
grantableBitmap &= privs->getGrantableBitmap();
}
}
// If view is not updatable or insertable, turn off privs in bitmaps
if (!createViewNode->getIsUpdatable())
{
privilegesBitmap.set(UPDATE_PRIV,false);
grantableBitmap.set(UPDATE_PRIV, false);
privilegesBitmap.set(DELETE_PRIV,false);
grantableBitmap.set(DELETE_PRIV, false);
}
if (!createViewNode->getIsInsertable())
{
privilegesBitmap.set(INSERT_PRIV,false);
grantableBitmap.set(INSERT_PRIV, false);
}
return 0;
}
// ****************************************************************************
// method: getListOfReferencedTables
//
// Returns a list of all tables that are being referenced by the passed in
// view UID
//
// Parameters:
// cliInterface - used to get the list of object usages
// objectUID - the UID being processed
// tableList - a list of objectRefdByMe structures describing each usage
//
// returns:
// 0 - successful
// -1 - unexpected error occurred
// ****************************************************************************
short CmpSeabaseDDL::getListOfReferencedTables(
ExeCliInterface * cliInterface,
const Int64 objectUID,
NAList<objectRefdByMe> &tablesList )
{
Lng32 retcode = 0;
NAList <objectRefdByMe> tempRefdList;
retcode = getListOfDirectlyReferencedObjects (cliInterface, objectUID, tempRefdList);
// If unexpected error - return
if (retcode < 0)
{
if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
SEABASEDDL_INTERNAL_ERROR("getting list of referenced tables");
return -1;
}
// For each view in the list, call getReferencedTables recursively
for (CollIndex i = 0; i < tempRefdList.entries(); i++)
{
objectRefdByMe objectRefd = tempRefdList[i];
// views should only be referencing tables, other views, or functions
CMPASSERT(objectRefd.objectType == COM_BASE_TABLE_OBJECT_LIT ||
objectRefd.objectType == COM_USER_DEFINED_ROUTINE_OBJECT_LIT ||
objectRefd.objectType == COM_SEQUENCE_GENERATOR_OBJECT_LIT ||
objectRefd.objectType == COM_VIEW_OBJECT_LIT);
// found a table, add to list
if (objectRefd.objectType == COM_BASE_TABLE_OBJECT_LIT)
{
// First make sure it has not already been added to the list
NABoolean foundEntry = FALSE;
for (CollIndex j = 0; j < tablesList.entries(); j++)
{
if (tablesList[j].objectUID == objectRefd.objectUID)
foundEntry = TRUE;
}
if (!foundEntry)
tablesList.insert(objectRefd);
}
// found a view, get objects associated with the view
if (objectRefd.objectType == COM_VIEW_OBJECT_LIT)
getListOfReferencedTables(cliInterface, objectRefd.objectUID, tablesList);
}
return 0;
}
// ****************************************************************************
// method: getListOfDirectlyReferencedObjects
//
// Returns a list of objects that are being directly referenced by the passed
// in objectUID
//
// Parameters:
// cliInterface - used to get the list of object usages
// objectUID - the UID being processed
// objectList - a list of objectRefdByMe structures describing each usage
//
// returns:
// 0 - successful
// -1 - unexpected error occurred
// ****************************************************************************
short CmpSeabaseDDL::getListOfDirectlyReferencedObjects (
ExeCliInterface *cliInterface,
const Int64 objectUID,
NAList<objectRefdByMe> &objectsList)
{
// Select all the rows from views_usage associated with the passed in
// objectUID
Lng32 cliRC = 0;
char buf[4000];
str_sprintf(buf, "select object_type, object_uid, catalog_name,"
"schema_name, object_name from %s.\"%s\".%s T, %s.\"%s\".%s VU "
"where VU.using_view_uid = %Ld "
"and T.object_uid = VU.used_object_uid",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_OBJECTS,
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS_USAGE,
objectUID);
Queue * usingObjectsQueue = NULL;
cliRC = cliInterface->fetchAllRows(usingObjectsQueue, buf, 0, FALSE, FALSE, TRUE);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
return -1;
}
// set up an objectRefdByMe struct for each returned row
usingObjectsQueue->position();
for (int idx = 0; idx < usingObjectsQueue->numEntries(); idx++)
{
OutputInfo * oi = (OutputInfo*)usingObjectsQueue->getNext();
objectRefdByMe objectInfo;
objectInfo.objectType = NAString(oi->get(0));
objectInfo.objectUID = *(Int64*)oi->get(1);
objectInfo.catalogName = NAString(oi->get(2));
objectInfo.schemaName = NAString(oi->get(3));
objectInfo.objectName = NAString(oi->get(4));
objectsList.insert(objectInfo);
}
return 0;
}
void CmpSeabaseDDL::createSeabaseView(
StmtDDLCreateView * createViewNode,
NAString &currCatName, NAString &currSchName)
{
Lng32 retcode = 0;
Lng32 cliRC = 0;
ComObjectName viewName(createViewNode->getViewName());
ComAnsiNamePart currCatAnsiName(currCatName);
ComAnsiNamePart currSchAnsiName(currSchName);
viewName.applyDefaults(currCatAnsiName, currSchAnsiName);
const NAString catalogNamePart = viewName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = viewName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = viewName.getObjectNamePartAsAnsiString(TRUE);
const NAString extViewName = viewName.getExternalName(TRUE);
const NAString extNameForHbase = catalogNamePart + "." + schemaNamePart + "." + objectNamePart;
ExeCliInterface cliInterface(STMTHEAP, NULL, NULL,
CmpCommon::context()->sqlSession()->getParentQid());
Int32 objectOwnerID = SUPER_USER;
Int32 schemaOwnerID = SUPER_USER;
ComSchemaClass schemaClass;
retcode = verifyDDLCreateOperationAuthorized(&cliInterface,
SQLOperation::CREATE_VIEW,
catalogNamePart,
schemaNamePart,
schemaClass,
objectOwnerID,
schemaOwnerID);
if (retcode != 0)
{
handleDDLCreateAuthorizationError(retcode,catalogNamePart,schemaNamePart);
return;
}
ExpHbaseInterface * ehi = NULL;
ehi = allocEHI();
if (ehi == NULL)
{
processReturn();
return;
}
if ((isSeabaseReservedSchema(viewName)) &&
(!Get_SqlParser_Flags(INTERNAL_QUERY_FROM_EXEUTIL)))
{
*CmpCommon::diags() << DgSqlCode(-1118)
<< DgTableName(extViewName);
deallocEHI(ehi);
return;
}
//if metadata views are being created and seabase is uninitialized, then this
//indicates that these views are being created during 'initialize trafodion'
//and this compiler contains stale version.
//Reload version info.
//
if ((isSeabaseMD(viewName)) &&
(CmpCommon::context()->isUninitializedSeabase()))
{
CmpCommon::context()->setIsUninitializedSeabase(FALSE);
CmpCommon::context()->uninitializedSeabaseErrNum() = 0;
}
retcode = existsInSeabaseMDTable(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_UNKNOWN_OBJECT, FALSE, FALSE);
if (retcode < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
if (retcode == 1) // already exists
{
if (NOT ((createViewNode->isCreateOrReplaceViewCascade())||
(createViewNode->isCreateOrReplaceView())))
{
*CmpCommon::diags() << DgSqlCode(-1390)
<< DgString0(extViewName);
deallocEHI(ehi);
processReturn();
return;
}
}
char * query = NULL;
int64_t objectUID = -1;
std::vector<ObjectPrivsRow> viewPrivsRows;
bool replacingView = false;
if ((retcode == 1) && // exists
((createViewNode->isCreateOrReplaceViewCascade())||
(createViewNode->isCreateOrReplaceView())))
{
// Replace view. Drop this view and recreate it.
Int32 objectOwnerID = 0;
Int32 schemaOwnerID = 0;
Int64 objUID = getObjectUIDandOwners(&cliInterface,
catalogNamePart.data(), schemaNamePart.data(),
objectNamePart.data(),
COM_VIEW_OBJECT,
objectOwnerID,schemaOwnerID);
if (objUID < 0 || objectOwnerID == 0)
{
if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
SEABASEDDL_INTERNAL_ERROR("getting object UID and owner for create or replace view");
deallocEHI(ehi);
processReturn();
return;
}
if (isAuthorizationEnabled())
{
// Verify user can perform operation
if (!isDDLOperationAuthorized(SQLOperation::ALTER_VIEW,objectOwnerID,schemaOwnerID))
{
*CmpCommon::diags() << DgSqlCode(-CAT_NOT_AUTHORIZED);
deallocEHI(ehi);
processReturn ();
return;
}
// Initiate the privilege manager interface class
NAString privMgrMDLoc;
CONCAT_CATSCH(privMgrMDLoc,getSystemCatalog(),SEABASE_PRIVMGR_SCHEMA);
PrivMgrCommands privInterface(std::string(privMgrMDLoc.data()),
CmpCommon::diags());
PrivStatus privStatus = privInterface.getPrivRowsForObject(objUID,viewPrivsRows);
if (privStatus != PrivStatus::STATUS_GOOD)
{
SEABASEDDL_INTERNAL_ERROR("Unable to retrieve privileges for replaced view");
deallocEHI(ehi);
processReturn();
return;
}
}
if (dropOneTableorView(cliInterface,extViewName.data(),COM_VIEW_OBJECT,false))
{
deallocEHI(ehi);
processReturn();
return;
}
replacingView = true;
}
// Gather the object and grantable privileges that the view creator has.
// This code also verifies that the current user has the necessary
// privileges to create the view.
PrivMgrBitmap privilegesBitmap;
PrivMgrBitmap grantableBitmap;
privilegesBitmap.set();
grantableBitmap.set();
if (gatherViewPrivileges(createViewNode,
&cliInterface,
privilegesBitmap,
grantableBitmap))
{
processReturn();
deallocEHI(ehi);
return;
}
NAString viewText(STMTHEAP);
buildViewText(createViewNode, viewText);
NAString newViewText(STMTHEAP);
for (Lng32 i = 0; i < viewText.length(); i++)
{
if (viewText.data()[i] == '\'')
newViewText += "''";
else
newViewText += viewText.data()[i];
}
ElemDDLColDefArray colDefArray(STMTHEAP);
if (buildViewColInfo(createViewNode, &colDefArray))
{
deallocEHI(ehi);
processReturn();
return;
}
Lng32 numCols = colDefArray.entries();
ComTdbVirtTableColumnInfo * colInfoArray =
new(STMTHEAP) ComTdbVirtTableColumnInfo[numCols];
if (buildColInfoArray(&colDefArray, colInfoArray, FALSE, 0, FALSE))
{
deallocEHI(ehi);
processReturn();
return;
}
Int64 objUID = -1;
if (updateSeabaseMDTable(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_VIEW_OBJECT,
"N",
NULL,
numCols,
colInfoArray,
0, NULL,
0, NULL,
objectOwnerID,
schemaOwnerID,
objUID))
{
deallocEHI(ehi);
processReturn();
return;
}
if (objUID < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
// grant privileges for view
if (isAuthorizationEnabled())
{
char authName[MAX_AUTHNAME_LEN+1];
Int32 lActualLen = 0;
Int16 status = ComUser::getAuthNameFromAuthID( (Int32) objectOwnerID
, (char *)&authName
, MAX_AUTHNAME_LEN
, lActualLen );
if (status != FEOK)
{
*CmpCommon::diags() << DgSqlCode(-20235)
<< DgInt0(status)
<< DgInt1(objectOwnerID);
deallocEHI(ehi);
processReturn();
return;
}
// Initiate the privilege manager interface class
NAString privMgrMDLoc;
CONCAT_CATSCH(privMgrMDLoc, getSystemCatalog(), SEABASE_PRIVMGR_SCHEMA);
PrivMgrCommands privInterface(std::string(privMgrMDLoc.data()),
CmpCommon::diags());
retcode = privInterface.grantObjectPrivilege
(objUID, std::string(extViewName.data()), COM_VIEW_OBJECT,
objectOwnerID, std::string(authName),
privilegesBitmap, grantableBitmap);
if (retcode != STATUS_GOOD && retcode != STATUS_WARNING)
{
deallocEHI(ehi);
processReturn();
return;
}
if (replacingView)
{
PrivStatus privStatus = privInterface.insertPrivRowsForObject(objUID,viewPrivsRows);
if (privStatus != PrivStatus::STATUS_GOOD)
{
SEABASEDDL_INTERNAL_ERROR("Unable to restore privileges for replaced view");
deallocEHI(ehi);
processReturn();
return;
}
}
}
query = new(STMTHEAP) char[newViewText.length() + 1000];
str_sprintf(query, "upsert into %s.\"%s\".%s values (%Ld, '%s', %d, %d, 0)",
getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_VIEWS,
objUID,
computeCheckOption(createViewNode),
(createViewNode->getIsUpdatable() ? 1 : 0),
(createViewNode->getIsInsertable() ? 1 : 0));
cliRC = cliInterface.executeImmediate(query);
NADELETEBASIC(query, STMTHEAP);
if (cliRC < 0)
{
if (cliRC == -8402)
// string overflow, view text does not fit into metadata table
*CmpCommon::diags() << DgSqlCode(-1198);
else
cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
deallocEHI(ehi);
processReturn();
return;
}
if (updateTextTable(&cliInterface, objUID, COM_VIEW_TEXT, 0, newViewText))
{
deallocEHI(ehi);
processReturn();
return;
}
if (updateViewUsage(createViewNode, objUID, &cliInterface))
{
deallocEHI(ehi);
processReturn();
return;
}
if (updateObjectValidDef(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_VIEW_OBJECT_LIT,
"Y"))
{
deallocEHI(ehi);
processReturn();
return;
}
CorrName cn(objectNamePart, STMTHEAP, schemaNamePart, catalogNamePart);
ActiveSchemaDB()->getNATableDB()->removeNATable(cn,
NATableDB::REMOVE_MINE_ONLY, COM_VIEW_OBJECT);
deallocEHI(ehi);
processReturn();
return;
}
void CmpSeabaseDDL::dropSeabaseView(
StmtDDLDropView * dropViewNode,
NAString &currCatName, NAString &currSchName)
{
Lng32 cliRC = 0;
Lng32 retcode = 0;
const NAString &tabName = dropViewNode->getViewName();
ComObjectName viewName(tabName);
ComAnsiNamePart currCatAnsiName(currCatName);
ComAnsiNamePart currSchAnsiName(currSchName);
viewName.applyDefaults(currCatAnsiName, currSchAnsiName);
const NAString catalogNamePart = viewName.getCatalogNamePartAsAnsiString();
const NAString schemaNamePart = viewName.getSchemaNamePartAsAnsiString(TRUE);
const NAString objectNamePart = viewName.getObjectNamePartAsAnsiString(TRUE);
const NAString extViewName = viewName.getExternalName(TRUE);
ExeCliInterface cliInterface(STMTHEAP, NULL, NULL,
CmpCommon::context()->sqlSession()->getParentQid());
ExpHbaseInterface * ehi = allocEHI();
if (ehi == NULL)
return;
if ((isSeabaseReservedSchema(viewName)) &&
(!Get_SqlParser_Flags(INTERNAL_QUERY_FROM_EXEUTIL)))
{
*CmpCommon::diags() << DgSqlCode(-1119)
<< DgTableName(extViewName);
deallocEHI(ehi);
processReturn();
return;
}
retcode = existsInSeabaseMDTable(&cliInterface,
catalogNamePart, schemaNamePart, objectNamePart,
COM_VIEW_OBJECT, TRUE, FALSE);
if (retcode < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
if (retcode == 0) // does not exist
{
*CmpCommon::diags() << DgSqlCode(-1389)
<< DgString0(extViewName);
deallocEHI(ehi);
processReturn();
return;
}
Int32 objectOwnerID = 0;
Int32 schemaOwnerID = 0;
Int64 objUID = getObjectUIDandOwners(&cliInterface,
catalogNamePart.data(), schemaNamePart.data(),
objectNamePart.data(),
COM_VIEW_OBJECT,
objectOwnerID,schemaOwnerID);
if (objUID < 0 || objectOwnerID == 0)
{
if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
SEABASEDDL_INTERNAL_ERROR("getting object UID and owner for drop view");
deallocEHI(ehi);
processReturn();
return;
}
// Verify user can perform operation
if (!isDDLOperationAuthorized(SQLOperation::DROP_VIEW,objectOwnerID,schemaOwnerID))
{
*CmpCommon::diags() << DgSqlCode(-CAT_NOT_AUTHORIZED);
deallocEHI(ehi);
processReturn ();
return;
}
Queue * usingViewsQueue = NULL;
if (dropViewNode->getDropBehavior() == COM_RESTRICT_DROP_BEHAVIOR)
{
NAString usingObjName;
cliRC = getUsingObject(&cliInterface, objUID, usingObjName);
if (cliRC < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
if (cliRC != 100) // found an object
{
*CmpCommon::diags() << DgSqlCode(-1047)
<< DgTableName(usingObjName);
deallocEHI(ehi);
processReturn();
return;
}
}
else if (dropViewNode->getDropBehavior() == COM_CASCADE_DROP_BEHAVIOR)
{
cliRC = getUsingViews(&cliInterface, objUID, usingViewsQueue);
if (cliRC < 0)
{
deallocEHI(ehi);
processReturn();
return;
}
}
// get the list of all tables referenced by the view. Save this list so
// referenced tables can be removed from cache later
NAList<objectRefdByMe> tablesRefdList;
short status = getListOfReferencedTables(&cliInterface, objUID, tablesRefdList);
if (usingViewsQueue)
{
usingViewsQueue->position();
for (int idx = 0; idx < usingViewsQueue->numEntries(); idx++)
{
OutputInfo * vi = (OutputInfo*)usingViewsQueue->getNext();
char * viewName = vi->get(0);
if (dropSeabaseObject(ehi, viewName,
currCatName, currSchName, COM_VIEW_OBJECT))
{
deallocEHI(ehi);
processReturn();
return;
}
}
}
if (dropSeabaseObject(ehi, tabName,
currCatName, currSchName, COM_VIEW_OBJECT))
{
deallocEHI(ehi);
processReturn();
return;
}
// clear view definition from my cache only.
CorrName cn(objectNamePart, STMTHEAP, schemaNamePart, catalogNamePart);
ActiveSchemaDB()->getNATableDB()->removeNATable(cn,
NATableDB::REMOVE_MINE_ONLY, COM_VIEW_OBJECT);
// clear view from all other caches here. This compensates for a
// scenario where the object UID is not available in removeNATable,
// and the look up failed too. Solution is just to use the objectUID
// here.
SQL_QIKEY qiKey;
qiKey.operation[0] = 'O';
qiKey.operation[1] = 'R';
qiKey.ddlObjectUID = objUID;
SQL_EXEC_SetSecInvalidKeys(1, &qiKey);
// Now remove referenced tables from cache.
// When a query that references a view is compiled, all views are converted
// to the underlying base tables. Query plans are generated to access the
// tables, and the views are no longer relevant.
// When dropping a view, query plans that reference the dropped view will
// continue to work if the plans are cached. This code removes the
// referenced tables from caches to force recompilations so dropped views
// are noticed.
for (CollIndex i = 0; i < tablesRefdList.entries(); i++)
{
CorrName cn(tablesRefdList[i].objectName,
STMTHEAP,
tablesRefdList[i].schemaName,
tablesRefdList[i].catalogName);
ActiveSchemaDB()->getNATableDB()->removeNATable(cn,
NATableDB::REMOVE_FROM_ALL_USERS, COM_BASE_TABLE_OBJECT);
}
deallocEHI(ehi);
processReturn();
return;
}
void CmpSeabaseDDL::glueQueryFragments(Lng32 queryArraySize,
const QString * queryArray,
char * &gluedQuery,
Lng32 &gluedQuerySize)
{
Int32 i = 0;
gluedQuerySize = 0;
gluedQuery = NULL;
for (i = 0; i < queryArraySize; i++)
{
UInt32 j = 0;
const char * partn_frag = queryArray[i].str;
while ((j < strlen(queryArray[i].str)) &&
(partn_frag[j] == ' '))
j++;
if (j < strlen(queryArray[i].str))
gluedQuerySize += strlen(&partn_frag[j]);
}
gluedQuery =
new(STMTHEAP) char[gluedQuerySize + 100];
gluedQuery[0] = 0;
for (i = 0; i < queryArraySize; i++)
{
UInt32 j = 0;
const char * partn_frag = queryArray[i].str;
while ((j < strlen(queryArray[i].str)) &&
(partn_frag[j] == ' '))
j++;
if (j < strlen(queryArray[i].str))
strcat(gluedQuery, &partn_frag[j]);
}
}
short CmpSeabaseDDL::createMetadataViews(ExeCliInterface * cliInterface)
{
Lng32 cliRC = 0;
Lng32 retcode = 0;
char queryBuf[5000];
for (Int32 i = 0; i < sizeof(allMDviewsInfo)/sizeof(MDViewInfo); i++)
{
const MDViewInfo &mdi = allMDviewsInfo[i];
if (! mdi.viewName)
continue;
for (Int32 j = 0; j < NUM_MAX_PARAMS; j++)
{
param_[j] = NULL;
}
const QString * qs = NULL;
Int32 sizeOfqs = 0;
qs = mdi.viewDefnQuery;
sizeOfqs = mdi.sizeOfDefnArr;
Int32 qryArraySize = sizeOfqs / sizeof(QString);
char * gluedQuery;
Lng32 gluedQuerySize;
glueQueryFragments(qryArraySize, qs,
gluedQuery, gluedQuerySize);
if (strcmp(mdi.viewName, TRAF_TABLES_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_TABLES;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_BASE_TABLE_OBJECT_LIT;
}
else if (strcmp(mdi.viewName, TRAF_COLUMNS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_COLUMNS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_BASE_TABLE_OBJECT_LIT;
}
else if (strcmp(mdi.viewName, TRAF_INDEXES_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_INDEXES;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_OBJECTS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = SEABASE_OBJECTS;
param_[11] = getSystemCatalog();
param_[12] = SEABASE_MD_SCHEMA;
}
else if (strcmp(mdi.viewName, TRAF_KEYS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_TABLE_CONSTRAINTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_OBJECTS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = SEABASE_OBJECTS;
param_[11] = getSystemCatalog();
param_[12] = SEABASE_MD_SCHEMA;
param_[13] = SEABASE_KEYS;
param_[14] = getSystemCatalog();
param_[15] = SEABASE_MD_SCHEMA;
}
else if (strcmp(mdi.viewName, TRAF_REF_CONSTRAINTS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_REF_CONSTRAINTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_OBJECTS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = SEABASE_OBJECTS;
param_[11] = getSystemCatalog();
param_[12] = SEABASE_MD_SCHEMA;
param_[13] = SEABASE_OBJECTS;
param_[14] = getSystemCatalog();
param_[15] = SEABASE_MD_SCHEMA;
param_[16] = SEABASE_TABLE_CONSTRAINTS;
param_[17] = getSystemCatalog();
param_[18] = SEABASE_MD_SCHEMA;
}
else if (strcmp(mdi.viewName, TRAF_SEQUENCES_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_SEQ_GEN;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_SEQUENCE_GENERATOR_OBJECT_LIT;
}
else if (strcmp(mdi.viewName, TRAF_VIEWS_VIEW) == 0)
{
param_[0] = getSystemCatalog();
param_[1] = SEABASE_MD_SCHEMA;
param_[2] = getSystemCatalog();
param_[3] = SEABASE_MD_SCHEMA;
param_[4] = SEABASE_OBJECTS;
param_[5] = getSystemCatalog();
param_[6] = SEABASE_MD_SCHEMA;
param_[7] = SEABASE_VIEWS;
param_[8] = getSystemCatalog();
param_[9] = SEABASE_MD_SCHEMA;
param_[10] = COM_VIEW_OBJECT_LIT;
}
else
{
NADELETEBASIC(gluedQuery, STMTHEAP);
continue;
}
str_sprintf(queryBuf, gluedQuery,
param_[0], param_[1], param_[2], param_[3], param_[4],
param_[5], param_[6], param_[7], param_[8], param_[9],
param_[10], param_[11], param_[12], param_[13], param_[14],
param_[15], param_[16], param_[17], param_[18]);
NADELETEBASIC(gluedQuery, STMTHEAP);
NABoolean xnWasStartedHere = FALSE;
if (beginXnIfNotInProgress(cliInterface, xnWasStartedHere))
return -1;
cliRC = cliInterface->executeImmediate(queryBuf);
if (cliRC == -1390) // view already exists
{
// ignore the error.
cliRC = 0;
}
else if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
}
if (endXnIfStartedHere(cliInterface, xnWasStartedHere, cliRC) < 0)
return -1;
} // for
return 0;
}
short CmpSeabaseDDL::dropMetadataViews(ExeCliInterface * cliInterface)
{
Lng32 cliRC = 0;
Lng32 retcode = 0;
char queryBuf[5000];
for (Int32 i = 0; i < sizeof(allMDviewsInfo)/sizeof(MDViewInfo); i++)
{
const MDViewInfo &mdi = allMDviewsInfo[i];
if (! mdi.viewName)
continue;
str_sprintf(queryBuf, "drop view %s.\"%s\".%s",
getSystemCatalog(), SEABASE_MD_SCHEMA,
mdi.viewName);
NABoolean xnWasStartedHere = FALSE;
if (beginXnIfNotInProgress(cliInterface, xnWasStartedHere))
return -1;
cliRC = cliInterface->executeImmediate(queryBuf);
if (cliRC < 0)
{
cliInterface->retrieveSQLDiagnostics(CmpCommon::diags());
}
if (endXnIfStartedHere(cliInterface, xnWasStartedHere, cliRC) < 0)
return -1;
} // for
return 0;
}
|
/*************************************************************************
*
* $RCSfile: urihelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-01-11 13:10:57 $
*
* 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 SVTOOLS_URIHELPER_HXX
#define SVTOOLS_URIHELPER_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_TEXTENC_H
#include <rtl/textenc.h>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
namespace com { namespace sun { namespace star {
namespace uno { class XComponentContext; }
namespace uri { class XUriReference; }
} } }
namespace rtl { class OUString; }
class ByteString;
class CharClass;
class UniString;
//============================================================================
namespace URIHelper {
UniString
SmartRel2Abs(INetURLObject const & rTheBaseURIRef,
ByteString const & rTheRelURIRef,
Link const & rMaybeFileHdl = Link(),
bool bCheckFileExists = true,
bool bIgnoreFragment = false,
INetURLObject::EncodeMechanism eEncodeMechanism
= INetURLObject::WAS_ENCODED,
INetURLObject::DecodeMechanism eDecodeMechanism
= INetURLObject::DECODE_TO_IURI,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8,
bool bRelativeNonURIs = false,
INetURLObject::FSysStyle eStyle = INetURLObject::FSYS_DETECT);
UniString
SmartRel2Abs(INetURLObject const & rTheBaseURIRef,
UniString const & rTheRelURIRef,
Link const & rMaybeFileHdl = Link(),
bool bCheckFileExists = true,
bool bIgnoreFragment = false,
INetURLObject::EncodeMechanism eEncodeMechanism
= INetURLObject::WAS_ENCODED,
INetURLObject::DecodeMechanism eDecodeMechanism
= INetURLObject::DECODE_TO_IURI,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8,
bool bRelativeNonURIs = false,
INetURLObject::FSysStyle eStyle = INetURLObject::FSYS_DETECT);
//============================================================================
void SetMaybeFileHdl(Link const & rTheMaybeFileHdl);
//============================================================================
Link GetMaybeFileHdl();
/**
Converts a URI reference to a relative one, ignoring certain differences (for
example, treating file URLs for case-ignoring file systems
case-insensitively).
@param context a component context; must not be null
@param baseUriReference a base URI reference
@param uriReference a URI reference
@return a URI reference representing the given uriReference relative to the
given baseUriReference; if the given baseUriReference is not an absolute,
hierarchical URI reference, or the given uriReference is not a valid URI
reference, null is returned
@exception std::bad_alloc if an out-of-memory condition occurs
@exception com::sun::star::uno::RuntimeException if any error occurs
*/
com::sun::star::uno::Reference< com::sun::star::uri::XUriReference >
normalizedMakeRelative(
com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >
const & context,
rtl::OUString const & baseUriReference, rtl::OUString const & uriReference);
/**
A variant of normalizedMakeRelative with a simplified interface.
Internally calls normalizedMakeRelative with the default component context.
@param baseUriReference a base URI reference, passed to
normalizedMakeRelative
@param uriReference a URI reference, passed to normalizedMakeRelative
@return if the XUriReference returnd by normalizedMakeRelative is empty,
uriReference is returned unmodified; otherwise, the result of calling
XUriReference::getUriReference on the XUriReference returnd by
normalizedMakeRelative is returned
@exception std::bad_alloc if an out-of-memory condition occurs
@exception com::sun::star::uno::RuntimeException if any error occurs
@deprecated
No code should rely on the default component context.
*/
rtl::OUString simpleNormalizedMakeRelative(
rtl::OUString const & baseUriReference, rtl::OUString const & uriReference);
//============================================================================
UniString
FindFirstURLInText(UniString const & rText,
xub_StrLen & rBegin,
xub_StrLen & rEnd,
CharClass const & rCharClass,
INetURLObject::EncodeMechanism eMechanism
= INetURLObject::WAS_ENCODED,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8,
INetURLObject::FSysStyle eStyle
= INetURLObject::FSYS_DETECT);
//============================================================================
/** Remove any password component from both absolute and relative URLs.
@ATT The current implementation will not remove a password from a
relative URL that has an authority component (e.g., the password is not
removed from the relative ftp URL <//user:password@domain/path>). But
since our functions to translate between absolute and relative URLs never
produce relative URLs with authority components, this is no real problem.
@ATT For relative URLs (or anything not recognized as an absolute URI),
the current implementation will return the input unmodified, not applying
any translations implied by the encode/decode parameters.
@param rURI An absolute or relative URI reference.
@param eEncodeMechanism See the general discussion for INetURLObject set-
methods.
@param eDecodeMechanism See the general discussion for INetURLObject get-
methods.
@param eCharset See the general discussion for INetURLObject get- and
set-methods.
@return The input URI with any password component removed.
*/
UniString
removePassword(UniString const & rURI,
INetURLObject::EncodeMechanism eEncodeMechanism
= INetURLObject::WAS_ENCODED,
INetURLObject::DecodeMechanism eDecodeMechanism
= INetURLObject::DECODE_TO_IURI,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8);
//============================================================================
/** Query the notational conventions used in the file system provided by some
file content provider.
@param rFileUrl This file URL determines which file content provider is
used to query the desired information. (The UCB's usual mapping from URLs
to content providers is used.)
@param bAddConvenienceStyles If true, the return value contains not only
the style bit corresponding to the queried content provider's conventions,
but may also contain additional style bits that make using this function
more convenient in certain situations. Currently, the effect is that
FSYS_UNX is extended with FSYS_VOS, and both FSYS_DOS and FSYS_MAC are
extended with FSYS_VOS and FSYS_UNX (i.e., the---unambiguous---detection
of VOS style and Unix style file system paths is always enabled); also, in
case the content provider's conventions cannot be determined, FSYS_DETECT
is returned instead of FSysStyle(0).
@return The style bit corresponding to the queried content provider's
conventions, or FSysStyle(0) if these cannot be determined.
*/
INetURLObject::FSysStyle queryFSysStyle(UniString const & rFileUrl,
bool bAddConvenienceStyles = true)
throw (com::sun::star::uno::RuntimeException);
}
#endif // SVTOOLS_URIHELPER_HXX
INTEGRATION: CWS fwkpostbeta1 (1.3.42); FILE MERGED
2005/02/14 09:42:39 sb 1.3.42.1: #119209# Added documentation about potential problems.
/*************************************************************************
*
* $RCSfile: urihelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-03-21 13:30:20 $
*
* 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 SVTOOLS_URIHELPER_HXX
#define SVTOOLS_URIHELPER_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_TEXTENC_H
#include <rtl/textenc.h>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
namespace com { namespace sun { namespace star {
namespace uno { class XComponentContext; }
namespace uri { class XUriReference; }
} } }
namespace rtl { class OUString; }
class ByteString;
class CharClass;
class UniString;
//============================================================================
namespace URIHelper {
/**
@ATT
Calling this function with defaulted arguments rMaybeFileHdl = Link() and
bCheckFileExists = true often leads to results that are not intended:
Whenever the given rTheBaseURIRef is a file URL, the given rTheRelURIRef is
relative, and rTheRelURIRef could also be smart-parsed as a non-file URL
(e.g., the relative URL "foo/bar" can be smart-parsed as "http://foo/bar"),
then SmartRel2Abs called with rMaybeFileHdl = Link() and bCheckFileExists =
true returns the non-file URL interpretation. To avoid this, either pass
some non-null rMaybeFileHdl if you want to check generated file URLs for
existence (see URIHelper::GetMaybeFileHdl), or use bCheckFileExists = false
if you want to generate file URLs without checking for their existence.
*/
UniString
SmartRel2Abs(INetURLObject const & rTheBaseURIRef,
ByteString const & rTheRelURIRef,
Link const & rMaybeFileHdl = Link(),
bool bCheckFileExists = true,
bool bIgnoreFragment = false,
INetURLObject::EncodeMechanism eEncodeMechanism
= INetURLObject::WAS_ENCODED,
INetURLObject::DecodeMechanism eDecodeMechanism
= INetURLObject::DECODE_TO_IURI,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8,
bool bRelativeNonURIs = false,
INetURLObject::FSysStyle eStyle = INetURLObject::FSYS_DETECT);
/**
@ATT
Calling this function with defaulted arguments rMaybeFileHdl = Link() and
bCheckFileExists = true often leads to results that are not intended:
Whenever the given rTheBaseURIRef is a file URL, the given rTheRelURIRef is
relative, and rTheRelURIRef could also be smart-parsed as a non-file URL
(e.g., the relative URL "foo/bar" can be smart-parsed as "http://foo/bar"),
then SmartRel2Abs called with rMaybeFileHdl = Link() and bCheckFileExists =
true returns the non-file URL interpretation. To avoid this, either pass
some non-null rMaybeFileHdl if you want to check generated file URLs for
existence (see URIHelper::GetMaybeFileHdl), or use bCheckFileExists = false
if you want to generate file URLs without checking for their existence.
*/
UniString
SmartRel2Abs(INetURLObject const & rTheBaseURIRef,
UniString const & rTheRelURIRef,
Link const & rMaybeFileHdl = Link(),
bool bCheckFileExists = true,
bool bIgnoreFragment = false,
INetURLObject::EncodeMechanism eEncodeMechanism
= INetURLObject::WAS_ENCODED,
INetURLObject::DecodeMechanism eDecodeMechanism
= INetURLObject::DECODE_TO_IURI,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8,
bool bRelativeNonURIs = false,
INetURLObject::FSysStyle eStyle = INetURLObject::FSYS_DETECT);
//============================================================================
void SetMaybeFileHdl(Link const & rTheMaybeFileHdl);
//============================================================================
Link GetMaybeFileHdl();
/**
Converts a URI reference to a relative one, ignoring certain differences (for
example, treating file URLs for case-ignoring file systems
case-insensitively).
@param context a component context; must not be null
@param baseUriReference a base URI reference
@param uriReference a URI reference
@return a URI reference representing the given uriReference relative to the
given baseUriReference; if the given baseUriReference is not an absolute,
hierarchical URI reference, or the given uriReference is not a valid URI
reference, null is returned
@exception std::bad_alloc if an out-of-memory condition occurs
@exception com::sun::star::uno::RuntimeException if any error occurs
*/
com::sun::star::uno::Reference< com::sun::star::uri::XUriReference >
normalizedMakeRelative(
com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >
const & context,
rtl::OUString const & baseUriReference, rtl::OUString const & uriReference);
/**
A variant of normalizedMakeRelative with a simplified interface.
Internally calls normalizedMakeRelative with the default component context.
@param baseUriReference a base URI reference, passed to
normalizedMakeRelative
@param uriReference a URI reference, passed to normalizedMakeRelative
@return if the XUriReference returnd by normalizedMakeRelative is empty,
uriReference is returned unmodified; otherwise, the result of calling
XUriReference::getUriReference on the XUriReference returnd by
normalizedMakeRelative is returned
@exception std::bad_alloc if an out-of-memory condition occurs
@exception com::sun::star::uno::RuntimeException if any error occurs
@deprecated
No code should rely on the default component context.
*/
rtl::OUString simpleNormalizedMakeRelative(
rtl::OUString const & baseUriReference, rtl::OUString const & uriReference);
//============================================================================
UniString
FindFirstURLInText(UniString const & rText,
xub_StrLen & rBegin,
xub_StrLen & rEnd,
CharClass const & rCharClass,
INetURLObject::EncodeMechanism eMechanism
= INetURLObject::WAS_ENCODED,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8,
INetURLObject::FSysStyle eStyle
= INetURLObject::FSYS_DETECT);
//============================================================================
/** Remove any password component from both absolute and relative URLs.
@ATT The current implementation will not remove a password from a
relative URL that has an authority component (e.g., the password is not
removed from the relative ftp URL <//user:password@domain/path>). But
since our functions to translate between absolute and relative URLs never
produce relative URLs with authority components, this is no real problem.
@ATT For relative URLs (or anything not recognized as an absolute URI),
the current implementation will return the input unmodified, not applying
any translations implied by the encode/decode parameters.
@param rURI An absolute or relative URI reference.
@param eEncodeMechanism See the general discussion for INetURLObject set-
methods.
@param eDecodeMechanism See the general discussion for INetURLObject get-
methods.
@param eCharset See the general discussion for INetURLObject get- and
set-methods.
@return The input URI with any password component removed.
*/
UniString
removePassword(UniString const & rURI,
INetURLObject::EncodeMechanism eEncodeMechanism
= INetURLObject::WAS_ENCODED,
INetURLObject::DecodeMechanism eDecodeMechanism
= INetURLObject::DECODE_TO_IURI,
rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8);
//============================================================================
/** Query the notational conventions used in the file system provided by some
file content provider.
@param rFileUrl This file URL determines which file content provider is
used to query the desired information. (The UCB's usual mapping from URLs
to content providers is used.)
@param bAddConvenienceStyles If true, the return value contains not only
the style bit corresponding to the queried content provider's conventions,
but may also contain additional style bits that make using this function
more convenient in certain situations. Currently, the effect is that
FSYS_UNX is extended with FSYS_VOS, and both FSYS_DOS and FSYS_MAC are
extended with FSYS_VOS and FSYS_UNX (i.e., the---unambiguous---detection
of VOS style and Unix style file system paths is always enabled); also, in
case the content provider's conventions cannot be determined, FSYS_DETECT
is returned instead of FSysStyle(0).
@return The style bit corresponding to the queried content provider's
conventions, or FSysStyle(0) if these cannot be determined.
*/
INetURLObject::FSysStyle queryFSysStyle(UniString const & rFileUrl,
bool bAddConvenienceStyles = true)
throw (com::sun::star::uno::RuntimeException);
}
#endif // SVTOOLS_URIHELPER_HXX
|
#include "xshcolumnviewer.h"
// Tnz6 includes
#include "xsheetviewer.h"
#include "tapp.h"
#include "menubarcommandids.h"
#include "columnselection.h"
#include "xsheetdragtool.h"
#include "tapp.h"
// TnzTools includes
#include "tools/toolhandle.h"
#include "tools/toolcommandids.h"
// TnzQt includes
#include "toonzqt/tselectionhandle.h"
#include "toonzqt/gutil.h"
#include "toonzqt/icongenerator.h"
#include "toonzqt/intfield.h"
// TnzLib includes
#include "toonz/tscenehandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/stage2.h"
#include "toonz/txshpalettecolumn.h"
#include "toonz/txsheet.h"
#include "toonz/toonzscene.h"
#include "toonz/txshcell.h"
#include "toonz/tstageobject.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/sceneproperties.h"
#include "toonz/txshzeraryfxcolumn.h"
#include "toonz/tcolumnfx.h"
#include "toonz/txshsoundcolumn.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/columnfan.h"
#include "toonz/tstageobjectcmd.h"
#include "toonz/fxcommand.h"
#include "toonz/txshleveltypes.h"
#include "toonz/levelproperties.h"
#include "toonz/preferences.h"
#include "toonz/childstack.h"
#include "toonz/txshlevelcolumn.h"
#include "toonz/tfxhandle.h"
// TnzCore includes
#include "tconvert.h"
#include <QMainWindow>
#include <QPainter>
#include <QMouseEvent>
#include <QMenu>
#include <QToolTip>
#include <QTimer>
#include <QLabel>
//=============================================================================
namespace
{
const QSet<TXshSimpleLevel *> getLevels(TXshColumn *column)
{
QSet<TXshSimpleLevel *> levels;
TXshCellColumn *cellColumn = column->getCellColumn();
if (cellColumn) {
int i, r0, r1;
cellColumn->getRange(r0, r1);
for (i = r0; i <= r1; i++) {
TXshCell cell = cellColumn->getCell(i);
TXshSimpleLevel *sl = cell.getSimpleLevel();
if (sl)
levels.insert(sl);
}
}
return levels;
}
bool containsRasterLevel(TColumnSelection *selection)
{
if (!selection || selection->isEmpty())
return false;
set<int> indexes = selection->getIndices();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
set<int>::iterator it;
for (it = indexes.begin(); it != indexes.end(); it++) {
TXshColumn *col = xsh->getColumn(*it);
if (!col || col->getColumnType() != TXshColumn::eLevelType)
continue;
TXshCellColumn *cellCol = col->getCellColumn();
if (!cellCol)
continue;
int i;
for (i = 0; i < cellCol->getMaxFrame() + 1; i++) {
TXshCell cell = cellCol->getCell(i);
if (cell.isEmpty())
continue;
TXshSimpleLevel *level = cell.getSimpleLevel();
if (!level || level->getChildLevel() || level->getProperties()->getDirtyFlag())
continue;
int type = level->getType();
if (type == OVL_XSHLEVEL || type == TZP_XSHLEVEL)
return true;
}
}
return false;
}
}
//-----------------------------------------------------------------------------
namespace XsheetGUI
{
//-----------------------------------------------------------------------------
void getVolumeCursorRect(
QRect &out,
double volume,
const QPoint &origin)
{
int ly = 60;
int v = tcrop(0, ly, (int)(volume * ly));
out.setX(origin.x() + 11);
out.setY(origin.y() + 60 - v);
out.setWidth(8);
out.setHeight(8);
}
//=============================================================================
// MotionPathMenu
//-----------------------------------------------------------------------------
#if QT_VERSION >= 0x050500
MotionPathMenu::MotionPathMenu(QWidget *parent, Qt::WindowFlags flags)
#else
MotionPathMenu::MotionPathMenu(QWidget *parent, Qt::WFlags flags)
#endif
: QWidget(parent, flags), m_mDeleteRect(QRect(0, 0, ColumnWidth - 13, RowHeight)), m_mNormalRect(QRect(0, RowHeight, ColumnWidth - 13, RowHeight)), m_mRotateRect(QRect(0, RowHeight * 2, ColumnWidth - 13, RowHeight)), m_pos(QPoint())
{
setMouseTracking(true);
setFixedSize(ColumnWidth - 12, 3 * RowHeight);
setWindowFlags(Qt::FramelessWindowHint);
}
//-----------------------------------------------------------------------------
MotionPathMenu::~MotionPathMenu()
{
}
//-----------------------------------------------------------------------------
void MotionPathMenu::paintEvent(QPaintEvent *)
{
QPainter p(this);
static QPixmap motionPixmap = QPixmap(":Resources/motionpath.svg");
static QPixmap motionDeletePixmap = QPixmap(":Resources/motionpath_delete.svg");
static QPixmap motionRotatePixmap = QPixmap(":Resources/motionpath_rot.svg");
QColor overColor = QColor(49, 106, 197);
p.fillRect(m_mDeleteRect, QBrush((m_mDeleteRect.contains(m_pos)) ? overColor : grey225));
p.drawPixmap(m_mDeleteRect, motionDeletePixmap);
p.fillRect(m_mNormalRect, QBrush((m_mNormalRect.contains(m_pos)) ? overColor : grey225));
p.drawPixmap(m_mNormalRect, motionPixmap);
p.fillRect(m_mRotateRect, QBrush((m_mRotateRect.contains(m_pos)) ? overColor : grey225));
p.drawPixmap(m_mRotateRect, motionRotatePixmap);
}
//-----------------------------------------------------------------------------
void MotionPathMenu::mousePressEvent(QMouseEvent *event)
{
m_pos = event->pos();
TStageObjectId objectId = TApp::instance()->getCurrentObject()->getObjectId();
TStageObject *pegbar = TApp::instance()->getCurrentXsheet()->getXsheet()->getStageObject(objectId);
if (m_mDeleteRect.contains(m_pos))
pegbar->setStatus(TStageObject::XY);
else if (m_mNormalRect.contains(m_pos)) {
pegbar->setStatus(TStageObject::PATH);
TApp::instance()->getCurrentObject()->setIsSpline(true);
} else if (m_mRotateRect.contains(m_pos)) {
pegbar->setStatus(TStageObject::PATH_AIM);
TApp::instance()->getCurrentObject()->setIsSpline(true);
}
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
hide();
}
//-----------------------------------------------------------------------------
void MotionPathMenu::mouseMoveEvent(QMouseEvent *event)
{
m_pos = event->pos();
update();
}
//-----------------------------------------------------------------------------
void MotionPathMenu::mouseReleaseEvent(QMouseEvent *event)
{
}
//-----------------------------------------------------------------------------
void MotionPathMenu::leaveEvent(QEvent *event)
{
hide();
}
//=============================================================================
// ChangeObjectWidget
//-----------------------------------------------------------------------------
ChangeObjectWidget::ChangeObjectWidget(QWidget *parent)
: QListWidget(parent), m_width(40)
{
setMouseTracking(true);
setObjectName("XshColumnChangeObjectWidget");
setAutoFillBackground(true);
}
//-----------------------------------------------------------------------------
ChangeObjectWidget::~ChangeObjectWidget()
{
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::show(const QPoint &pos)
{
refresh();
int itemNumber = count();
if (itemNumber > 10) {
itemNumber = 10;
m_width += 15;
}
setGeometry(pos.x(), pos.y(), m_width, itemNumber * 16 + 2);
QListWidget::show();
setFocus();
scrollToItem(currentItem());
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::setObjectHandle(TObjectHandle *objectHandle)
{
m_objectHandle = objectHandle;
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::setXsheetHandle(TXsheetHandle *xsheetHandle)
{
m_xsheetHandle = xsheetHandle;
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::mouseMoveEvent(QMouseEvent *event)
{
QListWidgetItem *currentWidgetItem = itemAt(event->pos());
if (!currentWidgetItem)
return;
clearSelection();
currentWidgetItem->setSelected(true);
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::focusOutEvent(QFocusEvent *e)
{
if (!isVisible())
return;
hide();
parentWidget()->update();
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::selectCurrent(const QString &text)
{
QList<QListWidgetItem *> itemList = findItems(text, Qt::MatchExactly);
clearSelection();
if (itemList.size() < 1)
return;
QListWidgetItem *currentWidgetItem = itemList.at(0);
setCurrentItem(currentWidgetItem);
}
//=============================================================================
// ChangeObjectParent
//-----------------------------------------------------------------------------
ChangeObjectParent::ChangeObjectParent(QWidget *parent)
: ChangeObjectWidget(parent)
{
bool ret = connect(this, SIGNAL(currentTextChanged(const QString &)), this, SLOT(onTextChanged(const QString &)));
assert(ret);
}
//-----------------------------------------------------------------------------
ChangeObjectParent::~ChangeObjectParent()
{
}
//-----------------------------------------------------------------------------
void ChangeObjectParent::refresh()
{
clear();
assert(m_xsheetHandle);
assert(m_objectHandle);
TXsheet *xsh = m_xsheetHandle->getXsheet();
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
TStageObjectId parentId = xsh->getStageObject(currentObjectId)->getParent();
TStageObjectTree *tree = xsh->getStageObjectTree();
int objectCount = tree->getStageObjectCount();
QString text;
QList<QString> pegbarList;
QList<QString> columnList;
int maxTextLength = 0;
int i;
for (i = 0; i < objectCount; i++) {
TStageObjectId id = tree->getStageObject(i)->getId();
int index = id.getIndex();
QString indexStr = QString(toString(id.getIndex() + 1).c_str());
QString newText;
if (id == parentId) {
if (parentId.isPegbar())
text = QString("Peg ") + indexStr;
else if (parentId.isColumn())
text = QString("Col ") + indexStr;
}
if (id == currentObjectId)
continue;
if (id.isPegbar()) {
newText = QString("Peg ") + indexStr;
pegbarList.append(newText);
}
if (id.isColumn() && (!xsh->isColumnEmpty(index) || index < 2)) {
newText = QString("Col ") + indexStr;
columnList.append(newText);
}
if (newText.length() > maxTextLength)
maxTextLength = newText.length();
}
for (i = 0; i < columnList.size(); i++)
addItem(columnList.at(i));
for (i = 0; i < pegbarList.size(); i++)
addItem(pegbarList.at(i));
m_width = maxTextLength * XSHEET_FONT_SIZE + 2;
selectCurrent(text);
}
//-----------------------------------------------------------------------------
void ChangeObjectParent::onTextChanged(const QString &text)
{
assert(m_xsheetHandle);
assert(m_objectHandle);
if (text.isEmpty()) {
hide();
return;
}
bool isPegbar = false;
if (text.startsWith("Peg"))
isPegbar = true;
QString number = text;
number.remove(0, 4);
int index = number.toInt() - 1;
if (index < 0) {
hide();
return;
}
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
TStageObjectId newStageObjectId;
if (isPegbar)
newStageObjectId = TStageObjectId::PegbarId(index);
else
newStageObjectId = TStageObjectId::ColumnId(index);
if (newStageObjectId == currentObjectId)
return;
TStageObject *stageObject = m_xsheetHandle->getXsheet()->getStageObject(currentObjectId);
TStageObjectCmd::setParent(currentObjectId, newStageObjectId, "B", m_xsheetHandle);
hide();
m_objectHandle->notifyObjectIdChanged(false);
m_xsheetHandle->notifyXsheetChanged();
}
//=============================================================================
// ChangeObjectHandle
//-----------------------------------------------------------------------------
ChangeObjectHandle::ChangeObjectHandle(QWidget *parent)
: ChangeObjectWidget(parent)
{
bool ret = connect(this, SIGNAL(currentTextChanged(const QString &)), this, SLOT(onTextChanged(const QString &)));
assert(ret);
}
//-----------------------------------------------------------------------------
ChangeObjectHandle::~ChangeObjectHandle()
{
}
//-----------------------------------------------------------------------------
void ChangeObjectHandle::refresh()
{
clear();
assert(m_xsheetHandle);
assert(m_objectHandle);
TXsheet *xsh = m_xsheetHandle->getXsheet();
assert(xsh);
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
TStageObject *stageObject = xsh->getStageObject(currentObjectId);
m_width = 28;
int i;
QString str;
if (stageObject->getParent().isColumn()) {
for (i = 0; i < 20; i++)
addItem(str.number(20 - i));
}
for (i = 0; i < 26; i++)
addItem(QString(char('A' + i)));
std::string handle = stageObject->getParentHandle();
if (handle[0] == 'H' && handle.length() > 1)
handle = handle.substr(1);
selectCurrent(QString::fromStdString(handle));
}
//-----------------------------------------------------------------------------
void ChangeObjectHandle::onTextChanged(const QString &text)
{
assert(m_xsheetHandle);
assert(m_objectHandle);
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
QString handle = text;
if (text.toInt() != 0)
handle = QString("H") + handle;
if (handle.isEmpty())
return;
std::vector<TStageObjectId> ids;
ids.push_back(currentObjectId);
TStageObjectCmd::setParentHandle(ids, handle.toStdString(), m_xsheetHandle);
hide();
m_objectHandle->notifyObjectIdChanged(false);
m_xsheetHandle->notifyXsheetChanged();
}
//=============================================================================
// RenameColumnField
//-----------------------------------------------------------------------------
RenameColumnField::RenameColumnField(QWidget *parent, XsheetViewer *viewer)
: QLineEdit(parent), m_col(-1)
{
setFixedSize(XsheetGUI::ColumnWidth + 3, XsheetGUI::RowHeight + 4);
connect(this, SIGNAL(returnPressed()), SLOT(renameColumn()));
}
//-----------------------------------------------------------------------------
void RenameColumnField::show(QPoint pos, int col)
{
move(pos);
static QFont font("Helvetica", XSHEET_FONT_SIZE, QFont::Normal);
setFont(font);
m_col = col;
TXsheet *xsh = m_xsheetHandle->getXsheet();
std::string name = xsh->getStageObject(TStageObjectId::ColumnId(col))->getName();
TXshColumn *column = xsh->getColumn(col);
TXshZeraryFxColumn *zColumn = dynamic_cast<TXshZeraryFxColumn *>(column);
if (zColumn)
name = toString(zColumn->getZeraryColumnFx()->getZeraryFx()->getName());
setText(QString(name.c_str()));
selectAll();
QWidget::show();
raise();
setFocus();
}
//-----------------------------------------------------------------------------
void RenameColumnField::renameColumn()
{
std::string newName = text().toStdString();
TStageObjectId columnId = TStageObjectId::ColumnId(m_col);
TXshColumn *column = m_xsheetHandle->getXsheet()->getColumn(columnId.getIndex());
TXshZeraryFxColumn *zColumn = dynamic_cast<TXshZeraryFxColumn *>(column);
if (zColumn)
TFxCommand::renameFx(zColumn->getZeraryColumnFx(), toWideString(newName), m_xsheetHandle);
else
TStageObjectCmd::rename(columnId, newName, m_xsheetHandle);
m_xsheetHandle->notifyXsheetChanged();
m_col = -1;
setText("");
hide();
}
//-----------------------------------------------------------------------------
void RenameColumnField::focusOutEvent(QFocusEvent *e)
{
std::wstring newName = text().toStdWString();
if (!newName.empty())
renameColumn();
else
hide();
QLineEdit::focusOutEvent(e);
}
//=============================================================================
// ColumnArea
//-----------------------------------------------------------------------------
#if QT_VERSION >= 0x050500
ColumnArea::ColumnArea(XsheetViewer *parent, Qt::WindowFlags flags)
#else
ColumnArea::ColumnArea(XsheetViewer *parent, Qt::WFlags flags)
#endif
: QWidget(parent, flags), m_viewer(parent), m_indexBox(0, 3, ColumnWidth - RowHeight * 3 - 1, RowHeight), m_tabBox(ColumnWidth - RowHeight * 3 - 1, 3, RowHeight * 3, RowHeight + 1), m_nameBox(0, RowHeight + 3, ColumnWidth, RowHeight), m_linkBox(0, RowHeight * 7 + 3, 12, RowHeight), m_pos(-1, -1), m_tooltip(tr("")), m_col(-1), m_columnTransparencyPopup(0), m_transparencyPopupTimer(0), m_prevViewBox(10, 6, ColumnWidth - 12, RowHeight - 3), m_tableViewBox(10, RowHeight + 6, ColumnWidth - 12, RowHeight - 3), m_lockBox(9, RowHeight + 6, RowHeight - 4, RowHeight - 4), m_isPanning(false)
{
TXsheetHandle *xsheetHandle = TApp::instance()->getCurrentXsheet();
#ifndef LINETEST
TObjectHandle *objectHandle = TApp::instance()->getCurrentObject();
m_changeObjectParent = new ChangeObjectParent(0);
m_changeObjectParent->setObjectHandle(objectHandle);
m_changeObjectParent->setXsheetHandle(xsheetHandle);
m_changeObjectParent->hide();
m_changeObjectHandle = new ChangeObjectHandle(0);
m_changeObjectHandle->setObjectHandle(objectHandle);
m_changeObjectHandle->setXsheetHandle(xsheetHandle);
m_changeObjectHandle->hide();
#else
m_motionPathMenu = new MotionPathMenu(0);
#endif
m_renameColumnField = new RenameColumnField(this, m_viewer);
m_renameColumnField->setXsheetHandle(xsheetHandle);
m_renameColumnField->hide();
QActionGroup *actionGroup = new QActionGroup(this);
m_subsampling1 = new QAction(tr("&Subsampling 1"), actionGroup);
m_subsampling2 = new QAction(tr("&Subsampling 2"), actionGroup);
m_subsampling3 = new QAction(tr("&Subsampling 3"), actionGroup);
m_subsampling4 = new QAction(tr("&Subsampling 4"), actionGroup);
actionGroup->addAction(m_subsampling1);
actionGroup->addAction(m_subsampling2);
actionGroup->addAction(m_subsampling3);
actionGroup->addAction(m_subsampling4);
connect(actionGroup, SIGNAL(triggered(QAction *)), this, SLOT(onSubSampling(QAction *)));
setMouseTracking(true);
}
//-----------------------------------------------------------------------------
ColumnArea::~ColumnArea()
{
}
//-----------------------------------------------------------------------------
DragTool *ColumnArea::getDragTool() const { return m_viewer->getDragTool(); }
void ColumnArea::setDragTool(DragTool *dragTool) { m_viewer->setDragTool(dragTool); }
//-----------------------------------------------------------------------------
void ColumnArea::drawLevelColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
// Preparing painter
#ifdef _WIN32
QFont font("Arial", XSHEET_FONT_SIZE, QFont::Normal);
#else
QFont font("Helvetica", XSHEET_FONT_SIZE, QFont::Normal);
#endif
p.setFont(font);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
// Retrieve reference coordinates
int currentColumnIndex = m_viewer->getCurrentColumn();
int x = m_viewer->columnToX(col);
QRect rect(x, 0, ColumnWidth, height());
TApp *app = TApp::instance();
TXsheet *xsh = m_viewer->getXsheet();
TStageObjectId columnId = m_viewer->getObjectId(col);
TStageObjectId currentColumnId = app->getCurrentObject()->getObjectId();
TStageObjectId parentId = xsh->getStageObjectParent(columnId);
TStageObject *columnObject = xsh->getStageObject(columnId);
// Build column name
std::string name(columnObject->getName());
if (col < 0)
name = std::string("Camera");
// Retrieve column properties
bool isEmpty = false;
if (col >= 0) // Verifico se la colonna e' vuota
isEmpty = xsh->isColumnEmpty(col);
bool isEditingSpline = app->getCurrentObject()->isSpline();
//check if the column is reference
TXshColumn *column = col >= 0 ? xsh->getColumn(col) : 0;
enum { Normal,
Reference,
Control } usage = Reference;
if (column) {
if (column->isControl())
usage = Control;
if (column->isRendered() || column->getMeshColumn())
usage = Normal;
}
bool isLocked = column != 0 && column->isLocked();
//check if the column is current
bool isCurrent = false;
if (currentColumnId == TStageObjectId::CameraId(0)) //CAMERA
isCurrent = col == -1;
else
isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col) && !isEditingSpline;
bool isCameraSelected = col == -1 && isCurrent && !isEditingSpline;
// Draw column
QPoint orig = rect.topLeft();
QPoint columnNamePos = orig + QPoint(12, RowHeight);
QPoint pegbarNamePos = orig + QPoint(12, RowHeight * 3 + 48);
QPoint handleNamePos = orig + QPoint(ColumnWidth - 10 - p.fontMetrics().width('B'), RowHeight * 3 + 48);
int x0 = rect.x();
int x1 = x0 + rect.width() - 1;
int y0 = rect.y();
int y1 = y0 + rect.height() - 1;
//fill base color
if (isEmpty || col < 0) {
p.fillRect(rect, m_viewer->getEmptyColumnHeadColor());
p.setPen(Qt::black);
p.drawLine(x0, y0, x0, y1);
p.setPen(Qt::white);
p.drawLine(x1, y0, x1, y1);
} else {
QColor columnColor, sideColor;
if (usage == Reference) {
columnColor = m_viewer->getReferenceColumnColor();
sideColor = m_viewer->getReferenceColumnBorderColor();
} else
m_viewer->getColumnColor(columnColor, sideColor, col, xsh);
p.fillRect(rect, sideColor);
p.fillRect(rect.adjusted(7, 3, 0, 0), columnColor);
// column handle
QRect sideBar(x0, y0, 7, rect.height() - 5);
if (sideBar.contains(m_pos)) {
p.fillRect(sideBar, Qt::yellow);
}
}
QColor pastelizer(m_viewer->getColumnHeadPastelizer());
pastelizer.setAlpha(50);
QColor colorSelection(m_viewer->getSelectedColumnHead());
colorSelection.setAlpha(170);
p.fillRect(rect, (isSelected || isCameraSelected) ? colorSelection : pastelizer);
int prevViewImgHeight = RowHeight - 5;
int prevViewImgWidth = prevViewImgHeight * 5 / 4;
QRect prevViewRect = m_prevViewBox.translated(orig);
QRect prevViewImgRect(prevViewRect.right() - prevViewImgWidth - 1, 7, prevViewImgWidth, prevViewImgHeight);
static QPixmap prevViewPix = QPixmap(":Resources/x_prev_eye.png");
QRect tableViewRect = m_tableViewBox.translated(orig);
QRect tableViewImgRect = prevViewImgRect.translated(0, RowHeight);
static QPixmap tableViewPix = QPixmap(":Resources/x_table_view.png");
static QPixmap tableTranspViewPix = QPixmap(":Resources/x_table_view_transp.png");
QRect lockModeRect = m_lockBox.translated(orig);
static QPixmap lockModePix = QPixmap(":Resources/x_lock.png");
if (col >= 0 && !isEmpty) {
// preview visible toggle
if (column->isPreviewVisible()) {
p.fillRect(prevViewRect, PreviewVisibleColor);
p.drawPixmap(prevViewImgRect, prevViewPix);
}
// camstand visible toggle
if (column->isCamstandVisible()) {
p.fillRect(tableViewRect, CamStandVisibleColor);
p.drawPixmap(tableViewImgRect, column->getOpacity() < 255 ? tableTranspViewPix : tableViewPix);
}
// lock button
p.setPen(Qt::gray);
p.setBrush(QColor(255, 255, 255, 128));
p.drawRect(lockModeRect);
lockModeRect.adjust(1, 1, -1, -1);
if (isLocked) {
p.drawPixmap(lockModeRect, lockModePix);
}
}
// column number
if (!isEmpty)
p.setPen((isCurrent) ? Qt::red : Qt::black);
else
p.setPen((isCurrent) ? m_viewer->getSelectedColumnTextColor() : m_viewer->getTextColor());
p.drawText(columnNamePos, QString(name.c_str()));
p.setPen(m_viewer->getTextColor());
if (col >= 0 && !isEmpty) {
// pegbar name
p.drawText(pegbarNamePos, QString(parentId.toString().c_str()));
std::string handle = xsh->getStageObject(columnId)->getParentHandle();
if (handle[0] == 'H' && handle.length() > 1)
handle = handle.substr(1);
if (parentId != TStageObjectId::TableId)
p.drawText(handleNamePos, QString::fromStdString(handle));
//thumbnail
QRect thumbnailRect(orig.x() + 9, orig.y() + RowHeight * 2 + 7, ColumnWidth - 11, 42);
// for zerary fx, display fxId here instead of thumbnail
TXshZeraryFxColumn *zColumn = dynamic_cast<TXshZeraryFxColumn *>(column);
if (zColumn) {
QFont font("Verdana", 8);
p.setFont(font);
TFx *fx = zColumn->getZeraryColumnFx()->getZeraryFx();
QString fxName = QString::fromStdWString(fx->getFxId());
p.drawText(thumbnailRect, Qt::TextWrapAnywhere | Qt::TextWordWrap, fxName);
} else {
TXshLevelColumn *levelColumn = column->getLevelColumn();
if (levelColumn &&
Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand &&
!levelColumn->isIconVisible()) {
//display nothing
} else {
QPixmap iconPixmap = getColumnIcon(col);
if (!iconPixmap.isNull()) {
p.drawPixmap(thumbnailRect, iconPixmap);
}
// notify that the column icon is already shown
if (levelColumn)
levelColumn->setIconVisible(true);
}
}
}
}
//-----------------------------------------------------------------------------
void ColumnArea::drawSoundColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
QFont font("Helvetica");
font.setPointSize(XSHEET_FONT_SIZE);
p.setFont(font);
int x = m_viewer->columnToX(col);
TXsheet *xsh = m_viewer->getXsheet();
TXshSoundColumn *sc = xsh->getColumn(col) ? xsh->getColumn(col)->getSoundColumn() : 0;
QRect rect(x, 0, ColumnWidth, height());
QPoint orig = rect.topLeft();
QPoint columnNamePos = orig + QPoint(12, RowHeight);
bool isEmpty = xsh->isColumnEmpty(col);
bool isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col);
bool isPrecSelected = col > 0 ? m_viewer->getColumnSelection()->isColumnSelected(col - 1) : false;
bool isActive = sc && sc->isPreviewVisible();
bool isLocked = sc && sc->isLocked();
bool isLeftBorderHighlighted = isSelected || isPrecSelected;
int x0 = rect.x();
int x1 = x0 + rect.width() - 1;
int y0 = rect.y();
int y1 = y0 + rect.height() - 1;
// base color
if (isEmpty || col < 0) {
p.fillRect(rect, EmptyColumnHeadColor);
p.setPen(Qt::black);
p.drawLine(x0, y0, x0, y1);
p.setPen(Qt::white);
p.drawLine(x1, y0, x1, y1);
} else {
QColor columnColor, sideColor;
m_viewer->getColumnColor(columnColor, sideColor, col, xsh);
p.fillRect(rect, sideColor);
p.fillRect(rect.adjusted(7, 3, 0, 0), columnColor);
// column handle
QRect sideBar(x0, y0, 7, rect.height() - 5);
if (sideBar.contains(m_pos)) {
p.fillRect(sideBar, Qt::yellow);
}
}
QColor pastelizer(m_viewer->getColumnHeadPastelizer());
p.fillRect(rect, (isSelected) ? ColorSelection : pastelizer);
int prevViewImgHeight = RowHeight - 5;
int prevViewImgWidth = prevViewImgHeight * 5 / 4;
QRect prevViewRect = m_prevViewBox.translated(orig);
QRect prevViewImgRect(prevViewRect.right() - prevViewImgWidth - 1, 7, prevViewImgWidth, prevViewImgHeight);
static QPixmap prevViewPix = QPixmap(":Resources/x_prev_eye.png");
QRect tableViewRect = m_tableViewBox.translated(orig);
QRect tableViewImgRect = prevViewImgRect.translated(0, RowHeight);
static QPixmap tableViewPix = QPixmap(":Resources/x_table_view.png");
static QPixmap tableTranspViewPix = QPixmap(":Resources/x_table_view_transp.png");
QRect lockModeRect = m_lockBox.translated(orig);
static QPixmap lockModePix = QPixmap(":Resources/x_lock.png");
if (col >= 0 && !isEmpty) {
// preview visible toggle
if (isActive) {
p.fillRect(prevViewRect, PreviewVisibleColor);
p.drawPixmap(prevViewImgRect, prevViewPix);
}
// camstand visible toggle
if (sc->isCamstandVisible()) {
p.fillRect(tableViewRect, CamStandVisibleColor);
p.drawPixmap(tableViewImgRect, tableViewPix);
}
// lock button
p.setPen(Qt::gray);
p.setBrush(QColor(255, 255, 255, 128));
p.drawRect(lockModeRect);
lockModeRect.adjust(1, 1, -1, -1);
if (isLocked) {
p.drawPixmap(lockModeRect, lockModePix);
}
}
// column number
p.setPen((isCurrent) ? Qt::red : Qt::black);
p.drawText(columnNamePos, QString(toString(col + 1).c_str()));
//Icona sound
if (sc->isPlaying()) {
static QPixmap soundActiveIcon = QPixmap(":Resources/sound_header_on.png");
p.drawPixmap(x + 29, 3 * RowHeight + 4, 40, 30, soundActiveIcon);
} else {
static QPixmap soundIcon = QPixmap(":Resources/sound_header_off.png");
p.drawPixmap(x + 29, 3 * RowHeight + 4, 40, 30, soundIcon);
}
QRect rr(rect.x() + 8, RowHeight * 2 + 3, rect.width() - 7, m_tabBox.y() - 3);
// suddivisioni slider
p.setPen(Qt::black);
int xa = rr.x() + 7, ya = rr.y() + 4;
int y = ya;
for (int i = 0; i <= 20; i++, y += 3)
if ((i % 10) == 0)
p.drawLine(xa - 3, y, xa, y);
else if (i & 1)
p.drawLine(xa, y, xa, y);
else
p.drawLine(xa - 2, y, xa, y);
// slider
int ly = 60;
xa += 5;
p.drawPoint(xa, ya);
p.drawPoint(xa, ya + ly);
p.drawLine(xa - 1, ya + 1, xa - 1, ya + ly - 1);
p.drawLine(xa + 1, ya + 1, xa + 1, ya + ly - 1);
// cursore
QRect cursorRect;
getVolumeCursorRect(
cursorRect, sc->getVolume(), rr.topLeft());
std::vector<QPointF> pts;
x = cursorRect.x();
y = cursorRect.y() + 4;
pts.push_back(QPointF(x, y));
pts.push_back(QPointF(x + 4.0, y + 4.0));
pts.push_back(QPointF(x + 8.0, y + 4.0));
pts.push_back(QPointF(x + 8.0, y - 4.0));
pts.push_back(QPointF(x + 4.0, y - 4.0));
drawPolygon(p, pts, true, m_viewer->getLightLineColor());
}
//-----------------------------------------------------------------------------
void ColumnArea::drawPaletteColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
#ifdef _WIN32
QFont font("Arial", XSHEET_FONT_SIZE, QFont::Normal);
#else
QFont font("Helvetica", XSHEET_FONT_SIZE, QFont::Normal);
#endif
p.setFont(font);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
int currentColumnIndex = m_viewer->getCurrentColumn();
int x = m_viewer->columnToX(col);
QRect rect(x, 0, ColumnWidth, height());
TApp *app = TApp::instance();
TXsheet *xsh = m_viewer->getXsheet();
TStageObjectId columnId = m_viewer->getObjectId(col);
TStageObjectId currentColumnId = app->getCurrentObject()->getObjectId();
TStageObjectId parentId = xsh->getStageObjectParent(columnId);
std::string name = xsh->getStageObject(columnId)->getName();
bool isEmpty = false;
if (col >= 0) // Verifico se la colonna e' vuota
isEmpty = xsh->isColumnEmpty(col);
bool isEditingSpline = app->getCurrentObject()->isSpline();
TXshColumn *column = col >= 0 ? xsh->getColumn(col) : 0;
enum { Normal,
Reference,
Control } usage = Reference;
if (column) { // Verifico se la colonna e' una mask
if (column->isControl())
usage = Control;
if (column->isRendered())
usage = Normal;
}
bool isLocked = column != 0 && column->isLocked();
bool isCurrent = false;
if (currentColumnId == TStageObjectId::CameraId(0)) //CAMERA
isCurrent = col == -1;
else
isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col) && !isEditingSpline;
bool isCameraSelected = col == -1 && isCurrent && !isEditingSpline;
QPoint orig = rect.topLeft();
QPoint columnNamePos = orig + QPoint(12, RowHeight);
QPoint pegbarNamePos = orig + QPoint(12, RowHeight * 3 + 48);
QPoint handleNamePos = orig + QPoint(ColumnWidth - 10 - p.fontMetrics().width('B'), RowHeight * 3 + 48);
int x0 = rect.x();
int x1 = x0 + rect.width() - 1;
int y0 = rect.y();
int y1 = y0 + rect.height() - 1;
// fill base color
if (isEmpty || col < 0) {
p.fillRect(rect, EmptyColumnHeadColor);
p.setPen(Qt::black);
p.drawLine(x0, y0, x0, y1);
p.setPen(Qt::white);
p.drawLine(x1, y0, x1, y1);
} else {
QColor columnColor, sideColor;
if (usage == Reference) {
columnColor = m_viewer->getReferenceColumnColor();
sideColor = m_viewer->getReferenceColumnBorderColor();
} else {
columnColor = m_viewer->getPaletteColumnColor();
sideColor = m_viewer->getPaletteColumnBorderColor();
}
p.fillRect(rect, sideColor);
p.fillRect(rect.adjusted(7, 3, 0, 0), columnColor);
// column handle
QRect sideBar(x0, y0, 7, rect.height() - 5);
if (sideBar.contains(m_pos)) {
p.fillRect(sideBar, Qt::yellow);
}
}
QColor pastelizer(m_viewer->getColumnHeadPastelizer());
pastelizer.setAlpha(50);
p.fillRect(rect, (isSelected || isCameraSelected) ? ColorSelection : pastelizer);
int prevViewImgHeight = RowHeight - 5;
int prevViewImgWidth = prevViewImgHeight * 5 / 4;
QRect prevViewRect = m_prevViewBox.translated(orig);
QRect prevViewImgRect(prevViewRect.right() - prevViewImgWidth - 1, 7, prevViewImgWidth, prevViewImgHeight);
static QPixmap prevViewPix = QPixmap(":Resources/x_prev_eye.png");
QRect lockModeRect = m_lockBox.translated(orig);
static QPixmap lockModePix = QPixmap(":Resources/x_lock.png");
if (col >= 0 && !isEmpty) {
//preiew visible toggle
if (column->isPreviewVisible()) {
p.fillRect(prevViewRect, PreviewVisibleColor);
p.drawPixmap(prevViewImgRect, prevViewPix);
}
// lock button
p.setPen(Qt::gray);
p.setBrush(QColor(255, 255, 255, 128));
p.drawRect(lockModeRect);
lockModeRect.adjust(1, 1, -1, -1);
if (isLocked) {
p.drawPixmap(lockModeRect, lockModePix);
}
}
// column number
p.setPen((isCurrent) ? Qt::red : Qt::black);
p.drawText(columnNamePos, QString(name.c_str()));
p.setPen(Qt::black);
if (col >= 0 && !isEmpty) {
static QPixmap paletteHeader(":Resources/palette_header.png");
QRect thumbnailRect(orig.x() + 9, orig.y() + RowHeight * 2 + 7, ColumnWidth - 11, 42);
p.drawPixmap(thumbnailRect, paletteHeader);
}
}
//-----------------------------------------------------------------------------
void ColumnArea::drawSoundTextColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
QFont font("Helvetica");
font.setPointSize(XSHEET_FONT_SIZE);
p.setFont(font);
int x = m_viewer->columnToX(col);
QRect rect(x, 0, ColumnWidth, height());
int x0, x1, y, y0, y1;
TApp *app = TApp::instance();
TXsheet *xsh = m_viewer->getXsheet();
TStageObjectId columnId = m_viewer->getObjectId(col);
std::string name = xsh->getStageObject(columnId)->getName();
bool isEditingSpline = app->getCurrentObject()->isSpline();
//Verifico se la colonna e' lockata se e' quella corrente e se e' selezionata
TXshColumn *column = col >= 0 ? xsh->getColumn(col) : 0;
bool isLocked = column != 0 && column->isLocked();
bool isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col) && !isEditingSpline;
QPoint orig = rect.topLeft();
x0 = rect.x() + 1;
x1 = orig.x() + m_tabBox.x() + m_tabBox.width();
y = orig.y() + m_tabBox.height();
static QPixmap header(":Resources/magpie.png");
int iconW = header.width();
int iconH = header.height();
QRect iconBox(orig.x() + m_nameBox.x(), orig.y() + m_nameBox.y() + m_nameBox.height() + 2, iconW + 1, iconH + 1);
p.drawPixmap(iconBox, header);
bool isPrecedentColSelected = selection->isColumnSelected(col - 1) && !isEditingSpline;
// bordo sinistro
if (isSelected || col > 0 && isPrecedentColSelected) {
p.setPen(ColorSelection);
p.drawLine(rect.x(), orig.y(), rect.x(), height());
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(rect.x(), orig.y(), rect.x(), y + 2);
} else {
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(rect.x(), orig.y(), rect.x(), height());
}
if (col >= 0) {
// sfondo della parte indice
QRect indexBox(orig.x() + 1, orig.y(), m_indexBox.width(), m_indexBox.height() + 3);
p.fillRect(indexBox, m_viewer->getDarkBGColor());
// indice colonna in alto a sinistra
p.setPen(isCurrent ? Qt::red : Qt::black);
p.drawText(indexBox.adjusted(0, 2, -2, 0), Qt::AlignRight, QString(toString(col + 1).c_str()));
x0 = orig.x() + m_tabBox.x() + 1;
int x1 = x0 + RowHeight;
int x2 = x0 + 2 * RowHeight;
int x3 = x0 + 3 * RowHeight + 2;
y0 = orig.y() + m_tabBox.y();
y1 = orig.y() + m_tabBox.height() + 1;
//Sfondo dei due bottoni che non vengono mostrati
p.fillRect(QRect(x0, y0, 2 * RowHeight, RowHeight), m_viewer->getDarkBGColor());
p.setPen(m_viewer->getDarkBGColor());
p.drawLine(x0, y0 - 1, x3, y0 - 1);
p.drawLine(x0, y0 - 2, x3, y0 - 2);
//Linea di separazione tra indice e nome
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(orig.x(), y1 + 1, orig.x() + ColumnWidth, y1 + 1);
// contorno del bottone in alto a dx
p.drawLine(x2, y0, x2, y1);
p.drawLine(x2, y0, x3, y0);
// lucchetto
QRect lockBox(x2 + 1, y0 + 1, 11, 11);
p.fillRect(lockBox, QBrush(m_viewer->getLightLightBGColor()));
if (isLocked) {
static QPixmap lockMode = QPixmap(":Resources/lock_toggle.png");
p.drawPixmap(lockBox, lockMode);
}
}
// nome colonna
QColor cellColor = m_viewer->getLightLightBGColor();
QColor dummyColor;
m_viewer->getColumnColor(cellColor, dummyColor, col, xsh);
QRect nameBox(orig.x() + m_nameBox.x() + 1, orig.y() + m_nameBox.y() + 1, m_nameBox.width() - 1, m_nameBox.height());
QColor columnColor = (isSelected) ? ColorSelection : cellColor;
p.fillRect(nameBox, QBrush(columnColor));
p.setPen(isCurrent ? Qt::red : Qt::black);
p.drawText(nameBox.adjusted(3, -1, -3, 0), Qt::AlignLeft, QString(name.c_str())); //Adjusted to match with lineEdit
// separazione fra nome e icona
p.setPen(isSelected ? ColorSelection : m_viewer->getLightLineColor());
x0 = nameBox.x();
x1 = x0 + nameBox.width();
y0 = nameBox.y() + nameBox.height();
p.drawLine(x0, y0, x1, y0);
if (isSelected) {
QRect box(x0, y0 + 1, ColumnWidth, height() - 3 * RowHeight - 6);
QRect adjustBox = box.adjusted(0, 0, -2, -1);
p.setPen(ColorSelection);
p.drawRect(adjustBox);
}
}
//-----------------------------------------------------------------------------
QPixmap ColumnArea::getColumnIcon(int columnIndex)
{
if (columnIndex == -1) { // Indice colonna = -1 -> CAMERA
TApp *app = TApp::instance();
static QPixmap camera = QPixmap(":Resources/camera.png");
return camera;
}
TXsheet *xsh = m_viewer->getXsheet();
if (!xsh)
return QPixmap();
if (xsh->isColumnEmpty(columnIndex))
return QPixmap();
int r0, r1;
xsh->getCellRange(columnIndex, r0, r1);
if (r0 > r1)
return QPixmap();
TXshCell cell = xsh->getCell(r0, columnIndex);
TXshLevel *xl = cell.m_level.getPointer();
if (!xl)
return QPixmap();
else {
bool onDemand = false;
if (Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand)
onDemand = m_viewer->getCurrentColumn() != columnIndex;
QPixmap icon = IconGenerator::instance()->getIcon(xl, cell.m_frameId, false, onDemand);
#ifndef LINETEST
return scalePixmapKeepingAspectRatio(icon, QSize(ColumnWidth, height() - 3 * RowHeight - 8));
#else
return scalePixmapKeepingAspectRatio(icon, QSize(ColumnWidth, height() - 4 * RowHeight - 8));
#endif
}
}
//-----------------------------------------------------------------------------
void ColumnArea::paintEvent(QPaintEvent *event)
{
QRect toBeUpdated = event->rect();
QPainter p(this);
p.setClipRect(toBeUpdated);
int c0, c1; // range di righe visibili
c0 = m_viewer->xToColumn(toBeUpdated.left());
c1 = m_viewer->xToColumn(toBeUpdated.right());
TXsheet *xsh = m_viewer->getXsheet();
ColumnFan *columnFan = xsh->getColumnFan();
int col;
for (col = c0; col <= c1; col++) {
//draw column fan (collapsed columns)
if (!columnFan->isActive(col)) {
int x = m_viewer->columnToX(col);
QRect rect(x, 0, 8, height());
int x0 = rect.topLeft().x() + 1;
int y = 16;
p.setPen(m_viewer->getDarkLineColor());
p.fillRect(x0, 0, 8, 18, QBrush(m_viewer->getDarkBGColor()));
p.fillRect(x0, y, 2, 84, QBrush(m_viewer->getLightLightBGColor()));
p.fillRect(x0 + 3, y + 3, 2, 82, QBrush(m_viewer->getLightLightBGColor()));
p.fillRect(x0 + 6, y, 2, 84, QBrush(m_viewer->getLightLightBGColor()));
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(x0 - 1, y, x0 - 1, rect.height());
p.drawLine(x0 + 2, y, x0 + 2, rect.height());
p.drawLine(x0 + 5, y, x0 + 5, rect.height());
p.drawLine(x0, y, x0 + 1, y);
p.drawLine(x0 + 3, y + 3, x0 + 4, y + 3);
p.drawLine(x0 + 6, y, x0 + 7, y);
//triangolini
p.setPen(Qt::black);
x = x0;
y = y - 4;
p.drawPoint(QPointF(x, y));
x++;
p.drawLine(x, y - 1, x, y + 1);
x++;
p.drawLine(x, y - 2, x, y + 2);
x += 3;
p.drawLine(x, y - 2, x, y + 2);
x++;
p.drawLine(x, y - 1, x, y + 1);
x++;
p.drawPoint(x, y);
} else if (col >= 0) {
TXshColumn *column = m_viewer->getXsheet()->getColumn(col);
int colType = (column && !column->isEmpty()) ? column->getColumnType() : TXshColumn::eLevelType;
switch (colType) {
case TXshColumn::ePaletteType:
drawPaletteColumnHead(p, col);
CASE TXshColumn::eSoundType : drawSoundColumnHead(p, col);
CASE TXshColumn::eSoundTextType : drawSoundTextColumnHead(p, col);
DEFAULT:
drawLevelColumnHead(p, col);
}
}
}
p.setPen(grey150);
p.setBrush(Qt::NoBrush);
p.drawRect(toBeUpdated.adjusted(0, 0, -1, -1));
if (getDragTool())
getDragTool()->drawColumnsArea(p);
}
//-----------------------------------------------------------------------------
using namespace DVGui;
ColumnTransparencyPopup::ColumnTransparencyPopup(QWidget *parent)
: QWidget(parent, Qt::Popup)
{
setFixedWidth(8 + 30 + 8 + 100 + 8 + 8 + 8 - 4);
m_slider = new QSlider(Qt::Horizontal, this);
m_slider->setMinimum(1);
m_slider->setMaximum(100);
m_slider->setFixedHeight(14);
m_slider->setFixedWidth(100);
m_value = new DVGui::IntLineEdit(this, 1, 1, 100);
/*m_value->setValidator(new QIntValidator (1, 100, m_value));
m_value->setFixedHeight(16);
m_value->setFixedWidth(30);
static QFont font("Helvetica", 7, QFont::Normal);
m_value->setFont(font);*/
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->setContentsMargins(0, 3, 0, 3);
hlayout->setSpacing(1);
hlayout->addWidget(m_slider);
hlayout->addWidget(m_value);
hlayout->addWidget(new QLabel("%"));
setLayout(hlayout);
bool ret = connect(m_slider, SIGNAL(sliderReleased()), this, SLOT(onSliderReleased()));
ret = ret && connect(m_slider, SIGNAL(sliderMoved(int)), this, SLOT(onSliderChange(int)));
ret = ret && connect(m_slider, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged(int)));
ret = ret && connect(m_value, SIGNAL(textChanged(const QString &)), this, SLOT(onValueChanged(const QString &)));
assert(ret);
}
//----------------------------------------------------------------
void ColumnTransparencyPopup::onSliderValueChanged(int val)
{
if (m_slider->isSliderDown())
return;
m_value->setText(QString::number(val));
onSliderReleased();
}
void ColumnTransparencyPopup::onSliderReleased()
{
m_column->setOpacity(troundp(255.0 * m_slider->value() / 100.0));
TApp::instance()->getCurrentScene()->notifySceneChanged();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
((ColumnArea *)parent())->update();
}
//-----------------------------------------------------------------------
void ColumnTransparencyPopup::onSliderChange(int val)
{
disconnect(m_value, SIGNAL(textChanged(const QString &)), 0, 0);
m_value->setText(QString::number(val));
connect(m_value, SIGNAL(textChanged(const QString &)), this, SLOT(onValueChanged(const QString &)));
}
//----------------------------------------------------------------
void ColumnTransparencyPopup::onValueChanged(const QString &str)
{
int val = str.toInt();
m_slider->setValue(val);
m_column->setOpacity(troundp(255.0 * val / 100.0));
TApp::instance()->getCurrentScene()->notifySceneChanged();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
((ColumnArea *)parent())->update();
}
//----------------------------------------------------------------
void ColumnTransparencyPopup::setColumn(TXshColumn *column)
{
m_column = column;
assert(m_column);
int val = (int)troundp(100.0 * m_column->getOpacity() / 255.0);
m_slider->setValue(val);
disconnect(m_value, SIGNAL(textChanged(const QString &)), 0, 0);
m_value->setText(QString::number(val));
connect(m_value, SIGNAL(textChanged(const QString &)), this, SLOT(onValueChanged(const QString &)));
}
/*void ColumnTransparencyPopup::mouseMoveEvent ( QMouseEvent * e )
{
int val = tcrop((e->pos().x()+10)/(this->width()/(99-1+1)), 1, 99);
m_value->setText(QString::number(val));
m_slider->setValue(val);
}*/
void ColumnTransparencyPopup::mouseReleaseEvent(QMouseEvent *e)
{
//hide();
}
//------------------------------------------------------------------------------
void ColumnArea::openTransparencyPopup()
{
if (m_transparencyPopupTimer)
m_transparencyPopupTimer->stop();
if (m_col < 0)
return;
TXshColumn *column = m_viewer->getXsheet()->getColumn(m_col);
if (!column || column->isEmpty())
return;
if (!column->isCamstandVisible()) {
column->setCamstandVisible(true);
TApp::instance()->getCurrentScene()->notifySceneChanged();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
update();
}
m_columnTransparencyPopup->setColumn(column);
m_columnTransparencyPopup->show();
}
//----------------------------------------------------------------
void ColumnArea::startTransparencyPopupTimer(QMouseEvent *e)
{
if (!m_columnTransparencyPopup)
m_columnTransparencyPopup = new ColumnTransparencyPopup(this); // Qt::ToolTip|Qt::MSWindowsFixedSizeDialogHint);//Qt::MSWindowsFixedSizeDialogHint|Qt::Tool);
int x = e->pos().x() - m_tabBox.left() - m_viewer->columnToX(m_col);
int y = e->pos().y() - m_tabBox.bottom();
m_columnTransparencyPopup->move(e->globalPos().x() - x + 2, e->globalPos().y() - y + 1);
if (!m_transparencyPopupTimer) {
m_transparencyPopupTimer = new QTimer(this);
bool ret = connect(m_transparencyPopupTimer, SIGNAL(timeout()), this, SLOT(openTransparencyPopup()));
assert(ret);
m_transparencyPopupTimer->setSingleShot(true);
}
m_transparencyPopupTimer->start(300);
}
//----------------------------------------------------------------
void ColumnArea::mousePressEvent(QMouseEvent *event)
{
m_doOnRelease = 0;
m_viewer->setQtModifiers(event->modifiers());
assert(getDragTool() == 0);
m_col = -1; //new in 6.4
//both left and right click can change the selection
if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton) {
TXsheet *xsh = m_viewer->getXsheet();
m_col = m_viewer->xToColumn(event->pos().x());
// do nothing for the camera column
if (m_col < 0) //CAMERA
{
TApp::instance()->getCurrentSelection()->getSelection()->makeNotCurrent();
m_viewer->getColumnSelection()->selectNone();
}
// when clicking the column fan
else if (m_col >= 0 && !xsh->getColumnFan()->isActive(m_col)) //column Fan
{
for (;;) {
xsh->getColumnFan()->activate(m_col);
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
m_col--;
if (m_col < 0 || xsh->getColumnFan()->isActive(m_col))
break;
}
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
return;
}
// set the clicked column to current
else
m_viewer->setCurrentColumn(m_col);
TXshColumn *column = xsh->getColumn(m_col);
bool isEmpty = !column || column->isEmpty();
TApp::instance()->getCurrentObject()->setIsSpline(false);
// get mouse position
int x = event->pos().x() - m_viewer->columnToX(m_col);
int y = event->pos().y();
QPoint mousePos(x, y);
if (!isEmpty && m_col >= 0) {
// grabbing the left side of the column enables column move
if (x <= 7) {
setDragTool(XsheetGUI::DragTool::makeColumnMoveTool(m_viewer));
}
// lock button
else if (m_lockBox.contains(mousePos) && event->button() == Qt::LeftButton) {
m_doOnRelease = ToggleLock;
}
// preview button
else if (m_prevViewBox.contains(mousePos) && event->button() == Qt::LeftButton) {
m_doOnRelease = TogglePreviewVisible;
if (column->getSoundColumn())
TApp::instance()->getCurrentXsheet()->notifyXsheetSoundChanged();
}
// camstand button
else if (m_tableViewBox.contains(mousePos) && event->button() == Qt::LeftButton) {
m_doOnRelease = ToggleTransparency;
if (column->getSoundColumn()) {
//do nothing
} else
startTransparencyPopupTimer(event);
}
// sound column
else if (column && column->getSoundColumn()) {
if (x > 29 && 3 * RowHeight + 5 <= y && y < 3 * RowHeight + 33) {
TXshSoundColumn *s = column->getSoundColumn();
if (s) {
if (s->isPlaying())
s->stop();
else {
s->play();
if (!s->isPlaying())
s->stop(); //Serve per vista, quando le casse non sono attaccate
}
int interval = 0;
if (s->isPlaying()) {
TSoundTrackP sTrack = s->getCurrentPlaySoundTruck();
interval = sTrack->getDuration() * 1000 + 300;
}
if (s->isPlaying() && interval > 0)
QTimer::singleShot(interval, this, SLOT(update()));
}
int x0 = m_viewer->columnToX(m_col);
int x1 = m_viewer->columnToX(m_col + 1);
update();
} else if (x >= 15 && x <= 25 && RowHeight * 2 + 4 < y && y < 8 * RowHeight + 4)
setDragTool(XsheetGUI::DragTool::makeVolumeDragTool(m_viewer));
else
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
} else if (column && column->getSoundTextColumn()) {
if (y < m_tabBox.bottom() || m_nameBox.contains(x, y))
setDragTool(XsheetGUI::DragTool::makeColumnMoveTool(m_viewer));
else
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
}
// clicking another area means column selection
else {
if (m_viewer->getColumnSelection()->isColumnSelected(m_col) && event->button() == Qt::RightButton)
return;
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
// toggle columnIcon visibility with alt+click
TXshLevelColumn *levelColumn = column->getLevelColumn();
if (levelColumn && Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand && (event->modifiers() & Qt::AltModifier)) {
levelColumn->setIconVisible(!levelColumn->isIconVisible());
}
}
// synchronize the current column and the current fx
TApp::instance()->getCurrentFx()->setFx(column->getFx());
} else if (m_col >= 0) {
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
TApp::instance()->getCurrentFx()->setFx(0);
}
m_viewer->dragToolClick(event);
update();
} else if (event->button() == Qt::MidButton) {
m_pos = event->pos();
m_isPanning = true;
}
}
//-----------------------------------------------------------------------------
void ColumnArea::mouseMoveEvent(QMouseEvent *event)
{
m_viewer->setQtModifiers(event->modifiers());
QPoint pos = event->pos();
if (m_isPanning) { //Pan tasto centrale
QPoint delta = m_pos - pos;
delta.setY(0);
m_viewer->scroll(delta);
return;
}
int col = m_viewer->xToColumn(pos.x());
if (col < -1)
col = 0;
TXsheet *xsh = m_viewer->getXsheet();
TXshColumn *column = xsh->getColumn(col);
int x = pos.x() - m_viewer->columnToX(col);
int y = pos.y();
#ifdef LINETEST
// Controllo che il menu del motion Path sia chiuso.
if ((x - m_mtypeBox.left() > 20 || y < m_mtypeBox.y() || y > m_mtypeBox.bottom()) && !m_motionPathMenu->isHidden())
m_motionPathMenu->hide();
#endif
if ((event->buttons() & Qt::LeftButton) != 0 && !visibleRegion().contains(pos)) {
QRect bounds = visibleRegion().boundingRect();
m_viewer->setAutoPanSpeed(bounds, QPoint(pos.x(), bounds.top()));
} else
m_viewer->stopAutoPan();
m_pos = pos;
if (event->buttons() && getDragTool()) {
m_viewer->dragToolDrag(event);
update();
return;
}
// Setto i toolTip
TStageObjectId columnId = m_viewer->getObjectId(col);
TStageObjectId parentId = xsh->getStageObjectParent(columnId);
QRect sideBar(0, 0, 7, height());
if (col < 0)
m_tooltip = tr("Click to select camera");
if (column && column->getSoundTextColumn())
m_tooltip = tr("");
else if (sideBar.contains(x, y)) {
m_tooltip = tr("Click to select column, drag to move it");
} else if (m_lockBox.contains(x, y)) {
m_tooltip = tr("Lock Toggle");
} else if (m_prevViewBox.contains(x, y)) {
m_tooltip = tr("Preview Visibility Toggle");
} else if (m_tableViewBox.contains(x, y)) {
m_tooltip = tr("Camera Stand Visibility Toggle");
} else {
if (column && column->getSoundColumn()) {
// sound column
if (x > 20 && 3 * RowHeight + 5 <= y && y < 3 * RowHeight + 33)
m_tooltip = tr("Click to play the soundtrack back");
else if (x >= 10 && x <= 20 &&
RowHeight + RowHeight / 2 < y && y < 8 * RowHeight - RowHeight / 2)
m_tooltip = tr("Set the volume of the soundtrack");
}
else if (Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand)
m_tooltip = tr("Alt + Click to Toggle Thumbnail");
else
m_tooltip = tr("");
}
update();
}
//-----------------------------------------------------------------------------
bool ColumnArea::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
if (!m_tooltip.isEmpty())
QToolTip::showText(mapToGlobal(m_pos), m_tooltip);
else
QToolTip::hideText();
}
return QWidget::event(event);
}
//-----------------------------------------------------------------------------
void ColumnArea::mouseReleaseEvent(QMouseEvent *event)
{
TApp *app = TApp::instance();
if (m_doOnRelease != 0 && m_col != -1) {
TXshColumn *column = m_viewer->getXsheet()->getColumn(m_col);
if (m_doOnRelease == ToggleTransparency && (!m_columnTransparencyPopup || m_columnTransparencyPopup->isHidden())) {
column->setCamstandVisible(!column->isCamstandVisible());
app->getCurrentXsheet()->notifyXsheetSoundChanged();
} else if (m_doOnRelease == TogglePreviewVisible)
column->setPreviewVisible(!column->isPreviewVisible());
else if (m_doOnRelease == ToggleLock)
column->lock(!column->isLocked());
else
assert(false);
app->getCurrentScene()->notifySceneChanged();
app->getCurrentXsheet()->notifyXsheetChanged();
update();
m_doOnRelease = 0;
}
if (m_transparencyPopupTimer)
m_transparencyPopupTimer->stop();
m_viewer->setQtModifiers(0);
m_viewer->dragToolRelease(event);
m_isPanning = false;
m_viewer->stopAutoPan();
}
//-----------------------------------------------------------------------------
void ColumnArea::mouseDoubleClickEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
int col = m_viewer->xToColumn(pos.x());
int x0 = m_viewer->columnToX(col);
#ifdef LINETEST
// Camera column
if (col == -1)
return;
#endif
if (!m_prevViewBox.translated(x0, 0).adjusted(0, 0, -ColumnWidth / 2, 0).contains(pos)) {
return;
}
TXsheet *xsh = m_viewer->getXsheet();
if (col >= 0 && xsh->isColumnEmpty(col))
return;
pos = QPoint(x0 + m_prevViewBox.x() - 10, m_prevViewBox.y() - 2);
m_renameColumnField->show(pos, col);
}
//-----------------------------------------------------------------------------
void ColumnArea::contextMenuEvent(QContextMenuEvent *event)
{
QPoint qPos = event->pos();
TPoint pos(qPos.x(), qPos.y());
int row = m_viewer->yToRow(pos.y);
int col = m_viewer->xToColumn(pos.x);
if (col < 0) //CAMERA
return;
m_viewer->setCurrentColumn(col);
TXsheet *xsh = m_viewer->getXsheet();
int x0 = m_viewer->columnToX(col);
QMenu menu(this);
CommandManager *cmdManager = CommandManager::instance();
//---- Preview
if (!xsh->isColumnEmpty(col) && m_prevViewBox.translated(x0, 0).contains(qPos)) {
menu.setObjectName("xsheetColumnAreaMenu_Preview");
menu.addAction(cmdManager->getAction("MI_EnableThisColumnOnly"));
menu.addAction(cmdManager->getAction("MI_EnableSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_EnableAllColumns"));
menu.addAction(cmdManager->getAction("MI_DisableAllColumns"));
menu.addAction(cmdManager->getAction("MI_DisableSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_SwapEnabledColumns"));
}
//---- Lock
else if (!xsh->isColumnEmpty(col) && m_lockBox.translated(x0, 0).contains(qPos)) {
menu.setObjectName("xsheetColumnAreaMenu_Lock");
menu.addAction(cmdManager->getAction("MI_LockThisColumnOnly"));
menu.addAction(cmdManager->getAction("MI_LockSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_LockAllColumns"));
menu.addAction(cmdManager->getAction("MI_UnlockSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_UnlockAllColumns"));
menu.addAction(cmdManager->getAction("MI_ToggleColumnLocks"));
}
//---- Camstand
else if (!xsh->isColumnEmpty(col) && m_tableViewBox.translated(x0, 0).contains(qPos)) {
menu.setObjectName("xsheetColumnAreaMenu_Camstand");
menu.addAction(cmdManager->getAction("MI_ActivateThisColumnOnly"));
menu.addAction(cmdManager->getAction("MI_ActivateSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_ActivateAllColumns"));
menu.addAction(cmdManager->getAction("MI_DeactivateAllColumns"));
menu.addAction(cmdManager->getAction("MI_DeactivateSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_ToggleColumnsActivation"));
// hide all columns placed on the left
menu.addAction(cmdManager->getAction("MI_DeactivateUpperColumns"));
}
// right clicking another area / right clicking empty column head
else {
int r0, r1;
xsh->getCellRange(col, r0, r1);
TXshCell cell = xsh->getCell(r0, col);
menu.addAction(cmdManager->getAction(MI_Cut));
menu.addAction(cmdManager->getAction(MI_Copy));
menu.addAction(cmdManager->getAction(MI_Paste));
menu.addAction(cmdManager->getAction(MI_Clear));
menu.addAction(cmdManager->getAction(MI_Insert));
menu.addSeparator();
menu.addAction(cmdManager->getAction(MI_InsertFx));
menu.addSeparator();
if (m_viewer->getXsheet()->isColumnEmpty(col) ||
(cell.m_level && cell.m_level->getChildLevel()))
menu.addAction(cmdManager->getAction(MI_OpenChild));
// Close sub xsheet and move to parent sheet
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
ChildStack *childStack = scene->getChildStack();
if (childStack && childStack->getAncestorCount() > 0) {
menu.addAction(cmdManager->getAction(MI_CloseChild));
}
menu.addAction(cmdManager->getAction(MI_Collapse));
if (cell.m_level && cell.m_level->getChildLevel()) {
menu.addAction(cmdManager->getAction(MI_Resequence));
menu.addAction(cmdManager->getAction(MI_CloneChild));
menu.addAction(cmdManager->getAction(MI_ExplodeChild));
}
menu.addSeparator();
menu.addAction(cmdManager->getAction(MI_FoldColumns));
// force the selected cells placed in n-steps
if (!xsh->isColumnEmpty(col)) {
menu.addSeparator();
QMenu *reframeSubMenu = new QMenu(tr("Reframe"), this);
{
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe1));
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe2));
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe3));
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe4));
}
menu.addMenu(reframeSubMenu);
}
if (containsRasterLevel(m_viewer->getColumnSelection())) {
QMenu *subsampleSubMenu = new QMenu(tr("Subsampling"), this);
{
subsampleSubMenu->addAction(m_subsampling1);
subsampleSubMenu->addAction(m_subsampling2);
subsampleSubMenu->addAction(m_subsampling3);
subsampleSubMenu->addAction(m_subsampling4);
}
menu.addMenu(subsampleSubMenu);
}
if (!xsh->isColumnEmpty(col)) {
menu.addAction(cmdManager->getAction(MI_ReplaceLevel));
menu.addAction(cmdManager->getAction(MI_ReplaceParentDirectory));
}
}
menu.exec(event->globalPos());
}
//-----------------------------------------------------------------------------
void ColumnArea::onSubSampling(QAction *action)
{
int subsampling;
if (action == m_subsampling1)
subsampling = 1;
else if (action == m_subsampling2)
subsampling = 2;
else if (action == m_subsampling3)
subsampling = 3;
else if (action == m_subsampling4)
subsampling = 4;
TColumnSelection *selection = m_viewer->getColumnSelection();
TXsheet *xsh = m_viewer->getXsheet();
assert(selection && xsh);
const set<int> indexes = selection->getIndices();
set<int>::const_iterator it;
for (it = indexes.begin(); it != indexes.end(); it++) {
TXshColumn *column = xsh->getColumn(*it);
TXshColumn::ColumnType type = column->getColumnType();
if (type != TXshColumn::eLevelType)
continue;
const QSet<TXshSimpleLevel *> levels = getLevels(column);
QSet<TXshSimpleLevel *>::const_iterator it2;
for (it2 = levels.begin(); it2 != levels.end(); it2++) {
TXshSimpleLevel *sl = *it2;
if (sl->getProperties()->getDirtyFlag())
continue;
int type = sl->getType();
if (type == TZI_XSHLEVEL || type == TZP_XSHLEVEL || type == OVL_XSHLEVEL) {
sl->getProperties()->setSubsampling(subsampling);
sl->invalidateFrames();
}
}
}
TApp::instance()->getCurrentXsheet()->getXsheet()->getStageObjectTree()->invalidateAll();
TApp::instance()->getCurrentScene()->notifySceneChanged();
}
} //namespace XsheetGUI
add fake mouseReleaseEvent in contextMenuEvent (#285)
#include "xshcolumnviewer.h"
// Tnz6 includes
#include "xsheetviewer.h"
#include "tapp.h"
#include "menubarcommandids.h"
#include "columnselection.h"
#include "xsheetdragtool.h"
#include "tapp.h"
// TnzTools includes
#include "tools/toolhandle.h"
#include "tools/toolcommandids.h"
// TnzQt includes
#include "toonzqt/tselectionhandle.h"
#include "toonzqt/gutil.h"
#include "toonzqt/icongenerator.h"
#include "toonzqt/intfield.h"
// TnzLib includes
#include "toonz/tscenehandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/stage2.h"
#include "toonz/txshpalettecolumn.h"
#include "toonz/txsheet.h"
#include "toonz/toonzscene.h"
#include "toonz/txshcell.h"
#include "toonz/tstageobject.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/sceneproperties.h"
#include "toonz/txshzeraryfxcolumn.h"
#include "toonz/tcolumnfx.h"
#include "toonz/txshsoundcolumn.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/columnfan.h"
#include "toonz/tstageobjectcmd.h"
#include "toonz/fxcommand.h"
#include "toonz/txshleveltypes.h"
#include "toonz/levelproperties.h"
#include "toonz/preferences.h"
#include "toonz/childstack.h"
#include "toonz/txshlevelcolumn.h"
#include "toonz/tfxhandle.h"
// TnzCore includes
#include "tconvert.h"
#include <QApplication>
#include <QMainWindow>
#include <QPainter>
#include <QMouseEvent>
#include <QMenu>
#include <QToolTip>
#include <QTimer>
#include <QLabel>
//=============================================================================
namespace
{
const QSet<TXshSimpleLevel *> getLevels(TXshColumn *column)
{
QSet<TXshSimpleLevel *> levels;
TXshCellColumn *cellColumn = column->getCellColumn();
if (cellColumn) {
int i, r0, r1;
cellColumn->getRange(r0, r1);
for (i = r0; i <= r1; i++) {
TXshCell cell = cellColumn->getCell(i);
TXshSimpleLevel *sl = cell.getSimpleLevel();
if (sl)
levels.insert(sl);
}
}
return levels;
}
bool containsRasterLevel(TColumnSelection *selection)
{
if (!selection || selection->isEmpty())
return false;
set<int> indexes = selection->getIndices();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
set<int>::iterator it;
for (it = indexes.begin(); it != indexes.end(); it++) {
TXshColumn *col = xsh->getColumn(*it);
if (!col || col->getColumnType() != TXshColumn::eLevelType)
continue;
TXshCellColumn *cellCol = col->getCellColumn();
if (!cellCol)
continue;
int i;
for (i = 0; i < cellCol->getMaxFrame() + 1; i++) {
TXshCell cell = cellCol->getCell(i);
if (cell.isEmpty())
continue;
TXshSimpleLevel *level = cell.getSimpleLevel();
if (!level || level->getChildLevel() || level->getProperties()->getDirtyFlag())
continue;
int type = level->getType();
if (type == OVL_XSHLEVEL || type == TZP_XSHLEVEL)
return true;
}
}
return false;
}
}
//-----------------------------------------------------------------------------
namespace XsheetGUI
{
//-----------------------------------------------------------------------------
void getVolumeCursorRect(
QRect &out,
double volume,
const QPoint &origin)
{
int ly = 60;
int v = tcrop(0, ly, (int)(volume * ly));
out.setX(origin.x() + 11);
out.setY(origin.y() + 60 - v);
out.setWidth(8);
out.setHeight(8);
}
//=============================================================================
// MotionPathMenu
//-----------------------------------------------------------------------------
#if QT_VERSION >= 0x050500
MotionPathMenu::MotionPathMenu(QWidget *parent, Qt::WindowFlags flags)
#else
MotionPathMenu::MotionPathMenu(QWidget *parent, Qt::WFlags flags)
#endif
: QWidget(parent, flags), m_mDeleteRect(QRect(0, 0, ColumnWidth - 13, RowHeight)), m_mNormalRect(QRect(0, RowHeight, ColumnWidth - 13, RowHeight)), m_mRotateRect(QRect(0, RowHeight * 2, ColumnWidth - 13, RowHeight)), m_pos(QPoint())
{
setMouseTracking(true);
setFixedSize(ColumnWidth - 12, 3 * RowHeight);
setWindowFlags(Qt::FramelessWindowHint);
}
//-----------------------------------------------------------------------------
MotionPathMenu::~MotionPathMenu()
{
}
//-----------------------------------------------------------------------------
void MotionPathMenu::paintEvent(QPaintEvent *)
{
QPainter p(this);
static QPixmap motionPixmap = QPixmap(":Resources/motionpath.svg");
static QPixmap motionDeletePixmap = QPixmap(":Resources/motionpath_delete.svg");
static QPixmap motionRotatePixmap = QPixmap(":Resources/motionpath_rot.svg");
QColor overColor = QColor(49, 106, 197);
p.fillRect(m_mDeleteRect, QBrush((m_mDeleteRect.contains(m_pos)) ? overColor : grey225));
p.drawPixmap(m_mDeleteRect, motionDeletePixmap);
p.fillRect(m_mNormalRect, QBrush((m_mNormalRect.contains(m_pos)) ? overColor : grey225));
p.drawPixmap(m_mNormalRect, motionPixmap);
p.fillRect(m_mRotateRect, QBrush((m_mRotateRect.contains(m_pos)) ? overColor : grey225));
p.drawPixmap(m_mRotateRect, motionRotatePixmap);
}
//-----------------------------------------------------------------------------
void MotionPathMenu::mousePressEvent(QMouseEvent *event)
{
m_pos = event->pos();
TStageObjectId objectId = TApp::instance()->getCurrentObject()->getObjectId();
TStageObject *pegbar = TApp::instance()->getCurrentXsheet()->getXsheet()->getStageObject(objectId);
if (m_mDeleteRect.contains(m_pos))
pegbar->setStatus(TStageObject::XY);
else if (m_mNormalRect.contains(m_pos)) {
pegbar->setStatus(TStageObject::PATH);
TApp::instance()->getCurrentObject()->setIsSpline(true);
} else if (m_mRotateRect.contains(m_pos)) {
pegbar->setStatus(TStageObject::PATH_AIM);
TApp::instance()->getCurrentObject()->setIsSpline(true);
}
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
hide();
}
//-----------------------------------------------------------------------------
void MotionPathMenu::mouseMoveEvent(QMouseEvent *event)
{
m_pos = event->pos();
update();
}
//-----------------------------------------------------------------------------
void MotionPathMenu::mouseReleaseEvent(QMouseEvent *event)
{
}
//-----------------------------------------------------------------------------
void MotionPathMenu::leaveEvent(QEvent *event)
{
hide();
}
//=============================================================================
// ChangeObjectWidget
//-----------------------------------------------------------------------------
ChangeObjectWidget::ChangeObjectWidget(QWidget *parent)
: QListWidget(parent), m_width(40)
{
setMouseTracking(true);
setObjectName("XshColumnChangeObjectWidget");
setAutoFillBackground(true);
}
//-----------------------------------------------------------------------------
ChangeObjectWidget::~ChangeObjectWidget()
{
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::show(const QPoint &pos)
{
refresh();
int itemNumber = count();
if (itemNumber > 10) {
itemNumber = 10;
m_width += 15;
}
setGeometry(pos.x(), pos.y(), m_width, itemNumber * 16 + 2);
QListWidget::show();
setFocus();
scrollToItem(currentItem());
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::setObjectHandle(TObjectHandle *objectHandle)
{
m_objectHandle = objectHandle;
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::setXsheetHandle(TXsheetHandle *xsheetHandle)
{
m_xsheetHandle = xsheetHandle;
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::mouseMoveEvent(QMouseEvent *event)
{
QListWidgetItem *currentWidgetItem = itemAt(event->pos());
if (!currentWidgetItem)
return;
clearSelection();
currentWidgetItem->setSelected(true);
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::focusOutEvent(QFocusEvent *e)
{
if (!isVisible())
return;
hide();
parentWidget()->update();
}
//-----------------------------------------------------------------------------
void ChangeObjectWidget::selectCurrent(const QString &text)
{
QList<QListWidgetItem *> itemList = findItems(text, Qt::MatchExactly);
clearSelection();
if (itemList.size() < 1)
return;
QListWidgetItem *currentWidgetItem = itemList.at(0);
setCurrentItem(currentWidgetItem);
}
//=============================================================================
// ChangeObjectParent
//-----------------------------------------------------------------------------
ChangeObjectParent::ChangeObjectParent(QWidget *parent)
: ChangeObjectWidget(parent)
{
bool ret = connect(this, SIGNAL(currentTextChanged(const QString &)), this, SLOT(onTextChanged(const QString &)));
assert(ret);
}
//-----------------------------------------------------------------------------
ChangeObjectParent::~ChangeObjectParent()
{
}
//-----------------------------------------------------------------------------
void ChangeObjectParent::refresh()
{
clear();
assert(m_xsheetHandle);
assert(m_objectHandle);
TXsheet *xsh = m_xsheetHandle->getXsheet();
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
TStageObjectId parentId = xsh->getStageObject(currentObjectId)->getParent();
TStageObjectTree *tree = xsh->getStageObjectTree();
int objectCount = tree->getStageObjectCount();
QString text;
QList<QString> pegbarList;
QList<QString> columnList;
int maxTextLength = 0;
int i;
for (i = 0; i < objectCount; i++) {
TStageObjectId id = tree->getStageObject(i)->getId();
int index = id.getIndex();
QString indexStr = QString(toString(id.getIndex() + 1).c_str());
QString newText;
if (id == parentId) {
if (parentId.isPegbar())
text = QString("Peg ") + indexStr;
else if (parentId.isColumn())
text = QString("Col ") + indexStr;
}
if (id == currentObjectId)
continue;
if (id.isPegbar()) {
newText = QString("Peg ") + indexStr;
pegbarList.append(newText);
}
if (id.isColumn() && (!xsh->isColumnEmpty(index) || index < 2)) {
newText = QString("Col ") + indexStr;
columnList.append(newText);
}
if (newText.length() > maxTextLength)
maxTextLength = newText.length();
}
for (i = 0; i < columnList.size(); i++)
addItem(columnList.at(i));
for (i = 0; i < pegbarList.size(); i++)
addItem(pegbarList.at(i));
m_width = maxTextLength * XSHEET_FONT_SIZE + 2;
selectCurrent(text);
}
//-----------------------------------------------------------------------------
void ChangeObjectParent::onTextChanged(const QString &text)
{
assert(m_xsheetHandle);
assert(m_objectHandle);
if (text.isEmpty()) {
hide();
return;
}
bool isPegbar = false;
if (text.startsWith("Peg"))
isPegbar = true;
QString number = text;
number.remove(0, 4);
int index = number.toInt() - 1;
if (index < 0) {
hide();
return;
}
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
TStageObjectId newStageObjectId;
if (isPegbar)
newStageObjectId = TStageObjectId::PegbarId(index);
else
newStageObjectId = TStageObjectId::ColumnId(index);
if (newStageObjectId == currentObjectId)
return;
TStageObject *stageObject = m_xsheetHandle->getXsheet()->getStageObject(currentObjectId);
TStageObjectCmd::setParent(currentObjectId, newStageObjectId, "B", m_xsheetHandle);
hide();
m_objectHandle->notifyObjectIdChanged(false);
m_xsheetHandle->notifyXsheetChanged();
}
//=============================================================================
// ChangeObjectHandle
//-----------------------------------------------------------------------------
ChangeObjectHandle::ChangeObjectHandle(QWidget *parent)
: ChangeObjectWidget(parent)
{
bool ret = connect(this, SIGNAL(currentTextChanged(const QString &)), this, SLOT(onTextChanged(const QString &)));
assert(ret);
}
//-----------------------------------------------------------------------------
ChangeObjectHandle::~ChangeObjectHandle()
{
}
//-----------------------------------------------------------------------------
void ChangeObjectHandle::refresh()
{
clear();
assert(m_xsheetHandle);
assert(m_objectHandle);
TXsheet *xsh = m_xsheetHandle->getXsheet();
assert(xsh);
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
TStageObject *stageObject = xsh->getStageObject(currentObjectId);
m_width = 28;
int i;
QString str;
if (stageObject->getParent().isColumn()) {
for (i = 0; i < 20; i++)
addItem(str.number(20 - i));
}
for (i = 0; i < 26; i++)
addItem(QString(char('A' + i)));
std::string handle = stageObject->getParentHandle();
if (handle[0] == 'H' && handle.length() > 1)
handle = handle.substr(1);
selectCurrent(QString::fromStdString(handle));
}
//-----------------------------------------------------------------------------
void ChangeObjectHandle::onTextChanged(const QString &text)
{
assert(m_xsheetHandle);
assert(m_objectHandle);
TStageObjectId currentObjectId = m_objectHandle->getObjectId();
QString handle = text;
if (text.toInt() != 0)
handle = QString("H") + handle;
if (handle.isEmpty())
return;
std::vector<TStageObjectId> ids;
ids.push_back(currentObjectId);
TStageObjectCmd::setParentHandle(ids, handle.toStdString(), m_xsheetHandle);
hide();
m_objectHandle->notifyObjectIdChanged(false);
m_xsheetHandle->notifyXsheetChanged();
}
//=============================================================================
// RenameColumnField
//-----------------------------------------------------------------------------
RenameColumnField::RenameColumnField(QWidget *parent, XsheetViewer *viewer)
: QLineEdit(parent), m_col(-1)
{
setFixedSize(XsheetGUI::ColumnWidth + 3, XsheetGUI::RowHeight + 4);
connect(this, SIGNAL(returnPressed()), SLOT(renameColumn()));
}
//-----------------------------------------------------------------------------
void RenameColumnField::show(QPoint pos, int col)
{
move(pos);
static QFont font("Helvetica", XSHEET_FONT_SIZE, QFont::Normal);
setFont(font);
m_col = col;
TXsheet *xsh = m_xsheetHandle->getXsheet();
std::string name = xsh->getStageObject(TStageObjectId::ColumnId(col))->getName();
TXshColumn *column = xsh->getColumn(col);
TXshZeraryFxColumn *zColumn = dynamic_cast<TXshZeraryFxColumn *>(column);
if (zColumn)
name = toString(zColumn->getZeraryColumnFx()->getZeraryFx()->getName());
setText(QString(name.c_str()));
selectAll();
QWidget::show();
raise();
setFocus();
}
//-----------------------------------------------------------------------------
void RenameColumnField::renameColumn()
{
std::string newName = text().toStdString();
TStageObjectId columnId = TStageObjectId::ColumnId(m_col);
TXshColumn *column = m_xsheetHandle->getXsheet()->getColumn(columnId.getIndex());
TXshZeraryFxColumn *zColumn = dynamic_cast<TXshZeraryFxColumn *>(column);
if (zColumn)
TFxCommand::renameFx(zColumn->getZeraryColumnFx(), toWideString(newName), m_xsheetHandle);
else
TStageObjectCmd::rename(columnId, newName, m_xsheetHandle);
m_xsheetHandle->notifyXsheetChanged();
m_col = -1;
setText("");
hide();
}
//-----------------------------------------------------------------------------
void RenameColumnField::focusOutEvent(QFocusEvent *e)
{
std::wstring newName = text().toStdWString();
if (!newName.empty())
renameColumn();
else
hide();
QLineEdit::focusOutEvent(e);
}
//=============================================================================
// ColumnArea
//-----------------------------------------------------------------------------
#if QT_VERSION >= 0x050500
ColumnArea::ColumnArea(XsheetViewer *parent, Qt::WindowFlags flags)
#else
ColumnArea::ColumnArea(XsheetViewer *parent, Qt::WFlags flags)
#endif
: QWidget(parent, flags), m_viewer(parent), m_indexBox(0, 3, ColumnWidth - RowHeight * 3 - 1, RowHeight), m_tabBox(ColumnWidth - RowHeight * 3 - 1, 3, RowHeight * 3, RowHeight + 1), m_nameBox(0, RowHeight + 3, ColumnWidth, RowHeight), m_linkBox(0, RowHeight * 7 + 3, 12, RowHeight), m_pos(-1, -1), m_tooltip(tr("")), m_col(-1), m_columnTransparencyPopup(0), m_transparencyPopupTimer(0), m_prevViewBox(10, 6, ColumnWidth - 12, RowHeight - 3), m_tableViewBox(10, RowHeight + 6, ColumnWidth - 12, RowHeight - 3), m_lockBox(9, RowHeight + 6, RowHeight - 4, RowHeight - 4), m_isPanning(false)
{
TXsheetHandle *xsheetHandle = TApp::instance()->getCurrentXsheet();
#ifndef LINETEST
TObjectHandle *objectHandle = TApp::instance()->getCurrentObject();
m_changeObjectParent = new ChangeObjectParent(0);
m_changeObjectParent->setObjectHandle(objectHandle);
m_changeObjectParent->setXsheetHandle(xsheetHandle);
m_changeObjectParent->hide();
m_changeObjectHandle = new ChangeObjectHandle(0);
m_changeObjectHandle->setObjectHandle(objectHandle);
m_changeObjectHandle->setXsheetHandle(xsheetHandle);
m_changeObjectHandle->hide();
#else
m_motionPathMenu = new MotionPathMenu(0);
#endif
m_renameColumnField = new RenameColumnField(this, m_viewer);
m_renameColumnField->setXsheetHandle(xsheetHandle);
m_renameColumnField->hide();
QActionGroup *actionGroup = new QActionGroup(this);
m_subsampling1 = new QAction(tr("&Subsampling 1"), actionGroup);
m_subsampling2 = new QAction(tr("&Subsampling 2"), actionGroup);
m_subsampling3 = new QAction(tr("&Subsampling 3"), actionGroup);
m_subsampling4 = new QAction(tr("&Subsampling 4"), actionGroup);
actionGroup->addAction(m_subsampling1);
actionGroup->addAction(m_subsampling2);
actionGroup->addAction(m_subsampling3);
actionGroup->addAction(m_subsampling4);
connect(actionGroup, SIGNAL(triggered(QAction *)), this, SLOT(onSubSampling(QAction *)));
setMouseTracking(true);
}
//-----------------------------------------------------------------------------
ColumnArea::~ColumnArea()
{
}
//-----------------------------------------------------------------------------
DragTool *ColumnArea::getDragTool() const { return m_viewer->getDragTool(); }
void ColumnArea::setDragTool(DragTool *dragTool) { m_viewer->setDragTool(dragTool); }
//-----------------------------------------------------------------------------
void ColumnArea::drawLevelColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
// Preparing painter
#ifdef _WIN32
QFont font("Arial", XSHEET_FONT_SIZE, QFont::Normal);
#else
QFont font("Helvetica", XSHEET_FONT_SIZE, QFont::Normal);
#endif
p.setFont(font);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
// Retrieve reference coordinates
int currentColumnIndex = m_viewer->getCurrentColumn();
int x = m_viewer->columnToX(col);
QRect rect(x, 0, ColumnWidth, height());
TApp *app = TApp::instance();
TXsheet *xsh = m_viewer->getXsheet();
TStageObjectId columnId = m_viewer->getObjectId(col);
TStageObjectId currentColumnId = app->getCurrentObject()->getObjectId();
TStageObjectId parentId = xsh->getStageObjectParent(columnId);
TStageObject *columnObject = xsh->getStageObject(columnId);
// Build column name
std::string name(columnObject->getName());
if (col < 0)
name = std::string("Camera");
// Retrieve column properties
bool isEmpty = false;
if (col >= 0) // Verifico se la colonna e' vuota
isEmpty = xsh->isColumnEmpty(col);
bool isEditingSpline = app->getCurrentObject()->isSpline();
//check if the column is reference
TXshColumn *column = col >= 0 ? xsh->getColumn(col) : 0;
enum { Normal,
Reference,
Control } usage = Reference;
if (column) {
if (column->isControl())
usage = Control;
if (column->isRendered() || column->getMeshColumn())
usage = Normal;
}
bool isLocked = column != 0 && column->isLocked();
//check if the column is current
bool isCurrent = false;
if (currentColumnId == TStageObjectId::CameraId(0)) //CAMERA
isCurrent = col == -1;
else
isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col) && !isEditingSpline;
bool isCameraSelected = col == -1 && isCurrent && !isEditingSpline;
// Draw column
QPoint orig = rect.topLeft();
QPoint columnNamePos = orig + QPoint(12, RowHeight);
QPoint pegbarNamePos = orig + QPoint(12, RowHeight * 3 + 48);
QPoint handleNamePos = orig + QPoint(ColumnWidth - 10 - p.fontMetrics().width('B'), RowHeight * 3 + 48);
int x0 = rect.x();
int x1 = x0 + rect.width() - 1;
int y0 = rect.y();
int y1 = y0 + rect.height() - 1;
//fill base color
if (isEmpty || col < 0) {
p.fillRect(rect, m_viewer->getEmptyColumnHeadColor());
p.setPen(Qt::black);
p.drawLine(x0, y0, x0, y1);
p.setPen(Qt::white);
p.drawLine(x1, y0, x1, y1);
} else {
QColor columnColor, sideColor;
if (usage == Reference) {
columnColor = m_viewer->getReferenceColumnColor();
sideColor = m_viewer->getReferenceColumnBorderColor();
} else
m_viewer->getColumnColor(columnColor, sideColor, col, xsh);
p.fillRect(rect, sideColor);
p.fillRect(rect.adjusted(7, 3, 0, 0), columnColor);
// column handle
QRect sideBar(x0, y0, 7, rect.height() - 5);
if (sideBar.contains(m_pos)) {
p.fillRect(sideBar, Qt::yellow);
}
}
QColor pastelizer(m_viewer->getColumnHeadPastelizer());
pastelizer.setAlpha(50);
QColor colorSelection(m_viewer->getSelectedColumnHead());
colorSelection.setAlpha(170);
p.fillRect(rect, (isSelected || isCameraSelected) ? colorSelection : pastelizer);
int prevViewImgHeight = RowHeight - 5;
int prevViewImgWidth = prevViewImgHeight * 5 / 4;
QRect prevViewRect = m_prevViewBox.translated(orig);
QRect prevViewImgRect(prevViewRect.right() - prevViewImgWidth - 1, 7, prevViewImgWidth, prevViewImgHeight);
static QPixmap prevViewPix = QPixmap(":Resources/x_prev_eye.png");
QRect tableViewRect = m_tableViewBox.translated(orig);
QRect tableViewImgRect = prevViewImgRect.translated(0, RowHeight);
static QPixmap tableViewPix = QPixmap(":Resources/x_table_view.png");
static QPixmap tableTranspViewPix = QPixmap(":Resources/x_table_view_transp.png");
QRect lockModeRect = m_lockBox.translated(orig);
static QPixmap lockModePix = QPixmap(":Resources/x_lock.png");
if (col >= 0 && !isEmpty) {
// preview visible toggle
if (column->isPreviewVisible()) {
p.fillRect(prevViewRect, PreviewVisibleColor);
p.drawPixmap(prevViewImgRect, prevViewPix);
}
// camstand visible toggle
if (column->isCamstandVisible()) {
p.fillRect(tableViewRect, CamStandVisibleColor);
p.drawPixmap(tableViewImgRect, column->getOpacity() < 255 ? tableTranspViewPix : tableViewPix);
}
// lock button
p.setPen(Qt::gray);
p.setBrush(QColor(255, 255, 255, 128));
p.drawRect(lockModeRect);
lockModeRect.adjust(1, 1, -1, -1);
if (isLocked) {
p.drawPixmap(lockModeRect, lockModePix);
}
}
// column number
if (!isEmpty)
p.setPen((isCurrent) ? Qt::red : Qt::black);
else
p.setPen((isCurrent) ? m_viewer->getSelectedColumnTextColor() : m_viewer->getTextColor());
p.drawText(columnNamePos, QString(name.c_str()));
p.setPen(m_viewer->getTextColor());
if (col >= 0 && !isEmpty) {
// pegbar name
p.drawText(pegbarNamePos, QString(parentId.toString().c_str()));
std::string handle = xsh->getStageObject(columnId)->getParentHandle();
if (handle[0] == 'H' && handle.length() > 1)
handle = handle.substr(1);
if (parentId != TStageObjectId::TableId)
p.drawText(handleNamePos, QString::fromStdString(handle));
//thumbnail
QRect thumbnailRect(orig.x() + 9, orig.y() + RowHeight * 2 + 7, ColumnWidth - 11, 42);
// for zerary fx, display fxId here instead of thumbnail
TXshZeraryFxColumn *zColumn = dynamic_cast<TXshZeraryFxColumn *>(column);
if (zColumn) {
QFont font("Verdana", 8);
p.setFont(font);
TFx *fx = zColumn->getZeraryColumnFx()->getZeraryFx();
QString fxName = QString::fromStdWString(fx->getFxId());
p.drawText(thumbnailRect, Qt::TextWrapAnywhere | Qt::TextWordWrap, fxName);
} else {
TXshLevelColumn *levelColumn = column->getLevelColumn();
if (levelColumn &&
Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand &&
!levelColumn->isIconVisible()) {
//display nothing
} else {
QPixmap iconPixmap = getColumnIcon(col);
if (!iconPixmap.isNull()) {
p.drawPixmap(thumbnailRect, iconPixmap);
}
// notify that the column icon is already shown
if (levelColumn)
levelColumn->setIconVisible(true);
}
}
}
}
//-----------------------------------------------------------------------------
void ColumnArea::drawSoundColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
QFont font("Helvetica");
font.setPointSize(XSHEET_FONT_SIZE);
p.setFont(font);
int x = m_viewer->columnToX(col);
TXsheet *xsh = m_viewer->getXsheet();
TXshSoundColumn *sc = xsh->getColumn(col) ? xsh->getColumn(col)->getSoundColumn() : 0;
QRect rect(x, 0, ColumnWidth, height());
QPoint orig = rect.topLeft();
QPoint columnNamePos = orig + QPoint(12, RowHeight);
bool isEmpty = xsh->isColumnEmpty(col);
bool isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col);
bool isPrecSelected = col > 0 ? m_viewer->getColumnSelection()->isColumnSelected(col - 1) : false;
bool isActive = sc && sc->isPreviewVisible();
bool isLocked = sc && sc->isLocked();
bool isLeftBorderHighlighted = isSelected || isPrecSelected;
int x0 = rect.x();
int x1 = x0 + rect.width() - 1;
int y0 = rect.y();
int y1 = y0 + rect.height() - 1;
// base color
if (isEmpty || col < 0) {
p.fillRect(rect, EmptyColumnHeadColor);
p.setPen(Qt::black);
p.drawLine(x0, y0, x0, y1);
p.setPen(Qt::white);
p.drawLine(x1, y0, x1, y1);
} else {
QColor columnColor, sideColor;
m_viewer->getColumnColor(columnColor, sideColor, col, xsh);
p.fillRect(rect, sideColor);
p.fillRect(rect.adjusted(7, 3, 0, 0), columnColor);
// column handle
QRect sideBar(x0, y0, 7, rect.height() - 5);
if (sideBar.contains(m_pos)) {
p.fillRect(sideBar, Qt::yellow);
}
}
QColor pastelizer(m_viewer->getColumnHeadPastelizer());
p.fillRect(rect, (isSelected) ? ColorSelection : pastelizer);
int prevViewImgHeight = RowHeight - 5;
int prevViewImgWidth = prevViewImgHeight * 5 / 4;
QRect prevViewRect = m_prevViewBox.translated(orig);
QRect prevViewImgRect(prevViewRect.right() - prevViewImgWidth - 1, 7, prevViewImgWidth, prevViewImgHeight);
static QPixmap prevViewPix = QPixmap(":Resources/x_prev_eye.png");
QRect tableViewRect = m_tableViewBox.translated(orig);
QRect tableViewImgRect = prevViewImgRect.translated(0, RowHeight);
static QPixmap tableViewPix = QPixmap(":Resources/x_table_view.png");
static QPixmap tableTranspViewPix = QPixmap(":Resources/x_table_view_transp.png");
QRect lockModeRect = m_lockBox.translated(orig);
static QPixmap lockModePix = QPixmap(":Resources/x_lock.png");
if (col >= 0 && !isEmpty) {
// preview visible toggle
if (isActive) {
p.fillRect(prevViewRect, PreviewVisibleColor);
p.drawPixmap(prevViewImgRect, prevViewPix);
}
// camstand visible toggle
if (sc->isCamstandVisible()) {
p.fillRect(tableViewRect, CamStandVisibleColor);
p.drawPixmap(tableViewImgRect, tableViewPix);
}
// lock button
p.setPen(Qt::gray);
p.setBrush(QColor(255, 255, 255, 128));
p.drawRect(lockModeRect);
lockModeRect.adjust(1, 1, -1, -1);
if (isLocked) {
p.drawPixmap(lockModeRect, lockModePix);
}
}
// column number
p.setPen((isCurrent) ? Qt::red : Qt::black);
p.drawText(columnNamePos, QString(toString(col + 1).c_str()));
//Icona sound
if (sc->isPlaying()) {
static QPixmap soundActiveIcon = QPixmap(":Resources/sound_header_on.png");
p.drawPixmap(x + 29, 3 * RowHeight + 4, 40, 30, soundActiveIcon);
} else {
static QPixmap soundIcon = QPixmap(":Resources/sound_header_off.png");
p.drawPixmap(x + 29, 3 * RowHeight + 4, 40, 30, soundIcon);
}
QRect rr(rect.x() + 8, RowHeight * 2 + 3, rect.width() - 7, m_tabBox.y() - 3);
// suddivisioni slider
p.setPen(Qt::black);
int xa = rr.x() + 7, ya = rr.y() + 4;
int y = ya;
for (int i = 0; i <= 20; i++, y += 3)
if ((i % 10) == 0)
p.drawLine(xa - 3, y, xa, y);
else if (i & 1)
p.drawLine(xa, y, xa, y);
else
p.drawLine(xa - 2, y, xa, y);
// slider
int ly = 60;
xa += 5;
p.drawPoint(xa, ya);
p.drawPoint(xa, ya + ly);
p.drawLine(xa - 1, ya + 1, xa - 1, ya + ly - 1);
p.drawLine(xa + 1, ya + 1, xa + 1, ya + ly - 1);
// cursore
QRect cursorRect;
getVolumeCursorRect(
cursorRect, sc->getVolume(), rr.topLeft());
std::vector<QPointF> pts;
x = cursorRect.x();
y = cursorRect.y() + 4;
pts.push_back(QPointF(x, y));
pts.push_back(QPointF(x + 4.0, y + 4.0));
pts.push_back(QPointF(x + 8.0, y + 4.0));
pts.push_back(QPointF(x + 8.0, y - 4.0));
pts.push_back(QPointF(x + 4.0, y - 4.0));
drawPolygon(p, pts, true, m_viewer->getLightLineColor());
}
//-----------------------------------------------------------------------------
void ColumnArea::drawPaletteColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
#ifdef _WIN32
QFont font("Arial", XSHEET_FONT_SIZE, QFont::Normal);
#else
QFont font("Helvetica", XSHEET_FONT_SIZE, QFont::Normal);
#endif
p.setFont(font);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
int currentColumnIndex = m_viewer->getCurrentColumn();
int x = m_viewer->columnToX(col);
QRect rect(x, 0, ColumnWidth, height());
TApp *app = TApp::instance();
TXsheet *xsh = m_viewer->getXsheet();
TStageObjectId columnId = m_viewer->getObjectId(col);
TStageObjectId currentColumnId = app->getCurrentObject()->getObjectId();
TStageObjectId parentId = xsh->getStageObjectParent(columnId);
std::string name = xsh->getStageObject(columnId)->getName();
bool isEmpty = false;
if (col >= 0) // Verifico se la colonna e' vuota
isEmpty = xsh->isColumnEmpty(col);
bool isEditingSpline = app->getCurrentObject()->isSpline();
TXshColumn *column = col >= 0 ? xsh->getColumn(col) : 0;
enum { Normal,
Reference,
Control } usage = Reference;
if (column) { // Verifico se la colonna e' una mask
if (column->isControl())
usage = Control;
if (column->isRendered())
usage = Normal;
}
bool isLocked = column != 0 && column->isLocked();
bool isCurrent = false;
if (currentColumnId == TStageObjectId::CameraId(0)) //CAMERA
isCurrent = col == -1;
else
isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col) && !isEditingSpline;
bool isCameraSelected = col == -1 && isCurrent && !isEditingSpline;
QPoint orig = rect.topLeft();
QPoint columnNamePos = orig + QPoint(12, RowHeight);
QPoint pegbarNamePos = orig + QPoint(12, RowHeight * 3 + 48);
QPoint handleNamePos = orig + QPoint(ColumnWidth - 10 - p.fontMetrics().width('B'), RowHeight * 3 + 48);
int x0 = rect.x();
int x1 = x0 + rect.width() - 1;
int y0 = rect.y();
int y1 = y0 + rect.height() - 1;
// fill base color
if (isEmpty || col < 0) {
p.fillRect(rect, EmptyColumnHeadColor);
p.setPen(Qt::black);
p.drawLine(x0, y0, x0, y1);
p.setPen(Qt::white);
p.drawLine(x1, y0, x1, y1);
} else {
QColor columnColor, sideColor;
if (usage == Reference) {
columnColor = m_viewer->getReferenceColumnColor();
sideColor = m_viewer->getReferenceColumnBorderColor();
} else {
columnColor = m_viewer->getPaletteColumnColor();
sideColor = m_viewer->getPaletteColumnBorderColor();
}
p.fillRect(rect, sideColor);
p.fillRect(rect.adjusted(7, 3, 0, 0), columnColor);
// column handle
QRect sideBar(x0, y0, 7, rect.height() - 5);
if (sideBar.contains(m_pos)) {
p.fillRect(sideBar, Qt::yellow);
}
}
QColor pastelizer(m_viewer->getColumnHeadPastelizer());
pastelizer.setAlpha(50);
p.fillRect(rect, (isSelected || isCameraSelected) ? ColorSelection : pastelizer);
int prevViewImgHeight = RowHeight - 5;
int prevViewImgWidth = prevViewImgHeight * 5 / 4;
QRect prevViewRect = m_prevViewBox.translated(orig);
QRect prevViewImgRect(prevViewRect.right() - prevViewImgWidth - 1, 7, prevViewImgWidth, prevViewImgHeight);
static QPixmap prevViewPix = QPixmap(":Resources/x_prev_eye.png");
QRect lockModeRect = m_lockBox.translated(orig);
static QPixmap lockModePix = QPixmap(":Resources/x_lock.png");
if (col >= 0 && !isEmpty) {
//preiew visible toggle
if (column->isPreviewVisible()) {
p.fillRect(prevViewRect, PreviewVisibleColor);
p.drawPixmap(prevViewImgRect, prevViewPix);
}
// lock button
p.setPen(Qt::gray);
p.setBrush(QColor(255, 255, 255, 128));
p.drawRect(lockModeRect);
lockModeRect.adjust(1, 1, -1, -1);
if (isLocked) {
p.drawPixmap(lockModeRect, lockModePix);
}
}
// column number
p.setPen((isCurrent) ? Qt::red : Qt::black);
p.drawText(columnNamePos, QString(name.c_str()));
p.setPen(Qt::black);
if (col >= 0 && !isEmpty) {
static QPixmap paletteHeader(":Resources/palette_header.png");
QRect thumbnailRect(orig.x() + 9, orig.y() + RowHeight * 2 + 7, ColumnWidth - 11, 42);
p.drawPixmap(thumbnailRect, paletteHeader);
}
}
//-----------------------------------------------------------------------------
void ColumnArea::drawSoundTextColumnHead(QPainter &p, int col)
{
TColumnSelection *selection = m_viewer->getColumnSelection();
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
QFont font("Helvetica");
font.setPointSize(XSHEET_FONT_SIZE);
p.setFont(font);
int x = m_viewer->columnToX(col);
QRect rect(x, 0, ColumnWidth, height());
int x0, x1, y, y0, y1;
TApp *app = TApp::instance();
TXsheet *xsh = m_viewer->getXsheet();
TStageObjectId columnId = m_viewer->getObjectId(col);
std::string name = xsh->getStageObject(columnId)->getName();
bool isEditingSpline = app->getCurrentObject()->isSpline();
//Verifico se la colonna e' lockata se e' quella corrente e se e' selezionata
TXshColumn *column = col >= 0 ? xsh->getColumn(col) : 0;
bool isLocked = column != 0 && column->isLocked();
bool isCurrent = m_viewer->getCurrentColumn() == col;
bool isSelected = m_viewer->getColumnSelection()->isColumnSelected(col) && !isEditingSpline;
QPoint orig = rect.topLeft();
x0 = rect.x() + 1;
x1 = orig.x() + m_tabBox.x() + m_tabBox.width();
y = orig.y() + m_tabBox.height();
static QPixmap header(":Resources/magpie.png");
int iconW = header.width();
int iconH = header.height();
QRect iconBox(orig.x() + m_nameBox.x(), orig.y() + m_nameBox.y() + m_nameBox.height() + 2, iconW + 1, iconH + 1);
p.drawPixmap(iconBox, header);
bool isPrecedentColSelected = selection->isColumnSelected(col - 1) && !isEditingSpline;
// bordo sinistro
if (isSelected || col > 0 && isPrecedentColSelected) {
p.setPen(ColorSelection);
p.drawLine(rect.x(), orig.y(), rect.x(), height());
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(rect.x(), orig.y(), rect.x(), y + 2);
} else {
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(rect.x(), orig.y(), rect.x(), height());
}
if (col >= 0) {
// sfondo della parte indice
QRect indexBox(orig.x() + 1, orig.y(), m_indexBox.width(), m_indexBox.height() + 3);
p.fillRect(indexBox, m_viewer->getDarkBGColor());
// indice colonna in alto a sinistra
p.setPen(isCurrent ? Qt::red : Qt::black);
p.drawText(indexBox.adjusted(0, 2, -2, 0), Qt::AlignRight, QString(toString(col + 1).c_str()));
x0 = orig.x() + m_tabBox.x() + 1;
int x1 = x0 + RowHeight;
int x2 = x0 + 2 * RowHeight;
int x3 = x0 + 3 * RowHeight + 2;
y0 = orig.y() + m_tabBox.y();
y1 = orig.y() + m_tabBox.height() + 1;
//Sfondo dei due bottoni che non vengono mostrati
p.fillRect(QRect(x0, y0, 2 * RowHeight, RowHeight), m_viewer->getDarkBGColor());
p.setPen(m_viewer->getDarkBGColor());
p.drawLine(x0, y0 - 1, x3, y0 - 1);
p.drawLine(x0, y0 - 2, x3, y0 - 2);
//Linea di separazione tra indice e nome
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(orig.x(), y1 + 1, orig.x() + ColumnWidth, y1 + 1);
// contorno del bottone in alto a dx
p.drawLine(x2, y0, x2, y1);
p.drawLine(x2, y0, x3, y0);
// lucchetto
QRect lockBox(x2 + 1, y0 + 1, 11, 11);
p.fillRect(lockBox, QBrush(m_viewer->getLightLightBGColor()));
if (isLocked) {
static QPixmap lockMode = QPixmap(":Resources/lock_toggle.png");
p.drawPixmap(lockBox, lockMode);
}
}
// nome colonna
QColor cellColor = m_viewer->getLightLightBGColor();
QColor dummyColor;
m_viewer->getColumnColor(cellColor, dummyColor, col, xsh);
QRect nameBox(orig.x() + m_nameBox.x() + 1, orig.y() + m_nameBox.y() + 1, m_nameBox.width() - 1, m_nameBox.height());
QColor columnColor = (isSelected) ? ColorSelection : cellColor;
p.fillRect(nameBox, QBrush(columnColor));
p.setPen(isCurrent ? Qt::red : Qt::black);
p.drawText(nameBox.adjusted(3, -1, -3, 0), Qt::AlignLeft, QString(name.c_str())); //Adjusted to match with lineEdit
// separazione fra nome e icona
p.setPen(isSelected ? ColorSelection : m_viewer->getLightLineColor());
x0 = nameBox.x();
x1 = x0 + nameBox.width();
y0 = nameBox.y() + nameBox.height();
p.drawLine(x0, y0, x1, y0);
if (isSelected) {
QRect box(x0, y0 + 1, ColumnWidth, height() - 3 * RowHeight - 6);
QRect adjustBox = box.adjusted(0, 0, -2, -1);
p.setPen(ColorSelection);
p.drawRect(adjustBox);
}
}
//-----------------------------------------------------------------------------
QPixmap ColumnArea::getColumnIcon(int columnIndex)
{
if (columnIndex == -1) { // Indice colonna = -1 -> CAMERA
TApp *app = TApp::instance();
static QPixmap camera = QPixmap(":Resources/camera.png");
return camera;
}
TXsheet *xsh = m_viewer->getXsheet();
if (!xsh)
return QPixmap();
if (xsh->isColumnEmpty(columnIndex))
return QPixmap();
int r0, r1;
xsh->getCellRange(columnIndex, r0, r1);
if (r0 > r1)
return QPixmap();
TXshCell cell = xsh->getCell(r0, columnIndex);
TXshLevel *xl = cell.m_level.getPointer();
if (!xl)
return QPixmap();
else {
bool onDemand = false;
if (Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand)
onDemand = m_viewer->getCurrentColumn() != columnIndex;
QPixmap icon = IconGenerator::instance()->getIcon(xl, cell.m_frameId, false, onDemand);
#ifndef LINETEST
return scalePixmapKeepingAspectRatio(icon, QSize(ColumnWidth, height() - 3 * RowHeight - 8));
#else
return scalePixmapKeepingAspectRatio(icon, QSize(ColumnWidth, height() - 4 * RowHeight - 8));
#endif
}
}
//-----------------------------------------------------------------------------
void ColumnArea::paintEvent(QPaintEvent *event)
{
QRect toBeUpdated = event->rect();
QPainter p(this);
p.setClipRect(toBeUpdated);
int c0, c1; // range di righe visibili
c0 = m_viewer->xToColumn(toBeUpdated.left());
c1 = m_viewer->xToColumn(toBeUpdated.right());
TXsheet *xsh = m_viewer->getXsheet();
ColumnFan *columnFan = xsh->getColumnFan();
int col;
for (col = c0; col <= c1; col++) {
//draw column fan (collapsed columns)
if (!columnFan->isActive(col)) {
int x = m_viewer->columnToX(col);
QRect rect(x, 0, 8, height());
int x0 = rect.topLeft().x() + 1;
int y = 16;
p.setPen(m_viewer->getDarkLineColor());
p.fillRect(x0, 0, 8, 18, QBrush(m_viewer->getDarkBGColor()));
p.fillRect(x0, y, 2, 84, QBrush(m_viewer->getLightLightBGColor()));
p.fillRect(x0 + 3, y + 3, 2, 82, QBrush(m_viewer->getLightLightBGColor()));
p.fillRect(x0 + 6, y, 2, 84, QBrush(m_viewer->getLightLightBGColor()));
p.setPen(m_viewer->getDarkLineColor());
p.drawLine(x0 - 1, y, x0 - 1, rect.height());
p.drawLine(x0 + 2, y, x0 + 2, rect.height());
p.drawLine(x0 + 5, y, x0 + 5, rect.height());
p.drawLine(x0, y, x0 + 1, y);
p.drawLine(x0 + 3, y + 3, x0 + 4, y + 3);
p.drawLine(x0 + 6, y, x0 + 7, y);
//triangolini
p.setPen(Qt::black);
x = x0;
y = y - 4;
p.drawPoint(QPointF(x, y));
x++;
p.drawLine(x, y - 1, x, y + 1);
x++;
p.drawLine(x, y - 2, x, y + 2);
x += 3;
p.drawLine(x, y - 2, x, y + 2);
x++;
p.drawLine(x, y - 1, x, y + 1);
x++;
p.drawPoint(x, y);
} else if (col >= 0) {
TXshColumn *column = m_viewer->getXsheet()->getColumn(col);
int colType = (column && !column->isEmpty()) ? column->getColumnType() : TXshColumn::eLevelType;
switch (colType) {
case TXshColumn::ePaletteType:
drawPaletteColumnHead(p, col);
CASE TXshColumn::eSoundType : drawSoundColumnHead(p, col);
CASE TXshColumn::eSoundTextType : drawSoundTextColumnHead(p, col);
DEFAULT:
drawLevelColumnHead(p, col);
}
}
}
p.setPen(grey150);
p.setBrush(Qt::NoBrush);
p.drawRect(toBeUpdated.adjusted(0, 0, -1, -1));
if (getDragTool())
getDragTool()->drawColumnsArea(p);
}
//-----------------------------------------------------------------------------
using namespace DVGui;
ColumnTransparencyPopup::ColumnTransparencyPopup(QWidget *parent)
: QWidget(parent, Qt::Popup)
{
setFixedWidth(8 + 30 + 8 + 100 + 8 + 8 + 8 - 4);
m_slider = new QSlider(Qt::Horizontal, this);
m_slider->setMinimum(1);
m_slider->setMaximum(100);
m_slider->setFixedHeight(14);
m_slider->setFixedWidth(100);
m_value = new DVGui::IntLineEdit(this, 1, 1, 100);
/*m_value->setValidator(new QIntValidator (1, 100, m_value));
m_value->setFixedHeight(16);
m_value->setFixedWidth(30);
static QFont font("Helvetica", 7, QFont::Normal);
m_value->setFont(font);*/
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->setContentsMargins(0, 3, 0, 3);
hlayout->setSpacing(1);
hlayout->addWidget(m_slider);
hlayout->addWidget(m_value);
hlayout->addWidget(new QLabel("%"));
setLayout(hlayout);
bool ret = connect(m_slider, SIGNAL(sliderReleased()), this, SLOT(onSliderReleased()));
ret = ret && connect(m_slider, SIGNAL(sliderMoved(int)), this, SLOT(onSliderChange(int)));
ret = ret && connect(m_slider, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged(int)));
ret = ret && connect(m_value, SIGNAL(textChanged(const QString &)), this, SLOT(onValueChanged(const QString &)));
assert(ret);
}
//----------------------------------------------------------------
void ColumnTransparencyPopup::onSliderValueChanged(int val)
{
if (m_slider->isSliderDown())
return;
m_value->setText(QString::number(val));
onSliderReleased();
}
void ColumnTransparencyPopup::onSliderReleased()
{
m_column->setOpacity(troundp(255.0 * m_slider->value() / 100.0));
TApp::instance()->getCurrentScene()->notifySceneChanged();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
((ColumnArea *)parent())->update();
}
//-----------------------------------------------------------------------
void ColumnTransparencyPopup::onSliderChange(int val)
{
disconnect(m_value, SIGNAL(textChanged(const QString &)), 0, 0);
m_value->setText(QString::number(val));
connect(m_value, SIGNAL(textChanged(const QString &)), this, SLOT(onValueChanged(const QString &)));
}
//----------------------------------------------------------------
void ColumnTransparencyPopup::onValueChanged(const QString &str)
{
int val = str.toInt();
m_slider->setValue(val);
m_column->setOpacity(troundp(255.0 * val / 100.0));
TApp::instance()->getCurrentScene()->notifySceneChanged();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
((ColumnArea *)parent())->update();
}
//----------------------------------------------------------------
void ColumnTransparencyPopup::setColumn(TXshColumn *column)
{
m_column = column;
assert(m_column);
int val = (int)troundp(100.0 * m_column->getOpacity() / 255.0);
m_slider->setValue(val);
disconnect(m_value, SIGNAL(textChanged(const QString &)), 0, 0);
m_value->setText(QString::number(val));
connect(m_value, SIGNAL(textChanged(const QString &)), this, SLOT(onValueChanged(const QString &)));
}
/*void ColumnTransparencyPopup::mouseMoveEvent ( QMouseEvent * e )
{
int val = tcrop((e->pos().x()+10)/(this->width()/(99-1+1)), 1, 99);
m_value->setText(QString::number(val));
m_slider->setValue(val);
}*/
void ColumnTransparencyPopup::mouseReleaseEvent(QMouseEvent *e)
{
//hide();
}
//------------------------------------------------------------------------------
void ColumnArea::openTransparencyPopup()
{
if (m_transparencyPopupTimer)
m_transparencyPopupTimer->stop();
if (m_col < 0)
return;
TXshColumn *column = m_viewer->getXsheet()->getColumn(m_col);
if (!column || column->isEmpty())
return;
if (!column->isCamstandVisible()) {
column->setCamstandVisible(true);
TApp::instance()->getCurrentScene()->notifySceneChanged();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
update();
}
m_columnTransparencyPopup->setColumn(column);
m_columnTransparencyPopup->show();
}
//----------------------------------------------------------------
void ColumnArea::startTransparencyPopupTimer(QMouseEvent *e)
{
if (!m_columnTransparencyPopup)
m_columnTransparencyPopup = new ColumnTransparencyPopup(this); // Qt::ToolTip|Qt::MSWindowsFixedSizeDialogHint);//Qt::MSWindowsFixedSizeDialogHint|Qt::Tool);
int x = e->pos().x() - m_tabBox.left() - m_viewer->columnToX(m_col);
int y = e->pos().y() - m_tabBox.bottom();
m_columnTransparencyPopup->move(e->globalPos().x() - x + 2, e->globalPos().y() - y + 1);
if (!m_transparencyPopupTimer) {
m_transparencyPopupTimer = new QTimer(this);
bool ret = connect(m_transparencyPopupTimer, SIGNAL(timeout()), this, SLOT(openTransparencyPopup()));
assert(ret);
m_transparencyPopupTimer->setSingleShot(true);
}
m_transparencyPopupTimer->start(300);
}
//----------------------------------------------------------------
void ColumnArea::mousePressEvent(QMouseEvent *event)
{
m_doOnRelease = 0;
m_viewer->setQtModifiers(event->modifiers());
assert(getDragTool() == 0);
m_col = -1; //new in 6.4
//both left and right click can change the selection
if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton) {
TXsheet *xsh = m_viewer->getXsheet();
m_col = m_viewer->xToColumn(event->pos().x());
// do nothing for the camera column
if (m_col < 0) //CAMERA
{
TApp::instance()->getCurrentSelection()->getSelection()->makeNotCurrent();
m_viewer->getColumnSelection()->selectNone();
}
// when clicking the column fan
else if (m_col >= 0 && !xsh->getColumnFan()->isActive(m_col)) //column Fan
{
for (;;) {
xsh->getColumnFan()->activate(m_col);
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
m_col--;
if (m_col < 0 || xsh->getColumnFan()->isActive(m_col))
break;
}
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
return;
}
// set the clicked column to current
else
m_viewer->setCurrentColumn(m_col);
TXshColumn *column = xsh->getColumn(m_col);
bool isEmpty = !column || column->isEmpty();
TApp::instance()->getCurrentObject()->setIsSpline(false);
// get mouse position
int x = event->pos().x() - m_viewer->columnToX(m_col);
int y = event->pos().y();
QPoint mousePos(x, y);
if (!isEmpty && m_col >= 0) {
// grabbing the left side of the column enables column move
if (x <= 7) {
setDragTool(XsheetGUI::DragTool::makeColumnMoveTool(m_viewer));
}
// lock button
else if (m_lockBox.contains(mousePos) && event->button() == Qt::LeftButton) {
m_doOnRelease = ToggleLock;
}
// preview button
else if (m_prevViewBox.contains(mousePos) && event->button() == Qt::LeftButton) {
m_doOnRelease = TogglePreviewVisible;
if (column->getSoundColumn())
TApp::instance()->getCurrentXsheet()->notifyXsheetSoundChanged();
}
// camstand button
else if (m_tableViewBox.contains(mousePos) && event->button() == Qt::LeftButton) {
m_doOnRelease = ToggleTransparency;
if (column->getSoundColumn()) {
//do nothing
} else
startTransparencyPopupTimer(event);
}
// sound column
else if (column && column->getSoundColumn()) {
if (x > 29 && 3 * RowHeight + 5 <= y && y < 3 * RowHeight + 33) {
TXshSoundColumn *s = column->getSoundColumn();
if (s) {
if (s->isPlaying())
s->stop();
else {
s->play();
if (!s->isPlaying())
s->stop(); //Serve per vista, quando le casse non sono attaccate
}
int interval = 0;
if (s->isPlaying()) {
TSoundTrackP sTrack = s->getCurrentPlaySoundTruck();
interval = sTrack->getDuration() * 1000 + 300;
}
if (s->isPlaying() && interval > 0)
QTimer::singleShot(interval, this, SLOT(update()));
}
int x0 = m_viewer->columnToX(m_col);
int x1 = m_viewer->columnToX(m_col + 1);
update();
} else if (x >= 15 && x <= 25 && RowHeight * 2 + 4 < y && y < 8 * RowHeight + 4)
setDragTool(XsheetGUI::DragTool::makeVolumeDragTool(m_viewer));
else
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
} else if (column && column->getSoundTextColumn()) {
if (y < m_tabBox.bottom() || m_nameBox.contains(x, y))
setDragTool(XsheetGUI::DragTool::makeColumnMoveTool(m_viewer));
else
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
}
// clicking another area means column selection
else {
if (m_viewer->getColumnSelection()->isColumnSelected(m_col) && event->button() == Qt::RightButton)
return;
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
// toggle columnIcon visibility with alt+click
TXshLevelColumn *levelColumn = column->getLevelColumn();
if (levelColumn && Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand && (event->modifiers() & Qt::AltModifier)) {
levelColumn->setIconVisible(!levelColumn->isIconVisible());
}
}
// synchronize the current column and the current fx
TApp::instance()->getCurrentFx()->setFx(column->getFx());
} else if (m_col >= 0) {
setDragTool(XsheetGUI::DragTool::makeColumnSelectionTool(m_viewer));
TApp::instance()->getCurrentFx()->setFx(0);
}
m_viewer->dragToolClick(event);
update();
} else if (event->button() == Qt::MidButton) {
m_pos = event->pos();
m_isPanning = true;
}
}
//-----------------------------------------------------------------------------
void ColumnArea::mouseMoveEvent(QMouseEvent *event)
{
m_viewer->setQtModifiers(event->modifiers());
QPoint pos = event->pos();
if (m_isPanning) { //Pan tasto centrale
QPoint delta = m_pos - pos;
delta.setY(0);
m_viewer->scroll(delta);
return;
}
int col = m_viewer->xToColumn(pos.x());
if (col < -1)
col = 0;
TXsheet *xsh = m_viewer->getXsheet();
TXshColumn *column = xsh->getColumn(col);
int x = pos.x() - m_viewer->columnToX(col);
int y = pos.y();
#ifdef LINETEST
// Controllo che il menu del motion Path sia chiuso.
if ((x - m_mtypeBox.left() > 20 || y < m_mtypeBox.y() || y > m_mtypeBox.bottom()) && !m_motionPathMenu->isHidden())
m_motionPathMenu->hide();
#endif
if ((event->buttons() & Qt::LeftButton) != 0 && !visibleRegion().contains(pos)) {
QRect bounds = visibleRegion().boundingRect();
m_viewer->setAutoPanSpeed(bounds, QPoint(pos.x(), bounds.top()));
} else
m_viewer->stopAutoPan();
m_pos = pos;
if (event->buttons() && getDragTool()) {
m_viewer->dragToolDrag(event);
update();
return;
}
// Setto i toolTip
TStageObjectId columnId = m_viewer->getObjectId(col);
TStageObjectId parentId = xsh->getStageObjectParent(columnId);
QRect sideBar(0, 0, 7, height());
if (col < 0)
m_tooltip = tr("Click to select camera");
if (column && column->getSoundTextColumn())
m_tooltip = tr("");
else if (sideBar.contains(x, y)) {
m_tooltip = tr("Click to select column, drag to move it");
} else if (m_lockBox.contains(x, y)) {
m_tooltip = tr("Lock Toggle");
} else if (m_prevViewBox.contains(x, y)) {
m_tooltip = tr("Preview Visibility Toggle");
} else if (m_tableViewBox.contains(x, y)) {
m_tooltip = tr("Camera Stand Visibility Toggle");
} else {
if (column && column->getSoundColumn()) {
// sound column
if (x > 20 && 3 * RowHeight + 5 <= y && y < 3 * RowHeight + 33)
m_tooltip = tr("Click to play the soundtrack back");
else if (x >= 10 && x <= 20 &&
RowHeight + RowHeight / 2 < y && y < 8 * RowHeight - RowHeight / 2)
m_tooltip = tr("Set the volume of the soundtrack");
}
else if (Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand)
m_tooltip = tr("Alt + Click to Toggle Thumbnail");
else
m_tooltip = tr("");
}
update();
}
//-----------------------------------------------------------------------------
bool ColumnArea::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
if (!m_tooltip.isEmpty())
QToolTip::showText(mapToGlobal(m_pos), m_tooltip);
else
QToolTip::hideText();
}
return QWidget::event(event);
}
//-----------------------------------------------------------------------------
void ColumnArea::mouseReleaseEvent(QMouseEvent *event)
{
TApp *app = TApp::instance();
if (m_doOnRelease != 0 && m_col != -1) {
TXshColumn *column = m_viewer->getXsheet()->getColumn(m_col);
if (m_doOnRelease == ToggleTransparency && (!m_columnTransparencyPopup || m_columnTransparencyPopup->isHidden())) {
column->setCamstandVisible(!column->isCamstandVisible());
app->getCurrentXsheet()->notifyXsheetSoundChanged();
} else if (m_doOnRelease == TogglePreviewVisible)
column->setPreviewVisible(!column->isPreviewVisible());
else if (m_doOnRelease == ToggleLock)
column->lock(!column->isLocked());
else
assert(false);
app->getCurrentScene()->notifySceneChanged();
app->getCurrentXsheet()->notifyXsheetChanged();
update();
m_doOnRelease = 0;
}
if (m_transparencyPopupTimer)
m_transparencyPopupTimer->stop();
m_viewer->setQtModifiers(0);
m_viewer->dragToolRelease(event);
m_isPanning = false;
m_viewer->stopAutoPan();
}
//-----------------------------------------------------------------------------
void ColumnArea::mouseDoubleClickEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
int col = m_viewer->xToColumn(pos.x());
int x0 = m_viewer->columnToX(col);
#ifdef LINETEST
// Camera column
if (col == -1)
return;
#endif
if (!m_prevViewBox.translated(x0, 0).adjusted(0, 0, -ColumnWidth / 2, 0).contains(pos)) {
return;
}
TXsheet *xsh = m_viewer->getXsheet();
if (col >= 0 && xsh->isColumnEmpty(col))
return;
pos = QPoint(x0 + m_prevViewBox.x() - 10, m_prevViewBox.y() - 2);
m_renameColumnField->show(pos, col);
}
//-----------------------------------------------------------------------------
void ColumnArea::contextMenuEvent(QContextMenuEvent *event)
{
#ifndef _WIN32
/* On windows the widget receive the release event before the menu
is shown, on linux and osx the release event is lost, never
received by the widget */
QMouseEvent fakeRelease(QEvent::MouseButtonRelease, event->pos(),
Qt::RightButton, Qt::NoButton, Qt::NoModifier);
QApplication::instance()->sendEvent(this, &fakeRelease);
#endif
QPoint qPos = event->pos();
TPoint pos(qPos.x(), qPos.y());
int row = m_viewer->yToRow(pos.y);
int col = m_viewer->xToColumn(pos.x);
if (col < 0) //CAMERA
return;
m_viewer->setCurrentColumn(col);
TXsheet *xsh = m_viewer->getXsheet();
int x0 = m_viewer->columnToX(col);
QMenu menu(this);
CommandManager *cmdManager = CommandManager::instance();
//---- Preview
if (!xsh->isColumnEmpty(col) && m_prevViewBox.translated(x0, 0).contains(qPos)) {
menu.setObjectName("xsheetColumnAreaMenu_Preview");
menu.addAction(cmdManager->getAction("MI_EnableThisColumnOnly"));
menu.addAction(cmdManager->getAction("MI_EnableSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_EnableAllColumns"));
menu.addAction(cmdManager->getAction("MI_DisableAllColumns"));
menu.addAction(cmdManager->getAction("MI_DisableSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_SwapEnabledColumns"));
}
//---- Lock
else if (!xsh->isColumnEmpty(col) && m_lockBox.translated(x0, 0).contains(qPos)) {
menu.setObjectName("xsheetColumnAreaMenu_Lock");
menu.addAction(cmdManager->getAction("MI_LockThisColumnOnly"));
menu.addAction(cmdManager->getAction("MI_LockSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_LockAllColumns"));
menu.addAction(cmdManager->getAction("MI_UnlockSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_UnlockAllColumns"));
menu.addAction(cmdManager->getAction("MI_ToggleColumnLocks"));
}
//---- Camstand
else if (!xsh->isColumnEmpty(col) && m_tableViewBox.translated(x0, 0).contains(qPos)) {
menu.setObjectName("xsheetColumnAreaMenu_Camstand");
menu.addAction(cmdManager->getAction("MI_ActivateThisColumnOnly"));
menu.addAction(cmdManager->getAction("MI_ActivateSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_ActivateAllColumns"));
menu.addAction(cmdManager->getAction("MI_DeactivateAllColumns"));
menu.addAction(cmdManager->getAction("MI_DeactivateSelectedColumns"));
menu.addAction(cmdManager->getAction("MI_ToggleColumnsActivation"));
// hide all columns placed on the left
menu.addAction(cmdManager->getAction("MI_DeactivateUpperColumns"));
}
// right clicking another area / right clicking empty column head
else {
int r0, r1;
xsh->getCellRange(col, r0, r1);
TXshCell cell = xsh->getCell(r0, col);
menu.addAction(cmdManager->getAction(MI_Cut));
menu.addAction(cmdManager->getAction(MI_Copy));
menu.addAction(cmdManager->getAction(MI_Paste));
menu.addAction(cmdManager->getAction(MI_Clear));
menu.addAction(cmdManager->getAction(MI_Insert));
menu.addSeparator();
menu.addAction(cmdManager->getAction(MI_InsertFx));
menu.addSeparator();
if (m_viewer->getXsheet()->isColumnEmpty(col) ||
(cell.m_level && cell.m_level->getChildLevel()))
menu.addAction(cmdManager->getAction(MI_OpenChild));
// Close sub xsheet and move to parent sheet
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
ChildStack *childStack = scene->getChildStack();
if (childStack && childStack->getAncestorCount() > 0) {
menu.addAction(cmdManager->getAction(MI_CloseChild));
}
menu.addAction(cmdManager->getAction(MI_Collapse));
if (cell.m_level && cell.m_level->getChildLevel()) {
menu.addAction(cmdManager->getAction(MI_Resequence));
menu.addAction(cmdManager->getAction(MI_CloneChild));
menu.addAction(cmdManager->getAction(MI_ExplodeChild));
}
menu.addSeparator();
menu.addAction(cmdManager->getAction(MI_FoldColumns));
// force the selected cells placed in n-steps
if (!xsh->isColumnEmpty(col)) {
menu.addSeparator();
QMenu *reframeSubMenu = new QMenu(tr("Reframe"), this);
{
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe1));
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe2));
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe3));
reframeSubMenu->addAction(cmdManager->getAction(MI_Reframe4));
}
menu.addMenu(reframeSubMenu);
}
if (containsRasterLevel(m_viewer->getColumnSelection())) {
QMenu *subsampleSubMenu = new QMenu(tr("Subsampling"), this);
{
subsampleSubMenu->addAction(m_subsampling1);
subsampleSubMenu->addAction(m_subsampling2);
subsampleSubMenu->addAction(m_subsampling3);
subsampleSubMenu->addAction(m_subsampling4);
}
menu.addMenu(subsampleSubMenu);
}
if (!xsh->isColumnEmpty(col)) {
menu.addAction(cmdManager->getAction(MI_ReplaceLevel));
menu.addAction(cmdManager->getAction(MI_ReplaceParentDirectory));
}
}
menu.exec(event->globalPos());
}
//-----------------------------------------------------------------------------
void ColumnArea::onSubSampling(QAction *action)
{
int subsampling;
if (action == m_subsampling1)
subsampling = 1;
else if (action == m_subsampling2)
subsampling = 2;
else if (action == m_subsampling3)
subsampling = 3;
else if (action == m_subsampling4)
subsampling = 4;
TColumnSelection *selection = m_viewer->getColumnSelection();
TXsheet *xsh = m_viewer->getXsheet();
assert(selection && xsh);
const set<int> indexes = selection->getIndices();
set<int>::const_iterator it;
for (it = indexes.begin(); it != indexes.end(); it++) {
TXshColumn *column = xsh->getColumn(*it);
TXshColumn::ColumnType type = column->getColumnType();
if (type != TXshColumn::eLevelType)
continue;
const QSet<TXshSimpleLevel *> levels = getLevels(column);
QSet<TXshSimpleLevel *>::const_iterator it2;
for (it2 = levels.begin(); it2 != levels.end(); it2++) {
TXshSimpleLevel *sl = *it2;
if (sl->getProperties()->getDirtyFlag())
continue;
int type = sl->getType();
if (type == TZI_XSHLEVEL || type == TZP_XSHLEVEL || type == OVL_XSHLEVEL) {
sl->getProperties()->setSubsampling(subsampling);
sl->invalidateFrames();
}
}
}
TApp::instance()->getCurrentXsheet()->getXsheet()->getStageObjectTree()->invalidateAll();
TApp::instance()->getCurrentScene()->notifySceneChanged();
}
} //namespace XsheetGUI
|
/**
*
* @file IdealMolalSoln.cpp
*/
/*
* Copywrite (2006) Sandia Corporation. Under the terms of
* Contract DE-AC04-94AL85000 with Sandia Corporation, the
* U.S. Government retains certain rights in this software.
*/
/*
* $Author$
* $Date$
* $Revision$
*/
#include "IdealMolalSoln.h"
#include "importCTML.h"
namespace Cantera {
/**
* Default constructor
*/
IdealMolalSoln::IdealMolalSoln() :
MolalityVPSSTP(),
m_formGC(2)
{
}
/**
* Copy Constructor:
*
* Note this stuff will not work until the underlying phase
* has a working copy constructor
*/
IdealMolalSoln::IdealMolalSoln(const IdealMolalSoln &b) :
MolalityVPSSTP(b)
{
/*
* Use the assignment operator to do the brunt
* of the work for the copy construtor.
*/
*this = b;
}
/**
* operator=()
*
* Note this stuff will not work until the underlying phase
* has a working assignment operator
*/
IdealMolalSoln& IdealMolalSoln::
operator=(const IdealMolalSoln &b) {
if (&b != this) {
MolalityVPSSTP::operator=(b);
m_speciesMolarVolume = b.m_speciesMolarVolume;
m_formGC = b.m_formGC;
m_expg0_RT = b.m_expg0_RT;
m_pe = b.m_pe;
m_pp = b.m_pp;
m_tmpV = b.m_tmpV;
}
return *this;
}
IdealMolalSoln::IdealMolalSoln(std::string inputFile, std::string id) :
MolalityVPSSTP()
{
constructPhaseFile(inputFile, id);
}
IdealMolalSoln::IdealMolalSoln(XML_Node& root, std::string id) :
MolalityVPSSTP()
{
constructPhaseXML(root, id);
}
/**
*
* ~IdealMolalSoln(): (virtual)
*
* Destructor: does nothing:
*
*/
IdealMolalSoln::~IdealMolalSoln() {
}
/**
*
*/
ThermoPhase* IdealMolalSoln::duplMyselfAsThermoPhase() {
IdealMolalSoln* mtp = new IdealMolalSoln(*this);
return (ThermoPhase *) mtp;
}
//
// -------- Molar Thermodynamic Properties of the Solution ---------------
//
/*
* Molar enthalpy of the solution: Units: J/kmol.
*
* Returns the amount of enthalpy per mole of solution.
* For an ideal molal solution,
* \f[
* \bar{h}(T, P, X_k) = \sum_k X_k \bar{h}_k(T)
* \f]
* The formula is written in terms of the partial molar enthalpies.
* \f$ \bar{h}_k(T, p, m_k) \f$.
* See the partial molar enthalpy function, getPartialMolarEnthalpies(),
* for details.
*
* Units: J/kmol
*/
doublereal IdealMolalSoln::enthalpy_mole() const {
getPartialMolarEnthalpies(DATA_PTR(m_tmpV));
getMoleFractions(DATA_PTR(m_pp));
double val = mean_X(DATA_PTR(m_tmpV));
return val;
}
/*
* Molar internal energy of the solution: Units: J/kmol.
*
* Returns the amount of internal energy per mole of solution.
* For an ideal molal solution,
* \f[
* \bar{u}(T, P, X_k) = \sum_k X_k \bar{u}_k(T)
* \f]
* The formula is written in terms of the partial molar internal energy.
* \f$ \bar{u}_k(T, p, m_k) \f$.
*/
doublereal IdealMolalSoln::intEnergy_mole() const {
getPartialMolarEnthalpies(DATA_PTR(m_tmpV));
return mean_X(DATA_PTR(m_tmpV));
}
/*
* Molar entropy of the solution: Units J/kmol/K.
*
* Returns the amount of entropy per mole of solution.
* For an ideal molal solution,
* \f[
* \bar{s}(T, P, X_k) = \sum_k X_k \bar{s}_k(T)
* \f]
* The formula is written in terms of the partial molar entropies.
* \f$ \bar{s}_k(T, p, m_k) \f$.
* See the partial molar entropies function, getPartialMolarEntropies(),
* for details.
*
* Units: J/kmol/K.
*/
doublereal IdealMolalSoln::entropy_mole() const {
getPartialMolarEntropies(DATA_PTR(m_tmpV));
return mean_X(DATA_PTR(m_tmpV));
}
/*
* Molar Gibbs function for the solution: Units J/kmol.
*
* Returns the gibbs free energy of the solution per mole
* of the solution.
*
* \f[
* \bar{g}(T, P, X_k) = \sum_k X_k \mu_k(T)
* \f]
*
* Units: J/kmol
*/
doublereal IdealMolalSoln::gibbs_mole() const {
getChemPotentials(DATA_PTR(m_tmpV));
return mean_X(DATA_PTR(m_tmpV));
}
/*
* Molar heat capacity at constant pressure: Units: J/kmol/K.
* * \f[
* \bar{c}_p(T, P, X_k) = \sum_k X_k \bar{c}_{p,k}(T)
* \f]
*
* Units: J/kmol/K
*/
doublereal IdealMolalSoln::cp_mole() const {
getPartialMolarCp(DATA_PTR(m_tmpV));
double val = mean_X(DATA_PTR(m_tmpV));
return val;
}
/*
* Molar heat capacity at constant volume: Units: J/kmol/K.
* NOT IMPLEMENTED.
* Units: J/kmol/K
*/
doublereal IdealMolalSoln::cv_mole() const {
return err("not implemented");
}
//
// ------- Mechanical Equation of State Properties ------------------------
//
/*
* Pressure. Units: Pa.
* For this incompressible system, we return the internally storred
* independent value of the pressure.
*/
doublereal IdealMolalSoln::pressure() const {
return m_Pcurrent;
}
/*
* Set the pressure at constant temperature. Units: Pa.
* This method sets a constant within the object.
* The mass density is not a function of pressure.
*/
void IdealMolalSoln::setPressure(doublereal p) {
#ifdef DEBUG_MODE
//printf("setPressure: %g\n", p);
#endif
/*
* Store the current pressure
*/
m_Pcurrent = p;
/*
* update the standard state thermo
* -> This involves calling the water function and setting the pressure
*/
_updateStandardStateThermo();
/*
* Calculate all of the other standard volumes
* -> note these are constant for now
*/
/*
* Get the partial molar volumes of all of the
* species. -> note this is a lookup for
* water, here since it was done above.
*/
double *vbar = &m_pp[0];
getPartialMolarVolumes(vbar);
/*
* Get mole fractions of all species.
*/
double *x = &m_tmpV[0];
getMoleFractions(x);
/*
* Calculate the solution molar volume and the
* solution density.
*/
doublereal vtotal = 0.0;
for (int i = 0; i < m_kk; i++) {
vtotal += vbar[i] * x[i];
}
doublereal dd = meanMolecularWeight() / vtotal;
/*
* Now, update the State class with the results. This
* stores the density.
*/
State::setDensity(dd);
}
/*
* The isothermal compressibility. Units: 1/Pa.
* The isothermal compressibility is defined as
* \f[
* \kappa_T = -\frac{1}{v}\left(\frac{\partial v}{\partial P}\right)_T
* \f]
*
* It's equal to zero for this model, since the molar volume
* doesn't change with pressure or temperature.
*/
doublereal IdealMolalSoln::isothermalCompressibility() const {
return 0.0;
}
/*
* The thermal expansion coefficient. Units: 1/K.
* The thermal expansion coefficient is defined as
*
* \f[
* \beta = \frac{1}{v}\left(\frac{\partial v}{\partial T}\right)_P
* \f]
*
* It's equal to zero for this model, since the molar volume
* doesn't change with pressure or temperature.
*/
doublereal IdealMolalSoln::thermalExpansionCoeff() const {
return 0.0;
}
/*
* Overwritten setDensity() function is necessary because the
* density is not an indendent variable.
*
* This function will now throw an error condition
*
* @internal May have to adjust the strategy here to make
* the eos for these materials slightly compressible, in order
* to create a condition where the density is a function of
* the pressure.
*
* This function will now throw an error condition.
*
* NOTE: This is an overwritten function from the State.h
* class
*/
void IdealMolalSoln::setDensity(doublereal rho) {
double dens = density();
if (rho != dens) {
throw CanteraError("Idea;MolalSoln::setDensity",
"Density is not an independent variable");
}
}
/*
* Overwritten setMolarDensity() function is necessary because the
* density is not an indendent variable.
*
* This function will now throw an error condition.
*
* NOTE: This is a virtual function, overwritten function from the State.h
* class
*/
void IdealMolalSoln::setMolarDensity(doublereal conc) {
double concI = State::molarDensity();
if (conc != concI) {
throw CanteraError("IdealMolalSoln::setMolarDensity",
"molarDensity/denisty is not an independent variable");
}
}
//
// ------- Activities and Activity Concentrations
//
/*
* This method returns an array of activity concentrations \f$ C^a_k\f$.
* \f$ C^a_k\f$ are defined such that
* \f$ a_k = C^a_k / C^s_k, \f$ where \f$ C^s_k \f$
* is a standard concentration
* defined below. These activity concentrations are used
* by kinetics manager classes to compute the forward and
* reverse rates of elementary reactions.
*
* @param c Array of activity concentrations. The
* units depend upon the implementation of the
* reaction rate expressions within the phase.
*/
void IdealMolalSoln::getActivityConcentrations(doublereal* c) const {
if (m_formGC != 1) {
double c_solvent = standardConcentration();
getActivities(c);
for (int k = 0; k < m_kk; k++) {
c[k] *= c_solvent;
}
} else {
getActivities(c);
for (int k = 0; k < m_kk; k++) {
double c0 = standardConcentration(k);
c[k] *= c0;
}
}
}
/*
* The standard concentration \f$ C^s_k \f$ used to normalize
* the activity concentration. In many cases, this quantity
* will be the same for all species in a phase - for example,
* for an ideal gas \f$ C^s_k = P/\hat R T \f$. For this
* reason, this method returns a single value, instead of an
* array. However, for phases in which the standard
* concentration is species-specific (e.g. surface species of
* different sizes), this method may be called with an
* optional parameter indicating the species.
*
*/
doublereal IdealMolalSoln::standardConcentration(int k) const {
double c0 = 1.0, mvSolvent;
switch (m_formGC) {
case 0:
break;
case 1:
c0 = 1.0 /m_speciesMolarVolume[m_indexSolvent];
break;
case 2:
mvSolvent = m_speciesMolarVolume[m_indexSolvent];
c0 = 1.0 / mvSolvent;
break;
}
return c0;
}
/*
* Returns the natural logarithm of the standard
* concentration of the kth species
*/
doublereal IdealMolalSoln::logStandardConc(int k) const {
double c0 = standardConcentration(k);
return log(c0);
}
/*
* Returns the units of the standard and general concentrations
* Note they have the same units, as their divisor is
* defined to be equal to the activity of the kth species
* in the solution, which is unitless.
*
* This routine is used in print out applications where the
* units are needed. Usually, MKS units are assumed throughout
* the program and in the XML input files.
*
* On return uA contains the powers of the units (MKS assumed)
* of the standard concentrations and generalized concentrations
* for the kth species.
*
* uA[0] = kmol units - default = 1
* uA[1] = m units - default = -nDim(), the number of spatial
* dimensions in the Phase class.
* uA[2] = kg units - default = 0;
* uA[3] = Pa(pressure) units - default = 0;
* uA[4] = Temperature units - default = 0;
* uA[5] = time units - default = 0
*/
void IdealMolalSoln::getUnitsStandardConc(double *uA, int k, int sizeUA) {
int eos = eosType();
if (eos == 0) {
for (int i = 0; i < sizeUA; i++) {
uA[i] = 0.0;
}
} else {
for (int i = 0; i < sizeUA; i++) {
if (i == 0) uA[0] = 1.0;
if (i == 1) uA[1] = -nDim();
if (i == 2) uA[2] = 0.0;
if (i == 3) uA[3] = 0.0;
if (i == 4) uA[4] = 0.0;
if (i == 5) uA[5] = 0.0;
}
}
}
/*
* Get the array of non-dimensional molality-based
* activities at the current solution temperature,
* pressure, and solution concentration.
*
* The max against 8.689E-3 is to limit the activity
* coefficient to be greater than 1.0E-50.
*/
void IdealMolalSoln::getActivities(doublereal* ac) const {
_updateStandardStateThermo();
/*
* Update the molality array, m_molalities()
* This requires an update due to mole fractions
*/
calcMolalities();
for (int k = 0; k < m_kk; k++) {
ac[k] = m_molalities[k];
}
double xmolSolvent = moleFraction(m_indexSolvent);
xmolSolvent = fmaxx(8.689E-3, xmolSolvent);
ac[m_indexSolvent] =
exp((xmolSolvent - 1.0)/xmolSolvent);
}
/*
* Get the array of non-dimensional Molality based
* activity coefficients at
* the current solution temperature, pressure, and
* solution concentration.
* See Denbigh
* (note solvent activity coefficient is on the molar scale).
*
* The max against 5.0E-3 (1/200) is to limit the activity
* coefficient to be greater than 1.0E-50.
*/
void IdealMolalSoln::
getMolalityActivityCoefficients(doublereal* acMolality) const {
for (int k = 0; k < m_kk; k++) {
acMolality[k] = 1.0;
}
double xmolSolvent = moleFraction(m_indexSolvent);
xmolSolvent = fmaxx(8.689E-3, xmolSolvent);
acMolality[m_indexSolvent] =
exp((xmolSolvent - 1.0)/xmolSolvent) / xmolSolvent;
}
//
// ------ Partial Molar Properties of the Solution -----------------
//
/*
* Get the species chemical potentials: Units: J/kmol.
*
* This function returns a vector of chemical potentials of the
* species in solution.
*
* \f[
* \mu_k = \mu^{o}_k(T,P) + R T \ln(\frac{m_k}{m^\Delta})
* \f]
* \f[
* \mu_w = \mu^{o}_w(T,P) +
* R T ((X_w - 1.0) / X_w)
* \f]
*
* \f$ w \f$ refers to the solvent species.
* \f$ X_w \f$ is the mole fraction of the solvent.
* \f$ m_k \f$ is the molality of the kth solute.
* \f$ m^\Delta is 1 gmol solute per kg solvent. \f$
*
* Units: J/kmol.
*/
void IdealMolalSoln::getChemPotentials(doublereal* mu) const{
double xx;
const double xxSmall = 1.0E-150;
/*
* First get the standard chemical potentials
* -> this requires updates of standard state as a function
* of T and P
* These are defined at unit molality.
*/
getStandardChemPotentials(mu);
/*
* Update the molality array, m_molalities()
* This requires an update due to mole fractions
*/
calcMolalities();
/*
*
*/
doublereal RT = GasConstant * temperature();
for (int k = 0; k < m_kk; k++) {
if (k != m_indexSolvent) {
xx = fmaxx(m_molalities[k], xxSmall);
mu[k] += RT * log(xx);
}
}
/*
* Do the solvent
* -> see my notes
*/
double xmolSolvent = moleFraction(m_indexSolvent);
xx = fmaxx(xmolSolvent, xxSmall);
mu[m_indexSolvent] +=
(RT * (xmolSolvent - 1.0) / xx);
}
/*
* Returns an array of partial molar enthalpies for the species
* in the mixture: Units (J/kmol).
*
*/
void IdealMolalSoln::getPartialMolarEnthalpies(doublereal* hbar) const {
getEnthalpy_RT(hbar);
doublereal RT = _RT();
for (int k = 0; k < m_kk; k++) {
hbar[k] *= RT;
}
}
/*
* Returns an array of partial molar entropies of the species in the
* solution: Units: J/kmol.
*
* Maxwell's equations provide an insight in how to calculate this
* (p.215 Smith and Van Ness)
* \f[
* \frac{d(\mu_k)}{dT} = -\bar{s}_i
* \f]
* For this phase, the partial molar entropies are equal to the
* standard state species entropies plus the ideal molal solution contribution.
*
* \f[
* \bar{s}_k(T,P) = s^0_k(T) - R log( m_k )
* \f]
* \f[
* \bar{s}_w(T,P) = s^0_w(T) - R ((X_w - 1.0) / X_w)
* \f]
*
* The subscript, w, refers to the solvent species. \f$ X_w \f$ is
* the mole fraction of solvent.
* The reference-state pure-species entropies,\f$ s^0_k(T) \f$,
* at the reference pressure, \f$ P_{ref} \f$, are computed by the
* species thermodynamic
* property manager. They are polynomial functions of temperature.
* @see SpeciesThermo
*/
void IdealMolalSoln::
getPartialMolarEntropies(doublereal* sbar) const {
getEntropy_R(sbar);
doublereal R = GasConstant;
doublereal mm;
calcMolalities();
for (int k = 0; k < m_kk; k++) {
if (k != m_indexSolvent) {
mm = fmaxx(SmallNumber, m_molalities[k]);
sbar[k] -= R * log(mm);
}
}
double xmolSolvent = moleFraction(m_indexSolvent);
sbar[m_indexSolvent] -= (R * (xmolSolvent - 1.0) / xmolSolvent);
}
/*
* Returns an array of partial molar volumes of the species
* in the solution: Units: m^3 kmol-1.
*
* For this solution, the partial molar volumes are equal to the
* constant species molar volumes.
*
* Units: m^3 kmol-1.
*/
void IdealMolalSoln::getPartialMolarVolumes(doublereal* vbar) const {
getStandardVolumes(vbar);
}
/*
* Partial molar heat capacity of the solution: Units: J/kmol/K.
*
* The kth partial molar heat capacity is equal to
* the temperature derivative of the partial molar
* enthalpy of the kth species in the solution at constant
* P and composition (p. 220 Smith and Van Ness).
* \f[
* \bar{Cp}_k(T,P) = {Cp}^0_k(T)
* \f]
*
* For this solution, this is equal to the reference state
* heat capacities.
*
* Units: J/kmol/K
*/
void IdealMolalSoln::getPartialMolarCp(doublereal* cpbar) const {
/*
* Get the nondimensional gibbs standard state of the
* species at the T and P of the solution.
*/
getCp_R(cpbar);
for (int k = 0; k < m_kk; k++) {
cpbar[k] *= GasConstant;
}
}
/*
* -------- Properties of the Standard State of the Species
* in the Solution ------------------
*/
/*
* Get the standard state chemical potentials of the species.
* This is the array of chemical potentials at unit activity
* (Mole fraction scale)
* \f$ \mu^0_k(T,P) \f$.
* We define these here as the chemical potentials of the pure
* species at the temperature and pressure of the solution.
* This function is used in the evaluation of the
* equilibrium constant Kc. Therefore, Kc will also depend
* on T and P. This is the norm for liquid and solid systems.
*
* units = J / kmol
*/
void IdealMolalSoln::getStandardChemPotentials(doublereal* mu) const {
_updateStandardStateThermo();
getGibbs_ref(mu);
doublereal pref;
doublereal delta_p;
for (int k = 0; k < m_kk; k++) {
pref = m_spthermo->refPressure(k);
delta_p = m_Pcurrent - pref;
mu[k] += delta_p * m_speciesMolarVolume[k];
}
}
/*
* Get the nondimensional gibbs function for the species
* standard states at the current T and P of the solution.
*
* \f[
* \mu^0_k(T,P) = \mu^{ref}_k(T) + (P - P_{ref}) * V_k
* \f]
* where \f$V_k\f$ is the molar volume of pure species <I>k</I>.
* \f$ \mu^{ref}_k(T)\f$ is the chemical potential of pure
* species <I>k</I> at the reference pressure, \f$P_{ref}\f$.
*
* @param grt Vector of length m_kk, which on return sr[k]
* will contain the nondimensional
* standard state gibbs function for species k.
*/
void IdealMolalSoln::getGibbs_RT(doublereal* grt) const {
getPureGibbs(grt);
doublereal invRT = 1.0 / _RT();
for (int k = 0; k < m_kk; k++) {
grt[k] *= invRT;
}
}
/*
* Get the Gibbs functions for the pure species
* at the current <I>T</I> and <I>P</I> of the solution.
* We assume an incompressible constant partial molar
* volume here:
* \f[
* \mu^0_k(T,p) = \mu^{ref}_k(T) + (P - P_{ref}) * V_k
* \f]
* where \f$V_k\f$ is the molar volume of pure species <I>k</I>.
* \f$ u^{ref}_k(T)\f$ is the chemical potential of pure
* species <I>k</I> at the reference pressure, \f$P_{ref}\f$.
*
* Units: J/kmol
*/
void IdealMolalSoln::getPureGibbs(doublereal* gpure) const {
_updateStandardStateThermo();
getGibbs_ref(gpure);
doublereal pref;
doublereal delta_p;
for (int k = 0; k < m_kk; k++) {
pref = m_spthermo->refPressure(k);
delta_p = m_Pcurrent - pref;
gpure[k] += delta_p * m_speciesMolarVolume[k];
}
}
/*
* Get the array of nondimensional Enthalpy functions for the ss
* species at the current <I>T</I> and <I>P</I> of the solution.
* We assume an incompressible constant partial molar
* volume here:
* \f[
* h^0_k(T,P) = h^{ref}_k(T) + (P - P_{ref}) * V_k
* \f]
* where \f$V_k\f$ is the molar volume of SS species <I>k</I>.
* \f$ h^{ref}_k(T)\f$ is the enthalpy of the SS
* species <I>k</I> at the reference pressure, \f$P_{ref}\f$.
*
* Units: dimensionless.
*/
void IdealMolalSoln::
getEnthalpy_RT(doublereal* hrt) const {
_updateStandardStateThermo();
getEnthalpy_RT_ref(hrt);
doublereal pref;
doublereal delta_p;
double RT = _RT();
for (int k = 0; k < m_kk; k++) {
pref = m_spthermo->refPressure(k);
delta_p = m_Pcurrent - pref;
hrt[k] += delta_p/ RT * m_speciesMolarVolume[k];
}
}
/*
* Get the nondimensional Entropies for the species
* standard states: Units: J/kmol/K
*
* Note, this is equal to the reference state entropies
* due to the zero volume expansivity.
* i.e., (dS/dp)_T = (dV/dT)_P = 0.0
*
* \f[
* S^0_k(T,P) = S^{ref}_k(T)
* \f]
*
* Units: dimensionless
*
* @param sr Vector of length m_kk, which on return sr[k]
* will contain the nondimensional
* standard state entropy of species k.
*/
void IdealMolalSoln::
getEntropy_R(doublereal* sr) const {
_updateStandardStateThermo();
getEntropy_R_ref(sr);
}
/*
* Get the nondimensional heat capacity at constant pressure
* function for the species
* standard states: Units J/kmol/K
* \f[</I>
* Cp^0_k(T,P) = Cp^{ref}_k(T)
* \f]
* where \f$V_k\f$ is the molar volume of pure species <I>k</I>.
* \f$ Cp^{ref}_k(T)\f$ is the constant pressure heat capacity
* of species <I>k</I> at the reference pressure, \f$p_{ref}\f$.
*
* @param cpr Vector of length m_kk, which on return cpr[k]
* will contain the nondimensional
* constant pressure heat capacity for species k.
*/
void IdealMolalSoln::getCp_R(doublereal* cpr) const {
_updateStandardStateThermo();
getCp_R_ref(cpr);
}
/*
* Get the molar volumes of each species in their standard
* states at the current
* <I>T</I> and <I>P</I> of the solution.
*
* \f[
* V^0_k(T,P) = V^{ref}_k()
* \f]
* Units = m^3 / kmol
*/
void IdealMolalSoln::getStandardVolumes(doublereal *vol) const {
_updateStandardStateThermo();
copy(m_speciesMolarVolume.begin(),
m_speciesMolarVolume.end(), vol);
}
/*
* Updates the standard state thermodynamic functions at the current T and P of the solution.
*
* @internal
*
* This function gets called for every call to functions in this
* class. It checks to see whether the temperature or pressure has changed and
* thus the ss thermodynamics functions for all of the species
* must be recalculated.
*/
void IdealMolalSoln::_updateStandardStateThermo(doublereal pnow) const {
_updateRefStateThermo();
doublereal tnow = temperature();
if (pnow == -1.0) {
pnow = m_Pcurrent;
}
if (m_tlast != tnow || m_plast != pnow) {
m_tlast = tnow;
m_plast = pnow;
}
}
/*
* ------ Thermodynamic Values for the Species Reference States ---
*/
// -> This is handled by VPStandardStatesTP
/*
* -------------- Utilities -------------------------------
*/
/*
* Initialization routine for an IdealMolalSoln phase.
*
* This is a virtual routine. This routine will call initThermo()
* for the parent class as well.
*/
void IdealMolalSoln::initThermo() {
initLengths();
MolalityVPSSTP::initThermo();
}
/*
* Initialization of an IdealMolalSoln phase using an
* xml file
*
* This routine is a precursor to constructPhaseFile(XML_Node*)
* routine, which does most of the work.
*
* @param inputFile XML file containing the description of the
* phase
*
* @param id Optional parameter identifying the name of the
* phase. If none is given, the first XML
* phase element will be used.
*/
void IdealMolalSoln::constructPhaseFile(std::string inputFile,
std::string id) {
if (inputFile.size() == 0) {
throw CanteraError("IdealMolalSoln::constructPhaseFile",
"input file is null");
}
std::string path = findInputFile(inputFile);
std::ifstream fin(path.c_str());
if (!fin) {
throw CanteraError("IdealMolalSoln::constructPhaseFile",
"could not open "
+path+" for reading.");
}
/*
* The phase object automatically constructs an XML object.
* Use this object to store information.
*/
XML_Node &phaseNode_XML = xml();
XML_Node *fxml = new XML_Node();
fxml->build(fin);
XML_Node *fxml_phase = findXMLPhase(fxml, id);
if (!fxml_phase) {
throw CanteraError("IdealMolalSoln::constructPhaseFile",
"ERROR: Can not find phase named " +
id + " in file named " + inputFile);
}
fxml_phase->copy(&phaseNode_XML);
constructPhaseXML(*fxml_phase, id);
delete fxml;
}
/*
* Import and initialize an IdealMolalSoln phase
* specification in an XML tree into the current object.
* Here we read an XML description of the phase.
* We import descriptions of the elements that make up the
* species in a phase.
* We import information about the species, including their
* reference state thermodynamic polynomials. We then freeze
* the state of the species.
*
* Then, we read the species molar volumes from the xml
* tree to finish the initialization.
*
* @param phaseNode This object must be the phase node of a
* complete XML tree
* description of the phase, including all of the
* species data. In other words while "phase" must
* point to an XML phase object, it must have
* sibling nodes "speciesData" that describe
* the species in the phase.
* @param id ID of the phase. If nonnull, a check is done
* to see if phaseNode is pointing to the phase
* with the correct id.
*/
void IdealMolalSoln::constructPhaseXML(XML_Node& phaseNode,
std::string id) {
if (id.size() > 0) {
std::string idp = phaseNode.id();
if (idp != id) {
throw CanteraError("IdealMolalSoln::constructPhaseXML",
"phasenode and Id are incompatible");
}
}
/*
* Find the Thermo XML node
*/
if (!phaseNode.hasChild("thermo")) {
throw CanteraError("IdealMolalSoln::constructPhaseXML",
"no thermo XML node");
}
/*
* Call the Cantera importPhase() function. This will import
* all of the species into the phase. Then, it will call
* initThermoXML() below.
*/
bool m_ok = importPhase(phaseNode, this);
if (!m_ok) {
throw CanteraError("IdealMolalSoln::constructPhaseXML","importPhase failed ");
}
}
/*
* Import and initialize an IdealMolalSoln phase
* specification in an XML tree into the current object.
*
* This routine is called from importPhase() to finish
* up the initialization of the thermo object. It reads in the
* species molar volumes.
*
* @param phaseNode This object must be the phase node of a
* complete XML tree
* description of the phase, including all of the
* species data. In other words while "phase" must
* point to an XML phase object, it must have
* sibling nodes "speciesData" that describe
* the species in the phase.
* @param id ID of the phase. If nonnull, a check is done
* to see if phaseNode is pointing to the phase
* with the correct id.
*/
void IdealMolalSoln::initThermoXML(XML_Node& phaseNode, std::string id) {
/*
* Initialize the whole thermo object, using a virtual function.
*/
initThermo();
if (id.size() > 0) {
std::string idp = phaseNode.id();
if (idp != id) {
throw CanteraError("IdealMolalSoln::initThermo",
"phasenode and Id are incompatible");
}
}
/*
* Find the Thermo XML node
*/
if (!phaseNode.hasChild("thermo")) {
throw CanteraError("IdealMolalSoln::initThermo",
"no thermo XML node");
}
XML_Node& thermoNode = phaseNode.child("thermo");
/*
* Possible change the form of the standard concentrations
*/
if (thermoNode.hasChild("standardConc")) {
XML_Node& scNode = thermoNode.child("standardConc");
m_formGC = 2;
std::string formString = scNode.attrib("model");
if (formString != "") {
if (formString == "unity") {
m_formGC = 0;
} else if (formString == "molar_volume") {
m_formGC = 1;
} else if (formString == "solvent_volume") {
m_formGC = 2;
} else {
throw CanteraError("IdealMolalSoln::initThermo",
"Unknown standardConc model: " + formString);
}
}
}
/*
* Get the Name of the Solvent:
* <solvent> solventName </solvent>
*/
std::string solventName = "";
if (thermoNode.hasChild("solvent")) {
XML_Node& scNode = thermoNode.child("solvent");
std::vector<std::string> nameSolventa;
getStringArray(scNode, nameSolventa);
int nsp = static_cast<int>(nameSolventa.size());
if (nsp != 1) {
throw CanteraError("IdealMolalSoln::initThermoXML",
"badly formed solvent XML node");
}
solventName = nameSolventa[0];
}
/*
* Reconcile the solvent name and index.
*/
for (int k = 0; k < m_kk; k++) {
std::string sname = speciesName(k);
if (solventName == sname) {
m_indexSolvent = k;
break;
}
}
if (m_indexSolvent == -1) {
std::cout << "IdealMolalSoln::initThermo: Solvent Name not found"
<< std::endl;
throw CanteraError("IdealMolalSoln::initThermo",
"Solvent name not found");
}
if (m_indexSolvent != 0) {
throw CanteraError("IdealMolalSoln::initThermo",
"Solvent " + solventName +
" should be first species");
}
/*
* Now go get the molar volumes
*/
XML_Node& speciesList = phaseNode.child("speciesArray");
XML_Node* speciesDB =
get_XML_NameID("speciesData", speciesList["datasrc"],
&phaseNode.root());
const std::vector<std::string> &sss = speciesNames();
for (int k = 0; k < m_kk; k++) {
XML_Node* s = speciesDB->findByAttr("name", sss[k]);
XML_Node *ss = s->findByName("standardState");
m_speciesMolarVolume[k] = getFloat(*ss, "molarVolume", "-");
}
/*
* Set the state
*/
if (phaseNode.hasChild("state")) {
XML_Node& stateNode = phaseNode.child("state");
setStateFromXML(stateNode);
}
}
/*
* @internal
* Set equation of state parameters. The number and meaning of
* these depends on the subclass.
* @param n number of parameters
* @param c array of \i n coefficients
*
*/
void IdealMolalSoln::setParameters(int n, doublereal* c) {
}
void IdealMolalSoln::getParameters(int &n, doublereal * const c) {
}
/*
* Set equation of state parameter values from XML
* entries. This method is called by function importPhase in
* file importCTML.cpp when processing a phase definition in
* an input file. It should be overloaded in subclasses to set
* any parameters that are specific to that particular phase
* model.
*
* @param eosdata An XML_Node object corresponding to
* the "thermo" entry for this phase in the input file.
*
* HKM -> Right now, the parameters are set elsewhere (initThermo)
* It just didn't seem to fit.
*/
void IdealMolalSoln::setParametersFromXML(const XML_Node& eosdata) {
}
/*
* ----------- Critical State Properties --------------------------
*/
/*
* ------------ Private and Restricted Functions ------------------
*/
/*
* Bail out of functions with an error exit if they are not
* implemented.
*/
doublereal IdealMolalSoln::err(std::string msg) const {
throw CanteraError("IdealMolalSoln",
"Unfinished func called: " + msg );
return 0.0;
}
/*
* This internal function adjusts the lengths of arrays.
*
* This function is not virtual nor is it inherited
*/
void IdealMolalSoln::initLengths() {
m_kk = nSpecies();
/*
* Obtain the limits of the temperature from the species
* thermo handler's limits.
*/
int leng = m_kk;
m_expg0_RT.resize(leng);
m_pe.resize(leng, 0.0);
m_pp.resize(leng);
m_speciesMolarVolume.resize(leng);
m_tmpV.resize(leng);
}
}
Solaris 10 updaet
Put a std:: on copy.
/**
*
* @file IdealMolalSoln.cpp
*/
/*
* Copywrite (2006) Sandia Corporation. Under the terms of
* Contract DE-AC04-94AL85000 with Sandia Corporation, the
* U.S. Government retains certain rights in this software.
*/
/*
* $Author$
* $Date$
* $Revision$
*/
#include "IdealMolalSoln.h"
#include "importCTML.h"
#include <math.h>
namespace Cantera {
/**
* Default constructor
*/
IdealMolalSoln::IdealMolalSoln() :
MolalityVPSSTP(),
m_formGC(2)
{
}
/**
* Copy Constructor:
*
* Note this stuff will not work until the underlying phase
* has a working copy constructor
*/
IdealMolalSoln::IdealMolalSoln(const IdealMolalSoln &b) :
MolalityVPSSTP(b)
{
/*
* Use the assignment operator to do the brunt
* of the work for the copy construtor.
*/
*this = b;
}
/**
* operator=()
*
* Note this stuff will not work until the underlying phase
* has a working assignment operator
*/
IdealMolalSoln& IdealMolalSoln::
operator=(const IdealMolalSoln &b) {
if (&b != this) {
MolalityVPSSTP::operator=(b);
m_speciesMolarVolume = b.m_speciesMolarVolume;
m_formGC = b.m_formGC;
m_expg0_RT = b.m_expg0_RT;
m_pe = b.m_pe;
m_pp = b.m_pp;
m_tmpV = b.m_tmpV;
}
return *this;
}
IdealMolalSoln::IdealMolalSoln(std::string inputFile, std::string id) :
MolalityVPSSTP()
{
constructPhaseFile(inputFile, id);
}
IdealMolalSoln::IdealMolalSoln(XML_Node& root, std::string id) :
MolalityVPSSTP()
{
constructPhaseXML(root, id);
}
/**
*
* ~IdealMolalSoln(): (virtual)
*
* Destructor: does nothing:
*
*/
IdealMolalSoln::~IdealMolalSoln() {
}
/**
*
*/
ThermoPhase* IdealMolalSoln::duplMyselfAsThermoPhase() {
IdealMolalSoln* mtp = new IdealMolalSoln(*this);
return (ThermoPhase *) mtp;
}
//
// -------- Molar Thermodynamic Properties of the Solution ---------------
//
/*
* Molar enthalpy of the solution: Units: J/kmol.
*
* Returns the amount of enthalpy per mole of solution.
* For an ideal molal solution,
* \f[
* \bar{h}(T, P, X_k) = \sum_k X_k \bar{h}_k(T)
* \f]
* The formula is written in terms of the partial molar enthalpies.
* \f$ \bar{h}_k(T, p, m_k) \f$.
* See the partial molar enthalpy function, getPartialMolarEnthalpies(),
* for details.
*
* Units: J/kmol
*/
doublereal IdealMolalSoln::enthalpy_mole() const {
getPartialMolarEnthalpies(DATA_PTR(m_tmpV));
getMoleFractions(DATA_PTR(m_pp));
double val = mean_X(DATA_PTR(m_tmpV));
return val;
}
/*
* Molar internal energy of the solution: Units: J/kmol.
*
* Returns the amount of internal energy per mole of solution.
* For an ideal molal solution,
* \f[
* \bar{u}(T, P, X_k) = \sum_k X_k \bar{u}_k(T)
* \f]
* The formula is written in terms of the partial molar internal energy.
* \f$ \bar{u}_k(T, p, m_k) \f$.
*/
doublereal IdealMolalSoln::intEnergy_mole() const {
getPartialMolarEnthalpies(DATA_PTR(m_tmpV));
return mean_X(DATA_PTR(m_tmpV));
}
/*
* Molar entropy of the solution: Units J/kmol/K.
*
* Returns the amount of entropy per mole of solution.
* For an ideal molal solution,
* \f[
* \bar{s}(T, P, X_k) = \sum_k X_k \bar{s}_k(T)
* \f]
* The formula is written in terms of the partial molar entropies.
* \f$ \bar{s}_k(T, p, m_k) \f$.
* See the partial molar entropies function, getPartialMolarEntropies(),
* for details.
*
* Units: J/kmol/K.
*/
doublereal IdealMolalSoln::entropy_mole() const {
getPartialMolarEntropies(DATA_PTR(m_tmpV));
return mean_X(DATA_PTR(m_tmpV));
}
/*
* Molar Gibbs function for the solution: Units J/kmol.
*
* Returns the gibbs free energy of the solution per mole
* of the solution.
*
* \f[
* \bar{g}(T, P, X_k) = \sum_k X_k \mu_k(T)
* \f]
*
* Units: J/kmol
*/
doublereal IdealMolalSoln::gibbs_mole() const {
getChemPotentials(DATA_PTR(m_tmpV));
return mean_X(DATA_PTR(m_tmpV));
}
/*
* Molar heat capacity at constant pressure: Units: J/kmol/K.
* * \f[
* \bar{c}_p(T, P, X_k) = \sum_k X_k \bar{c}_{p,k}(T)
* \f]
*
* Units: J/kmol/K
*/
doublereal IdealMolalSoln::cp_mole() const {
getPartialMolarCp(DATA_PTR(m_tmpV));
double val = mean_X(DATA_PTR(m_tmpV));
return val;
}
/*
* Molar heat capacity at constant volume: Units: J/kmol/K.
* NOT IMPLEMENTED.
* Units: J/kmol/K
*/
doublereal IdealMolalSoln::cv_mole() const {
return err("not implemented");
}
//
// ------- Mechanical Equation of State Properties ------------------------
//
/*
* Pressure. Units: Pa.
* For this incompressible system, we return the internally storred
* independent value of the pressure.
*/
doublereal IdealMolalSoln::pressure() const {
return m_Pcurrent;
}
/*
* Set the pressure at constant temperature. Units: Pa.
* This method sets a constant within the object.
* The mass density is not a function of pressure.
*/
void IdealMolalSoln::setPressure(doublereal p) {
#ifdef DEBUG_MODE
//printf("setPressure: %g\n", p);
#endif
/*
* Store the current pressure
*/
m_Pcurrent = p;
/*
* update the standard state thermo
* -> This involves calling the water function and setting the pressure
*/
_updateStandardStateThermo();
/*
* Calculate all of the other standard volumes
* -> note these are constant for now
*/
/*
* Get the partial molar volumes of all of the
* species. -> note this is a lookup for
* water, here since it was done above.
*/
double *vbar = &m_pp[0];
getPartialMolarVolumes(vbar);
/*
* Get mole fractions of all species.
*/
double *x = &m_tmpV[0];
getMoleFractions(x);
/*
* Calculate the solution molar volume and the
* solution density.
*/
doublereal vtotal = 0.0;
for (int i = 0; i < m_kk; i++) {
vtotal += vbar[i] * x[i];
}
doublereal dd = meanMolecularWeight() / vtotal;
/*
* Now, update the State class with the results. This
* stores the density.
*/
State::setDensity(dd);
}
/*
* The isothermal compressibility. Units: 1/Pa.
* The isothermal compressibility is defined as
* \f[
* \kappa_T = -\frac{1}{v}\left(\frac{\partial v}{\partial P}\right)_T
* \f]
*
* It's equal to zero for this model, since the molar volume
* doesn't change with pressure or temperature.
*/
doublereal IdealMolalSoln::isothermalCompressibility() const {
return 0.0;
}
/*
* The thermal expansion coefficient. Units: 1/K.
* The thermal expansion coefficient is defined as
*
* \f[
* \beta = \frac{1}{v}\left(\frac{\partial v}{\partial T}\right)_P
* \f]
*
* It's equal to zero for this model, since the molar volume
* doesn't change with pressure or temperature.
*/
doublereal IdealMolalSoln::thermalExpansionCoeff() const {
return 0.0;
}
/*
* Overwritten setDensity() function is necessary because the
* density is not an indendent variable.
*
* This function will now throw an error condition
*
* @internal May have to adjust the strategy here to make
* the eos for these materials slightly compressible, in order
* to create a condition where the density is a function of
* the pressure.
*
* This function will now throw an error condition.
*
* NOTE: This is an overwritten function from the State.h
* class
*/
void IdealMolalSoln::setDensity(doublereal rho) {
double dens = density();
if (rho != dens) {
throw CanteraError("Idea;MolalSoln::setDensity",
"Density is not an independent variable");
}
}
/*
* Overwritten setMolarDensity() function is necessary because the
* density is not an indendent variable.
*
* This function will now throw an error condition.
*
* NOTE: This is a virtual function, overwritten function from the State.h
* class
*/
void IdealMolalSoln::setMolarDensity(doublereal conc) {
double concI = State::molarDensity();
if (conc != concI) {
throw CanteraError("IdealMolalSoln::setMolarDensity",
"molarDensity/denisty is not an independent variable");
}
}
//
// ------- Activities and Activity Concentrations
//
/*
* This method returns an array of activity concentrations \f$ C^a_k\f$.
* \f$ C^a_k\f$ are defined such that
* \f$ a_k = C^a_k / C^s_k, \f$ where \f$ C^s_k \f$
* is a standard concentration
* defined below. These activity concentrations are used
* by kinetics manager classes to compute the forward and
* reverse rates of elementary reactions.
*
* @param c Array of activity concentrations. The
* units depend upon the implementation of the
* reaction rate expressions within the phase.
*/
void IdealMolalSoln::getActivityConcentrations(doublereal* c) const {
if (m_formGC != 1) {
double c_solvent = standardConcentration();
getActivities(c);
for (int k = 0; k < m_kk; k++) {
c[k] *= c_solvent;
}
} else {
getActivities(c);
for (int k = 0; k < m_kk; k++) {
double c0 = standardConcentration(k);
c[k] *= c0;
}
}
}
/*
* The standard concentration \f$ C^s_k \f$ used to normalize
* the activity concentration. In many cases, this quantity
* will be the same for all species in a phase - for example,
* for an ideal gas \f$ C^s_k = P/\hat R T \f$. For this
* reason, this method returns a single value, instead of an
* array. However, for phases in which the standard
* concentration is species-specific (e.g. surface species of
* different sizes), this method may be called with an
* optional parameter indicating the species.
*
*/
doublereal IdealMolalSoln::standardConcentration(int k) const {
double c0 = 1.0, mvSolvent;
switch (m_formGC) {
case 0:
break;
case 1:
c0 = 1.0 /m_speciesMolarVolume[m_indexSolvent];
break;
case 2:
mvSolvent = m_speciesMolarVolume[m_indexSolvent];
c0 = 1.0 / mvSolvent;
break;
}
return c0;
}
/*
* Returns the natural logarithm of the standard
* concentration of the kth species
*/
doublereal IdealMolalSoln::logStandardConc(int k) const {
double c0 = standardConcentration(k);
return log(c0);
}
/*
* Returns the units of the standard and general concentrations
* Note they have the same units, as their divisor is
* defined to be equal to the activity of the kth species
* in the solution, which is unitless.
*
* This routine is used in print out applications where the
* units are needed. Usually, MKS units are assumed throughout
* the program and in the XML input files.
*
* On return uA contains the powers of the units (MKS assumed)
* of the standard concentrations and generalized concentrations
* for the kth species.
*
* uA[0] = kmol units - default = 1
* uA[1] = m units - default = -nDim(), the number of spatial
* dimensions in the Phase class.
* uA[2] = kg units - default = 0;
* uA[3] = Pa(pressure) units - default = 0;
* uA[4] = Temperature units - default = 0;
* uA[5] = time units - default = 0
*/
void IdealMolalSoln::getUnitsStandardConc(double *uA, int k, int sizeUA) {
int eos = eosType();
if (eos == 0) {
for (int i = 0; i < sizeUA; i++) {
uA[i] = 0.0;
}
} else {
for (int i = 0; i < sizeUA; i++) {
if (i == 0) uA[0] = 1.0;
if (i == 1) uA[1] = -nDim();
if (i == 2) uA[2] = 0.0;
if (i == 3) uA[3] = 0.0;
if (i == 4) uA[4] = 0.0;
if (i == 5) uA[5] = 0.0;
}
}
}
/*
* Get the array of non-dimensional molality-based
* activities at the current solution temperature,
* pressure, and solution concentration.
*
* The max against 8.689E-3 is to limit the activity
* coefficient to be greater than 1.0E-50.
*/
void IdealMolalSoln::getActivities(doublereal* ac) const {
_updateStandardStateThermo();
/*
* Update the molality array, m_molalities()
* This requires an update due to mole fractions
*/
calcMolalities();
for (int k = 0; k < m_kk; k++) {
ac[k] = m_molalities[k];
}
double xmolSolvent = moleFraction(m_indexSolvent);
xmolSolvent = fmaxx(8.689E-3, xmolSolvent);
ac[m_indexSolvent] =
exp((xmolSolvent - 1.0)/xmolSolvent);
}
/*
* Get the array of non-dimensional Molality based
* activity coefficients at
* the current solution temperature, pressure, and
* solution concentration.
* See Denbigh
* (note solvent activity coefficient is on the molar scale).
*
* The max against 5.0E-3 (1/200) is to limit the activity
* coefficient to be greater than 1.0E-50.
*/
void IdealMolalSoln::
getMolalityActivityCoefficients(doublereal* acMolality) const {
for (int k = 0; k < m_kk; k++) {
acMolality[k] = 1.0;
}
double xmolSolvent = moleFraction(m_indexSolvent);
xmolSolvent = fmaxx(8.689E-3, xmolSolvent);
acMolality[m_indexSolvent] =
exp((xmolSolvent - 1.0)/xmolSolvent) / xmolSolvent;
}
//
// ------ Partial Molar Properties of the Solution -----------------
//
/*
* Get the species chemical potentials: Units: J/kmol.
*
* This function returns a vector of chemical potentials of the
* species in solution.
*
* \f[
* \mu_k = \mu^{o}_k(T,P) + R T \ln(\frac{m_k}{m^\Delta})
* \f]
* \f[
* \mu_w = \mu^{o}_w(T,P) +
* R T ((X_w - 1.0) / X_w)
* \f]
*
* \f$ w \f$ refers to the solvent species.
* \f$ X_w \f$ is the mole fraction of the solvent.
* \f$ m_k \f$ is the molality of the kth solute.
* \f$ m^\Delta is 1 gmol solute per kg solvent. \f$
*
* Units: J/kmol.
*/
void IdealMolalSoln::getChemPotentials(doublereal* mu) const{
double xx;
const double xxSmall = 1.0E-150;
/*
* First get the standard chemical potentials
* -> this requires updates of standard state as a function
* of T and P
* These are defined at unit molality.
*/
getStandardChemPotentials(mu);
/*
* Update the molality array, m_molalities()
* This requires an update due to mole fractions
*/
calcMolalities();
/*
*
*/
doublereal RT = GasConstant * temperature();
for (int k = 0; k < m_kk; k++) {
if (k != m_indexSolvent) {
xx = fmaxx(m_molalities[k], xxSmall);
mu[k] += RT * log(xx);
}
}
/*
* Do the solvent
* -> see my notes
*/
double xmolSolvent = moleFraction(m_indexSolvent);
xx = fmaxx(xmolSolvent, xxSmall);
mu[m_indexSolvent] +=
(RT * (xmolSolvent - 1.0) / xx);
}
/*
* Returns an array of partial molar enthalpies for the species
* in the mixture: Units (J/kmol).
*
*/
void IdealMolalSoln::getPartialMolarEnthalpies(doublereal* hbar) const {
getEnthalpy_RT(hbar);
doublereal RT = _RT();
for (int k = 0; k < m_kk; k++) {
hbar[k] *= RT;
}
}
/*
* Returns an array of partial molar entropies of the species in the
* solution: Units: J/kmol.
*
* Maxwell's equations provide an insight in how to calculate this
* (p.215 Smith and Van Ness)
* \f[
* \frac{d(\mu_k)}{dT} = -\bar{s}_i
* \f]
* For this phase, the partial molar entropies are equal to the
* standard state species entropies plus the ideal molal solution contribution.
*
* \f[
* \bar{s}_k(T,P) = s^0_k(T) - R log( m_k )
* \f]
* \f[
* \bar{s}_w(T,P) = s^0_w(T) - R ((X_w - 1.0) / X_w)
* \f]
*
* The subscript, w, refers to the solvent species. \f$ X_w \f$ is
* the mole fraction of solvent.
* The reference-state pure-species entropies,\f$ s^0_k(T) \f$,
* at the reference pressure, \f$ P_{ref} \f$, are computed by the
* species thermodynamic
* property manager. They are polynomial functions of temperature.
* @see SpeciesThermo
*/
void IdealMolalSoln::
getPartialMolarEntropies(doublereal* sbar) const {
getEntropy_R(sbar);
doublereal R = GasConstant;
doublereal mm;
calcMolalities();
for (int k = 0; k < m_kk; k++) {
if (k != m_indexSolvent) {
mm = fmaxx(SmallNumber, m_molalities[k]);
sbar[k] -= R * log(mm);
}
}
double xmolSolvent = moleFraction(m_indexSolvent);
sbar[m_indexSolvent] -= (R * (xmolSolvent - 1.0) / xmolSolvent);
}
/*
* Returns an array of partial molar volumes of the species
* in the solution: Units: m^3 kmol-1.
*
* For this solution, the partial molar volumes are equal to the
* constant species molar volumes.
*
* Units: m^3 kmol-1.
*/
void IdealMolalSoln::getPartialMolarVolumes(doublereal* vbar) const {
getStandardVolumes(vbar);
}
/*
* Partial molar heat capacity of the solution: Units: J/kmol/K.
*
* The kth partial molar heat capacity is equal to
* the temperature derivative of the partial molar
* enthalpy of the kth species in the solution at constant
* P and composition (p. 220 Smith and Van Ness).
* \f[
* \bar{Cp}_k(T,P) = {Cp}^0_k(T)
* \f]
*
* For this solution, this is equal to the reference state
* heat capacities.
*
* Units: J/kmol/K
*/
void IdealMolalSoln::getPartialMolarCp(doublereal* cpbar) const {
/*
* Get the nondimensional gibbs standard state of the
* species at the T and P of the solution.
*/
getCp_R(cpbar);
for (int k = 0; k < m_kk; k++) {
cpbar[k] *= GasConstant;
}
}
/*
* -------- Properties of the Standard State of the Species
* in the Solution ------------------
*/
/*
* Get the standard state chemical potentials of the species.
* This is the array of chemical potentials at unit activity
* (Mole fraction scale)
* \f$ \mu^0_k(T,P) \f$.
* We define these here as the chemical potentials of the pure
* species at the temperature and pressure of the solution.
* This function is used in the evaluation of the
* equilibrium constant Kc. Therefore, Kc will also depend
* on T and P. This is the norm for liquid and solid systems.
*
* units = J / kmol
*/
void IdealMolalSoln::getStandardChemPotentials(doublereal* mu) const {
_updateStandardStateThermo();
getGibbs_ref(mu);
doublereal pref;
doublereal delta_p;
for (int k = 0; k < m_kk; k++) {
pref = m_spthermo->refPressure(k);
delta_p = m_Pcurrent - pref;
mu[k] += delta_p * m_speciesMolarVolume[k];
}
}
/*
* Get the nondimensional gibbs function for the species
* standard states at the current T and P of the solution.
*
* \f[
* \mu^0_k(T,P) = \mu^{ref}_k(T) + (P - P_{ref}) * V_k
* \f]
* where \f$V_k\f$ is the molar volume of pure species <I>k</I>.
* \f$ \mu^{ref}_k(T)\f$ is the chemical potential of pure
* species <I>k</I> at the reference pressure, \f$P_{ref}\f$.
*
* @param grt Vector of length m_kk, which on return sr[k]
* will contain the nondimensional
* standard state gibbs function for species k.
*/
void IdealMolalSoln::getGibbs_RT(doublereal* grt) const {
getPureGibbs(grt);
doublereal invRT = 1.0 / _RT();
for (int k = 0; k < m_kk; k++) {
grt[k] *= invRT;
}
}
/*
* Get the Gibbs functions for the pure species
* at the current <I>T</I> and <I>P</I> of the solution.
* We assume an incompressible constant partial molar
* volume here:
* \f[
* \mu^0_k(T,p) = \mu^{ref}_k(T) + (P - P_{ref}) * V_k
* \f]
* where \f$V_k\f$ is the molar volume of pure species <I>k</I>.
* \f$ u^{ref}_k(T)\f$ is the chemical potential of pure
* species <I>k</I> at the reference pressure, \f$P_{ref}\f$.
*
* Units: J/kmol
*/
void IdealMolalSoln::getPureGibbs(doublereal* gpure) const {
_updateStandardStateThermo();
getGibbs_ref(gpure);
doublereal pref;
doublereal delta_p;
for (int k = 0; k < m_kk; k++) {
pref = m_spthermo->refPressure(k);
delta_p = m_Pcurrent - pref;
gpure[k] += delta_p * m_speciesMolarVolume[k];
}
}
/*
* Get the array of nondimensional Enthalpy functions for the ss
* species at the current <I>T</I> and <I>P</I> of the solution.
* We assume an incompressible constant partial molar
* volume here:
* \f[
* h^0_k(T,P) = h^{ref}_k(T) + (P - P_{ref}) * V_k
* \f]
* where \f$V_k\f$ is the molar volume of SS species <I>k</I>.
* \f$ h^{ref}_k(T)\f$ is the enthalpy of the SS
* species <I>k</I> at the reference pressure, \f$P_{ref}\f$.
*
* Units: dimensionless.
*/
void IdealMolalSoln::
getEnthalpy_RT(doublereal* hrt) const {
_updateStandardStateThermo();
getEnthalpy_RT_ref(hrt);
doublereal pref;
doublereal delta_p;
double RT = _RT();
for (int k = 0; k < m_kk; k++) {
pref = m_spthermo->refPressure(k);
delta_p = m_Pcurrent - pref;
hrt[k] += delta_p/ RT * m_speciesMolarVolume[k];
}
}
/*
* Get the nondimensional Entropies for the species
* standard states: Units: J/kmol/K
*
* Note, this is equal to the reference state entropies
* due to the zero volume expansivity.
* i.e., (dS/dp)_T = (dV/dT)_P = 0.0
*
* \f[
* S^0_k(T,P) = S^{ref}_k(T)
* \f]
*
* Units: dimensionless
*
* @param sr Vector of length m_kk, which on return sr[k]
* will contain the nondimensional
* standard state entropy of species k.
*/
void IdealMolalSoln::
getEntropy_R(doublereal* sr) const {
_updateStandardStateThermo();
getEntropy_R_ref(sr);
}
/*
* Get the nondimensional heat capacity at constant pressure
* function for the species
* standard states: Units J/kmol/K
* \f[</I>
* Cp^0_k(T,P) = Cp^{ref}_k(T)
* \f]
* where \f$V_k\f$ is the molar volume of pure species <I>k</I>.
* \f$ Cp^{ref}_k(T)\f$ is the constant pressure heat capacity
* of species <I>k</I> at the reference pressure, \f$p_{ref}\f$.
*
* @param cpr Vector of length m_kk, which on return cpr[k]
* will contain the nondimensional
* constant pressure heat capacity for species k.
*/
void IdealMolalSoln::getCp_R(doublereal* cpr) const {
_updateStandardStateThermo();
getCp_R_ref(cpr);
}
/*
* Get the molar volumes of each species in their standard
* states at the current
* <I>T</I> and <I>P</I> of the solution.
*
* \f[
* V^0_k(T,P) = V^{ref}_k()
* \f]
* Units = m^3 / kmol
*/
void IdealMolalSoln::getStandardVolumes(doublereal *vol) const {
_updateStandardStateThermo();
std::copy(m_speciesMolarVolume.begin(),
m_speciesMolarVolume.end(), vol);
}
/*
* Updates the standard state thermodynamic functions at the current T and P of the solution.
*
* @internal
*
* This function gets called for every call to functions in this
* class. It checks to see whether the temperature or pressure has changed and
* thus the ss thermodynamics functions for all of the species
* must be recalculated.
*/
void IdealMolalSoln::_updateStandardStateThermo(doublereal pnow) const {
_updateRefStateThermo();
doublereal tnow = temperature();
if (pnow == -1.0) {
pnow = m_Pcurrent;
}
if (m_tlast != tnow || m_plast != pnow) {
m_tlast = tnow;
m_plast = pnow;
}
}
/*
* ------ Thermodynamic Values for the Species Reference States ---
*/
// -> This is handled by VPStandardStatesTP
/*
* -------------- Utilities -------------------------------
*/
/*
* Initialization routine for an IdealMolalSoln phase.
*
* This is a virtual routine. This routine will call initThermo()
* for the parent class as well.
*/
void IdealMolalSoln::initThermo() {
initLengths();
MolalityVPSSTP::initThermo();
}
/*
* Initialization of an IdealMolalSoln phase using an
* xml file
*
* This routine is a precursor to constructPhaseFile(XML_Node*)
* routine, which does most of the work.
*
* @param inputFile XML file containing the description of the
* phase
*
* @param id Optional parameter identifying the name of the
* phase. If none is given, the first XML
* phase element will be used.
*/
void IdealMolalSoln::constructPhaseFile(std::string inputFile,
std::string id) {
if (inputFile.size() == 0) {
throw CanteraError("IdealMolalSoln::constructPhaseFile",
"input file is null");
}
std::string path = findInputFile(inputFile);
std::ifstream fin(path.c_str());
if (!fin) {
throw CanteraError("IdealMolalSoln::constructPhaseFile",
"could not open "
+path+" for reading.");
}
/*
* The phase object automatically constructs an XML object.
* Use this object to store information.
*/
XML_Node &phaseNode_XML = xml();
XML_Node *fxml = new XML_Node();
fxml->build(fin);
XML_Node *fxml_phase = findXMLPhase(fxml, id);
if (!fxml_phase) {
throw CanteraError("IdealMolalSoln::constructPhaseFile",
"ERROR: Can not find phase named " +
id + " in file named " + inputFile);
}
fxml_phase->copy(&phaseNode_XML);
constructPhaseXML(*fxml_phase, id);
delete fxml;
}
/*
* Import and initialize an IdealMolalSoln phase
* specification in an XML tree into the current object.
* Here we read an XML description of the phase.
* We import descriptions of the elements that make up the
* species in a phase.
* We import information about the species, including their
* reference state thermodynamic polynomials. We then freeze
* the state of the species.
*
* Then, we read the species molar volumes from the xml
* tree to finish the initialization.
*
* @param phaseNode This object must be the phase node of a
* complete XML tree
* description of the phase, including all of the
* species data. In other words while "phase" must
* point to an XML phase object, it must have
* sibling nodes "speciesData" that describe
* the species in the phase.
* @param id ID of the phase. If nonnull, a check is done
* to see if phaseNode is pointing to the phase
* with the correct id.
*/
void IdealMolalSoln::constructPhaseXML(XML_Node& phaseNode,
std::string id) {
if (id.size() > 0) {
std::string idp = phaseNode.id();
if (idp != id) {
throw CanteraError("IdealMolalSoln::constructPhaseXML",
"phasenode and Id are incompatible");
}
}
/*
* Find the Thermo XML node
*/
if (!phaseNode.hasChild("thermo")) {
throw CanteraError("IdealMolalSoln::constructPhaseXML",
"no thermo XML node");
}
/*
* Call the Cantera importPhase() function. This will import
* all of the species into the phase. Then, it will call
* initThermoXML() below.
*/
bool m_ok = importPhase(phaseNode, this);
if (!m_ok) {
throw CanteraError("IdealMolalSoln::constructPhaseXML","importPhase failed ");
}
}
/*
* Import and initialize an IdealMolalSoln phase
* specification in an XML tree into the current object.
*
* This routine is called from importPhase() to finish
* up the initialization of the thermo object. It reads in the
* species molar volumes.
*
* @param phaseNode This object must be the phase node of a
* complete XML tree
* description of the phase, including all of the
* species data. In other words while "phase" must
* point to an XML phase object, it must have
* sibling nodes "speciesData" that describe
* the species in the phase.
* @param id ID of the phase. If nonnull, a check is done
* to see if phaseNode is pointing to the phase
* with the correct id.
*/
void IdealMolalSoln::initThermoXML(XML_Node& phaseNode, std::string id) {
/*
* Initialize the whole thermo object, using a virtual function.
*/
initThermo();
if (id.size() > 0) {
std::string idp = phaseNode.id();
if (idp != id) {
throw CanteraError("IdealMolalSoln::initThermo",
"phasenode and Id are incompatible");
}
}
/*
* Find the Thermo XML node
*/
if (!phaseNode.hasChild("thermo")) {
throw CanteraError("IdealMolalSoln::initThermo",
"no thermo XML node");
}
XML_Node& thermoNode = phaseNode.child("thermo");
/*
* Possible change the form of the standard concentrations
*/
if (thermoNode.hasChild("standardConc")) {
XML_Node& scNode = thermoNode.child("standardConc");
m_formGC = 2;
std::string formString = scNode.attrib("model");
if (formString != "") {
if (formString == "unity") {
m_formGC = 0;
} else if (formString == "molar_volume") {
m_formGC = 1;
} else if (formString == "solvent_volume") {
m_formGC = 2;
} else {
throw CanteraError("IdealMolalSoln::initThermo",
"Unknown standardConc model: " + formString);
}
}
}
/*
* Get the Name of the Solvent:
* <solvent> solventName </solvent>
*/
std::string solventName = "";
if (thermoNode.hasChild("solvent")) {
XML_Node& scNode = thermoNode.child("solvent");
std::vector<std::string> nameSolventa;
getStringArray(scNode, nameSolventa);
int nsp = static_cast<int>(nameSolventa.size());
if (nsp != 1) {
throw CanteraError("IdealMolalSoln::initThermoXML",
"badly formed solvent XML node");
}
solventName = nameSolventa[0];
}
/*
* Reconcile the solvent name and index.
*/
for (int k = 0; k < m_kk; k++) {
std::string sname = speciesName(k);
if (solventName == sname) {
m_indexSolvent = k;
break;
}
}
if (m_indexSolvent == -1) {
std::cout << "IdealMolalSoln::initThermo: Solvent Name not found"
<< std::endl;
throw CanteraError("IdealMolalSoln::initThermo",
"Solvent name not found");
}
if (m_indexSolvent != 0) {
throw CanteraError("IdealMolalSoln::initThermo",
"Solvent " + solventName +
" should be first species");
}
/*
* Now go get the molar volumes
*/
XML_Node& speciesList = phaseNode.child("speciesArray");
XML_Node* speciesDB =
get_XML_NameID("speciesData", speciesList["datasrc"],
&phaseNode.root());
const std::vector<std::string> &sss = speciesNames();
for (int k = 0; k < m_kk; k++) {
XML_Node* s = speciesDB->findByAttr("name", sss[k]);
XML_Node *ss = s->findByName("standardState");
m_speciesMolarVolume[k] = getFloat(*ss, "molarVolume", "-");
}
/*
* Set the state
*/
if (phaseNode.hasChild("state")) {
XML_Node& stateNode = phaseNode.child("state");
setStateFromXML(stateNode);
}
}
/*
* @internal
* Set equation of state parameters. The number and meaning of
* these depends on the subclass.
* @param n number of parameters
* @param c array of \i n coefficients
*
*/
void IdealMolalSoln::setParameters(int n, doublereal* c) {
}
void IdealMolalSoln::getParameters(int &n, doublereal * const c) {
}
/*
* Set equation of state parameter values from XML
* entries. This method is called by function importPhase in
* file importCTML.cpp when processing a phase definition in
* an input file. It should be overloaded in subclasses to set
* any parameters that are specific to that particular phase
* model.
*
* @param eosdata An XML_Node object corresponding to
* the "thermo" entry for this phase in the input file.
*
* HKM -> Right now, the parameters are set elsewhere (initThermo)
* It just didn't seem to fit.
*/
void IdealMolalSoln::setParametersFromXML(const XML_Node& eosdata) {
}
/*
* ----------- Critical State Properties --------------------------
*/
/*
* ------------ Private and Restricted Functions ------------------
*/
/*
* Bail out of functions with an error exit if they are not
* implemented.
*/
doublereal IdealMolalSoln::err(std::string msg) const {
throw CanteraError("IdealMolalSoln",
"Unfinished func called: " + msg );
return 0.0;
}
/*
* This internal function adjusts the lengths of arrays.
*
* This function is not virtual nor is it inherited
*/
void IdealMolalSoln::initLengths() {
m_kk = nSpecies();
/*
* Obtain the limits of the temperature from the species
* thermo handler's limits.
*/
int leng = m_kk;
m_expg0_RT.resize(leng);
m_pe.resize(leng, 0.0);
m_pp.resize(leng);
m_speciesMolarVolume.resize(leng);
m_tmpV.resize(leng);
}
}
|
/*
Copyright 2015 Shoestring Research, LLC. 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.
*/
#ifndef poolqueue_Promise_hpp
#define poolqueue_Promise_hpp
#include <atomic>
#include <functional>
#include <initializer_list>
#include <memory>
#include "Promise_detail.hpp"
namespace poolqueue {
// Promises/A+ style asynchronous operations.
//
// Promise is inspired by the Promises/A+ specification
// (https://promisesaplus.com/):
//
// A promise represents the eventual result of an asynchronous
// operation. The primary way of interacting with a promise is
// through its then method, which registers callbacks to receive
// either a promise’s eventual value or the reason why the
// promise cannot be fulfilled.
//
// A Promise instance references shared state. Copying an instance
// provides another reference to the same state. The lifetime of
// the state is independent of the instance; i.e. the state lives
// as long as necessary to propagate results.
class Promise {
public:
typedef detail::Any Value;
typedef detail::bad_cast bad_cast;
// Construct a non-dependent Promise.
//
// This creates a new instance that is not attached to any other
// instance.
Promise();
// Copy constructor.
//
// Copying a Promise instance results in a second instance that
// references the same state as the first, via a shared_ptr.
Promise(const Promise&) = default;
// Copy assignment.
//
// Copying a Promise instance results in a second instance that
// references the same state as the first, via a shared_ptr.
Promise& operator=(const Promise&) = default;
// Move constructor.
Promise(Promise&&) noexcept;
// Move assignment.
Promise& operator=(Promise&&) = default;
// Construct a non-dependent Promise with callbacks.
// @onFulfil Function/functor to be called if the Promise is fulfilled.
// onFulfil may take a single argument by value, const
// reference, or rvalue reference. In the case of an
// rvalue reference argument, the Promise will be closed
// to additional callbacks. onFulfil may return a value.
// @onReject Optional function/functor to be called if the Promise is
// rejected. onReject may take a single argument of
// const std::exception_ptr& and may return a value.
//
// This creates a new instance that is not attached to any other
// instance. When the instance is settled, the appropriate
// callback argument will be called.
template<typename Fulfil, typename Reject = detail::NullReject,
typename = typename std::enable_if<!std::is_same<typename std::decay<Fulfil>::type, Promise>::value>::type>
Promise(Fulfil&& onFulfil, Reject&& onReject = Reject())
: Promise(
!std::is_same<typename std::decay<Fulfil>::type, detail::NullFulfil>::value ?
detail::makeCallbackWrapper(std::forward<Fulfil>(onFulfil)) :
static_cast<detail::CallbackWrapper *>(nullptr),
!std::is_same<typename std::decay<Reject>::type, detail::NullReject>::value ?
detail::makeCallbackWrapper(std::forward<Reject>(onReject)) :
static_cast<detail::CallbackWrapper *>(nullptr)) {
typedef typename detail::CallableTraits<Fulfil>::ArgumentType FulfilArgument;
static_assert(!std::is_same<typename std::decay<FulfilArgument>::type, Promise>::value,
"onFulfil callback cannot take a Promise argument.");
static_assert(!std::is_same<typename std::decay<FulfilArgument>::type, std::exception_ptr>::value,
"onFulfil callback cannot take a std::exception_ptr argument.");
typedef typename detail::CallableTraits<Reject>::ArgumentType RejectArgument;
static_assert(std::is_same<typename std::decay<RejectArgument>::type, std::exception_ptr>::value ||
std::is_same<typename std::decay<RejectArgument>::type, void>::value,
"onReject callback must take a void or std::exception_ptr argument.");
constexpr bool isFulfilNull = std::is_same<typename std::decay<Fulfil>::type, detail::NullFulfil>::value;
constexpr bool isRejectNull = std::is_same<typename std::decay<Reject>::type, detail::NullReject>::value;
typedef typename detail::CallableTraits<Fulfil>::ResultType FulfilResult;
typedef typename detail::CallableTraits<Reject>::ResultType RejectResult;
static_assert(isFulfilNull || isRejectNull ||
std::is_same<FulfilResult, RejectResult>::value,
"onFulfil and onReject return types must match");
static_assert(!std::is_same<typename std::decay<FulfilResult>::type, void>::value,
"onFulfil callback must return a value.");
static_assert(!std::is_same<typename std::decay<RejectResult>::type, void>::value,
"onFulfil callback must return a value.");
}
~Promise() noexcept;
// Settle a non-dependent Promise with a value.
// @value Copyable or Movable value.
//
// @return *this to allow return Promise().settle(value);
template<typename T>
const Promise& settle(T&& value) const {
settle(Value(std::forward<T>(value)));
return *this;
}
// Settle a non-dependent Promise with an empty value.
//
// @return *this to allow return Promise().settle();
const Promise& settle() const {
settle(Value());
return *this;
}
// Attach fulfil/reject callbacks.
// @onFulfil Function/functor to be called if the Promise is fulfilled.
// onFulfil may take a single argument by value, const
// reference, or rvalue reference. In the case of an
// rvalue reference argument, the Promise will be closed
// to additional callbacks. onFulfil may return a value.
// @onReject Optional function/functor to be called if the Promise is
// rejected. onReject may take a single argument of
// const std::exception_ptr& and may return a value.
//
// This method produces a dependent Promise that receives the value
// or error from the upstream Promise and passes it through the
// matching callback. At most one of the callbacks will be invoked,
// never both.
//
// If the executed callback returns a value that is not a
// Promise, the Promise returned by then is fulfilled with that
// value. If the the executed callback throws an exception, the
// Promise returned by then() is rejected with that exception.
//
// If the executed callback returns a Promise q, the Promise p
// returned by then() will receive q's value or error (which may
// not happen immediately).
//
// @return Dependent Promise to receive the eventual result.
template<typename Fulfil, typename Reject = detail::NullReject >
Promise then(Fulfil&& onFulfil, Reject&& onReject = Reject()) const {
typedef typename detail::CallableTraits<Fulfil>::ResultType FulfilResult;
typedef typename detail::CallableTraits<Reject>::ResultType RejectResult;
static_assert(!std::is_same<typename std::decay<FulfilResult>::type, void>::value,
"onFulfil callback must return a value.");
static_assert(!std::is_same<typename std::decay<RejectResult>::type, void>::value,
"onFulfil callback must return a value.");
if (closed())
throw std::logic_error("Promise is closed");
Promise next(std::forward<Fulfil>(onFulfil), std::forward<Reject>(onReject));
attach(next);
return next;
}
// Attach reject callback only.
// @onReject Function/functor to be called if the Promise is
// rejected. onReject may take a single argument of
// const std::exception_ptr& and may return a value.
//
// This method is the same as then() except that it only
// attaches a reject callback.
//
// @return Dependent Promise to receive the eventual result.
template<typename Reject>
Promise except(Reject&& onReject) const {
typedef typename detail::CallableTraits<Reject>::ResultType RejectResult;
static_assert(!std::is_same<typename std::decay<RejectResult>::type, void>::value,
"onFulfil callback must return a value.");
return then(detail::NullFulfil(), std::forward<Reject>(onReject));
}
// Disallow future then/except calls.
//
// This method explicitly closes a Promise to disallow calling
// then() or except(). A closed Promise may settle slightly
// faster than an unclosed Promise.
//
// @return *this
Promise& close();
// Disallow future then/except calls.
//
// This method explicitly closes a Promise to disallow calling
// then() or except(). A closed Promise may settle slightly
// faster than an unclosed Promise.
//
// @return *this
const Promise& close() const;
// Get the settled state.
//
// A Promise is settled when it has been either fulfilled or
// rejected.
//
// @return true if settled.
bool settled() const;
// Get the closed state.
//
// A Promise is closed when either (1) its close() method has
// been called or (2) an onFulfil callback that takes an rvalue
// reference argument has been attached with then(). No
// additional callbacks can be added to a closed Promise (i.e.
// calls to then() or except() will throw an exception).
//
// @return true if closed.
bool closed() const;
// Promise conjunction on iterator range.
// @bgn Begin iterator.
// @end End iterator.
//
// This static function returns a Promise that fulfils when
// all of the Promises in the input range fulfil, or rejects
// when any of the Promises in the input range reject.
//
// If the returned Promise fulfils, the values from the input
// Promises can be received by an onFulfil callback as type
// std::vector<T> (if the input Promises all return the same
// type) or as type std::tuple<T0, T1...> (if the number of
// input Promises is known at compile time). For other cases the
// value can be retrieved from the individual input Promises.
//
// @return Dependent Promise that fulfils on all or rejects on
// any.
template<typename Iterator>
static Promise all(Iterator bgn, Iterator end) {
Promise p;
if (const size_t n = std::distance(bgn, end)) {
struct Context {
std::vector<Value> values;
std::atomic<size_t> count;
std::atomic<bool> rejected;
Context(size_t n)
: values(n)
, count(n)
, rejected(false) {
}
};
auto context = std::make_shared<Context>(n);
size_t index = 0;
for (auto i = bgn; i != end; ++i, ++index) {
i->then(
[=](const Value& value) {
context->values[index] = value;
if (context->count.fetch_sub(1) == 1) {
p.settle(std::move(context->values));
}
return detail::Null();
},
[=](const std::exception_ptr& e) {
if (!context->rejected.exchange(true, std::memory_order_relaxed))
p.settle(e);
return detail::Null();
});
}
}
else {
// Range is empty so fulfil immediately.
p.settle(std::vector<Value>());
}
return p;
}
// Promise conjunction on initializer list.
// @promises Input promises.
//
// This static function returns a Promise that fulfils when
// all of the Promises in the input list fulfil, or rejects
// when any of the Promises in the input list reject.
//
// If the returned Promise fulfils, the values from the input
// Promises can be received by an onFulfil callback as type
// std::vector<T> (if the input Promises all return the same
// type) or as type std::tuple<T0, T1...> (if the number of
// input Promises is known at compile time). For other cases the
// value can be retrieved from the individual input Promises.
//
// @return Dependent Promise that fulfils on all or rejects on
// any.
static Promise all(std::initializer_list<Promise> promises) {
return all(promises.begin(), promises.end());
}
// Fulfil with first Promise of iterator range to fulfil.
// @bgn Begin iterator.
// @end End iterator.
//
// This static function returns a Promise that fulfils when
// at least one of the Promises in the input range fulfils,
// or rejects when all of the Promises in the input range
// reject.
//
// If the returned Promise rejects, the std::exception_ptr
// argument does not contain an exception.
//
// @return Dependent Promise that fulfils on any or rejects
// on all.
template<typename Iterator>
static Promise any(Iterator bgn, Iterator end) {
Promise p;
if (const size_t n = std::distance(bgn, end)) {
struct Context {
std::atomic<size_t> count;
std::atomic<bool> fulfilled;
Context(size_t n)
: count(n)
, fulfilled(false) {
}
};
auto context = std::make_shared<Context>(n);
for (auto i = bgn; i != end; ++i) {
i->then(
[=](const Value& value) {
if (!context->fulfilled.exchange(true, std::memory_order_relaxed))
p.settle(value);
return detail::Null();
},
[=](const std::exception_ptr&) {
if (context->count.fetch_sub(1, std::memory_order_relaxed) == 1)
p.settle(std::exception_ptr());
return detail::Null();
});
}
}
else {
// Range is empty so reject immediately.
p.settle(std::exception_ptr());
}
return p;
}
// Fulfil with first Promise of initializer list to fulfil.
// @promises Input promises.
//
// This static function returns a Promise that fulfils when
// at least one of the Promises in the input list fulfils,
// or rejects when all of the Promises in the input list
// reject.
//
// If the returned Promise rejects, the std::exception_ptr
// argument does not contain an exception.
//
// @return Dependent Promise that fulfils on any or rejects
// on all.
static Promise any(std::initializer_list<Promise> promises) {
return any(promises.begin(), promises.end());
}
// Set undelivered exception handler.
// @handler Has signature void handler(const std::exception_ptr&).
//
// Callback exceptions that are never delivered to an
// onReject callback are passed to a global handler that can
// be set with this function. A copy of the previous handler
// is returned. The default handler calls std::unexpected().
//
// Note that the handler is called from the Promise destructor
// so the handler should not throw.
//
// @return Copy of the previous handler.
typedef std::function<void(const std::exception_ptr&)> ExceptionHandler;
static ExceptionHandler setUndeliveredExceptionHandler(const ExceptionHandler& handler);
// Set bad cast exception handler.
// @handler Has signature void handler(const Promise::bad_cast&).
//
// If the upstream value does not match the argument of an
// onFulfil callback a Promise::bad_cast exception is
// thrown. This mismatch between output and input is usually
// a programming error, so the default action is to let this
// exception propagate in the normal manner (i.e. unwind the
// stack) instead of capturing it to pass to the next
// Promise.
//
// If a different behavior is desired, the default handler
// can be replaced. If the replacement handler does not throw
// then the exception will be captured.
//
// @return Copy of the previous handler.
typedef std::function<void(const Promise::bad_cast&)> BadCastHandler;
static BadCastHandler setBadCastExceptionHandler(const BadCastHandler& handler);
friend bool operator==(const Promise& a, const Promise& b) {
return a.pimpl == b.pimpl;
}
friend bool operator<(const Promise& a, const Promise& b) {
return a.pimpl < b.pimpl;
}
size_t hash() const {
return std::hash<Pimpl *>()(pimpl.get());
}
void swap(Promise& other) {
pimpl.swap(other.pimpl);
}
private:
struct Pimpl;
std::shared_ptr<Pimpl> pimpl;
Promise(detail::CallbackWrapper *, detail::CallbackWrapper *);
void settle(Value&& result) const;
void attach(const Promise& next) const;
};
inline void swap(Promise& a, Promise& b) {
a.swap(b);
}
} // namespace poolqueue
namespace std {
template<>
struct hash<poolqueue::Promise> {
size_t operator()(const poolqueue::Promise& p) const {
return p.hash();
}
};
}
#endif // poolqueue_Promise_hpp
Update comments to reflect that callbacks must return a value.
/*
Copyright 2015 Shoestring Research, LLC. 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.
*/
#ifndef poolqueue_Promise_hpp
#define poolqueue_Promise_hpp
#include <atomic>
#include <functional>
#include <initializer_list>
#include <memory>
#include "Promise_detail.hpp"
namespace poolqueue {
// Promises/A+ style asynchronous operations.
//
// Promise is inspired by the Promises/A+ specification
// (https://promisesaplus.com/):
//
// A promise represents the eventual result of an asynchronous
// operation. The primary way of interacting with a promise is
// through its then method, which registers callbacks to receive
// either a promise’s eventual value or the reason why the
// promise cannot be fulfilled.
//
// A Promise instance references shared state. Copying an instance
// provides another reference to the same state. The lifetime of
// the state is independent of the instance; i.e. the state lives
// as long as necessary to propagate results.
class Promise {
public:
typedef detail::Any Value;
typedef detail::bad_cast bad_cast;
// Construct a non-dependent Promise.
//
// This creates a new instance that is not attached to any other
// instance.
Promise();
// Copy constructor.
//
// Copying a Promise instance results in a second instance that
// references the same state as the first, via a shared_ptr.
Promise(const Promise&) = default;
// Copy assignment.
//
// Copying a Promise instance results in a second instance that
// references the same state as the first, via a shared_ptr.
Promise& operator=(const Promise&) = default;
// Move constructor.
Promise(Promise&&) noexcept;
// Move assignment.
Promise& operator=(Promise&&) = default;
// Construct a non-dependent Promise with callbacks.
// @onFulfil Function/functor to be called if the Promise is fulfilled.
// onFulfil may take a single argument by value, const
// reference, or rvalue reference. In the case of an
// rvalue reference argument, the Promise will be closed
// to additional callbacks. onFulfil must return a value.
// @onReject Optional function/functor to be called if the Promise is
// rejected. onReject may take a single argument of
// const std::exception_ptr& and must return a value.
//
// This creates a new instance that is not attached to any other
// instance. When the instance is settled, the appropriate
// callback argument will be called.
template<typename Fulfil, typename Reject = detail::NullReject,
typename = typename std::enable_if<!std::is_same<typename std::decay<Fulfil>::type, Promise>::value>::type>
Promise(Fulfil&& onFulfil, Reject&& onReject = Reject())
: Promise(
!std::is_same<typename std::decay<Fulfil>::type, detail::NullFulfil>::value ?
detail::makeCallbackWrapper(std::forward<Fulfil>(onFulfil)) :
static_cast<detail::CallbackWrapper *>(nullptr),
!std::is_same<typename std::decay<Reject>::type, detail::NullReject>::value ?
detail::makeCallbackWrapper(std::forward<Reject>(onReject)) :
static_cast<detail::CallbackWrapper *>(nullptr)) {
typedef typename detail::CallableTraits<Fulfil>::ArgumentType FulfilArgument;
static_assert(!std::is_same<typename std::decay<FulfilArgument>::type, Promise>::value,
"onFulfil callback cannot take a Promise argument.");
static_assert(!std::is_same<typename std::decay<FulfilArgument>::type, std::exception_ptr>::value,
"onFulfil callback cannot take a std::exception_ptr argument.");
typedef typename detail::CallableTraits<Reject>::ArgumentType RejectArgument;
static_assert(std::is_same<typename std::decay<RejectArgument>::type, std::exception_ptr>::value ||
std::is_same<typename std::decay<RejectArgument>::type, void>::value,
"onReject callback must take a void or std::exception_ptr argument.");
constexpr bool isFulfilNull = std::is_same<typename std::decay<Fulfil>::type, detail::NullFulfil>::value;
constexpr bool isRejectNull = std::is_same<typename std::decay<Reject>::type, detail::NullReject>::value;
typedef typename detail::CallableTraits<Fulfil>::ResultType FulfilResult;
typedef typename detail::CallableTraits<Reject>::ResultType RejectResult;
static_assert(isFulfilNull || isRejectNull ||
std::is_same<FulfilResult, RejectResult>::value,
"onFulfil and onReject return types must match");
static_assert(!std::is_same<typename std::decay<FulfilResult>::type, void>::value,
"onFulfil callback must return a value.");
static_assert(!std::is_same<typename std::decay<RejectResult>::type, void>::value,
"onFulfil callback must return a value.");
}
~Promise() noexcept;
// Settle a non-dependent Promise with a value.
// @value Copyable or Movable value.
//
// @return *this to allow return Promise().settle(value);
template<typename T>
const Promise& settle(T&& value) const {
settle(Value(std::forward<T>(value)));
return *this;
}
// Settle a non-dependent Promise with an empty value.
//
// @return *this to allow return Promise().settle();
const Promise& settle() const {
settle(Value());
return *this;
}
// Attach fulfil/reject callbacks.
// @onFulfil Function/functor to be called if the Promise is fulfilled.
// onFulfil may take a single argument by value, const
// reference, or rvalue reference. In the case of an
// rvalue reference argument, the Promise will be closed
// to additional callbacks. onFulfil must return a value.
// @onReject Optional function/functor to be called if the Promise is
// rejected. onReject may take a single argument of
// const std::exception_ptr& and must return a value.
//
// This method produces a dependent Promise that receives the value
// or error from the upstream Promise and passes it through the
// matching callback. At most one of the callbacks will be invoked,
// never both.
//
// If the executed callback returns a value that is not a
// Promise, the Promise returned by then is fulfilled with that
// value. If the the executed callback throws an exception, the
// Promise returned by then() is rejected with that exception.
//
// If the executed callback returns a Promise q, the Promise p
// returned by then() will receive q's value or error (which may
// not happen immediately).
//
// @return Dependent Promise to receive the eventual result.
template<typename Fulfil, typename Reject = detail::NullReject >
Promise then(Fulfil&& onFulfil, Reject&& onReject = Reject()) const {
typedef typename detail::CallableTraits<Fulfil>::ResultType FulfilResult;
typedef typename detail::CallableTraits<Reject>::ResultType RejectResult;
static_assert(!std::is_same<typename std::decay<FulfilResult>::type, void>::value,
"onFulfil callback must return a value.");
static_assert(!std::is_same<typename std::decay<RejectResult>::type, void>::value,
"onFulfil callback must return a value.");
if (closed())
throw std::logic_error("Promise is closed");
Promise next(std::forward<Fulfil>(onFulfil), std::forward<Reject>(onReject));
attach(next);
return next;
}
// Attach reject callback only.
// @onReject Function/functor to be called if the Promise is
// rejected. onReject may take a single argument of
// const std::exception_ptr& and must return a value.
//
// This method is the same as then() except that it only
// attaches a reject callback.
//
// @return Dependent Promise to receive the eventual result.
template<typename Reject>
Promise except(Reject&& onReject) const {
typedef typename detail::CallableTraits<Reject>::ResultType RejectResult;
static_assert(!std::is_same<typename std::decay<RejectResult>::type, void>::value,
"onFulfil callback must return a value.");
return then(detail::NullFulfil(), std::forward<Reject>(onReject));
}
// Disallow future then/except calls.
//
// This method explicitly closes a Promise to disallow calling
// then() or except(). A closed Promise may settle slightly
// faster than an unclosed Promise.
//
// @return *this
Promise& close();
// Disallow future then/except calls.
//
// This method explicitly closes a Promise to disallow calling
// then() or except(). A closed Promise may settle slightly
// faster than an unclosed Promise.
//
// @return *this
const Promise& close() const;
// Get the settled state.
//
// A Promise is settled when it has been either fulfilled or
// rejected.
//
// @return true if settled.
bool settled() const;
// Get the closed state.
//
// A Promise is closed when either (1) its close() method has
// been called or (2) an onFulfil callback that takes an rvalue
// reference argument has been attached with then(). No
// additional callbacks can be added to a closed Promise (i.e.
// calls to then() or except() will throw an exception).
//
// @return true if closed.
bool closed() const;
// Promise conjunction on iterator range.
// @bgn Begin iterator.
// @end End iterator.
//
// This static function returns a Promise that fulfils when
// all of the Promises in the input range fulfil, or rejects
// when any of the Promises in the input range reject.
//
// If the returned Promise fulfils, the values from the input
// Promises can be received by an onFulfil callback as type
// std::vector<T> (if the input Promises all return the same
// type) or as type std::tuple<T0, T1...> (if the number of
// input Promises is known at compile time). For other cases the
// value can be retrieved from the individual input Promises.
//
// @return Dependent Promise that fulfils on all or rejects on
// any.
template<typename Iterator>
static Promise all(Iterator bgn, Iterator end) {
Promise p;
if (const size_t n = std::distance(bgn, end)) {
struct Context {
std::vector<Value> values;
std::atomic<size_t> count;
std::atomic<bool> rejected;
Context(size_t n)
: values(n)
, count(n)
, rejected(false) {
}
};
auto context = std::make_shared<Context>(n);
size_t index = 0;
for (auto i = bgn; i != end; ++i, ++index) {
i->then(
[=](const Value& value) {
context->values[index] = value;
if (context->count.fetch_sub(1) == 1) {
p.settle(std::move(context->values));
}
return detail::Null();
},
[=](const std::exception_ptr& e) {
if (!context->rejected.exchange(true, std::memory_order_relaxed))
p.settle(e);
return detail::Null();
});
}
}
else {
// Range is empty so fulfil immediately.
p.settle(std::vector<Value>());
}
return p;
}
// Promise conjunction on initializer list.
// @promises Input promises.
//
// This static function returns a Promise that fulfils when
// all of the Promises in the input list fulfil, or rejects
// when any of the Promises in the input list reject.
//
// If the returned Promise fulfils, the values from the input
// Promises can be received by an onFulfil callback as type
// std::vector<T> (if the input Promises all return the same
// type) or as type std::tuple<T0, T1...> (if the number of
// input Promises is known at compile time). For other cases the
// value can be retrieved from the individual input Promises.
//
// @return Dependent Promise that fulfils on all or rejects on
// any.
static Promise all(std::initializer_list<Promise> promises) {
return all(promises.begin(), promises.end());
}
// Fulfil with first Promise of iterator range to fulfil.
// @bgn Begin iterator.
// @end End iterator.
//
// This static function returns a Promise that fulfils when
// at least one of the Promises in the input range fulfils,
// or rejects when all of the Promises in the input range
// reject.
//
// If the returned Promise rejects, the std::exception_ptr
// argument does not contain an exception.
//
// @return Dependent Promise that fulfils on any or rejects
// on all.
template<typename Iterator>
static Promise any(Iterator bgn, Iterator end) {
Promise p;
if (const size_t n = std::distance(bgn, end)) {
struct Context {
std::atomic<size_t> count;
std::atomic<bool> fulfilled;
Context(size_t n)
: count(n)
, fulfilled(false) {
}
};
auto context = std::make_shared<Context>(n);
for (auto i = bgn; i != end; ++i) {
i->then(
[=](const Value& value) {
if (!context->fulfilled.exchange(true, std::memory_order_relaxed))
p.settle(value);
return detail::Null();
},
[=](const std::exception_ptr&) {
if (context->count.fetch_sub(1, std::memory_order_relaxed) == 1)
p.settle(std::exception_ptr());
return detail::Null();
});
}
}
else {
// Range is empty so reject immediately.
p.settle(std::exception_ptr());
}
return p;
}
// Fulfil with first Promise of initializer list to fulfil.
// @promises Input promises.
//
// This static function returns a Promise that fulfils when
// at least one of the Promises in the input list fulfils,
// or rejects when all of the Promises in the input list
// reject.
//
// If the returned Promise rejects, the std::exception_ptr
// argument does not contain an exception.
//
// @return Dependent Promise that fulfils on any or rejects
// on all.
static Promise any(std::initializer_list<Promise> promises) {
return any(promises.begin(), promises.end());
}
// Set undelivered exception handler.
// @handler Has signature void handler(const std::exception_ptr&).
//
// Callback exceptions that are never delivered to an
// onReject callback are passed to a global handler that can
// be set with this function. A copy of the previous handler
// is returned. The default handler calls std::unexpected().
//
// Note that the handler is called from the Promise destructor
// so the handler should not throw.
//
// @return Copy of the previous handler.
typedef std::function<void(const std::exception_ptr&)> ExceptionHandler;
static ExceptionHandler setUndeliveredExceptionHandler(const ExceptionHandler& handler);
// Set bad cast exception handler.
// @handler Has signature void handler(const Promise::bad_cast&).
//
// If the upstream value does not match the argument of an
// onFulfil callback a Promise::bad_cast exception is
// thrown. This mismatch between output and input is usually
// a programming error, so the default action is to let this
// exception propagate in the normal manner (i.e. unwind the
// stack) instead of capturing it to pass to the next
// Promise.
//
// If a different behavior is desired, the default handler
// can be replaced. If the replacement handler does not throw
// then the exception will be captured.
//
// @return Copy of the previous handler.
typedef std::function<void(const Promise::bad_cast&)> BadCastHandler;
static BadCastHandler setBadCastExceptionHandler(const BadCastHandler& handler);
friend bool operator==(const Promise& a, const Promise& b) {
return a.pimpl == b.pimpl;
}
friend bool operator<(const Promise& a, const Promise& b) {
return a.pimpl < b.pimpl;
}
size_t hash() const {
return std::hash<Pimpl *>()(pimpl.get());
}
void swap(Promise& other) {
pimpl.swap(other.pimpl);
}
private:
struct Pimpl;
std::shared_ptr<Pimpl> pimpl;
Promise(detail::CallbackWrapper *, detail::CallbackWrapper *);
void settle(Value&& result) const;
void attach(const Promise& next) const;
};
inline void swap(Promise& a, Promise& b) {
a.swap(b);
}
} // namespace poolqueue
namespace std {
template<>
struct hash<poolqueue::Promise> {
size_t operator()(const poolqueue::Promise& p) const {
return p.hash();
}
};
}
#endif // poolqueue_Promise_hpp
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any
// other contributors to this software 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 COPYRIGHT OWNER OR
// CONTRIBUTORS 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.
//
//////////////////////////////////////////////////////////////////////////
// This must come before the Cortex includes, because on OSX headers included
// by TBB define macros which conflict with the inline functions in ai_types.h.
#include "ai.h"
#include "OpenEXR/ImathBoxAlgo.h"
#include "boost/format.hpp"
#include "boost/algorithm/string/predicate.hpp"
#include "IECore/MessageHandler.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/Camera.h"
#include "IECore/Transform.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/PointsPrimitive.h"
#include "IECoreArnold/private/RendererImplementation.h"
#include "IECoreArnold/ToArnoldCameraConverter.h"
using namespace IECore;
using namespace IECoreArnold;
using namespace Imath;
using namespace std;
using namespace boost;
////////////////////////////////////////////////////////////////////////
// AttributeState implementation
////////////////////////////////////////////////////////////////////////
RendererImplementation::AttributeState::AttributeState()
{
surfaceShader = AiNode( "utility" );
displacementShader = 0;
attributes = new CompoundData;
attributes->writable()["ai:visibility:camera"] = new BoolData( true );
attributes->writable()["ai:visibility:shadow"] = new BoolData( true );
attributes->writable()["ai:visibility:reflected"] = new BoolData( true );
attributes->writable()["ai:visibility:refracted"] = new BoolData( true );
attributes->writable()["ai:visibility:diffuse"] = new BoolData( true );
attributes->writable()["ai:visibility:glossy"] = new BoolData( true );
}
RendererImplementation::AttributeState::AttributeState( const AttributeState &other )
{
surfaceShader = other.surfaceShader;
displacementShader = other.displacementShader;
shaders = other.shaders;
attributes = other.attributes->copy();
}
////////////////////////////////////////////////////////////////////////
// RendererImplementation implementation
////////////////////////////////////////////////////////////////////////
extern AtNodeMethods *ieDisplayDriverMethods;
IECoreArnold::RendererImplementation::RendererImplementation()
: m_defaultFilter( 0 )
{
constructCommon( Render );
}
IECoreArnold::RendererImplementation::RendererImplementation( const std::string &assFileName )
: m_defaultFilter( 0 )
{
m_assFileName = assFileName;
constructCommon( AssGen );
}
IECoreArnold::RendererImplementation::RendererImplementation( const RendererImplementation &other )
{
constructCommon( Procedural );
m_instancingConverter = other.m_instancingConverter;
m_transformStack.push( other.m_transformStack.top() );
m_attributeStack.push( AttributeState( other.m_attributeStack.top() ) );
}
IECoreArnold::RendererImplementation::RendererImplementation( const AtNode *proceduralNode )
{
constructCommon( Procedural );
m_instancingConverter = new InstancingConverter;
/// \todo Initialise stacks properly!!
m_transformStack.push( M44f() );
m_attributeStack.push( AttributeState() );
// the AttributeState constructor makes a surface shader node, and
// it's essential that we return that as one of the nodes created by
// the procedural - otherwise arnold hangs.
addNode( m_attributeStack.top().surfaceShader );
}
void IECoreArnold::RendererImplementation::constructCommon( Mode mode )
{
m_mode = mode;
if( mode != Procedural )
{
m_universe = boost::shared_ptr<UniverseBlock>( new UniverseBlock() );
m_instancingConverter = new InstancingConverter;
/// \todo Control with an option
AiMsgSetConsoleFlags( AI_LOG_ALL );
// create a generic filter we can use for all displays
m_defaultFilter = AiNode( "gaussian_filter" );
AiNodeSetStr( m_defaultFilter, "name", "ieCoreArnold:defaultFilter" );
m_transformStack.push( M44f() );
m_attributeStack.push( AttributeState() );
}
}
IECoreArnold::RendererImplementation::~RendererImplementation()
{
if( m_mode != Procedural )
{
AiEnd();
}
}
////////////////////////////////////////////////////////////////////////
// options
////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::setOption( const std::string &name, IECore::ConstDataPtr value )
{
if( 0 == name.compare( 0, 3, "ai:" ) )
{
AtNode *options = AiUniverseGetOptions();
const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( options ), name.c_str() + 3 );
if( parameter )
{
ToArnoldConverter::setParameter( options, name.c_str() + 3, value.get() );
return;
}
}
else if( 0 == name.compare( 0, 5, "user:" ) )
{
AtNode *options = AiUniverseGetOptions();
ToArnoldConverter::setParameter( options, name.c_str(), value.get() );
return;
}
else if( name.find_first_of( ":" )!=string::npos )
{
// ignore options prefixed for some other renderer
return;
}
msg( Msg::Warning, "IECoreArnold::RendererImplementation::setOption", format( "Unknown option \"%s\"." ) % name );
}
IECore::ConstDataPtr IECoreArnold::RendererImplementation::getOption( const std::string &name ) const
{
if( 0 == name.compare( 0, 3, "ai:" ) )
{
AtNode *options = AiUniverseGetOptions();
return ToArnoldConverter::getParameter( options, name.c_str() + 3 );
}
else if( 0 == name.compare( 0, 5, "user:" ) )
{
AtNode *options = AiUniverseGetOptions();
return ToArnoldConverter::getParameter( options, name.c_str() );
}
else if( name == "shutter" )
{
AtNode *camera = AiUniverseGetCamera();
float start = AiNodeGetFlt( camera, "shutter_start" );
float end = AiNodeGetFlt( camera, "shutter_end" );
return new V2fData( V2f( start, end ) );
}
return 0;
}
void IECoreArnold::RendererImplementation::camera( const std::string &name, const IECore::CompoundDataMap ¶meters )
{
CameraPtr cortexCamera = new Camera( name, 0, new CompoundData( parameters ) );
cortexCamera->addStandardParameters();
ToArnoldCameraConverterPtr converter = new ToArnoldCameraConverter( cortexCamera );
AtNode *arnoldCamera = converter->convert();
AtNode *options = AiUniverseGetOptions();
AiNodeSetPtr( options, "camera", arnoldCamera );
applyTransformToNode( arnoldCamera );
const V2iData *resolution = cortexCamera->parametersData()->member<V2iData>( "resolution" );
AiNodeSetInt( options, "xres", resolution->readable().x );
AiNodeSetInt( options, "yres", resolution->readable().y );
const FloatData *pixelAspectRatio = cortexCamera->parametersData()->member<FloatData>( "pixelAspectRatio" );
AiNodeSetFlt( options, "aspect_ratio", 1.0f / pixelAspectRatio->readable() ); // arnold is y/x, we're x/y
}
void IECoreArnold::RendererImplementation::display( const std::string &name, const std::string &type, const std::string &data, const IECore::CompoundDataMap ¶meters )
{
AtNode *driver = 0;
if( AiNodeEntryLookUp( type.c_str() ) )
{
driver = AiNode( type.c_str() );
}
else
{
// automatically map tiff to driver_tiff and so on, to provide a degree of
// compatibility with existing renderman driver names.
std::string prefixedType = "driver_" + type;
if( AiNodeEntryLookUp( prefixedType.c_str() ) )
{
driver = AiNode( prefixedType.c_str() );
}
}
if( !driver )
{
msg( Msg::Error, "IECoreArnold::RendererImplementation::display", boost::format( "Unable to create display of type \"%s\"" ) % type );
return;
}
string nodeName = boost::str( boost::format( "ieCoreArnold:display%d" ) % m_outputDescriptions.size() );
AiNodeSetStr( driver, "name", nodeName.c_str() );
const AtParamEntry *fileNameParameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( driver ), "filename" );
if( fileNameParameter )
{
AiNodeSetStr( driver, AiParamGetName( fileNameParameter ), name.c_str() );
}
ToArnoldConverter::setParameters( driver, parameters );
string d = data;
if( d=="rgb" )
{
d = "RGB RGB";
}
else if( d=="rgba" )
{
d = "RGBA RGBA";
}
std::string outputDescription = str( format( "%s %s %s" ) % d.c_str() % AiNodeGetName( m_defaultFilter ) % nodeName.c_str() );
m_outputDescriptions.push_back( outputDescription );
}
/////////////////////////////////////////////////////////////////////////////////////////
// world
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::worldBegin()
{
// reset transform stack
if( m_transformStack.size() > 1 )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::worldBegin", "Missing transformEnd() call detected." );
while( m_transformStack.size() > 1 )
{
m_transformStack.pop();
}
m_transformStack.top() = M44f();
}
// specify default camera if none has been specified yet
AtNode *options = AiUniverseGetOptions();
if( !AiNodeGetPtr( options, "camera" ) )
{
// no camera has been specified - make a default one
camera( "ieCoreArnold:defaultCamera", CompoundDataMap() );
}
// specify all the outputs
AtArray *outputsArray = AiArrayAllocate( m_outputDescriptions.size(), 1, AI_TYPE_STRING );
for( int i = 0, e = m_outputDescriptions.size(); i < e; i++ )
{
AiArraySetStr( outputsArray, i, m_outputDescriptions[i].c_str() );
}
AiNodeSetArray( options, "outputs", outputsArray );
}
void IECoreArnold::RendererImplementation::worldEnd()
{
if( m_mode == Render )
{
AiRender( AI_RENDER_MODE_CAMERA );
}
else if( m_mode == AssGen )
{
AiASSWrite( m_assFileName.c_str(), AI_NODE_ALL, false );
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// transforms
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::transformBegin()
{
m_transformStack.push( ( m_transformStack.top() ) );
}
void IECoreArnold::RendererImplementation::transformEnd()
{
if( m_transformStack.size() <= 1 )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::transformEnd", "No matching transformBegin() call." );
return;
}
m_transformStack.pop();
}
void IECoreArnold::RendererImplementation::setTransform( const Imath::M44f &m )
{
m_transformStack.top() = m;
}
void IECoreArnold::RendererImplementation::setTransform( const std::string &coordinateSystem )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::setTransform", "Not implemented" );
}
Imath::M44f IECoreArnold::RendererImplementation::getTransform() const
{
return m_transformStack.top();
}
Imath::M44f IECoreArnold::RendererImplementation::getTransform( const std::string &coordinateSystem ) const
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::getTransform", "Not implemented" );
M44f result;
return result;
}
void IECoreArnold::RendererImplementation::concatTransform( const Imath::M44f &m )
{
m_transformStack.top() = m * m_transformStack.top();
}
void IECoreArnold::RendererImplementation::coordinateSystem( const std::string &name )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::coordinateSystem", "Not implemented" );
}
//////////////////////////////////////////////////////////////////////////////////////////
// attribute code
//////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::attributeBegin()
{
transformBegin();
m_attributeStack.push( AttributeState( m_attributeStack.top() ) );
}
void IECoreArnold::RendererImplementation::attributeEnd()
{
m_attributeStack.pop();
transformEnd();
}
void IECoreArnold::RendererImplementation::setAttribute( const std::string &name, IECore::ConstDataPtr value )
{
m_attributeStack.top().attributes->writable()[name] = value->copy();
}
IECore::ConstDataPtr IECoreArnold::RendererImplementation::getAttribute( const std::string &name ) const
{
return m_attributeStack.top().attributes->member<Data>( name );
}
void IECoreArnold::RendererImplementation::shader( const std::string &type, const std::string &name, const IECore::CompoundDataMap ¶meters )
{
if(
type=="shader" || type=="ai:shader" ||
type=="surface" || type=="ai:surface" ||
type=="displacement" || type=="ai:displacement"
)
{
AtNode *s = 0;
if( 0 == name.compare( 0, 10, "reference:" ) )
{
s = AiNodeLookUpByName( name.c_str() + 10 );
if( !s )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Couldn't find shader \"%s\"" ) % name );
return;
}
}
else
{
s = AiNode( name.c_str() );
if( !s )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Couldn't load shader \"%s\"" ) % name );
return;
}
for( CompoundDataMap::const_iterator parmIt=parameters.begin(); parmIt!=parameters.end(); parmIt++ )
{
if( parmIt->second->isInstanceOf( IECore::StringDataTypeId ) )
{
const std::string &potentialLink = static_cast<const StringData *>( parmIt->second.get() )->readable();
if( 0 == potentialLink.compare( 0, 5, "link:" ) )
{
std::string linkHandle = potentialLink.c_str() + 5;
AttributeState::ShaderMap::const_iterator shaderIt = m_attributeStack.top().shaders.find( linkHandle );
if( shaderIt != m_attributeStack.top().shaders.end() )
{
AiNodeLinkOutput( shaderIt->second, "", s, parmIt->first.value().c_str() );
}
else
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Couldn't find shader handle \"%s\" for linking" ) % linkHandle );
}
continue;
}
}
ToArnoldConverter::setParameter( s, parmIt->first.value().c_str(), parmIt->second.get() );
}
addNode( s );
}
if( type=="shader" || type == "ai:shader" )
{
CompoundDataMap::const_iterator handleIt = parameters.find( "__handle" );
if( handleIt != parameters.end() && handleIt->second->isInstanceOf( IECore::StringDataTypeId ) )
{
const std::string &handle = static_cast<const StringData *>( handleIt->second.get() )->readable();
m_attributeStack.top().shaders[handle] = s;
}
else
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", "No __handle parameter specified." );
}
}
else if( type=="surface" || type == "ai:surface" )
{
m_attributeStack.top().surfaceShader = s;
}
else
{
m_attributeStack.top().displacementShader = s;
}
}
else
{
if( type.find( ':' ) == string::npos )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Unsupported shader type \"%s\"" ) % type );
}
}
}
void IECoreArnold::RendererImplementation::light( const std::string &name, const std::string &handle, const IECore::CompoundDataMap ¶meters )
{
const char *unprefixedName = name.c_str();
if( name.find( ':' ) != string::npos )
{
if( boost::starts_with( name, "ai:" ) )
{
unprefixedName += 3;
}
else
{
return;
}
}
AtNode *l = AiNode( unprefixedName );
if( !l )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::light", boost::format( "Couldn't load light \"%s\"" ) % unprefixedName );
return;
}
for( CompoundDataMap::const_iterator parmIt=parameters.begin(); parmIt!=parameters.end(); parmIt++ )
{
ToArnoldConverter::setParameter( l, parmIt->first.value().c_str(), parmIt->second.get() );
}
applyTransformToNode( l );
addNode( l );
}
void IECoreArnold::RendererImplementation::illuminate( const std::string &lightHandle, bool on )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::illuminate", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// motion blur
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::motionBegin( const std::set<float> × )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::motionBegin", "Not implemented" );
}
void IECoreArnold::RendererImplementation::motionEnd()
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::motionEnd", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// primitives
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::points( size_t numPoints, const IECore::PrimitiveVariableMap &primVars )
{
PointsPrimitivePtr points = new IECore::PointsPrimitive( numPoints );
points->variables = primVars;
addPrimitive( points.get(), "ai:points:" );
}
void IECoreArnold::RendererImplementation::disk( float radius, float z, float thetaMax, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::disk", "Not implemented" );
}
void IECoreArnold::RendererImplementation::curves( const IECore::CubicBasisf &basis, bool periodic, ConstIntVectorDataPtr numVertices, const IECore::PrimitiveVariableMap &primVars )
{
CurvesPrimitivePtr curves = new IECore::CurvesPrimitive( numVertices, basis, periodic );
curves->variables = primVars;
addPrimitive( curves.get(), "ai:curves:" );
}
void IECoreArnold::RendererImplementation::text( const std::string &font, const std::string &text, float kerning, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::text", "Not implemented" );
}
void IECoreArnold::RendererImplementation::sphere( float radius, float zMin, float zMax, float thetaMax, const IECore::PrimitiveVariableMap &primVars )
{
if( zMin != -1.0f )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::sphere", "zMin not supported" );
}
if( zMax != 1.0f )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::sphere", "zMax not supported" );
}
if( thetaMax != 360.0f )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::sphere", "thetaMax not supported" );
}
AtNode *sphere = AiNode( "sphere" );
AiNodeSetFlt( sphere, "radius", radius );
addShape( sphere );
}
void IECoreArnold::RendererImplementation::image( const Imath::Box2i &dataWindow, const Imath::Box2i &displayWindow, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::image", "Not implemented" );
}
void IECoreArnold::RendererImplementation::mesh( IECore::ConstIntVectorDataPtr vertsPerFace, IECore::ConstIntVectorDataPtr vertIds, const std::string &interpolation, const IECore::PrimitiveVariableMap &primVars )
{
MeshPrimitivePtr mesh = new IECore::MeshPrimitive( vertsPerFace, vertIds, interpolation );
mesh->variables = primVars;
addPrimitive( mesh.get(), "ai:polymesh:" );
}
void IECoreArnold::RendererImplementation::nurbs( int uOrder, IECore::ConstFloatVectorDataPtr uKnot, float uMin, float uMax, int vOrder, IECore::ConstFloatVectorDataPtr vKnot, float vMin, float vMax, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::nurbs", "Not implemented" );
}
void IECoreArnold::RendererImplementation::patchMesh( const CubicBasisf &uBasis, const CubicBasisf &vBasis, int nu, bool uPeriodic, int nv, bool vPeriodic, const PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::patchMesh", "Not implemented" );
}
void IECoreArnold::RendererImplementation::geometry( const std::string &type, const CompoundDataMap &topology, const PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::geometry", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// procedurals
/////////////////////////////////////////////////////////////////////////////////////////
int IECoreArnold::RendererImplementation::procLoader( AtProcVtable *vTable )
{
vTable->Init = procInit;
vTable->Cleanup = procCleanup;
vTable->NumNodes = procNumNodes;
vTable->GetNode = procGetNode;
strcpy( vTable->version, AI_VERSION );
return 1;
}
int IECoreArnold::RendererImplementation::procInit( AtNode *node, void **userPtr )
{
ProceduralData *data = (ProceduralData *)( AiNodeGetPtr( node, "userptr" ) );
data->procedural->render( data->renderer.get() );
data->procedural = 0;
*userPtr = data;
return 1;
}
int IECoreArnold::RendererImplementation::procCleanup( void *userPtr )
{
ProceduralData *data = (ProceduralData *)( userPtr );
delete data;
return 1;
}
int IECoreArnold::RendererImplementation::procNumNodes( void *userPtr )
{
ProceduralData *data = (ProceduralData *)( userPtr );
return data->renderer->m_implementation->m_nodes.size();
}
AtNode* IECoreArnold::RendererImplementation::procGetNode( void *userPtr, int i )
{
ProceduralData *data = (ProceduralData *)( userPtr );
return data->renderer->m_implementation->m_nodes[i];
}
void IECoreArnold::RendererImplementation::procedural( IECore::Renderer::ProceduralPtr proc )
{
Box3f bound = proc->bound();
if( bound.isEmpty() )
{
return;
}
AtNode *procedural = AiNode( "procedural" );
if( ExternalProcedural *externalProc = dynamic_cast<ExternalProcedural *>( proc.get() ) )
{
AiNodeSetStr( procedural, "dso", externalProc->fileName().c_str() );
ToArnoldConverter::setParameters( procedural, externalProc->parameters() );
applyTransformToNode( procedural );
}
else
{
// we have to transform the bound, as we're not applying the current transform to the
// procedural node, but instead applying absolute transforms to the shapes the procedural
// generates.
if( bound != Procedural::noBound )
{
bound = transform( bound, m_transformStack.top() );
}
AiNodeSetPtr( procedural, "funcptr", (void *)procLoader );
ProceduralData *data = new ProceduralData;
data->procedural = proc;
data->renderer = new IECoreArnold::Renderer( new RendererImplementation( *this ) );
AiNodeSetPtr( procedural, "userptr", data );
}
if( bound != Procedural::noBound )
{
AiNodeSetPnt( procedural, "min", bound.min.x, bound.min.y, bound.min.z );
AiNodeSetPnt( procedural, "max", bound.max.x, bound.max.y, bound.max.z );
}
else
{
// No bound available - expand procedural immediately.
AiNodeSetBool( procedural, "load_at_init", true );
}
// we call addNode() rather than addShape() as we don't want to apply transforms and
// shaders and attributes to procedurals. if we do, they override the things we set
// on the nodes generated by the procedurals, which is frankly useless.
addNode( procedural );
}
void IECoreArnold::RendererImplementation::addPrimitive( const IECore::Primitive *primitive, const std::string &attributePrefix )
{
const CompoundDataMap &attributes = m_attributeStack.top().attributes->readable();
bool automaticInstancing = true;
CompoundDataMap::const_iterator it = attributes.find( "ai:automaticInstancing" );
if( it != attributes.end() && it->second->typeId() == IECore::BoolDataTypeId )
{
automaticInstancing = static_cast<const IECore::BoolData *>( it->second.get() )->readable();
}
else
{
it = attributes.find( "automaticInstancing" );
if( it != attributes.end() && it->second->typeId() == IECore::BoolDataTypeId )
{
automaticInstancing = static_cast<const IECore::BoolData *>( it->second.get() )->readable();
}
}
AtNode *shape = 0;
if( automaticInstancing )
{
IECore::MurmurHash hash = primitive->::IECore::Object::hash();
for( CompoundDataMap::const_iterator it = attributes.begin(), eIt = attributes.end(); it != eIt; it++ )
{
if( it->first.value().compare( 0, attributePrefix.size(), attributePrefix )==0 )
{
hash.append( it->first.value() );
it->second->hash( hash );
}
}
shape = m_instancingConverter->convert( primitive, hash );
}
else
{
ToArnoldConverterPtr converter = ToArnoldConverter::create( const_cast<IECore::Primitive *>( primitive ) );
shape = converter->convert();
}
if( strcmp( AiNodeEntryGetName( AiNodeGetNodeEntry( shape ) ), "ginstance" ) )
{
// it's not an instance, copy over attributes destined for this object type.
const CompoundDataMap &attributes = m_attributeStack.top().attributes->readable();
for( CompoundDataMap::const_iterator it = attributes.begin(), eIt = attributes.end(); it != eIt; it++ )
{
if( it->first.value().compare( 0, attributePrefix.size(), attributePrefix )==0 )
{
ToArnoldConverter::setParameter( shape, it->first.value().c_str() + attributePrefix.size(), it->second.get() );
}
}
}
else
{
// it's an instance - make sure we don't get double transformations.
AiNodeSetBool( shape, "inherit_xform", false );
}
addShape( shape );
}
void IECoreArnold::RendererImplementation::addShape( AtNode *shape )
{
applyTransformToNode( shape );
applyVisibilityToNode( shape );
AiNodeSetPtr( shape, "shader", m_attributeStack.top().surfaceShader );
if( AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( shape ), "disp_map" ) )
{
if( m_attributeStack.top().displacementShader )
{
AiNodeSetPtr( shape, "disp_map", m_attributeStack.top().displacementShader );
}
}
addNode( shape );
}
void IECoreArnold::RendererImplementation::applyTransformToNode( AtNode *node )
{
/// \todo Make Convert.h
const Imath::M44f &m = m_transformStack.top();
AtMatrix mm;
for( unsigned int i=0; i<4; i++ )
{
for( unsigned int j=0; j<4; j++ )
{
mm[i][j] = m[i][j];
}
}
AiNodeSetMatrix( node, "matrix", mm );
}
void IECoreArnold::RendererImplementation::applyVisibilityToNode( AtNode *node )
{
int visibility = 0;
const BoolData *visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:camera" );
if( visData->readable() )
{
visibility |= AI_RAY_CAMERA;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:shadow" );
if( visData->readable() )
{
visibility |= AI_RAY_SHADOW;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:reflected" );
if( visData->readable() )
{
visibility |= AI_RAY_REFLECTED;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:refracted" );
if( visData->readable() )
{
visibility |= AI_RAY_REFRACTED;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:diffuse" );
if( visData->readable() )
{
visibility |= AI_RAY_DIFFUSE;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:glossy" );
if( visData->readable() )
{
visibility |= AI_RAY_GLOSSY;
}
AiNodeSetInt( node, "visibility", visibility );
}
void IECoreArnold::RendererImplementation::addNode( AtNode *node )
{
m_nodes.push_back( node );
}
/////////////////////////////////////////////////////////////////////////////////////////
// instancing
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::instanceBegin( const std::string &name, const IECore::CompoundDataMap ¶meters )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::instanceBegin", "Not implemented" );
}
void IECoreArnold::RendererImplementation::instanceEnd()
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::instanceEnd", "Not implemented" );
}
void IECoreArnold::RendererImplementation::instance( const std::string &name )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::instance", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// commands
/////////////////////////////////////////////////////////////////////////////////////////
IECore::DataPtr IECoreArnold::RendererImplementation::command( const std::string &name, const CompoundDataMap ¶meters )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::command", "Not implemented" );
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// rerendering
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::editBegin( const std::string &editType, const IECore::CompoundDataMap ¶meters )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::editBegin", "Not implemented" );
}
void IECoreArnold::RendererImplementation::editEnd()
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::editEnd", "Not implemented" );
}
IECoreArnold::Renderer : Use AtByte for setting visibility.
This fixes warnings coming from Arnold.
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any
// other contributors to this software 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 COPYRIGHT OWNER OR
// CONTRIBUTORS 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.
//
//////////////////////////////////////////////////////////////////////////
// This must come before the Cortex includes, because on OSX headers included
// by TBB define macros which conflict with the inline functions in ai_types.h.
#include "ai.h"
#include "OpenEXR/ImathBoxAlgo.h"
#include "boost/format.hpp"
#include "boost/algorithm/string/predicate.hpp"
#include "IECore/MessageHandler.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/Camera.h"
#include "IECore/Transform.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/PointsPrimitive.h"
#include "IECoreArnold/private/RendererImplementation.h"
#include "IECoreArnold/ToArnoldCameraConverter.h"
using namespace IECore;
using namespace IECoreArnold;
using namespace Imath;
using namespace std;
using namespace boost;
////////////////////////////////////////////////////////////////////////
// AttributeState implementation
////////////////////////////////////////////////////////////////////////
RendererImplementation::AttributeState::AttributeState()
{
surfaceShader = AiNode( "utility" );
displacementShader = 0;
attributes = new CompoundData;
attributes->writable()["ai:visibility:camera"] = new BoolData( true );
attributes->writable()["ai:visibility:shadow"] = new BoolData( true );
attributes->writable()["ai:visibility:reflected"] = new BoolData( true );
attributes->writable()["ai:visibility:refracted"] = new BoolData( true );
attributes->writable()["ai:visibility:diffuse"] = new BoolData( true );
attributes->writable()["ai:visibility:glossy"] = new BoolData( true );
}
RendererImplementation::AttributeState::AttributeState( const AttributeState &other )
{
surfaceShader = other.surfaceShader;
displacementShader = other.displacementShader;
shaders = other.shaders;
attributes = other.attributes->copy();
}
////////////////////////////////////////////////////////////////////////
// RendererImplementation implementation
////////////////////////////////////////////////////////////////////////
extern AtNodeMethods *ieDisplayDriverMethods;
IECoreArnold::RendererImplementation::RendererImplementation()
: m_defaultFilter( 0 )
{
constructCommon( Render );
}
IECoreArnold::RendererImplementation::RendererImplementation( const std::string &assFileName )
: m_defaultFilter( 0 )
{
m_assFileName = assFileName;
constructCommon( AssGen );
}
IECoreArnold::RendererImplementation::RendererImplementation( const RendererImplementation &other )
{
constructCommon( Procedural );
m_instancingConverter = other.m_instancingConverter;
m_transformStack.push( other.m_transformStack.top() );
m_attributeStack.push( AttributeState( other.m_attributeStack.top() ) );
}
IECoreArnold::RendererImplementation::RendererImplementation( const AtNode *proceduralNode )
{
constructCommon( Procedural );
m_instancingConverter = new InstancingConverter;
/// \todo Initialise stacks properly!!
m_transformStack.push( M44f() );
m_attributeStack.push( AttributeState() );
// the AttributeState constructor makes a surface shader node, and
// it's essential that we return that as one of the nodes created by
// the procedural - otherwise arnold hangs.
addNode( m_attributeStack.top().surfaceShader );
}
void IECoreArnold::RendererImplementation::constructCommon( Mode mode )
{
m_mode = mode;
if( mode != Procedural )
{
m_universe = boost::shared_ptr<UniverseBlock>( new UniverseBlock() );
m_instancingConverter = new InstancingConverter;
/// \todo Control with an option
AiMsgSetConsoleFlags( AI_LOG_ALL );
// create a generic filter we can use for all displays
m_defaultFilter = AiNode( "gaussian_filter" );
AiNodeSetStr( m_defaultFilter, "name", "ieCoreArnold:defaultFilter" );
m_transformStack.push( M44f() );
m_attributeStack.push( AttributeState() );
}
}
IECoreArnold::RendererImplementation::~RendererImplementation()
{
if( m_mode != Procedural )
{
AiEnd();
}
}
////////////////////////////////////////////////////////////////////////
// options
////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::setOption( const std::string &name, IECore::ConstDataPtr value )
{
if( 0 == name.compare( 0, 3, "ai:" ) )
{
AtNode *options = AiUniverseGetOptions();
const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( options ), name.c_str() + 3 );
if( parameter )
{
ToArnoldConverter::setParameter( options, name.c_str() + 3, value.get() );
return;
}
}
else if( 0 == name.compare( 0, 5, "user:" ) )
{
AtNode *options = AiUniverseGetOptions();
ToArnoldConverter::setParameter( options, name.c_str(), value.get() );
return;
}
else if( name.find_first_of( ":" )!=string::npos )
{
// ignore options prefixed for some other renderer
return;
}
msg( Msg::Warning, "IECoreArnold::RendererImplementation::setOption", format( "Unknown option \"%s\"." ) % name );
}
IECore::ConstDataPtr IECoreArnold::RendererImplementation::getOption( const std::string &name ) const
{
if( 0 == name.compare( 0, 3, "ai:" ) )
{
AtNode *options = AiUniverseGetOptions();
return ToArnoldConverter::getParameter( options, name.c_str() + 3 );
}
else if( 0 == name.compare( 0, 5, "user:" ) )
{
AtNode *options = AiUniverseGetOptions();
return ToArnoldConverter::getParameter( options, name.c_str() );
}
else if( name == "shutter" )
{
AtNode *camera = AiUniverseGetCamera();
float start = AiNodeGetFlt( camera, "shutter_start" );
float end = AiNodeGetFlt( camera, "shutter_end" );
return new V2fData( V2f( start, end ) );
}
return 0;
}
void IECoreArnold::RendererImplementation::camera( const std::string &name, const IECore::CompoundDataMap ¶meters )
{
CameraPtr cortexCamera = new Camera( name, 0, new CompoundData( parameters ) );
cortexCamera->addStandardParameters();
ToArnoldCameraConverterPtr converter = new ToArnoldCameraConverter( cortexCamera );
AtNode *arnoldCamera = converter->convert();
AtNode *options = AiUniverseGetOptions();
AiNodeSetPtr( options, "camera", arnoldCamera );
applyTransformToNode( arnoldCamera );
const V2iData *resolution = cortexCamera->parametersData()->member<V2iData>( "resolution" );
AiNodeSetInt( options, "xres", resolution->readable().x );
AiNodeSetInt( options, "yres", resolution->readable().y );
const FloatData *pixelAspectRatio = cortexCamera->parametersData()->member<FloatData>( "pixelAspectRatio" );
AiNodeSetFlt( options, "aspect_ratio", 1.0f / pixelAspectRatio->readable() ); // arnold is y/x, we're x/y
}
void IECoreArnold::RendererImplementation::display( const std::string &name, const std::string &type, const std::string &data, const IECore::CompoundDataMap ¶meters )
{
AtNode *driver = 0;
if( AiNodeEntryLookUp( type.c_str() ) )
{
driver = AiNode( type.c_str() );
}
else
{
// automatically map tiff to driver_tiff and so on, to provide a degree of
// compatibility with existing renderman driver names.
std::string prefixedType = "driver_" + type;
if( AiNodeEntryLookUp( prefixedType.c_str() ) )
{
driver = AiNode( prefixedType.c_str() );
}
}
if( !driver )
{
msg( Msg::Error, "IECoreArnold::RendererImplementation::display", boost::format( "Unable to create display of type \"%s\"" ) % type );
return;
}
string nodeName = boost::str( boost::format( "ieCoreArnold:display%d" ) % m_outputDescriptions.size() );
AiNodeSetStr( driver, "name", nodeName.c_str() );
const AtParamEntry *fileNameParameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( driver ), "filename" );
if( fileNameParameter )
{
AiNodeSetStr( driver, AiParamGetName( fileNameParameter ), name.c_str() );
}
ToArnoldConverter::setParameters( driver, parameters );
string d = data;
if( d=="rgb" )
{
d = "RGB RGB";
}
else if( d=="rgba" )
{
d = "RGBA RGBA";
}
std::string outputDescription = str( format( "%s %s %s" ) % d.c_str() % AiNodeGetName( m_defaultFilter ) % nodeName.c_str() );
m_outputDescriptions.push_back( outputDescription );
}
/////////////////////////////////////////////////////////////////////////////////////////
// world
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::worldBegin()
{
// reset transform stack
if( m_transformStack.size() > 1 )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::worldBegin", "Missing transformEnd() call detected." );
while( m_transformStack.size() > 1 )
{
m_transformStack.pop();
}
m_transformStack.top() = M44f();
}
// specify default camera if none has been specified yet
AtNode *options = AiUniverseGetOptions();
if( !AiNodeGetPtr( options, "camera" ) )
{
// no camera has been specified - make a default one
camera( "ieCoreArnold:defaultCamera", CompoundDataMap() );
}
// specify all the outputs
AtArray *outputsArray = AiArrayAllocate( m_outputDescriptions.size(), 1, AI_TYPE_STRING );
for( int i = 0, e = m_outputDescriptions.size(); i < e; i++ )
{
AiArraySetStr( outputsArray, i, m_outputDescriptions[i].c_str() );
}
AiNodeSetArray( options, "outputs", outputsArray );
}
void IECoreArnold::RendererImplementation::worldEnd()
{
if( m_mode == Render )
{
AiRender( AI_RENDER_MODE_CAMERA );
}
else if( m_mode == AssGen )
{
AiASSWrite( m_assFileName.c_str(), AI_NODE_ALL, false );
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// transforms
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::transformBegin()
{
m_transformStack.push( ( m_transformStack.top() ) );
}
void IECoreArnold::RendererImplementation::transformEnd()
{
if( m_transformStack.size() <= 1 )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::transformEnd", "No matching transformBegin() call." );
return;
}
m_transformStack.pop();
}
void IECoreArnold::RendererImplementation::setTransform( const Imath::M44f &m )
{
m_transformStack.top() = m;
}
void IECoreArnold::RendererImplementation::setTransform( const std::string &coordinateSystem )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::setTransform", "Not implemented" );
}
Imath::M44f IECoreArnold::RendererImplementation::getTransform() const
{
return m_transformStack.top();
}
Imath::M44f IECoreArnold::RendererImplementation::getTransform( const std::string &coordinateSystem ) const
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::getTransform", "Not implemented" );
M44f result;
return result;
}
void IECoreArnold::RendererImplementation::concatTransform( const Imath::M44f &m )
{
m_transformStack.top() = m * m_transformStack.top();
}
void IECoreArnold::RendererImplementation::coordinateSystem( const std::string &name )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::coordinateSystem", "Not implemented" );
}
//////////////////////////////////////////////////////////////////////////////////////////
// attribute code
//////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::attributeBegin()
{
transformBegin();
m_attributeStack.push( AttributeState( m_attributeStack.top() ) );
}
void IECoreArnold::RendererImplementation::attributeEnd()
{
m_attributeStack.pop();
transformEnd();
}
void IECoreArnold::RendererImplementation::setAttribute( const std::string &name, IECore::ConstDataPtr value )
{
m_attributeStack.top().attributes->writable()[name] = value->copy();
}
IECore::ConstDataPtr IECoreArnold::RendererImplementation::getAttribute( const std::string &name ) const
{
return m_attributeStack.top().attributes->member<Data>( name );
}
void IECoreArnold::RendererImplementation::shader( const std::string &type, const std::string &name, const IECore::CompoundDataMap ¶meters )
{
if(
type=="shader" || type=="ai:shader" ||
type=="surface" || type=="ai:surface" ||
type=="displacement" || type=="ai:displacement"
)
{
AtNode *s = 0;
if( 0 == name.compare( 0, 10, "reference:" ) )
{
s = AiNodeLookUpByName( name.c_str() + 10 );
if( !s )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Couldn't find shader \"%s\"" ) % name );
return;
}
}
else
{
s = AiNode( name.c_str() );
if( !s )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Couldn't load shader \"%s\"" ) % name );
return;
}
for( CompoundDataMap::const_iterator parmIt=parameters.begin(); parmIt!=parameters.end(); parmIt++ )
{
if( parmIt->second->isInstanceOf( IECore::StringDataTypeId ) )
{
const std::string &potentialLink = static_cast<const StringData *>( parmIt->second.get() )->readable();
if( 0 == potentialLink.compare( 0, 5, "link:" ) )
{
std::string linkHandle = potentialLink.c_str() + 5;
AttributeState::ShaderMap::const_iterator shaderIt = m_attributeStack.top().shaders.find( linkHandle );
if( shaderIt != m_attributeStack.top().shaders.end() )
{
AiNodeLinkOutput( shaderIt->second, "", s, parmIt->first.value().c_str() );
}
else
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Couldn't find shader handle \"%s\" for linking" ) % linkHandle );
}
continue;
}
}
ToArnoldConverter::setParameter( s, parmIt->first.value().c_str(), parmIt->second.get() );
}
addNode( s );
}
if( type=="shader" || type == "ai:shader" )
{
CompoundDataMap::const_iterator handleIt = parameters.find( "__handle" );
if( handleIt != parameters.end() && handleIt->second->isInstanceOf( IECore::StringDataTypeId ) )
{
const std::string &handle = static_cast<const StringData *>( handleIt->second.get() )->readable();
m_attributeStack.top().shaders[handle] = s;
}
else
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", "No __handle parameter specified." );
}
}
else if( type=="surface" || type == "ai:surface" )
{
m_attributeStack.top().surfaceShader = s;
}
else
{
m_attributeStack.top().displacementShader = s;
}
}
else
{
if( type.find( ':' ) == string::npos )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::shader", boost::format( "Unsupported shader type \"%s\"" ) % type );
}
}
}
void IECoreArnold::RendererImplementation::light( const std::string &name, const std::string &handle, const IECore::CompoundDataMap ¶meters )
{
const char *unprefixedName = name.c_str();
if( name.find( ':' ) != string::npos )
{
if( boost::starts_with( name, "ai:" ) )
{
unprefixedName += 3;
}
else
{
return;
}
}
AtNode *l = AiNode( unprefixedName );
if( !l )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::light", boost::format( "Couldn't load light \"%s\"" ) % unprefixedName );
return;
}
for( CompoundDataMap::const_iterator parmIt=parameters.begin(); parmIt!=parameters.end(); parmIt++ )
{
ToArnoldConverter::setParameter( l, parmIt->first.value().c_str(), parmIt->second.get() );
}
applyTransformToNode( l );
addNode( l );
}
void IECoreArnold::RendererImplementation::illuminate( const std::string &lightHandle, bool on )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::illuminate", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// motion blur
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::motionBegin( const std::set<float> × )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::motionBegin", "Not implemented" );
}
void IECoreArnold::RendererImplementation::motionEnd()
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::motionEnd", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// primitives
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::points( size_t numPoints, const IECore::PrimitiveVariableMap &primVars )
{
PointsPrimitivePtr points = new IECore::PointsPrimitive( numPoints );
points->variables = primVars;
addPrimitive( points.get(), "ai:points:" );
}
void IECoreArnold::RendererImplementation::disk( float radius, float z, float thetaMax, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::disk", "Not implemented" );
}
void IECoreArnold::RendererImplementation::curves( const IECore::CubicBasisf &basis, bool periodic, ConstIntVectorDataPtr numVertices, const IECore::PrimitiveVariableMap &primVars )
{
CurvesPrimitivePtr curves = new IECore::CurvesPrimitive( numVertices, basis, periodic );
curves->variables = primVars;
addPrimitive( curves.get(), "ai:curves:" );
}
void IECoreArnold::RendererImplementation::text( const std::string &font, const std::string &text, float kerning, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::text", "Not implemented" );
}
void IECoreArnold::RendererImplementation::sphere( float radius, float zMin, float zMax, float thetaMax, const IECore::PrimitiveVariableMap &primVars )
{
if( zMin != -1.0f )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::sphere", "zMin not supported" );
}
if( zMax != 1.0f )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::sphere", "zMax not supported" );
}
if( thetaMax != 360.0f )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::sphere", "thetaMax not supported" );
}
AtNode *sphere = AiNode( "sphere" );
AiNodeSetFlt( sphere, "radius", radius );
addShape( sphere );
}
void IECoreArnold::RendererImplementation::image( const Imath::Box2i &dataWindow, const Imath::Box2i &displayWindow, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::image", "Not implemented" );
}
void IECoreArnold::RendererImplementation::mesh( IECore::ConstIntVectorDataPtr vertsPerFace, IECore::ConstIntVectorDataPtr vertIds, const std::string &interpolation, const IECore::PrimitiveVariableMap &primVars )
{
MeshPrimitivePtr mesh = new IECore::MeshPrimitive( vertsPerFace, vertIds, interpolation );
mesh->variables = primVars;
addPrimitive( mesh.get(), "ai:polymesh:" );
}
void IECoreArnold::RendererImplementation::nurbs( int uOrder, IECore::ConstFloatVectorDataPtr uKnot, float uMin, float uMax, int vOrder, IECore::ConstFloatVectorDataPtr vKnot, float vMin, float vMax, const IECore::PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::nurbs", "Not implemented" );
}
void IECoreArnold::RendererImplementation::patchMesh( const CubicBasisf &uBasis, const CubicBasisf &vBasis, int nu, bool uPeriodic, int nv, bool vPeriodic, const PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::patchMesh", "Not implemented" );
}
void IECoreArnold::RendererImplementation::geometry( const std::string &type, const CompoundDataMap &topology, const PrimitiveVariableMap &primVars )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::geometry", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// procedurals
/////////////////////////////////////////////////////////////////////////////////////////
int IECoreArnold::RendererImplementation::procLoader( AtProcVtable *vTable )
{
vTable->Init = procInit;
vTable->Cleanup = procCleanup;
vTable->NumNodes = procNumNodes;
vTable->GetNode = procGetNode;
strcpy( vTable->version, AI_VERSION );
return 1;
}
int IECoreArnold::RendererImplementation::procInit( AtNode *node, void **userPtr )
{
ProceduralData *data = (ProceduralData *)( AiNodeGetPtr( node, "userptr" ) );
data->procedural->render( data->renderer.get() );
data->procedural = 0;
*userPtr = data;
return 1;
}
int IECoreArnold::RendererImplementation::procCleanup( void *userPtr )
{
ProceduralData *data = (ProceduralData *)( userPtr );
delete data;
return 1;
}
int IECoreArnold::RendererImplementation::procNumNodes( void *userPtr )
{
ProceduralData *data = (ProceduralData *)( userPtr );
return data->renderer->m_implementation->m_nodes.size();
}
AtNode* IECoreArnold::RendererImplementation::procGetNode( void *userPtr, int i )
{
ProceduralData *data = (ProceduralData *)( userPtr );
return data->renderer->m_implementation->m_nodes[i];
}
void IECoreArnold::RendererImplementation::procedural( IECore::Renderer::ProceduralPtr proc )
{
Box3f bound = proc->bound();
if( bound.isEmpty() )
{
return;
}
AtNode *procedural = AiNode( "procedural" );
if( ExternalProcedural *externalProc = dynamic_cast<ExternalProcedural *>( proc.get() ) )
{
AiNodeSetStr( procedural, "dso", externalProc->fileName().c_str() );
ToArnoldConverter::setParameters( procedural, externalProc->parameters() );
applyTransformToNode( procedural );
}
else
{
// we have to transform the bound, as we're not applying the current transform to the
// procedural node, but instead applying absolute transforms to the shapes the procedural
// generates.
if( bound != Procedural::noBound )
{
bound = transform( bound, m_transformStack.top() );
}
AiNodeSetPtr( procedural, "funcptr", (void *)procLoader );
ProceduralData *data = new ProceduralData;
data->procedural = proc;
data->renderer = new IECoreArnold::Renderer( new RendererImplementation( *this ) );
AiNodeSetPtr( procedural, "userptr", data );
}
if( bound != Procedural::noBound )
{
AiNodeSetPnt( procedural, "min", bound.min.x, bound.min.y, bound.min.z );
AiNodeSetPnt( procedural, "max", bound.max.x, bound.max.y, bound.max.z );
}
else
{
// No bound available - expand procedural immediately.
AiNodeSetBool( procedural, "load_at_init", true );
}
// we call addNode() rather than addShape() as we don't want to apply transforms and
// shaders and attributes to procedurals. if we do, they override the things we set
// on the nodes generated by the procedurals, which is frankly useless.
addNode( procedural );
}
void IECoreArnold::RendererImplementation::addPrimitive( const IECore::Primitive *primitive, const std::string &attributePrefix )
{
const CompoundDataMap &attributes = m_attributeStack.top().attributes->readable();
bool automaticInstancing = true;
CompoundDataMap::const_iterator it = attributes.find( "ai:automaticInstancing" );
if( it != attributes.end() && it->second->typeId() == IECore::BoolDataTypeId )
{
automaticInstancing = static_cast<const IECore::BoolData *>( it->second.get() )->readable();
}
else
{
it = attributes.find( "automaticInstancing" );
if( it != attributes.end() && it->second->typeId() == IECore::BoolDataTypeId )
{
automaticInstancing = static_cast<const IECore::BoolData *>( it->second.get() )->readable();
}
}
AtNode *shape = 0;
if( automaticInstancing )
{
IECore::MurmurHash hash = primitive->::IECore::Object::hash();
for( CompoundDataMap::const_iterator it = attributes.begin(), eIt = attributes.end(); it != eIt; it++ )
{
if( it->first.value().compare( 0, attributePrefix.size(), attributePrefix )==0 )
{
hash.append( it->first.value() );
it->second->hash( hash );
}
}
shape = m_instancingConverter->convert( primitive, hash );
}
else
{
ToArnoldConverterPtr converter = ToArnoldConverter::create( const_cast<IECore::Primitive *>( primitive ) );
shape = converter->convert();
}
if( strcmp( AiNodeEntryGetName( AiNodeGetNodeEntry( shape ) ), "ginstance" ) )
{
// it's not an instance, copy over attributes destined for this object type.
const CompoundDataMap &attributes = m_attributeStack.top().attributes->readable();
for( CompoundDataMap::const_iterator it = attributes.begin(), eIt = attributes.end(); it != eIt; it++ )
{
if( it->first.value().compare( 0, attributePrefix.size(), attributePrefix )==0 )
{
ToArnoldConverter::setParameter( shape, it->first.value().c_str() + attributePrefix.size(), it->second.get() );
}
}
}
else
{
// it's an instance - make sure we don't get double transformations.
AiNodeSetBool( shape, "inherit_xform", false );
}
addShape( shape );
}
void IECoreArnold::RendererImplementation::addShape( AtNode *shape )
{
applyTransformToNode( shape );
applyVisibilityToNode( shape );
AiNodeSetPtr( shape, "shader", m_attributeStack.top().surfaceShader );
if( AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( shape ), "disp_map" ) )
{
if( m_attributeStack.top().displacementShader )
{
AiNodeSetPtr( shape, "disp_map", m_attributeStack.top().displacementShader );
}
}
addNode( shape );
}
void IECoreArnold::RendererImplementation::applyTransformToNode( AtNode *node )
{
/// \todo Make Convert.h
const Imath::M44f &m = m_transformStack.top();
AtMatrix mm;
for( unsigned int i=0; i<4; i++ )
{
for( unsigned int j=0; j<4; j++ )
{
mm[i][j] = m[i][j];
}
}
AiNodeSetMatrix( node, "matrix", mm );
}
void IECoreArnold::RendererImplementation::applyVisibilityToNode( AtNode *node )
{
AtByte visibility = 0;
const BoolData *visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:camera" );
if( visData->readable() )
{
visibility |= AI_RAY_CAMERA;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:shadow" );
if( visData->readable() )
{
visibility |= AI_RAY_SHADOW;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:reflected" );
if( visData->readable() )
{
visibility |= AI_RAY_REFLECTED;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:refracted" );
if( visData->readable() )
{
visibility |= AI_RAY_REFRACTED;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:diffuse" );
if( visData->readable() )
{
visibility |= AI_RAY_DIFFUSE;
}
visData = m_attributeStack.top().attributes->member<BoolData>( "ai:visibility:glossy" );
if( visData->readable() )
{
visibility |= AI_RAY_GLOSSY;
}
AiNodeSetByte( node, "visibility", visibility );
}
void IECoreArnold::RendererImplementation::addNode( AtNode *node )
{
m_nodes.push_back( node );
}
/////////////////////////////////////////////////////////////////////////////////////////
// instancing
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::instanceBegin( const std::string &name, const IECore::CompoundDataMap ¶meters )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::instanceBegin", "Not implemented" );
}
void IECoreArnold::RendererImplementation::instanceEnd()
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::instanceEnd", "Not implemented" );
}
void IECoreArnold::RendererImplementation::instance( const std::string &name )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::instance", "Not implemented" );
}
/////////////////////////////////////////////////////////////////////////////////////////
// commands
/////////////////////////////////////////////////////////////////////////////////////////
IECore::DataPtr IECoreArnold::RendererImplementation::command( const std::string &name, const CompoundDataMap ¶meters )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::command", "Not implemented" );
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// rerendering
/////////////////////////////////////////////////////////////////////////////////////////
void IECoreArnold::RendererImplementation::editBegin( const std::string &editType, const IECore::CompoundDataMap ¶meters )
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::editBegin", "Not implemented" );
}
void IECoreArnold::RendererImplementation::editEnd()
{
msg( Msg::Warning, "IECoreArnold::RendererImplementation::editEnd", "Not implemented" );
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stest.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 15:32:44 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <svmedit.hxx>
#ifndef _TXTCMP_HXX //autogen
#include <txtcmp.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
class MyApp : public Application
{
public:
virtual void Main( );
};
class SearchWindow : public WorkWindow
{
PushButton aPB;
FixedText aFT1, aFT2, aFT3;
MultiLineEdit aEText, aESrch;
RadioButton aModeN, aModeR, aModeL;
SearchParam aParam;
public:
SearchWindow();
DECL_LINK( ClickHdl, Button * );
};
// --- SearchWindow::SearchWindow() ------------------------------------
SearchWindow::SearchWindow() :
WorkWindow( NULL, WinBits( WB_APP | WB_STDWORK )),
aPB( this, WinBits( 0 )),
aFT1( this, WinBits( 0 )),
aFT2( this, WinBits( 0 )),
aFT3( this, WinBits( 0 )),
aEText( this, WinBits( WB_BORDER )),
aESrch( this, WinBits( WB_BORDER )),
aModeN( this, WinBits( 0 )),
aModeR( this, WinBits( 0 )),
aModeL( this, WinBits( 0 )),
aParam( "" )
{
aPB.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
aModeN.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
aModeR.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
aModeL.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
SetMapMode( MapMode( MAP_APPFONT ));
SetSizePixel( LogicToPixel( Size( 300, 180 ) ) );
aEText.SetPosSizePixel( LogicToPixel( Point( 0, 22 )), LogicToPixel(Size( 270, 32 )) );
aFT1.SetPosSizePixel( LogicToPixel( Point( 0, 10 )), LogicToPixel(Size( 18, 11 )) );
aFT2.SetPosSizePixel( LogicToPixel( Point( 0, 60 )), LogicToPixel(Size( 24, 10 )) );
aESrch.SetPosSizePixel( LogicToPixel( Point( 0, 70 )), LogicToPixel(Size( 270, 24 )) );
aPB.SetPosSizePixel( LogicToPixel( Point( 223, 139 )), LogicToPixel(Size( 48, 12 )) );
aFT3.SetPosSizePixel( LogicToPixel( Point( 0, 104 )), LogicToPixel(Size( 270, 15 )) );
aModeN.SetPosSizePixel( LogicToPixel( Point( 5, 116 ) ), LogicToPixel( Size( 40, 12 ) ) );
aModeR.SetPosSizePixel( LogicToPixel( Point( 5, 126 ) ), LogicToPixel( Size( 40, 12 ) ) );
aModeL.SetPosSizePixel( LogicToPixel( Point( 5, 136 ) ), LogicToPixel( Size( 40, 12 ) ) );
aEText.Show();
aFT1.Show();
aFT2.Show();
aESrch.Show();
aPB.Show();
aFT3.Show();
aModeN.Show();
aModeR.Show();
aModeL.Show();
aFT3.SetText( "gefunden:" );
aFT1.SetText( "Text:" );
aFT2.SetText( "Suche:" );
aPB.SetText( "starte Suche" );
aModeN.SetText( "normal" );
aModeR.SetText( "RegExp" );
aModeL.SetText( "LevDis" );
SetText( "Such-Demo" );
}
// --- SearchWindow::SearchSelectHdl() ---------------------------------
IMPL_LINK( SearchWindow, ClickHdl, Button *, pButton )
{
if( pButton == &aPB )
{
String sText( aEText.GetText() );
String sSrch( aESrch.GetText() );
/* InfoBox( this, String( "T: " ) + sText +
String( "\nS: " ) + sSrch ).Execute();
*/
BOOL bRet = FALSE;
USHORT nStt = 0, nEnd = sText.Len();
{
aParam.SetSrchStr( sSrch );
SearchText aSrchText( aParam, GetpApp()->GetAppInternational() );
bRet = aSrchText.SearchFrwrd( sText, &nStt, &nEnd );
// BOOL SearchBkwrd( const String &rStr, USHORT* pStart, USHORT* pEnde );
}
String sFound( "gefunden" );
if( !bRet )
sFound.Insert( "nicht ", 0 );
sFound += ": S<";
sFound += nStt;
sFound += "> E<";
sFound += nEnd;
sFound += '>';
if( bRet )
{
sFound += '<';
sFound += sText.Copy( nStt, nEnd - nStt +1 );
sFound += '>';
}
aFT3.SetText( sFound );
}
else if( pButton == &aModeN )
{
aParam.SetSrchType( SearchParam::SRCH_NORMAL );
}
else if( pButton == &aModeR )
{
aParam.SetSrchType( SearchParam::SRCH_REGEXP );
}
else if( pButton == &aModeL )
{
aParam.SetSrchType( SearchParam::SRCH_LEVDIST );
}
return 0;
}
// --- MyApp::Main() -----------------------------------------------
void MyApp::Main( )
{
SearchWindow* pSearchWindow = new SearchWindow;
pSearchWindow->Show();
Execute();
delete pSearchWindow;
}
// --- aMyApp ------------------------------------------------------
MyApp aMyApp;
INTEGRATION: CWS vgbugs07 (1.4.200); FILE MERGED
2007/06/04 13:31:48 vg 1.4.200.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stest.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:04:02 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <svtools/svmedit.hxx>
#ifndef _TXTCMP_HXX //autogen
#include <txtcmp.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
class MyApp : public Application
{
public:
virtual void Main( );
};
class SearchWindow : public WorkWindow
{
PushButton aPB;
FixedText aFT1, aFT2, aFT3;
MultiLineEdit aEText, aESrch;
RadioButton aModeN, aModeR, aModeL;
SearchParam aParam;
public:
SearchWindow();
DECL_LINK( ClickHdl, Button * );
};
// --- SearchWindow::SearchWindow() ------------------------------------
SearchWindow::SearchWindow() :
WorkWindow( NULL, WinBits( WB_APP | WB_STDWORK )),
aPB( this, WinBits( 0 )),
aFT1( this, WinBits( 0 )),
aFT2( this, WinBits( 0 )),
aFT3( this, WinBits( 0 )),
aEText( this, WinBits( WB_BORDER )),
aESrch( this, WinBits( WB_BORDER )),
aModeN( this, WinBits( 0 )),
aModeR( this, WinBits( 0 )),
aModeL( this, WinBits( 0 )),
aParam( "" )
{
aPB.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
aModeN.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
aModeR.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
aModeL.SetClickHdl( LINK( this, SearchWindow, ClickHdl ));
SetMapMode( MapMode( MAP_APPFONT ));
SetSizePixel( LogicToPixel( Size( 300, 180 ) ) );
aEText.SetPosSizePixel( LogicToPixel( Point( 0, 22 )), LogicToPixel(Size( 270, 32 )) );
aFT1.SetPosSizePixel( LogicToPixel( Point( 0, 10 )), LogicToPixel(Size( 18, 11 )) );
aFT2.SetPosSizePixel( LogicToPixel( Point( 0, 60 )), LogicToPixel(Size( 24, 10 )) );
aESrch.SetPosSizePixel( LogicToPixel( Point( 0, 70 )), LogicToPixel(Size( 270, 24 )) );
aPB.SetPosSizePixel( LogicToPixel( Point( 223, 139 )), LogicToPixel(Size( 48, 12 )) );
aFT3.SetPosSizePixel( LogicToPixel( Point( 0, 104 )), LogicToPixel(Size( 270, 15 )) );
aModeN.SetPosSizePixel( LogicToPixel( Point( 5, 116 ) ), LogicToPixel( Size( 40, 12 ) ) );
aModeR.SetPosSizePixel( LogicToPixel( Point( 5, 126 ) ), LogicToPixel( Size( 40, 12 ) ) );
aModeL.SetPosSizePixel( LogicToPixel( Point( 5, 136 ) ), LogicToPixel( Size( 40, 12 ) ) );
aEText.Show();
aFT1.Show();
aFT2.Show();
aESrch.Show();
aPB.Show();
aFT3.Show();
aModeN.Show();
aModeR.Show();
aModeL.Show();
aFT3.SetText( "gefunden:" );
aFT1.SetText( "Text:" );
aFT2.SetText( "Suche:" );
aPB.SetText( "starte Suche" );
aModeN.SetText( "normal" );
aModeR.SetText( "RegExp" );
aModeL.SetText( "LevDis" );
SetText( "Such-Demo" );
}
// --- SearchWindow::SearchSelectHdl() ---------------------------------
IMPL_LINK( SearchWindow, ClickHdl, Button *, pButton )
{
if( pButton == &aPB )
{
String sText( aEText.GetText() );
String sSrch( aESrch.GetText() );
/* InfoBox( this, String( "T: " ) + sText +
String( "\nS: " ) + sSrch ).Execute();
*/
BOOL bRet = FALSE;
USHORT nStt = 0, nEnd = sText.Len();
{
aParam.SetSrchStr( sSrch );
SearchText aSrchText( aParam, GetpApp()->GetAppInternational() );
bRet = aSrchText.SearchFrwrd( sText, &nStt, &nEnd );
// BOOL SearchBkwrd( const String &rStr, USHORT* pStart, USHORT* pEnde );
}
String sFound( "gefunden" );
if( !bRet )
sFound.Insert( "nicht ", 0 );
sFound += ": S<";
sFound += nStt;
sFound += "> E<";
sFound += nEnd;
sFound += '>';
if( bRet )
{
sFound += '<';
sFound += sText.Copy( nStt, nEnd - nStt +1 );
sFound += '>';
}
aFT3.SetText( sFound );
}
else if( pButton == &aModeN )
{
aParam.SetSrchType( SearchParam::SRCH_NORMAL );
}
else if( pButton == &aModeR )
{
aParam.SetSrchType( SearchParam::SRCH_REGEXP );
}
else if( pButton == &aModeL )
{
aParam.SetSrchType( SearchParam::SRCH_LEVDIST );
}
return 0;
}
// --- MyApp::Main() -----------------------------------------------
void MyApp::Main( )
{
SearchWindow* pSearchWindow = new SearchWindow;
pSearchWindow->Show();
Execute();
delete pSearchWindow;
}
// --- aMyApp ------------------------------------------------------
MyApp aMyApp;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.